我正在尝试为一个游戏创建一个网格,并且设置好了网格,但是当我使用 for 循环显示所有单元格时,出现了一个错误 - Uncaught TypeError: Cannot convert undefined or null to object。我认为网格数组中存在未定义的内容,但实际上不应该存在。另一种解释是,网格是空的,尽管它应该有 16 个单元格。
let bgCol = '#A6A6A6';
let rows = 4;
let cols = 4;
let grid = [];
let size = 50;
function setup() {
createCanvas(windowWidth, windowHeight);
background(bgCol);
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
grid.push(new Cell({x: r * size, y: c * size}, 0));
}
}
}
function draw() {
background(bgCol);
for (let g of grid) {
grid[g].dis();
}
}
class Cell {
constructor(pos, num, col = '#FFFFFF') {
this.pos = pos;
this.num = num;
this.col = col; // White as placeholder until later
}
dis() {
stroke('#000000');
strokeWeight(2);
fill(this.col);
square(this.pos.x, this.pos.y, size, 5);
if (this.num) {
textSize(size - 5);
text(this.num, this.pos.x + 5, this.pos.y + 5);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.11.0/p5.js"></script>