so im programming conways game of life in GUI form. the output is not correct and i dont know why. this is the code that handles the “next generation”.
for(int i=0; i < ROW; i++) {
for(int j=0; j < COL; j++) {
if(i > 0 && i < ROW-1 && j > 0 && j < COL -1) {
if(grid.getButton(i-1, j-1).getBackground() == Color.BLUE) liveNeighbor++;
if(grid.getButton(i-1, j).getBackground() == Color.BLUE) liveNeighbor++;
if(grid.getButton(i-1, j+1).getBackground() == Color.BLUE) liveNeighbor++;
if(grid.getButton(i, j-1).getBackground() == Color.BLUE) liveNeighbor++;
if(grid.getButton(i, j+1).getBackground() == Color.BLUE) liveNeighbor++;
if(grid.getButton(i+1, j-1).getBackground() == Color.BLUE) liveNeighbor++;
if(grid.getButton(i+1, j).getBackground() == Color.BLUE) liveNeighbor++;
if(grid.getButton(i+1, j+1).getBackground() == Color.BLUE) liveNeighbor++;
if(grid.getButton(i, j).getBackground() == Color.WHITE) {
if(liveNeighbor == 3)
newGrid.getButton(i, j).setBackground(Color.BLUE);
} else {
if(liveNeighbor > 3 || liveNeighbor < 2)
newGrid.getButton(i, j).setBackground(Color.WHITE);
}
liveNeighbor=0;
}
}
}
maybe im missing something, but im pretty sure this is right. any suggestions?
This is the problem:
Your code only sets the color if the current tile is dead. If it’s alive, it will never become dead. I would write this as:
I’d also separate the logical data (a grid of boolean values) from the display part – the “business logic” here shouldn’t know anything about colors.