【问题标题】:C++ Game of Life infinite looping functionC++ 生命游戏无限循环函数
【发布时间】: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+2y+2 是否有错别字?
  • 这似乎是一个错字。 for(int x=-1; x&lt;2; x+2)x+2 不会改变 x。这就是为什么你有一个无限循环。您的意思是使用for(int x=-1; x&lt;2; x += 2) 吗? for(int y=-1;y&lt;2;y+2) 也存在同样的问题。
  • 这无论如何都行不通。你不能以这种方式更新网格,它不符合游戏规则。
  • 生命游戏要求您在一个干净的网格上开始每一代新人。然后更新新网格的单元格引用旧网格上的单元格。正如您所拥有的那样,您正在根据更新的单元格和未访问的单元格做出决策。不是你想要的。这不会生成你想要的板子。

标签: c++ conways-game-of-life


【解决方案1】:

您应该将此x + 2 更改为x += 2 并将y + 2 更改为y += 2,以使循环每个周期增加2。我还建议您删除此行中多余的括号 if (r + x &gt;= 0 &amp;&amp; r + x &lt; rows &amp;&amp; c + y &gt;= 0 &amp;&amp; c + y &lt; columns)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多