好的,所以我试图在p5.js中制作康威的生活游戏,我陷入了一些奇怪的错误。
function make2DArray(cols, rows) {
let arr = new Array(cols);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(rows);
}
return arr;
}
function countNeighbors(grid, x, y) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
let col = x + i;
let row = y + i;
if (grid[col][row] === undefined){
sum += grid[col][row];
}
}
}
sum-=grid[x][y]
return sum;
}
let grid;
let next;
let cols;
let rows;
let resolution = 20;
let fr = 15;
function setup() {
createCanvas(600, 400);
frameRate(fr);
cols = width / resolution;
rows = height / resolution;
next = make2DArray(cols, rows);
grid = make2DArray(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = floor(random(2));
}
}
}
function draw() {
background(0);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = i * resolution;
let y = j * resolution;
if (grid[i][j] == 1) {
fill(0);
stroke(150);
rect(x, y, resolution - 1, resolution - 1);
} else {
fill(255);
stroke(150);
rect(x, y, resolution - 1, resolution - 1);
}
}
}
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let state = grid[i][j];
let neighbors = countNeighbors(grid, i, j);
if (state == 0 && neighbors == 3) {
next[i][j] = 1;
} else if (state == 1 && (neighbors < 2 || neighbors > 3)) {
next[i][j] = 0;
} else {
next[i][j] = state;
}
}
}
grid = next;
}
Soo基本上我有函数countNeighbors,我认为bug在那里,我试着检查col和row是否是数组的边界 像这样
if (col>-1 && col <grid.length && row>-1 && row < grid[0].length){
//increase sum
}
但更糟糕的是。我是js的新手,所以我想出来,例如
let x=new Array(10);
//and then when i try this
console.log(c[-1])
//it should give undefined
但程序仍然无法正常工作:( 谢谢!
答案 0 :(得分:0)
通过一些更改,您可以使其工作:
1)将let row = y + i;
替换为let row = y + j;
该拼写错误导致大部分失控。
2)替换条件
if (grid[col][row] === undefined){
通过
if (0 <= col && col < cols && 0 <= row && row < rows){
原始状况的问题是,如果grid[col]
未定义,那么grid[col][row]
为undefined[row]
,这是没有意义的。
3)为了保持一致,请在sum-=grid[x][y]
4)最后,为了不创建非预期的别名,您需要用以下内容替换grid = next
:
for(let i = 0; i < grid.length; i++){
grid[i] = next[i].slice();
}
或者,将next
变为draw()
的本地变量,并将行let next = make2DArray(cols, rows);
放在draw()
的开头。