我们需要为学校项目编写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
语句的建议?我们尝试过了,结果变得更长了哈哈。 - Dat8StringGuy