我自己实现的康威的生命游戏并没有按我预期的方式运作

编程语言 2026-07-10

最近,我尝试用Java重现约翰·康威的生命游戏。
在编码过程中,我做了大量测试,一切看起来都没问题。
然而,当我实际测试时,结果并不正确。不知何故,在第3 代,索引 [2][1] 的格子(从右边数第三,从上边数第二)变成了活细胞,尽管它有4 个邻居,而不是3。

Here is a video showing the problem:

https://www.dropbox.com/scl/fi/5mcx0hwj13cavmd5vz2ho/2026-04-16-21-00-16.mp4?rlkey=3broyygeqkjje25ml5tiezgwd&st=7nr1szdj&dl=0

This is the code that creates the next generation:

public int getNeighbors(int x, int y) {
    int neighbors = (cells[y][x] == 1) ? -1 : 0;

    for(int i = -1; i < 2; i++) {
        for(int j = -1; j < 2; j++) {
            if(x-j >= 0 && y-i >= 0 && x-j <=4 && y-i <= 4) {
                neighbors += cells[y-i][x-j];
            }
        }
    }

    return neighbors;
}

public int nextCellGen(int x, int y) {
    int neighbors = getNeighbors(x, y);
    int newStatus = 0;

    if(neighbors < 2) {
        newStatus = 0;
    }
    if((neighbors == 2 || neighbors == 3) && cells[y][x] == 1) {
        newStatus = 1;
    }
    if(neighbors > 3) {
        newStatus = 0;
    }
    if(neighbors == 3 && cells[y][x] == 0) {
        newStatus = 1;
    }

    return newStatus;
}

public void nextFullGen() {
    for(int i = 0; i < 6; i++) {
        for(int j = 0; j < 6; j++) {
            newCells[i][j] = nextCellGen(j, i);
        }
    }
}

解决方案

First, let’s establish that we need getNeighbors(), since the rules to be applied are based on how many “live” neighbors each cell has that’s exactly what we want to obtain, anything else is noise (since the nextCellGen() handles the rest of the operation), so all we need to do is traverse the neighboring locations and count how many are “alive,” and we can do this with the following approach (which isn’t the only one, and certainly not the best):

int relative_neighbors_positions[][] = {
   { -1, -1 },
   {  0, -1 },
   {  1, -1 },
   { -1,  0 }, 
   {  1,  0 },
   { -1,  1 },
   {  0,  1 },
   {  1,  1 }
};

  // we verify that the position is indeed within the
  // boundaries of the... “universe”
  // I'm assuming that “cells” has the same number of
  // rows and columns
booleam isInRange( int x ) {  
   return x >= 0 && x < cells.length; 
}

public int getNeighbors( int x, int y ) {
   int neighbors = 0;
   for( int relative_position[] : relative_neighbors_positions ) {
      int nb_x = x + relative_position[ 0 ];
      int nb_y = y + relative_position[ 1 ];
      if( isInRange( nb_x ) && isInRange( nb_y ) && cells[ nb_x ][ nb_y == 1 ) 
         neighbors++;
   }
   return neighbors;
}

Note: You could omit the isInRange() method and even the two lines preceding the if statement, but I prefer more verbose code that is easier to read。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章