我正在编写康威的生命游戏,但我对活细胞的检测揭示了当我尝试使用 [36 ][22] 到 [36][24]。我的迭代更新方法是这样的:
private void nextGeneration() {
for (int i = 0; i < cell.length; i++) {
for (int j = 0; j < cell[i].length; j++) {
if(i>0 && i<79 && j>0 && j<99){
if(cell[i][j].getAlive()){
cell[i][j].calcNeighbors(cell, i, j);
if(cell[i][j].getNeighbors() < 2){
cell[i][j].setAlive(false);
}
if(cell[i][j].getNeighbors() == 2 || cell[i][j].getNeighbors() == 3 && cell[i][j].getAlive()){
cell[i][j].setAlive(true);
}
if(cell[i][j].getNeighbors() > 3){
cell[i][j].setAlive(false);
}
}
else {
cell[i][j].calcNeighborsForNull(cell, i, j);
if (cell[i][j].getNeighborsForNull() == 3) {
cell[i][j].setAlive(true);
}
}
}
}
}
}
其中 nextGeneration() 每 1 秒调用一次,而 cell[][] 是 Cell 类的数组
我使用以下代码检测细胞:
myNeighbors = 0;
if(cell[i-1][j-1].myAlive){
myNeighbors++;
System.out.println("top left");
}
if(cell[i-1][j].myAlive){
myNeighbors++;
System.out.println("top center");
}
if(cell[i-1][j+1].myAlive){
myNeighbors++;
System.out.println("top right");
}
if(cell[i][j-1].myAlive){
myNeighbors++;
System.out.println("mid left");
}
if(cell[i][j+1].myAlive){
myNeighbors++;
System.out.println("mid right");
}
if(cell[i+1][j-1].myAlive){
myNeighbors++;
System.out.println("lower left");
}
if(cell[i+1][j].myAlive){
myNeighbors++;
System.out.println("lower center");
}
if(cell[i+1][j+1].myAlive){
myNeighbors++;
System.out.println("lower right");
}
System.out.println(myNeighbors +" at " + j + "," + -i);
当我运行代码时,我得到以下控制台输出:
top right
mid right
2 at 22,-36
top center
top right
mid left
mid right
4 at 23,-36
top left
top center
2 at 24,-36
mid right
lower left
lower right
3 at 23,-35
mid left
lower center
2 at 24,-35
top right
1 at 22,-36
top left
top center
mid left
3 at 24,-36
mid right
lower center
lower right
3 at 23,-35
编译器认为活细胞上方的死细胞也是活细胞。有人可以看到我做错了什么吗?谢谢。