-4

我必须为大学的编程模块编写康威生活模拟游戏。该程序的工作原理是每次迭代都能正确计算邻居的数量。它应该如何工作是:

Current State       Neighbors              Next State
Alive                   2                  Alive
Alive                   3                  Alive
Alive                  <2                  Dead
Alive                  >3                  Dead
Dead                    3                  Alive   

每次改变一个细胞状态时,其周围的 8 个细胞相邻字段都会增加或减少。

public static Cell[][] updateGrid(Cell[][] theMatrix){
Cell[][] copy = new Cell[DIMENSIONX][DIMENSIONY];
for(int x = 0; x < DIMENSIONX; x++){
    for(int y = 0; y < DIMENSIONY; y++ ){
        copy[x][y] = theMatrix[x][y];
    }
}
int increment;
for(int x = 0; x < DIMENSIONX; x++){
    for(int y = 0; y < DIMENSIONY; y++ ){
        //Underpopulation
        if((copy[x][y].alive == false)&&(copy[x][y].neighbours == 3)){
            theMatrix[x][y].alive = true;
            increment = 1;
            theMatrix = addNeighbours(theMatrix, increment, x,y);
        }
        //Over Population
        else if((copy[x][y].alive==true)&&(copy[x][y].neighbours > 3)){
            theMatrix[x][y].alive = false;
            increment = -1;
            theMatrix = addNeighbours(theMatrix, increment, x,y);
        }
    }
}
return theMatrix;
}

感谢您抽出时间来看看!〜保罗

4

2 回答 2

1

您没有对活细胞进行所有检查。您还需要检查单元格的其他参数

你有:

for(int x = 0; x < DIMENSIONX; x++){
    for(int y = 0; y < DIMENSIONY; y++ ){
        //Underpopulation
        if((copy[x][y].alive == false)&&(copy[x][y].neighbours == 3)){
            theMatrix[x][y].alive = true;
            increment = 1;
            theMatrix = addNeighbours(theMatrix, increment, x,y);
        }
        //Over Population
        else if((copy[x][y].alive==true)&&(copy[x][y].neighbours > 3)){
            theMatrix[x][y].alive = false;
            increment = -1;
            theMatrix = addNeighbours(theMatrix, increment, x,y);
        }
    }
}

简而言之是:

for all cells of the grid:
  if dead and neighbor count is 3, make alive
  if alive and neighbor count is > 3 make dead

你需要:

for all cells of the grid:
  if dead and neighbor count is 3, make alive
  if alive and neighbor count is > 3 make dead
  if alive and neighbor count is 0 or 1 make dead // ** need this

另请注意,在 if 块中,不要使用== false诸如,

if((copy[x][y].alive == false) && .....

而是做

if((!copy[x][y].alive) && .....
于 2013-11-11T23:22:47.927 回答
0

您的评论需要一些工作。“人口不足”线并没有真正测试人口不足。这是对创造的测试:当一个死细胞恰好有三个活着的邻居时,就会产生新的生命。

你根本没有人口不足测试。这就是一个活细胞死亡的地方,只有不到 2 个活的邻居来维持它。

最简单的解决方法是将“人口过剩”测试修改为“过度/不足”灭绝:

   //Overpopulation or underpopulation
    else if ( (copy[x][y].alive==true) && 
              ( copy[x][y].neighbours > 3 || copy[x][y].neighbours< < 2) ) {
        theMatrix[x][y].alive = false;
        increment = -1;
        theMatrix = addNeighbours(theMatrix, increment, x,y);
    }

确保这addNeighbors是使用新值创建new Cell对象,否则您将遇到其他问题。

于 2013-11-12T00:06:00.890 回答