xxxxxxxxxx
74
let w = 10;
let columns, rows;
let board;
let x = 300;
let y =150;
function setup() {
createCanvas(900, 600);
columns = width / w;
rows = height / w;
board = create2DArray(columns, rows);
for (let i = 8; i < 42; i++) {
for (let j = 15; j < 35; j++) {
board[i][j] = floor(random(2));
}
}
}
function draw() {
let next = create2DArray(columns, rows);
// Looping but skipping the edge cells
for (let i = 8; i < 42; i++) {
for (let j = 15; j < 35; j++) {
// Randomly reinitialize some cells
if (random() < 0.025) { // 1% chance to restart the life of a cell
next[i][j] = floor(random(2)); // Randomly set to 0 or 1
continue;
}
let neighbors = 0;
for (let k = -1; k <= 1; k++) {
for (let l = -1; l <= 1; l++) {
neighbors += board[i + k][j + l];
}
}
neighbors -= board[i][j];
// The rules of life!
if (board[i][j] == 1 && neighbors < 2) next[i][j] = 0;
else if (board[i][j] == 1 && neighbors > 3) next[i][j] = 0;
else if (board[i][j] == 0 && neighbors == 3) next[i][j] = 1;
else next[i][j] = board[i][j];
}
}
// Drawing the cells
for (let i = 0; i < columns; i++) {
for (let j = 0; j < rows; j++) {
if (board[i][j] === 0) {
fill(255); // White for dead cells
} else {
fill(0, 0, 255,25); // Blue for alive cells
}
noStroke();
square(i * w, j * w, w);
}
}
board = next;
noFill()
stroke(0);
ellipse(width/2, height/2, x, y);
}
function create2DArray(columns, rows) {
let arr = new Array(columns);
for (let i = 0; i < columns; i++) {
arr[i] = new Array(rows);
for (let j = 0; j < rows; j++) {
arr[i][j] = 0;
}
}
return arr;
}