My method for counting neighbors in my soon-to-be Game of Life implementation is very repetitive and I was wondering if this could be done more elegantly:
static int countNeighbours(Board b, int x, int y) {
int count = 0;
if (b.getTile(x - 1, y - 1)) {
++count;
}
if (b.getTile(x, y - 1)) {
++count;
}
if (b.getTile(x + 1, y - 1)) {
++count;
}
if (b.getTile(x + 1, y)) {
++count;
}
if (b.getTile(x + 1, y + 1)) {
++count;
}
if (b.getTile(x, y + 1)) {
++count;
}
if (b.getTile(x - 1, y + 1)) {
++count;
}
if (b.getTile(x - 1, y)) {
++count;
}
return count;
}
Because officially the board should be infinite, I don't need out-of-bounds checks in this code - I assume the board is infinite here -, but my Board implementation secretly looks like this:
// TODO: make the board 'infinite'
public boolean getTile(int x, int y) {
if (x < 0 || y < 0 || x > getWidth() - 1 || y > getHeight() -1) return false;
return tiles[y][x];
}
public void setTile(int x, int y, boolean val) {
if (x < 0 || y < 0 || x > getWidth() - 1 || y > getHeight() -1) return;
tiles[y][x] = val;
}
(Just to save you the time it costs to type 'your code will cause an IndexOutOfBoundsException
for the tile on (0,0)'. This question is on the implementation of static int countNeighbours(Board, int, int)
.)
I'm stuck with Java 6 by the way.