PIbd-23_Minhasapov_R.H._Exc.../AbstractMap.java

118 lines
3.7 KiB
Java

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public abstract class AbstractMap {
private IDrawningObject _drawningObject = null;
protected int[][] _map = null;
protected int _width;
protected int _height;
protected float _size_x;
protected float _size_y;
protected final Random _random = new Random();
protected final int _freeRoad = 0;
protected final int _barrier = 1;
public Image CreateMap(int width, int height, IDrawningObject drawningObject)
{
_width = width;
_height = height;
_drawningObject = drawningObject;
do {
GenerateMap();
} while (!SetObjectOnMap());
return DrawMapWithObject();
}
public Image MoveObject(Direction direction)
{
_drawningObject.moveObject(direction);
if (objectIntersects()) {
switch (direction) {
case Left -> _drawningObject.moveObject(Direction.Right);
case Right -> _drawningObject.moveObject(Direction.Left);
case Up -> _drawningObject.moveObject(Direction.Down);
case Down -> _drawningObject.moveObject(Direction.Up);
}
}
return DrawMapWithObject();
}
private boolean SetObjectOnMap()
{
if (_drawningObject == null || _map == null)
{
return false;
}
int x = _random.nextInt(0, 10);
int y = _random.nextInt(0, 10);
_drawningObject.setObject(x, y, _width, _height);
var Location = _drawningObject.getCurrentPosition();
if (objectIntersects()){
int startLocX = (int)(Location[0] / _size_x);
int startLocY = (int)(Location[2] / _size_y);
int endLocX = (int)(Location[1] / _size_x);
int endLocY = (int)(Location[3] / _size_y);
for (int j = startLocX; j <= endLocX; j++)
{
for (int i = startLocY; i <= endLocY; i++)
{
if (_map[i][j] == _barrier) _map[i][j] = _freeRoad;
}
}
}
return true;
}
private boolean objectIntersects() {
float[] location = _drawningObject.getCurrentPosition();
Rectangle self = new Rectangle((int) location[0], (int) location[2], (int) location[1] - (int) location[0], (int) location[3] - (int) location[2]);
for (int i = 0; i < _map.length; i++)
{
for (int j = 0; j < _map[i].length; j++)
{
if (_map[i][j] == _barrier)
{
if (self.intersects(new Rectangle(j * (int) _size_x, i * (int) _size_y, (int) _size_x, (int) _size_y)))
{
return true;
}
}
}
}
return false;
}
private Image DrawMapWithObject() {
Image img = new BufferedImage(_width, _height, BufferedImage.TYPE_INT_ARGB);
if (_drawningObject == null || _map == null) {
return img;
}
Graphics2D g = (Graphics2D) img.getGraphics();
for (int i = 0; i < _map.length; ++i)
{
for (int j = 0; j < _map[i].length; ++j)
{
if (_map[i][j] == _freeRoad)
{
DrawRoadPart(g, i, j);
} else if (_map[i][j] == _barrier)
{
DrawBarrierPart(g, i, j);
}
}
}
_drawningObject.drawningObject(g);
return img;
}
protected abstract void GenerateMap();
protected abstract void DrawRoadPart(Graphics2D g, int i, int j);
protected abstract void DrawBarrierPart(Graphics2D g, int i, int j);
}