Skip to content

Instantly share code, notes, and snippets.

@jprochazk
Last active October 27, 2021 20:55
Show Gist options
  • Save jprochazk/4eb6ef2c25877b2750f0324fb505ec61 to your computer and use it in GitHub Desktop.
Save jprochazk/4eb6ef2c25877b2750f0324fb505ec61 to your computer and use it in GitHub Desktop.
Game of life which runs in a browser console
const console_render = (state) => console.log(state.map(row => row.map(v => '☐◼'[v]).join("")).join("\n"));
function game_of_life(w, h, fps, render = console_render) {
const state = (w, h) => Array(w).fill(0).map(() => Array(h).fill(0));
const randomize = (state) => state.map(a => a.map(b => Math.round(Math.random())));
const neighbours = (state, x, y) => [
state[x-1]?.[y-1], state[x]?.[y-1], state[x+1]?.[y-1],
state[x-1]?.[y ], state[x+1]?.[y ],
state[x-1]?.[y+1], state[x]?.[y+1], state[x+1]?.[y+1]
].map(v => v ?? 0);
const step = (state) => state.map((r, x) => r.map((v, y) => {
const n = neighbours(state, x, y).reduce((t, v) => t + v);
return (v && (n === 2 || n === 3)) || n === 3 ? 1 : 0;
}));
const done = (p, c) => (p = p.flat(Infinity), c = c.flat(Infinity), !p.map((v, i) => c[i] === v).some(v => !v));
const delay = (ms) => new Promise(r => setTimeout(r, ms));
let board = randomize(state(h, w));
let prev = null;
const loop = () => {
render(board);
prev = board;
board = step(board);
if (!done(prev, board))
delay(1000/fps).then(() => requestAnimationFrame(loop));
};
requestAnimationFrame(loop);
};
game_of_life(40, 20, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment