javascript - 在 JS 中坚持编程 Conway 的 "Game of Life"

标签 javascript conways-game-of-life cellular-automata

我们必须为一个学校项目编写康威生命游戏的 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;
};

谢谢!

最佳答案

我会选择更像这样的东西:
如您所见,我重构了一点。

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;
};

PS:您的原始代码示例是 37 行没有注释。我的代码示例是 52 行注释和 33 行没有注释。

据我所知,这条路更干净、更短。 ;)

关于javascript - 在 JS 中坚持编程 Conway 的 "Game of Life",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40273943/

相关文章:

javascript - flexWrap 不适用于 React Native 中的 <Text> 元素

javascript - 在 Google Apps 脚本 MailApp 中,是否可以在 htmlBody 中传递 javascript?

php - JavaScript 无法在 <head> 或 <body> 标签内工作

javascript - 在 onclick 事件上更改按钮的背景图像

c++ - _mm256_shuffle_epi8 在这个生命游戏实现中有何意义?

javascript - 是否有已知的算法来检测确保形状连续性所需的像素?

python - 在纯 numpy 中矢量化康威的生命游戏?

algorithm - C# 中的生命游戏

康威的生命游戏 : extraneous cells being printed when program run with only blank/dead cells (C/SDL2)

arrays - Julia /元胞自动机 : efficient way to get neighborhood