我不确定我是否会生气,但这就是我的问题所在:
我编写了生命游戏,并采用了一种“精确”的方法来计算有多少周围场地的存在。
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;
}
这种方法似乎完全正常。但是当我这样做时
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;
}
我在控制台中得到了这个:
2
i = 1j = 1 1
i = 1j = 2 1
i = 1j = 3 1
i = 1j = 4 1
i = 1j = 5 0
...
即使i = 1且j = 3也应该是2而不是1.正如您所看到的那样,方法countalive(board,1,3)可以工作但是在for循环中它给出了不同的结果。你能找到我的错误吗?
答案 0 :(得分:2)
您正在迭代期间更改单元格的活动性。你需要做的是为下一代创建一个单独的数组,并根据这一代更新,然后在完全查看当前一代后交换它们。