xxxxxxxxxx
// code is adapted from the YouTube video https://www.youtube.com/watch?v=FWSR_7kZuYg
// Rules:
// if cell has less than two or more than three living neighbors it dies
// if empty cell has three neighbors it will become alive
//function that creates two dimensional array representing the grid
function make2DArray(cols, rows) {
let arr = new Array(cols);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(rows);
}
return arr;
}
let grid;
let cols;
let rows;
let resolution = 20; // how big squares are drawn
let generation = 0; // counter for generations
function setup() {
createCanvas(windowWidth, windowHeight);//createCanvas(600, 400);
cols = round(width / resolution);
rows = round(height / resolution);
grid = make2DArray(cols, rows);
// fills the initial grid with ones and zeros randomly
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = floor(random(2));
}
}
}
function draw() {
stroke(0);
//the world's colours change every 200 generation, every 1000 generation starts all over again
if(generation - floor(generation / 1000)*1000 < 200 ){
background(0);
fill(255);
} else if (generation - floor(generation / 1000)*1000 < 400){
background(50);
fill(200);
} else if (generation - floor(generation / 1000)*1000 < 600){
background(100);
fill(150);
} else if (generation -floor(generation / 1000)*1000 < 800){
background(150);
fill(100);
} else {
background(200);
fill(50);
}
//user can add living cells
if(mouseX < windowWidth*(1000-resolution)/1000 && mouseX > 0 && mouseY < windowHeight && mouseY > 0){
grid[round(mouseX/resolution)][round(mouseY/resolution)] = 1;
}
//draws the living cells
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = i * resolution;
let y = j * resolution;
if (grid[i][j] == 1) {
rect(x, y, resolution - 1, resolution - 1);
}
}
}
//compute next based on previous grid
let next = make2DArray(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let state = grid[i][j];
//count live neighbours
let sum = 0;
let neighbors = counts(grid, i, j); //counts is function
if (state == 0 && neighbors == 3) {
next[i][j] = 1; // new is born
} else if (state == 1 && (neighbors < 2 || neighbors > 3)) {
next[i][j] = 0 // living cell dies
} else {
next[i][j] = grid[i][j]; // otherwise no changes
}
}
}
grid = next; // grid is updated
generation+=1; // updates the current generation
console.log(generation); // prints generations to the console
}
//function to count cells living neighbors
function counts(grid, x, y) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
let col = (x + i + cols) % cols;
let row = (y + j + rows) % rows;
sum += grid[col][row];
}
}
sum -= grid[x][y]; // not counting itself to as a neighbor
return sum;
}