xxxxxxxxxx
128
// Collaboration with Lulu for ICM 2019 Part 2, project 1
// Game of Life part of the code borrowed and modified from Dan Shiffman
let w;
let columns;
let rows;
let board;
let next;
let pic;
let counter = 0;
let r;
let g;
let b;
function preload(){
pic = loadImage('desert1.jpg');
pic2 = loadImage('chicago.jpg');
}
function setup() {
createCanvas(720, 400);
w = 12;
// Calculate columns and rows
columns = floor(width / w);
rows = floor(height / w);
// Make a 2D array in 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 (i = 0; i < columns; i++) {
next[i] = new Array(rows);
}
init();
}
function draw() {
background(255);
pic.loadPixels();
pic2.loadPixels();
generate();
for ( let i = 0; i < columns;i++) {
for ( let j = 0; j < rows;j++) {
if (counter%2==0){
r = pic.pixels[(i*w+j*w*width)*4];
g = pic.pixels[((i*w+j*w*width)*4)+1];
b = pic.pixels[((i*w+j*w*width)*4)+2];
}
else {
r = pic2.pixels[(i*w+j*w*width)*4];
g = pic2.pixels[((i*w+j*w*width)*4)+1];
b = pic2.pixels[((i*w+j*w*width)*4)+2];
}
if ((board[i][j] == 0)) {
fill(r,g,b,200);
noStroke();
rect(i * w, j * w, w, w);
}
else {
strokeWeight(10);
if (counter%2 == 0) {
stroke(r-50,g+10,b+50,150);
line((i) * w, (j) * w, (i+0.5) * w, (j+0.5) * w+20*w);}
else {
fill(r/2,g,b/2);
rect(i * w, j * w, w, w);}
}
}
}
}
// To fix in the future: there should be a function that handles all of the picture-dependent logic together, rather than all of the if statements nested throughout dra
// reset board when mouse is pressed
function mousePressed() {
init();
counter++;
}
// 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] = floor(random(2));
next[i][j] = 0;
}
}
}
// The process of creating the new generation
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;
}