【发布时间】:2019-09-29 05:31:00
【问题描述】:
生命游戏任务中的这个函数应该遍历第二个数组并检查每个单元格有多少邻居。当我在 main 中调用它时,即使在任何类型的循环中,终端都会冻结,就像在无限的 while 循环中一样。谁能告诉我我的代码有什么问题?谢谢。
void Grids::simulate(int** myGrid, int rows, int columns)
{
int neighbors = 0; //variable to store how many neighbors a cell has
for (int r = 0; r < rows; ++r) // iterates through rows
{
for(int c = 0; c < columns; ++c)//iterates through columns
{
for(int x = -1; x < 2; x + 2) //iterates through -1 and 1, the spaces next to the cell
{
for(int y = -1; y < 2; y + 2)
{
if ((r + x >= 0) && (r + x < rows) && (c + y >= 0) && (c + y < columns)) //prevents indexing the 2d array outside of its bounds
{
if (myGrid[r + x][c + y] == 1) //checks if the surrounding cells are alive
{
++neighbors;
}
}
}
}
if (neighbors < 2) //underpopulation
{
myGrid[r][c] = 0; //dead
}
else if (neighbors == 3) //reproduction
{
myGrid[r][c] = 1; //alive
}
else if (neighbors >= 4) //overpopulation
{
myGrid[r][c] = 0; //dead
}
}
}
}
【问题讨论】:
-
在您的第三个和第四个
for循环中,x+2和y+2是否有错别字? -
这似乎是一个错字。
for(int x=-1; x<2; x+2)。x+2不会改变x。这就是为什么你有一个无限循环。您的意思是使用for(int x=-1; x<2; x += 2)吗?for(int y=-1;y<2;y+2)也存在同样的问题。 -
这无论如何都行不通。你不能以这种方式更新网格,它不符合游戏规则。
-
生命游戏要求您在一个干净的网格上开始每一代新人。然后更新新网格的单元格引用旧网格上的单元格。正如您所拥有的那样,您正在根据更新的单元格和未访问的单元格做出决策。不是你想要的。这不会生成你想要的板子。