C++年康威生命游戏的相邻细胞计数

Counting neighboring cells for Conway's Game of Life in C++

本文关键字:细胞计数 游戏 康威 生命 C++      更新时间:2023-10-16

我正在尝试为康威的生活游戏写一个计数邻居方法。如果一个死细胞周围有2到3个活细胞,它就会活过来。然而,我的代码没有正确地计算所有的邻居。如果我给出输入坐标(10,10)(10,11)(10,12)这将产生

   ***

程序将把下一代打印为

    *
    *

,坐标为(10,11)和(11,11)。然而,也应该有一个点在(9,11)。我知道问题出现在这个函数中对于点(9,11)这个函数没有计算3个邻居。

int Life::neighbor_count (int row, int col)
{
  int i, j;
  int count=0;
  for(i=row-1; i<row+1; i++){
    for (j=col-1; j<=col+1; j++){
      count +=grid[i][j];//increase the count is neighbor is alive
    }
  }
  count -=grid [row][col];//reduce count, since cell is not its own neighbor
  return count;
}

正如@AlexD指出的,i<row+1应该是i<=row+1,这就解释了你的答案