I have Tiles which represent the tiles in a game’s 2-dimensional world. The tiles can have walls on any number of their 4 sides. I have something like this at the moment:
interface Tile {
boolean isWallAtTop();
boolean isWallAtRight();
boolean isWallAtLeft();
boolean isWallAtBottom();
}
Somewhere else I also have 16 images, one for each possible tile wall configuration. Something like this:
static final Image WALLS_ALL_AROUND = ...
static final Image WALL_ON_TOP_AND_RIGHT = ...
/* etc etc all 16 possibilities */
I want to write a
static Image getWallImage(Tile tile)
What I’d like to avoid is the torture of going through the possibilities like
if (tile.isWallTop && tile.isWallRight
&& !tile.isWallBottom && !tile.isWallLeft) {
return WALL_ON_TOP_AND_RIGHT;
}
Does anyone know a cuter way to do this?
Go go gadget bitmasks. Use a 4 bit mask for each tile, stating which side has a wall.
Bit A indicates a wall on the top, B the right, C the bottom, D the left. Define constants to help you that you can just logically intersect with the mask, i.e.
For finding the image, this 4 bit mask produces the 16 possibilities. Use it as an index into an images “array”, so you can directly find the correct image without any effort.