我们必须为学校项目编写一个JavaScript版本的Conway's Game of Life,但是我们被困在了循环边上。整个过程运行良好,但是计算邻居数量的函数对边缘上的单元格不起作用(因为它必须计算数组外的值,这些值是未定义的)。我们尝试了几个选项,但它们都改变了程序其余部分的功能。
我们应该添加什么使它在网格边缘工作?
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行不带有注释的。 据我所知,这种方法更简洁,更短。div;)