生命游戏规则不正常

时间:2013-01-03 15:54:32

标签: java math conways-game-of-life cellular-automata

我在Java中的Game of Life应用程序中有以下逻辑代码。我有一个问题,规则不像默认的康威的生命游戏规则。我已经在Wikipedia上阅读了它们,它们是以下内容;

  • 任何活着的邻居少于两个的活细胞都会死亡,好像是由于人口不足造成的。
  • 任何有两三个活邻居的活细胞都会留在下一代。
  • 任何有三个以上活着的邻居的活细胞都会死亡,就像过度拥挤一样。
  • 任何有三个活着的邻居的死细胞都会成为活细胞,好像通过繁殖一样。

我试图在以下代码中复制这些规则,但它的行为与正常的Conway'生命游戏不同;

int surroundingLife = 0;
if (lifeMap[cX+1][cY]) { //Right
    surroundingLife++;
}
if (lifeMap[cX-1][cY]) { // Left
    surroundingLife++;
}
if (lifeMap[cX][cY+1]) { // Above
    surroundingLife++;
}
if (lifeMap[cX][cY-1]) { // Below
    surroundingLife++;
}
if (lifeMap[cX-1][cY-1]) { // Bottom left
    surroundingLife++;
}
if (lifeMap[cX+1][cY+1]) { // Top Right
    surroundingLife++;
}
if (lifeMap[cX-1][cY+1]) { // Some other corner (I don't know which one)
    surroundingLife++;
}
if (lifeMap[cX+1][cY-1]) { // Yet another corner (I don't know which one)
    surroundingLife++;
}
if (running) {
    // Logic for life
    if (surroundingLife < 2 && lifeMap[cX][cY]) {// Rule 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
        lifeMap[cX][cY] = false;
    } else if (surroundingLife == 2 && lifeMap[cX][cY]) { // Rule 2. Any live cell with two or three live neighbours lives on to the next generation.
        lifeMap[cX][cY] = true;
    } else if (surroundingLife == 3 && lifeMap[cX][cY]) { // Rule 3. Same as above
        lifeMap[cX][cY] = true;
    } else if (surroundingLife > 3 && lifeMap[cX][cY]) { // Rule 4. Any live cell with more than three live neighbours dies, as if by overcrowding.
        lifeMap[cX][cY] = false;
    } else if (surroundingLife == 3 && !lifeMap[cX][cY]) { // Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
        lifeMap[cX][cY] = true;
    }
}   

这是运行几代后的看法;

GameOfBugs, or BugsOfLife.

它让我想起了“迷宫”规则集,这很奇怪。

我不相信我的surroundLife计算器有问题,因为当实体有8个其他围绕它们时它返回8。问题是由于我循环通过Y然后X?

1 个答案:

答案 0 :(得分:9)

问题在于,您在评估需要更改的内容时,在同一个过程中修改网格。每次更改单元格时,都会影响与该单元格相邻的同一遍中所有未来测试的结果。

您需要制作网格的副本。始终从该副本中测试(读取),并将更改(写入)应用于原始文件。