Skip to content

Instantly share code, notes, and snippets.

@jakwuh
Last active February 20, 2016 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakwuh/b4cc317c7853044d0d81 to your computer and use it in GitHub Desktop.
Save jakwuh/b4cc317c7853044d0d81 to your computer and use it in GitHub Desktop.
Conway's Game of Life
<!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