提问人:Zabon 提问时间:4/26/2022 更新时间:4/26/2022 访问量:15
嵌套函数不影响在全局范围内声明的二维数组中的对象
Nested functions not affecting objects in bidimensional array declared within global scope
问:
我有一个充满 Cell 对象的二维数组。
我怎样才能使(和嵌套函数)使用每个单元格的上下文进行设置,以便我可以在方法中使用它?addToGrid(asset);
cells
draw
class Cell {
constructor(value) {
this.value = value;
}
makeAlive = () => {
this.value |= (1 << 0)
}
incrementNeighbours = (num) => {
this.value += 2;
}
}
// Main
let cols;
let rows;
let cells;
let resolution = 2;
let infos = {};
s.setup = async () => {
cols = 256;
rows = 256;
s.createCanvas(cols * resolution, rows * resolution);
s.frameRate(60);
cells = [...Array(cols)].map(x => Array(rows).fill(new Cell(0)));
const loader = new AssetLoader();
const asset= await loader.loadAsync('type', 'name');
addToGrid(asset);
}
s.draw = () => {
.
.
.
// cells is not affected by addToGrid
}
const addToGrid = (asset) => {
for (let i = 0; i < asset.length; i++) {
.
.
.
addStrToGrid(col, row, asset[i]);
}
}
const addStrToGrid = (col, row, str) => {
for (const c of str) {
becomeAlive(col, row);
}
}
const becomeAlive = (x, y) => {
cells[x - 1][y - 1].incrementNeighbours();
cells[x - 1][y].incrementNeighbours();
cells[x - 1][y + 1].incrementNeighbours();
cells[x][y - 1].incrementNeighbours();
cells[x][y].makeAlive();
cells[x][y + 1].incrementNeighbours();
cells[x + 1][y - 1].incrementNeighbours();
cells[x + 1][y].incrementNeighbours();
cells[x + 1][y + 1].incrementNeighbours();
}
s.setup
&s.draw
分别来自库 p5.js !
答: 暂无答案
评论
cells
Grid
.cells
Array(rows).fill(new Cell(0))