Why isn't my game of life working correctly? They don't always die when they're too crowded.
Relevant code is grann(x,y) which is supposed to return the number of living cells surrounding matrix[x][y], run is supposed to calculate the next generation:
private int grann(int x,int y) {
int n = 0;
for(int i=-1; i<2; i++) {
for(int j=-1; j<2; j++) {
if(i!=0 || j!=0) {
if(matrix[x+i][y+j]) {
n++;
}
}
}
}
return n;
}
public void run() {
boolean[][] next = matrix;
for(int i=1; i<w; i++) {
for(int j=1; j<h; j++) {
int n = grann(i,j);
if(matrix[i][j]) {
if(!(n==2 || n==3)) {
next[i][j] = false;
}
} else {
if(n==3) {
next[i][j] = true;
}
}
}
}
matrix = next;
}
The object has a matrix, width and height. matrix is a boolean[w+2][h+2], and w and h are ints.
If you don't know the rules of Conway's game of life: http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life