【问题标题】:Java Game of Life not checking neighbors correctlyJava Game of Life 未正确检查邻居
【发布时间】:2016-06-16 02:07:35
【问题描述】:

我为我的生命游戏设置了初始的细胞模式 (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);
        }
    }
 }

【问题讨论】:

  • 好吧,您可以创建一个包含两种状态的更大图像并使用它:-)
  • @Leo 如果有帮助,我现在可以编辑它。
  • 很难说,因为我们看不到调用evolution的代码。但我的猜测是,当你将一个单元格设置为 Alive 或 Dead 时,它会影响 同一代 其余部分的计算,这是不应该发生的。
  • @ajb 是的,我就是这么想的——我 90% 确定进化是在同一代人中产生和杀死细胞,但我不知道如何解决这个问题。我在原代码sn-p的底部添加了调用进化的方法。
  • 在创建世代时,您可能需要拥有数组的两个副本。 (复制二维数组时要小心。二维数组是对一维数组的引用数组,如果只复制引用而不复制数据,会遇到麻烦。)

标签: java conways-game-of-life


【解决方案1】:

您正在更改数组的值,然后使用新的(而不是旧的)值来决定其他单元格的状态。解决方案是在每个刻度上创建一个新数组,然后使用旧数组设置其值:

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;
}

【讨论】:

  • @pianos:这是大意。还要注意evolution 需要从colony 读取并写入nextStep。最重要的是:在sprinter 的代码中,nextStep 以所有“死”单元格开头,因此您不再需要setCellDead,您必须确保已经活着并需要的单元格保持活力由setCellAlive 设置。
猜你喜欢
  • 2015-09-05
  • 2022-12-26
  • 1970-01-01
  • 2021-04-13
  • 2023-04-01
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多