xxxxxxxxxx
85
const SZ = 500;
const GRIDSIZE = 32;
const GENCOUNT = GRIDSIZE;
const BOXSIZE = SZ/GRIDSIZE;
let currentWorld;
function setup() {
createCanvas(SZ,SZ);
currentWorld = makeFreshWorld(.5);
}
function mousePressed(){
currentWorld = makeFreshWorld(map(mouseY,0,height,0,1));
}
function draw() {
background(220);
paintWorld2D(currentWorld);
currentWorld = nextWorldState(currentWorld);
}
function nextWorldState(oldworld) {
const newworld = [];
for(let x = 0; x < GRIDSIZE; x++){
newworld[x] = [];
for(let y = 0; y < GRIDSIZE; y++){
if(oldworld[x][y]){ //was alive, stay alive with two or three neightbors
const count = getNeighborCount(oldworld,x,y);
newworld[x][y] = (count == 2 || count == 3);
} else { //is dead, but will be alive
newworld[x][y] = getNeighborCount(oldworld,x,y) == 3;
}
}
}
return newworld;
}
function getNeighborCount(world, x, y) {
return world[(x + 1) % GRIDSIZE][y] +
world[x][(y + 1) % GRIDSIZE] +
world[(x + GRIDSIZE - 1) % GRIDSIZE][y] +
world[x][(y + GRIDSIZE - 1) % GRIDSIZE] +
world[(x + 1) % GRIDSIZE][(y + 1) % GRIDSIZE] +
world[(x + GRIDSIZE - 1) % GRIDSIZE][(y + 1) % GRIDSIZE] +
world[(x + GRIDSIZE - 1) % GRIDSIZE][(y + GRIDSIZE - 1) % GRIDSIZE] +
world[(x + 1) % GRIDSIZE][(y + GRIDSIZE - 1) % GRIDSIZE];
}
function cloneWorld(oldworld) {
const world = [];
for(let x = 0; x < GRIDSIZE; x++){
world[x] = [];
for(let y = 0; y < GRIDSIZE; y++){
world[x][y] = oldworld[x][y];
}
}
return world;
}
function makeFreshWorld(prob){
const world = [];
for(let x = 0; x < GRIDSIZE; x++){
world[x] = [];
for(let y = 0; y < GRIDSIZE; y++){
world[x][y] = (random() > prob) ;
}
}
return world;
}
function paintWorld2D(world){
for(let x = 0; x < GRIDSIZE; x++){
for(let y = 0; y < GRIDSIZE; y++){
if(world[x][y]){
rect(x * BOXSIZE, y * BOXSIZE, BOXSIZE, BOXSIZE);
}
}
}
}