我为我的生命游戏设置了一个初始的细胞模式(initial state screenshot),但是代码似乎没有正确地进化细胞。相反,它会停止here,但这一代不应该是这样的。 (我为此带来的不便表示道歉,但由于缺乏声誉,我无法发布州的情况)。我已经查看了我的进化方法,但我似乎无法找到问题,因为我相信所有周围的细胞都被考虑在内。非常感谢帮助。
public void setCellAlive (int row, int col){
if (row <= numberRows){
colony [row][col] = 1;
}else{
System.out.println ("Index out of range.");
}
}
public void setCellDead (int row, int col){
if (row <= numberRows){
colony [row][col]=0;
}else{
System.out.println ("Index out of range.");
}
}
private void evolution(int i, int j) {
int left = 0, right = 0, up = 0, down = 0;
int topLeft = 0, topRight = 0, bottomLeft = 0, bottomRight = 0;
if (j < colony.length - 1) {
right = colony[i][j + 1];
if(i>0)
bottomRight = colony[i - 1][j + 1];
if (i < colony.length - 1)
topRight = colony[i + 1][j + 1];
}
if (j > 0) {
left = colony[i][j - 1];
if (i > 0)
bottomLeft = colony[i - 1][j - 1];
if (i< colony.length-1)
topLeft = colony[i + 1][j - 1];
}
if (i > 0)
up = colony[i + 1][j];
if (i < colony.length - 1)
down = colony[i - 1][j];
int sum = left + right + up + down + topLeft + topRight
+ bottomLeft + bottomRight;
if (colony[i][j] == 1) {
if (sum < 2)
setCellDead (i,j);
if (sum > 3)
setCellDead(i,j);
}
else {
if (sum == 3)
setCellAlive (i,j);
}
}
public void updateColony() {
for (int i = 0; i < colony.length; i++) {
for (int j = 0; j < colony[i].length; j++) {
evolution(i, j);
}
}
}
答案 0 :(得分:2)
您正在更改数组的值,然后使用新的(而不是旧的)值来确定更多单元格的状态。解决方案是每个tick创建一个新数组,然后使用旧数组设置其值:
public void updateColony() {
int [][] nextStep = new int[colony.length][colony[0].length];
for (int i = 0; i < colony.length; i++) {
for (int j = 0; j < colony[i].length; j++) {
evolution(nextStep, i, j);
}
}
colony = nextStep;
}