在JS中编写康威生命游戏的程序遇到困难

3
我们需要为学校项目编写Conway生命游戏的JavaScript版本,但我们在循环边缘方面遇到了困难。整个程序运行正常,但是计算邻居数量的函数无法处理在边缘上的细胞(因为它必须评估数组外的值,这些值未定义)。我们尝试了几种选项,但它们都会改变其余程序的功能。
我们应该添加什么来使其在网格边缘上工作?

    var totalNeighbors = function(x, y) {
    var total = 0;

    if (x > 0 && cells[(x - 1)][y] == 1) {
        total++;
    }

    if (x < (width - 1) && cells[x + 1][y] == 1) {
        total++;
    }

    if (y > 0 && cells[x][y - 1] == 1) {
        total++;
    }

    if (y < (height - 1) && cells[x][y + 1] == 1) {
        total++;
    }

    if (y > 0 && x > 0 && cells[x - 1][y - 1] == 1) {
        total++;
    }

    if (y > 0 && x < (width - 1) && cells[x + 1][y - 1] == 1) {
        total++;
    }

    if (y < (height - 1) && x > 0 && cells[x - 1][y + 1] == 1) {
        total++;
    }

    if (y < (height - 1) && x < (width - 1) && cells[x + 1][y + 1] == 1) {
        total++;
    }

    return total;
};

谢谢!


检查是否在边缘上进行块操作。如果是,则不要尝试访问您无法访问的块。我认为所有这些“if”都可以重构。这样做将使应用第一点更容易。 (如果必须将边缘访问循环到零号位置,请记住取模运算符“%”是您的朋友。) - J. Allan
“block on the edge”是什么意思?有没有关于如何重构if语句的建议?我们尝试过了,结果变得更长了哈哈。 - Dat8StringGuy
我所说的“边缘上的块”是指一个单元格在一侧或多侧没有其他单元格(即它上面、旁边和/或下面没有其他单元格)。快速跑一趟杂货店后,我可以回来尝试重构它。(它可能会以更长的解决方案方式结束,但应该是一个更清晰的解决方案。) - J. Allan
发布了我的想法。欢迎评论、提问等。 - J. Allan
1个回答

3
我会选择更像这样的东西: 正如您所看到的,我进行了一些重构。
var isvalid = function(x, y) {
        /*
         * This returns 1 if cells[x][y] == 1.
         * Otherwise, we return 0.
         * NOTE: If cells[x, y] is out of bounds, we return 0.
         * GLOBALS USED: cells, width, and height.
         */

        //This returns true if (index < size && index >= 0)
        //Used to check that index is not an invalid index.
        var inbounds = function (size, index) {
                return (index >= 0 && index < size);
        };

        //given point is out of bounds
        if (!inbounds(width, x) || !inbounds(height, y)) {
                return 0;
        }

        //everything is good
        return (cells[x][y] === 1) ? 1 : 0;
    };

var totalNeighbors = function(x, y) {
    var total = 0;

    //cells[x-1][y]
    total += isvalid(x-1, y);

    //cells[x + 1][y]
    total += isvalid(x+1, y);

    //cells[x][y - 1]
    total += isvalid(x, y-1);

    //cells[x][y + 1]
    total += isvalid(x, y+1);

    //cells[x - 1][y - 1]
    total += isvalid(x-1, y-1);

    //cells[x + 1][y - 1]
    total += isvalid(x+1, y-1);

    //cells[x - 1][y + 1]
    total += isvalid(x-1, y+1);

    //cells[x + 1][y + 1]
    total += isvalid(x+1, y+1);

    return total;
};

注意: 原始代码示例包含37行,不包括注释。我的代码示例包含52行注释和33行不含注释的代码。

据我所知,这种方式更清晰、更简短;)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接