问题描述
我不确定我是否会发疯,但这就是我的问题所在:
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
...
即使i = 1和j = 3应该是2而不是1.正如您所看到的,方法countalive(board,1,3)起作用,但是在for循环中它给了我不同的结果.你能找到我的错误吗?
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?
推荐答案
您正在迭代中更改单元格的活动性.您需要做的是为下一代拥有一个单独的阵列,并根据这一代对其进行更新,然后在完全了解了当前一代之后将其交换.
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.
这篇关于生活游戏,方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!