Conway 在 Matlab 中的生命游戏 - 函数在嵌套循环中返回意外数字

Conway's game of life in Matlab - function returning unexpected numbers when in nested loop

嘿,我正在为一个项目在 Matlab 中制作 Conway 的生命游戏,到目前为止,我已经创建了一个函数来查找原始细胞周围的活细胞数量,我相信它可以正常工作,因为我已经测试过它并且玩了很多,但是当我将它实现到我的主脚本中时,它包含了生活游戏的条件规则,它似乎停止工作了。

function [alive] = cellStat(grid,row,col)
%this function finds the number of alive cells surrounding it
alive = 0;

    for i = row-1:row+1
        %making sure the cell is on the board
        if i <= 0 || i > length(grid)
            continue
        end

        for j = col-1:col+1
            %making sure the cell is on the board
            if j <= 0 || j > length(grid)
                continue
            end
            %making sure the cell is not counted as its own neighbour
            if i == row && j == col
                continue
            end
            %disp(i + " " + j + " = " + grid(i,j));
            if grid(i,j) == 1
                alive = alive + 1;
            end
        end
    end
end

主脚本

r = [0 0 1 0 0;1 0 1 0 0;0 1 1 0 0;0 0 0 0 0;0 0 0 0 0];
years = 1;
alive = 0;

for n = 1:years
    for i = 1:length(r)
        for j = 1:length(r)
            alive = cellStat(r,i,j);
            if alive <= 1 && r(i,j) == 1
                r(i,j) = 0;
            elseif alive > 3 && r(i,j) == 1
                r(i,j) = 0;
            elseif alive == 3 && r(i,j) == 0
                r(i,j) = 1;
            end
        end
    end
    disp(r);
end

例如,我一直在尝试测试康威生命游戏中的滑翔机模式,即前面代码中的数组 r。但是当我 运行 代码时,输​​出并不像预期的那样。 Here is the command window, the first array is the initial array r

我还尝试通过放入一个 disp 函数来调试它,以找出 cellStat 函数在主脚本中的整个 for 循环中返回的内容 (disp(i + " " + j + " = " + alive) ;) 就在找到当前细胞周围活细胞数量的线下方,它会返回有趣的结果。例如,它说第 2 行第 2 列的单元格有 6 个活着的邻居,但网格上什至没有 6 个活着的单元格。

我认为这是主脚本中 for 循环的错误,因为当我在该单元格上使用该函数时,它只给出了正确的结果 (5)。

非常感谢您的帮助,因为我不确定从哪里开始解决这个问题。

您只对单元格执行一个循环,在该循环中您既计算邻居又修改它们。这不起作用,因为您在循环早期所做的修改会改变您稍后计算的邻居数量。

您需要 两个 循环:在第一个循环中,您计算​​所有单元格的邻居数,在第二个循环中,您根据邻居的数量修改每个单元格。