我试图用javascript制作康威的生命游戏。我做了一个函数来计算邻居,以及一个生成下一代单元格的函数。但是,我尝试了测试输入,结果没有正确显示,我无法找到错误的位置。请帮忙。
以下是代码:
(附件)
/* Draws grid */
for (var i = 0; i < 15; i++) {
for (var j = 0; j < 15; j++) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FFFFFF";
ctx.strokeStyle = "grey";
ctx.strokeRect(10 * j, 10 * i, 10, 10);
}
}
/* draws live cells */
function drawSquares(a) {
for (var i = 0; i < 15; i++) {
for (var j = 0; j < 15; j++) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#000000";
if (a[i][j] === 1) {
ctx.fillRect(10 * j, 10 * i, 10, 10);
}
}
}
}/* Counts neighbors */
function neighborCount(a, i, j, height, width){
var lifes = 0;
var neighbors = [
[-1, 1],
[0, 1],
[1, 1],
[-1, 0],
[1, 0],
[-1, -1],
[0, -1],
[1, -1]
];
/* loops through a cell's neighbors */
for (var z = 0; z < 8; z++){
/*checks if the neighbor isn't off the grid*/
if ((i + neighbors[z][0]) >=0 && (i + neighbors[z][0]) < height && (j + neighbors[z][1]) >=0 && (j + neighbors[z][1]) < width){
/*checks if it's alive*/
if (a[i + neighbors[z][0]][j + neighbors[z][1]] === 1){
lifes++;
}
}
}
return lifes;
}
/* game of life */
function life(a) {
var n = a; /*new generation of life */
var lifes = 0; /*neighbor counter*/
var height = a.length;
var width = a[0].length;
/*loops through all cells*/
for (var i = 0; i < height; i++){
for (var j = 0; j < width; j++){
lifes = neighborCount(a, i, j, height, width);
/* kills alive cells */
if(a[i][j] === 1 && (lifes < 2 || lifes > 3)){
n[i][j] = 0;
}
/* brings dead cells to life */
else if (a[i][j] === 0 && lifes ===3){
n[i][j] = 1;
}
}
}
drawSquares(n);
return(n);
}
/* test input */
var a = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 0, 0, 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