xxxxxxxxxx
105
// Conway's Game of Life
// https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
//
// Controls:
// P - Play/Pause
// R - Randomise all cells (also pauses)
// C - Clear all cells (also pauses)
//
// Left click - turn cell on
// Right click - turn cell off
//
// (Make sure you click on the canvas first
// for keypresses to register)
let playmode = true;
let lastUpdate = 0;
let speed = 230; // Higher number == slower speed
let buttons = [];
function setup() {
let w = min(600, Math.floor(window.innerWidth));
let cellSize = int(map(w, 300, 600, 15, 20, true));
let numCells = int(w / cellSize);
w = numCells * cellSize;
let h = w + 70;
createCanvas(w, h);
generateGridcells(cellSize); // cellsize
randomiseGridcells();
buttons = [
new ClickButton(10, height-60, 80, 30, ["Pause", "Play"], playPause),
new ClickButton(100, height-60, 80, 30, ["Randomise"], randomiseCells),
new ClickButton(190, height-60, 80, 30, ["Clear"], clearCells)
]
}
function draw() {
background(220);
drawGridcells();
if (playmode && millis() > lastUpdate){
lastUpdate = millis() + speed;
updateGridcells();
}
if (mouseIsPressed){
if (mouseButton === LEFT) {
turnOnCell(mouseX, mouseY);
}
else{
turnOffCell(mouseX, mouseY);
}
}
let insideButton = false;
for(let b of buttons){
if (b.isMouseInside()) insideButton = true;
b.display();
}
if (insideButton) cursor('pointer');
else cursor('default');
textAlign(LEFT, CENTER)
text("Left click on grid: turn cell on | right click: turn cell off", 10, height-15);
}
function playPause(){
playmode = !playmode;
}
function randomiseCells(){
playmode = false;
randomiseGridcells();
buttons[0].changeLabel(1);
}
function clearCells(){
playmode = false;
clearGridcells();
buttons[0].changeLabel(1);
}
function keyPressed(){
if(key == 'p'){
playPause();
}
if (key == 'r'){
randomiseCells();
}
if (key == 'c'){
clearCells();
}
}