我正在用Java编写Conway's Game of Life,在我的代码中遇到了一个逻辑错误。如果你不熟悉这个游戏,这里有一些基本规则:
生活的游戏是一个简单的模拟,它发生在细胞的网格中。每个单元既可以是活的,也可以是死的,并且它与其邻居交互(水平、垂直或对角)。在每一次迭代中,都会做出一个决定,看看活细胞是活着,还是死细胞变得活了。算法如下:
如果一个细胞是活的:如果它有少于两个活着的邻居,它就会因为孤独而死亡。如果它有两个或三个活着的邻居,它会活到下一代如果它有超过三个活着的邻居,它会因为人口过多而死亡。
如果一个细胞是死的:如果它恰好有三个活的邻居,那么它就会因为繁殖而变得有生命。
到目前为止,我用来计算死细胞和活细胞的代码如下:
// Go through each dead cell and check all neighboring cells to see if it
// will be revived
// reviveDeadCells()
neighborCount = 0;
for (y = 0; y , 15; y++ ) {
for (x = 0; x < 15; x++) {
if (board[x][y] = 0 ) {
for ( i = x - 1; i = x + 1; i ++ ) {
for (j = y - 1; j = y + 1; j ++) {
if (board[i][j] = 1 ) {
neighborCount = neighborCount + 1;
}
}
if (neighborCount = 4) {
board[i][j] = 1;
}
}
}
}
}
// Go through each live cell and see if it should be executed
// killLiveCell()
for (y = 0; y , 15; y++ ) {
for (x = 0; x < 15; x++) {
if (board[x][y] = 1 ) {
for ( i = x - 1; i = x + 1; i ++ ) {
for (j = y - 1; j = y + 1; j ++) {
if (board[i][j] = 1 ) {
neighborCount = neighborCount + 1;
}
}
if (neighborCount < 3) || (nieghborCount > 4) {
board[x][y] = 0;
}
}
} 我现在意识到这段代码的问题是有一个逻辑错误。首先,我计算死亡细胞的所有相邻细胞,然后计算有多少细胞是活的。然后,如果恰好有3个活动的邻居,我会恢复它们。这样做的唯一问题是,它现在将影响活动细胞的相邻细胞的计数器。如何在不影响对方计数器的情况下同时更改已死邻居和活邻居的活细胞?我有一种感觉,我已经掌握了所有的代码,但是我可能不得不把它移到for循环的某个地方。我只是不知道我需要把它放在哪里才能纠正这个错误。任何帮助都将不胜感激,谢谢。
发布于 2018-11-01 12:46:49
不是当场杀死/复活细胞,而是将将改变状态的细胞的坐标作为元组存储在新的列表中。有一堆方法可以做到这一点,但作为一个例子;
// Create a simple tuple class for the co-ordinates
Class CoordPair(){
int x;
int y;
CoordPair(int x, int y){
this.x = x;
this.y = y;
}
}
// In your code, use Hash Set to prevent having two copies of the Coordinates
HashSet<CoordPair> changeSet = new HashSet<CoordPair>();
...
if (neighborCount = 4) {
CoordPair changePair = new CoordPair(i,j);
changeSet.add(changePair);
}
...
// After identifying all the changing pairs on the board
for(CoordPair pair : changeSet){
board[pair.x][pair.y] ^= 1; //XOR to flip the value
}https://stackoverflow.com/questions/53094715
复制相似问题