I m trying to make the game of life on p5.js. I have used a 2d array of CA class object called ‘cell’ and saving every iteration in ‘new_cell’ and finally copying back the values from ‘new _cell’ to ‘cell’. The code works fine when i create the object ‘new_cell’ in the draw loop but gives a weird output when I create the new_cell object with the cell object in the setup loop.(i have commented out the statements for new_cell in setup). I am unable to understand why does it give wrong value when I initialize in setup versus in draw loop when i anyway reassign the values in every draw loop.
let row_tot, col_tot; //total row and col
let cell = [];
let spacer = 10; //cell size
function setup() {
createCanvas(500, 500);
frameRate(10);
//row_tot and col_tot
row_tot = height / spacer;
col_tot = width / spacer;
//initialize cell
for (let i = 0; i < col_tot; i++) {
cell[i] = [];
// next_cell[i] = [];
for (let j = 0; j < row_tot; j++) {
cell[i][j] = new CA();
// next_cell[i][j] = new CA();
}
}
}
function draw() {
background(0); //black background
//initialize cell
let next_cell = [];
for (let i = 0; i < col_tot; i++) {
next_cell[i] = [];
for (let j = 0; j < row_tot; j++) {
next_cell[i][j] = new CA();
}
}
//rule
for (let i = 0; i < col_tot; i++) {
for (let j = 0; j < row_tot; j++) {
//edge case
//count the neighbour
let sum = 0;
for (let p = -1; p <= 1; p++) {
for (let q = -1; q <= 1; q++) {
let col = (i + p + col_tot) % col_tot;
let row = (j + q + row_tot) % row_tot;
sum += cell[col][row].state;
}
}
sum -= cell[i][j].state;
//Game of life rule
if (cell[i][j].state == 1 && (sum < 2 || sum > 3)) next_cell[i][j].death(); //death
else if ((cell[i][j].state == 0) && (sum == 3)) next_cell[i][j].birth(); //birth
else next_cell[i][j] = cell[i][j]; //stasis
}
}
//update old
cell = next_cell;
//render
for (let i = 0; i < col_tot; i++) {
for (let j = 0; j < row_tot; j++) {
cell[i][j].show(i, j);
}
}
}
class CA {
constructor() {
this.state = random(1) < .5 ? 0 : 1;
}
show(a, b) {
let p = a * spacer;
let q = b * spacer;
//draw the rec
if (this.state == 1) {
noStroke();
fill(255);
rect(p, q, spacer, spacer);
}
}
death() {
this.state = 0;
}
birth() {
this.state = 1;
}
}