未正确计算存活的相邻细胞

Alive neighbour cells not correctly counted

我知道我的标题不是很具体,但那是因为我不知道问题出在哪里。自 2 或 3 小时以来,我一直被这个问题困扰,理论上一切都应该正常工作,但事实并非如此。 这段代码:

for ( int x = -1; x <= 1; x++ ) {       //Iterate through the 8 neighbour cells plus the one indicated
    for ( int y = -1; y <= 1; y++ ) {

        neighbour = coords(locX + x, locY + y, width);      //Get the cell index in the array

        if (existsInOrtho(ortho, neighbour)) {      //If the index exists in the array

            if (ortho[neighbour] == 0) {        //Cell is dead
                cnt--;      //Remove one from the number of alive neighbour cells
            }

        } else {        //Cell is not in the zone
            cnt--;      //Remove one from the number of alive neighbour cells
        }

    }
}

遍历所有相邻单元格以获取它们在数组中的值(1 表示存活,0 表示死亡)。 "coords" 函数,如下所示:

int coords(int locX, int locY, int width)
{
    int res = -1;

    locX = locX - 1;    //Remove one from both coordinates, since an index    starts at 0 (and the zone starts at (1;1) )
    locY = locY - 1;

    res = locX * width + locY;      //Small calculation to get the index of the pixel in the array

    return res;
}

获取数组中单元格的索引。但是当我 运行 代码时,它不起作用,相邻单元格的数量不正确(就像每次附近有一些活着的单元格都没有计算在内)。我尝试手动分解所有内容,它有效,所以我不知道是什么破坏了最终代码中的所有内容...Here is the complete code. 抱歉,如果我犯了任何英语错误,那不是我的母语。

此代码...

for ( int x = -1; x <= 1; x++ ) {       //Iterate through the 8 neighbour cells plus the one indicated
    for ( int y = -1; y <= 1; y++ ) {

实际检查 9 个单元格。也许您忘记了它检查 (x,y) = (0,0)。这将包括小区本身及其邻居。

一个简单的修复方法是:

for ( int x = -1; x <= 1; x++ ) {       //Iterate through the 8 neighbour cells plus the one indicated
    for ( int y = -1; y <= 1; y++ ) {
        if (x || y) {

此外,simulate 函数(来自您的 link)犯了一个常见错误,即在处理其旁边的单元格所需的状态更改之前更新同一数组中单元格的值。最简单的解决方法是保留两个数组——网格的两个完整副本(两个 ortho 数组,在您的代码中)。从 orthoA 读取时,更新 orthoB。然后在下一代上,翻转。从 orthoB 读取并写入 orthoA。