149 lines
4.0 KiB
Java

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public abstract class AbstractMap {
private IDrawingObject _drawingObject = 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 _freeWaterArea = 0;
protected final int _land = 1;
public BufferedImage CreateMap(int width, int height, IDrawingObject drawingObject)
{
_width = width;
_height = height;
_drawingObject = drawingObject;
GenerateMap();
while (!SetObjectOnMap())
{
GenerateMap();
}
return DrawMapWithObject();
}
public BufferedImage MoveObject(Direction direction)
{
float[] dim = _drawingObject.GetCurrentPosition();
if (CheckLand(dim[0], dim[1], dim[2], dim[3]) != 0)
{
_drawingObject.MoveObject(SetOppositDirection(direction));
}
if (true)
{
_drawingObject.MoveObject(direction);
}
return DrawMapWithObject();
}
private boolean SetObjectOnMap()
{
if (_drawingObject==null || _map == null)
{
return false;
}
int x = _random.nextInt(10);
int y = _random.nextInt(10);
_drawingObject.SetObject(x, y, _width, _height);
float[] dim = _drawingObject.GetCurrentPosition();
while (CheckLand(dim[0], dim[1], dim[2], dim[3]) != 2)
{
int res;
do
{
res = CheckLand(dim[0], dim[1], dim[2], dim[3]);
if (res == 0)
{
_drawingObject.SetObject((int)dim[0], (int)dim[1], _width, _height);
return true;
}
else
{
dim[0] += _size_x;
}
} while (res != 2);
dim[0] = x;
dim[1] += _size_y;
}
return false;
}
private BufferedImage DrawMapWithObject()
{
BufferedImage bmp = new BufferedImage(_width, _height,BufferedImage.TYPE_INT_RGB);
if (_drawingObject == null || _map == null)
{
return bmp;
}
Graphics gr = bmp.getGraphics();
for (int i = 0; i < _map.length; ++i)
{
for (int j = 0; j < _map[i].length; ++j)
{
if (_map[i][j] == _freeWaterArea)
{
DrawWaterPart(gr, i, j);
}
else if (_map[i][j] == _land)
{
DrawLandPart(gr, i, j);
}
}
}
_drawingObject.DrawingObject(gr);
return bmp;
}
private int CheckLand(float Left, float Right, float Top, float Bottom)
{
int RUi = (int)(Left / _size_x);
int RUj = (int)(Right / _size_y);
int LDi = (int)(Top / _size_x);
int LDj = (int)(Bottom / _size_y);
if (RUi < 0 || RUj < 0 || LDi >= _map[0].length || LDj >= _map.length)
{
return -1;
}
for (int x = RUi; x <= LDi; x++)
{
for (int y = RUj; y <= LDj; y++)
{
if (_map[x][y] == _land)
{
return 1;
}
}
}
return 0;
}
private Direction SetOppositDirection(Direction dir)
{
switch (dir)
{
case Up:
return Direction.Down;
case Down:
return Direction.Up;
case Left:
return Direction.Right;
case Right:
return Direction.Left;
case None:
return Direction.None;
}
return Direction.None;
}
protected abstract void GenerateMap();
protected abstract void DrawWaterPart(Graphics gr, int i, int j);
protected abstract void DrawLandPart(Graphics gr, int i, int j);
}