xxxxxxxxxx
132
function setup() {
createCanvas(800, 700);
background(211, 211, 211);
grid();
}
function find_fps(num) {
let fps = frameRate();
fill(255);
stroke(0);
text("FPS: " + fps.toFixed(num), 40, height - 10);
}
let array = Array(200)
.fill()
.map(() => Array(200).fill(0));
function grid() {
for (var row = 0; row < array.length; row++) {
for (var col = 0; col < array[row].length; col++) {
if (array[row][col] == 0) {
fill(211, 211, 211);
stroke(0);
rect(col * 20, row * 20, 20, 20);
}
}
}
}
function checkCellArray(cell, focused) {
for (let f of focused) {
if (f[0] === cell[0] && f[1] === cell[1]) {
return true;
}
}
return false;
}
// checks and fills cell with colour depending on its state
function alive_or_dead(state, row, col) {
if (state == 1) {
fill(42, 170, 138);
rect(col * 20, row * 20, 20, 20);
} else if (state == 0) {
fill(211, 211, 211);
rect(col * 20, row * 20, 20, 20);
}
}
// Moore neighbourhood
function finding_neighbours(row, col) {
return [
[row - 1, col],
[row - 1, col + 1],
[row, col + 1],
[row + 1, col + 1],
[row + 1, col],
[row + 1, col - 1],
[row, col - 1],
[row - 1, col - 1],
];
}
// based on neighbours, will the cell survive?
function next_gen(cell, neighbours, alive) {
var counter = 0;
for (let n = 0; n < neighbours.length; n++) {
if (checkCellArray(neighbours[n], alive)) {
counter += 1;
}
}
if (checkCellArray(cell, alive)) {
// alive
if (counter === 2 || counter === 3) {
return 1;
} else {
return 0;
}
} else {
// dead
if (counter === 3) {
return 1;
} else {
return 0;
}
}
}
let focused = [];
let alive = [
[21, 21],
[20, 20],
[20, 21],
[20, 19],
[22, 20],
[30, 30],
[30, 31],
];
let current_state = 0;
function draw() {
find_fps(2)
// Build focus
focused = focused.concat(alive);
for (let a = 0; a < alive.length; a++) {
r = alive[a][0];
c = alive[a][1];
neighbours = finding_neighbours(r, c);
for (let n of neighbours) {
if (!checkCellArray(n, focused)) {
focused.push(n);
}
}
}
next_alive = focused.filter(
(cell) => next_gen(cell, finding_neighbours(cell), alive) === 1
);
dead_cells = focused.filter(
(cell) => next_gen(cell, finding_neighbours(cell), alive) === 0
);
for(let l = 0; l < next_alive.length; l++) {
alive_or_dead(1, next_alive[l][0], next_alive[l][1])
}
for(let d = 0; d < dead_cells.length; d++) {
alive_or_dead(0, dead_cells[d][0], dead_cells[d][1])
}
focused = [];
alive = next_alive
}