0

I have a bidimensional array filled with Cell objects.

How can I do to make addToGrid(asset); (and nested functions) use the context of each Cell to set cells so that I can use it in draw method ?

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 are from the library p5.js which are triggered respectively !

Zabon
  • 241
  • 2
  • 18
  • Just pass `cells` as an argument to all the functions? Alternatively, introduce a `Grid` class with a `.cells` property, and make them methods of that class. – Bergi Apr 26 '22 at 01:48
  • 1
    Btw, `Array(rows).fill(new Cell(0))` [does not do what you meant to do](https://stackoverflow.com/q/35578478/1048572). – Bergi Apr 26 '22 at 01:50

0 Answers0