Back to KB
Difficulty
Beginner
Read Time
37 min

Four Rules, Infinite Worlds: Building Conway's Game of Life from Scratch

By Codcompass TeamΒ·Β·37 min read

Conway's Game of Life is the most famous program that isn't really a game. There's no player, no score, no way to win. You draw a few cells on a grid, press play, and watch. What comes back is uncanny: patterns that crawl across the screen, blink forever, collide, and occasionally build machines. All of it falls out of four tiny rules that a mathematician named John Conway scribbled down in 1970. Today (Day 21 of GameFromZero) we built a real, running Game of Life in plain vanilla JavaScript. Here's exactly how it works.

Play the finished version here: https://dev48v.infy.uk/game/day21-game-of-life.html

The grid is just an array of ones and zeros

Every cell is in one of two states β€” alive or dead β€” so the whole universe is a flat array of 0s and 1s. We use 40 columns by 30 rows, which is 1,200 cells.

const COLS = 40, ROWS = 30, CELLS = COLS * ROWS;
let grid = new Uint8Array(CELLS);   // 0 = dead, 1 = alive

const rowOf = i => Math.floor(i / COLS);
const colOf = i => i % COLS;
const idx   = (r, c) => r * COLS + c;

Enter fullscreen mode Exit fullscreen mode

We keep it flat β€” one array, not a grid of arrays β€” because scanning and copying become simple loops. When we need a cell's position we convert its index; when we need the index we convert its row and column back. That's the entire data model.

Everything depends on counting eight neighbours

Each cell has eight neighbours: up, down, left, right, and the four diagonals. The single number that drives the whole simulation is how many of those eight are currently alive. We loop over the nine offsets around a cell and skip the centre.

function neighb

πŸŽ‰ Mid-Year Sale β€” Unlock Full Article

Base plan from just $4.99/mo or $49/yr

Sign in to read the full article and unlock all 635+ tutorials.

Sign In / Register β€” Start Free Trial

7-day free trial Β· Cancel anytime Β· 30-day money-back