Jon Wire

A Software Engineer exploring the world with code.

Conway's Game of Life

In my last article, I created a fun looking DOS monitor and drew random dots and lines on it. Today, to celebrate the Resurrection of Christ (Easter), I'll code up a little version of Conway's Game of Life.

I'll go a little sparse on the details. It's Easter, and I want to focus the code today. But, to quickly summarize the rules:

  1. Any live cell with fewer than two live neighbors dies.
  2. Any live cell with two or three live neighbors stays alive.
  3. Any live cell with more than three live neighbors dies.
  4. Any dead cell with exactly three live neighbors becomes a live cell.

A "live" cell (pixel) will be painted white in my implementation. All other (dead) cells will be painted black. We'll use a resolution of 320 x 200 on our trusty old Interweb VGA.

Here's my implementation:

${DosMonitor().onadd(self => {
	// initialize a grid of living and dead cells
	let grid = new Grid<boolean>(200, 320, false);
	for (let i = 0; i < STARTING_LIVE_CELLS; i++) {
		const [ x, y ] = randomCoord(self.draw);
		grid.set(Math.floor(y), Math.floor(x), true);
	}

	setInterval(() => {
		// draw the current state
		self.draw.imageData(grid.toImageData(
			v => v ? [255, 255, 255, 255] : [0, 0, 0, 255])
		);

		// prepare the next state by mapping the current state
		grid = grid.map((cell, row, col, self) => {
			const neighbors = grid.getNeighbors(row, col);
			const liveNeighbors = neighbors.filter(Boolean).length;

			if (cell) {
				return liveNeighbors < 2 || liveNeighbors > 3 ? false : true;
			} else {
				return liveNeighbors === 3 ? true : false;
			}
		});
	}, FPS_INTERVAL);
}

For brevity, I've left my Grid implementatin out of the article. You can see it in this Gist.

Grid and drawing manipulations aside, the code is as incredibly simple as the rules. Starting with a completely random set of 4000 live cells and running at 10 frames/second, it looks like this.

Interweb VGA

The rules are known for being incredibly simple while leading to some pretty complex and interesting (life-like) behaviors.

If you enjoyed anything about this article, subscribe so you don't miss out!

* indicates required

Intuit Mailchimp

Published: 4/20/2025.
Topics: html, typescript, javascript, canvas, graphics, retro, play, life, Easter