xxxxxxxxxx
69
let cells = [];
let span, rows;
let pendingDeaths = [],
pendingLives = [];
function setup() {
createCanvas(400, 400);
rows = 15;
span = width / rows;
for (let i = 0; i < rows; i++) {
cells[i] = [];
for (let j = 0; j < rows; j++) {
cells[i][j] = new Cell(j, i);
}
}
getCell(2, 4).alive = true;
getCell(4, 4).alive = true;
getCell(1, 3).alive = true;
getCell(2, 3).alive = true;
getCell(3, 3).alive = true;
getCell(3, 4).alive = true;
getCell(7, 6).alive = true;
getCell(7, 7).alive = true;
getCell(7, 8).alive = true;
// frameRate(0.5);
}
function draw() {
background(220);
forAllCells((cell) => {
cell.display();
cell.getNeighbours();
})
/**
Any live cell with fewer than two live neighbours dies, as if by underpopulation.
Any live cell with two or three live neighbours lives on to the next generation.
Any live cell with more than three live neighbours dies, as if by overpopulation.
Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
*/
for (let row of cells) {
for (let cell of row) {
if (cell.alive && cell.totalLiveNeighbours() < 2) {
pendingDeaths.push(cell)
continue;
}
if (cell.alive && cell.totalLiveNeighbours() > 3) {
pendingDeaths.push(cell)
continue;
}
if (!cell.alive && cell.totalLiveNeighbours() == 3) {
pendingDeaths.push(cell)
continue;
}
}
}
for (let death of pendingDeaths) {
death.toggle();
}
pendingDeaths = [];
}
function forAllCells(fnc) {
for (let row of cells) {
for (let cell of row) {
fnc(cell);
}
}
}