Last active
February 20, 2016 17:45
-
-
Save jakwuh/b4cc317c7853044d0d81 to your computer and use it in GitHub Desktop.
Conway's Game of Life
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Conway's Game of Life</title> | |
</head> | |
<body> | |
<canvas width="300" height="300" id="grid"></canvas> | |
<button id="start">Start</button> | |
<script> | |
void function(n) { | |
'use strict'; | |
let canvas = document.querySelector("#grid"), | |
context = canvas.getContext("2d"), | |
grid, range = Array(n).fill(0).map((_v, i) => i + 1), | |
interval; | |
function init() { | |
grid = Array(n + 2).fill(0).map(() => Array(n + 2)); | |
for (let i of range) | |
for (let j of range) | |
grid[i][j] = Math.random() > 0.5; | |
interval && window.clearInterval(interval); | |
interval = setInterval(() => { | |
draw(); | |
step() | |
}, 25); | |
} | |
function step() { | |
let cache = grid.map((x) => x.slice()); | |
for (let i of range) | |
for (let j of range) { | |
let count = 0; | |
for (let k of[-1, 0, 1]) | |
for (let l of[-1, 0, 1]) | |
count += cache[i + k][j + l]; | |
grid[i][j] = (count === 3) || | |
(count === 4 && cache[i][j]) ? 1 : 0; | |
} | |
} | |
function draw() { | |
let cellX = Math.floor(canvas.width / (n + 2)); | |
let cellY = Math.floor(canvas.height / (n + 2)); | |
context.clearRect(0, 0, canvas.width, canvas.height); | |
for (let i of range) | |
for (let j of range) | |
grid[i][j] && context.fillRect(cellX * i, cellY * j, cellX, cellY); | |
} | |
document.querySelector("#start").onclick = init; | |
}(50); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment