Reputation: 1311
I'm implementing Bomberman clone in Java. Its map has a scale of 17*13 tiles. Now I'm storing the game map in the ArrayList
. Obviously it's unproductive since game mechanics provides only discrete moving (right, left, up, down). Bombs can have only discrete position too. So with the ArrayList
I have to look for four adjacent tiles through whole list while processing collisions or fire generating. So what are the best practices for storing such maps in Java.
Upvotes: 0
Views: 607
Reputation: 27966
There are lots of ways you could model this. Here's a suggestion that I've used often for similar problems:
enum Direction {
NORTH, SOUTH, EAST, WEST;
}
class Position {
private final int x;
private final int y;
public static Stream<Position> getAllPositions();
public Stream<Position> getNeighbours();
public Optional<Position> positionInDirection(Direction direction);
// make sure you implement equals and hashCode
}
class Map {
private final Map<Position, Tile> tiles = new HashMap<>();
public Map() {
Position.getAllPositions().forEach(pos -> tiles.put(pos, new Tile());
}
public Tile getTile(Position position) {
return tiles.get(position);
}
}
This provides lots of useful encapsulation. For example the Position
class is the only one that needs to know about the size of the map and edges.
Now to see if an adjacent position has a bomb (for example), you would use:
position.getNeighbours().map(map::getTile).anyMatch(Tile::hasBomb);
Upvotes: 2