Published
Edited
Apr 25, 2021
3 stars
Also listed in…
p5
Insert cell
Insert cell
Insert cell
Insert cell
p5(sketch => {
let system;
let w;
let columns;
let rows;
let board;
let next;
sketch.setup = function() {
sketch.createCanvas(width, 400);
w = 20;
// Calculate columns and rows
columns = sketch.floor(sketch.width / w);
rows = sketch.floor(sketch.height / w);
// Wacky way to make a 2D array is JS
board = new Array(columns);
for (let i = 0; i < columns; i++) {
board[i] = new Array(rows);
}

// Going to use multiple 2D arrays and swap them
next = new Array(columns);
for (let j = 0; j < columns; j++) {
next[j] = new Array(rows);
}

init();
};
sketch.draw = function() {
//sketch.translate(sketch.width / 2, sketch.height / 2);
//sketch.background(200);
//sketch.rect(-50, -50, 100, 100);

sketch.background(255);
generate();
for ( let i = 0; i < columns;i++) {
for ( let j = 0; j < rows;j++) {
if ((board[i][j] == 1)) sketch.fill(sketch.random(255), sketch.random(255), sketch.random(255));
else sketch.fill(255);
sketch.stroke(0);
sketch.rect(i * w, j * w, w-1, w-1);
}
}
}

// reset board when mouse is pressed
sketch.mousePressed = function() {
init();
}

// Fill board randomly
function init() {
for (let i = 0; i < columns; i++) {
for (let j = 0; j < rows; j++) {
// Lining the edges with 0s
if (i == 0 || j == 0 || i == columns-1 || j == rows-1) board[i][j] = 0;
// Filling the rest randomly
else board[i][j] = sketch.floor(sketch.random(2));
next[i][j] = 0;
}
}
}


function generate() {

// Loop through every spot in our 2D array and check spots neighbors
for (let x = 1; x < columns - 1; x++) {
for (let y = 1; y < rows - 1; y++) {
// Add up all the states in a 3x3 surrounding grid
let neighbors = 0;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
neighbors += board[x+i][y+j];
}
}

// A little trick to subtract the current cell's state since
// we added it in the above loop
neighbors -= board[x][y];
// Rules of Life
if ((board[x][y] == 1) && (neighbors < 2)) next[x][y] = 0; // Loneliness
else if ((board[x][y] == 1) && (neighbors > 3)) next[x][y] = 0; // Overpopulation
else if ((board[x][y] == 0) && (neighbors == 3)) next[x][y] = 1; // Reproduction
else next[x][y] = board[x][y]; // Stasis
}
}

// Swap!
let temp = board;
board = next;
next = temp;
}
});
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more