问题
I'm not sure if I am turning mad but this is what my problem is:
I programm Game of Life and have a "countalive" method which counts how many surrounding fields are alive.
public int countalive(Board board, int yaxis, int xaxis) { //defekt
int living = board.getfields()[yaxis - 1][xaxis - 1] + board.getfields()[yaxis - 1][xaxis] + board.getfields()[yaxis - 1][xaxis + 1] +
board.getfields()[yaxis][xaxis - 1] + board.getfields()[yaxis][xaxis + 1] + board.getfields()[yaxis + 1][xaxis - 1] +
board.getfields()[yaxis + 1][xaxis] + board.getfields()[yaxis + 1][xaxis + 1];
return living;
}
This method seems to work perfectly fine. But when i do this
public Board evolve(Board board) {
Board tmpboard = board;
System.out.println(countalive(board, 1, 3)); //I test with this. SHOULD AND IS 2!!
int aliveneighbours = 0;
for (int i = 1; i < board.getfields().length - 1; i++) {
for (int j = 1; j < board.getfields()[i].length - 1; j++) {
System.out.print("i = " +i);
System.out.print("j = " +j +" ");
aliveneighbours = countalive(board, i, j);
System.out.println(aliveneighbours);
if (aliveneighbours == 3) {
tmpboard.getfields()[i][j] = 1;
} else if (aliveneighbours < 2 || aliveneighbours > 3) {
tmpboard.getfields()[i][j] = 0;
}
}
System.out.println("");
}
return tmpboard;
}
I get this in the console:
2
i = 1j = 1 1
i = 1j = 2 1
i = 1j = 3 1
i = 1j = 4 1
i = 1j = 5 0
...
even though i = 1 and j =3 should be 2 and not 1. As you see the the method countalive(board, 1, 3) works but in the for loop it gives me a different result. Can you find my error?
回答1:
You are changing the aliveness of cells during the iteration. What you need to do is to have a separate array for the next generation and update that based on this generation, then swap them once you have completely looked at the current generation.
来源:https://stackoverflow.com/questions/25832120/game-of-life-method-doesnt-work