下面的代码是我为我的生活游戏编写的代码。出于某种原因,它的工作方式非常奇怪。游戏的前几步是错误的,然后整个输出变为零。我不知道是哪种方法导致了问题,但我认为这是计数邻居方法。
该板是一个称为GOLBoard
的二维数组,x和y坐标是cellRow
和cellCol
。活细胞为1,死细胞为0。我避免越界问题的方法是将板设为 12x12,但我只对行和列使用 1 到 11。
<code> @Override
public int countNeighbours(int cellRow, int cellCol) {
int neighbours = 0;
for (int i = cellRow-1; i < cellRow + 2; i++) {
for (int j = cellCol - 1; j < cellCol + 2; j++) {
if (GOLBoard[i][j] == 1) {
neighbours += 1;
}
}
}
if (GOLBoard[cellRow][cellCol] == 1) {
return(neighbours-1);
} else {
return(neighbours);
}
}
@Override
public int applyRules(int cellRow, int cellCol) {
int alive = 0;
if (GOLBoard[cellRow][cellCol] == 1) {
if (countNeighbours(cellRow, cellCol) == 2 || countNeighbours(cellRow, cellCol) == 3) {
alive = 1;
} else if (countNeighbours(cellRow, cellCol) < 2 || countNeighbours(cellRow, cellCol) > 3) {
alive = 0;
}
}
if (GOLBoard[cellRow][cellCol] == 0) {
if (countNeighbours(cellRow, cellCol) == 3) {
alive = 1;
}
}
return (alive);
}
@Override
public void takeStep() {
for (int row = 1; row < 11; row++) {
for (int col = 1; col < 11; col++) {
GOLBoard[row][col] = applyRules(row, col);
}
}
}
@Override
public String toString() {
for (int row = 1; row < 11; row++) {
for (int col = 1; col < 11; col++) {
System.out.print("[" + GOLBoard[row][col] + "]");
}
System.out.println("");
}
return("");
}
} <code>
如果我正确地回顾了 GOL 的规则,那么电路板的演变应该在一系列"世代"中进行,其中"新"板上每个单元的状态完全取决于"旧"板上相应单元的条件。 您的程序正在尝试不断改进单个板,因此对先前计算的单元的更改会影响尚未计算的单元的结果。 你的takeStep
例程应该做一些更像这样的事情:
newBoard = new int[12][12];
for (int row = 1; row < 11; row++) {
for (int col = 1; col < 11; col++) {
newBoard[row][col] = applyRules(row, col);
}
}
GOLBoard = newBoard;
据我所知,你的countNeighbours
没问题。