PIbd-22_Aleikin_A.M._AirBom.../AbstractMap.java

115 lines
3.6 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 Random _random = new Random();
protected int _freeRoad = 0;
protected int _barrier = 1;
public BufferedImage CreateMap(int width, int height, IDrawningObject drawningObject)
{
_width = width;
_height = height;
_drawningObject = drawningObject;
GenerateMap();
while (!SetObjectOnMap())
{
GenerateMap();
}
return DrawMapWithObject();
}
private boolean CanMove(float[] position) //Проверка на возможность шага
{
for (int i = (int)(position[2] / _size_y); i <= (int)(position[3] / _size_y); ++i)
{
for (int j = (int)(position[0] / _size_x); j <= (int)(position[1] / _size_x); ++j)
{
if (i >= 0 && j >= 0 && i < _map.length && j < _map[0].length && _map[i][j] == _barrier) return false;
}
}
return true;
}
public BufferedImage MoveObject(Direction direction)
{
float[] position = _drawningObject.GetCurrentPosition();
if (direction == Direction.Left)
{
position[0] -= _drawningObject.getStep();
}
else if (direction == Direction.Right)
{
position[1] += _drawningObject.getStep();
}
else if (direction == Direction.Up)
{
position[2] -= _drawningObject.getStep();
}
else if (direction == Direction.Down)
{
position[3] += _drawningObject.getStep();
}
if (CanMove(position))
{
_drawningObject.MoveObject(direction);
}
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);
for (int i = (int)(_drawningObject.GetCurrentPosition()[2] / _size_y); i <= (int)(_drawningObject.GetCurrentPosition()[3] / _size_y); ++i)
{
for (int j = (int)(_drawningObject.GetCurrentPosition()[0] / _size_x); j <= (int)(_drawningObject.GetCurrentPosition()[1] / _size_x); ++j)
{
if (_map[i][j] == _barrier) _map[i][j] = _freeRoad;
}
}
return true;
}
private BufferedImage DrawMapWithObject()
{
BufferedImage bmp = new BufferedImage(_width, _height, BufferedImage.TYPE_INT_RGB);
if (_drawningObject == null || _map == null)
{
return bmp;
}
Graphics g = bmp.getGraphics();
for (int i = 0; i < _map.length; ++i)
{
for (int j = 0; j < _map[0].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 bmp;
}
protected abstract void GenerateMap();
protected abstract void DrawRoadPart(Graphics g, int i, int j);
protected abstract void DrawBarrierPart(Graphics g, int i, int j);
}