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 _freeRoad = 0; protected final int _barrier = 1; public Image createMap(int width, int height, IDrawingObject drawingObject) { _width = width; _height = height; _drawingObject = drawingObject; do { generateMap(); } while (!setObjectOnMap()); return drawMapWithObject(); } public Image moveObject(Direction direction) { _drawingObject.moveObject(direction); if (objectIntersects()) { switch (direction) { case Left -> _drawingObject.moveObject(Direction.Right); case Right -> _drawingObject.moveObject(Direction.Left); case Up -> _drawingObject.moveObject(Direction.Down); case Down -> _drawingObject.moveObject(Direction.Up); } } return drawMapWithObject(); } private boolean setObjectOnMap() { if (_drawingObject == null || _map == null) { return false; } for (int i = 2; i < _map.length; i++) { for (int j = 2; j < _map[i].length; j++) { _drawingObject.setObject((int) (i * _size_x), (int) (j * _size_y), _width, _height); if (!objectIntersects()) return true; } } return true; } private boolean objectIntersects() { float[] location = _drawingObject.getCurrentPosition(); for (int i = 0; i < _map.length; i++) { for (int j = 0; j < _map[i].length; j++) { if (_map[i][j] == _barrier) { if (i * _size_x >= location[0] && (i + 1) * _size_x <= location[1] && j * _size_y >= location[2] && (j + 1) * _size_y <= location[3]) { return true; } } } } return false; } private Image drawMapWithObject() { Image img = new BufferedImage(_width, _height, BufferedImage.TYPE_INT_ARGB); if (_drawingObject == 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); } } } _drawingObject.drawingObject(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); }