Skip to content
Ayotl

← Algorithms · Lesson 9/11

The Game of Life

▶ Watch it as a video: one minute with LeIA

Watch on YouTube →

✕
1/10

Counting neighbors

A board of cells; each one is alive or dead. There's no player: the board changes on its own, in generations. In each one, every cell looks at the eight around it (diagonals too) and counts how many are alive.

The mathematician John Conway invented it, and it became famous in October 1970, in Martin Gardner's column in *Scientific American*. At first people played it by hand, with counters.

  • O alive
  • . dead
leccion.js

$ node leccion.js

Press RUN (or Ctrl+Enter).

What to look at

  • The center one has 2 live neighbors; the ones at the ends, 1; the ones above and below the center, 3.
  • m[i]?.[j] ?? 0: if the row doesn't exist you get undefined, and ?? 0 counts it as dead. That way the edges don't crash.
The whole lesson on one page

Counting neighbors

A board of cells; each one is alive or dead. There's no player: the board changes on its own, in generations. In each one, every cell looks at the eight around it (diagonals too) and counts how many are alive.

The mathematician John Conway invented it, and it became famous in October 1970, in Martin Gardner's column in *Scientific American*. At first people played it by hand, with counters.

  • O alive
  • . dead
// the eight around it
const ocho = (y, x) => [[y - 1, x - 1], [y - 1, x], [y - 1, x + 1], [y, x - 1],
                        [y, x + 1], [y + 1, x - 1], [y + 1, x], [y + 1, x + 1]];

const m = [
  [0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0],
  [0, 1, 1, 1, 0],
  [0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0],
];

function vecinas(y, x) {
  let n = 0;
  for (const [i, j] of ocho(y, x)) n += m[i]?.[j] ?? 0;   // off the board, 0
  return n;
}

// how many live neighbors each cell has
for (let y = 0; y < 5; y++)
  console.log([0, 1, 2, 3, 4].map((x) => vecinas(y, x)).join(" "));
  • The center one has 2 live neighbors; the ones at the ends, 1; the ones above and below the center, 3.
  • m[i]?.[j] ?? 0: if the row doesn't exist you get undefined, and ?? 0 counts it as dead. That way the edges don't crash.

The rule, in two lines

The number of live neighbors decides the next generation:

  • With three, the cell lives: if it was dead, it's born; if it was alive, it stays.
  • With two, it stays as it is.
  • With any other number it dies or stays dead: with one or none, of loneliness; with four or more, of crowding.

That's all. siguiente ("next") takes the board and returns the one that follows.

// the eight around it
const ocho = (y, x) => [[y - 1, x - 1], [y - 1, x], [y - 1, x + 1], [y, x - 1],
                        [y, x + 1], [y + 1, x - 1], [y + 1, x], [y + 1, x + 1]];

function siguiente(m) {
  return m.map((fila, y) =>
    fila.map((viva, x) => {
      let n = 0;
      for (const [i, j] of ocho(y, x))
        n += m[i]?.[j] ?? 0;
      if (n === 3) return 1;
      return viva && n === 2 ? 1 : 0;
    }));
}

const leer = (filas) => filas.map((f) => [...f].map((c) => (c === "O" ? 1 : 0)));
const ver = (m) => console.log(m.map((f) => f.map((v) => (v ? "O" : ".")).join(" ")).join("\n") + "\n");

let m = leer([".....", ".....", ".OOO.", ".....", "....."]);
for (let g = 0; g < 4; g++) {
  console.log("generation", g);
  ver(m);
  m = siguiente(m);
}
  • The ends die (they had one neighbor) and two are born above and below (they had three). In the next one, the other way around: it spins forever. It's called the blinker.
  • Try ["....", ".OO.", ".OO.", "...."]: each one has three neighbors and it never changes. That's the block.

All at once

Notice that siguiente uses map: it doesn't touch the old board, it builds a new one. That's the most important thing in the program. If you changed the cells in the same board as you go, the lower ones would count neighbors that already belong to the next generation, and the upper ones wouldn't: you'd get something else.

This comes up in many simulations: you read from one copy and write to another. It's sometimes called *double buffering*.

// the eight around it
const ocho = (y, x) => [[y - 1, x - 1], [y - 1, x], [y - 1, x + 1], [y, x - 1],
                        [y, x + 1], [y + 1, x - 1], [y + 1, x], [y + 1, x + 1]];

function siguiente(m) {
  return m.map((fila, y) =>
    fila.map((viva, x) => {
      let n = 0;
      for (const [i, j] of ocho(y, x))
        n += m[i]?.[j] ?? 0;
      if (n === 3) return 1;
      return viva && n === 2 ? 1 : 0;
    }));
}

// wrong: it changes the same board while counting
function malo(m) {
  for (let y = 0; y < m.length; y++)
    for (let x = 0; x < m[y].length; x++) {
      let n = 0;
      for (const [i, j] of ocho(y, x)) n += m[i]?.[j] ?? 0;
      m[y][x] = n === 3 || (m[y][x] && n === 2) ? 1 : 0;
    }
  return m;
}

const leer = (filas) => filas.map((f) => [...f].map((c) => (c === "O" ? 1 : 0)));
const ver = (m) => console.log(m.map((f) => f.map((v) => (v ? "O" : ".")).join(" ")).join("\n") + "\n");

const filas = [".....", ".....", ".OOO.", ".....", "....."];
console.log("right:"); ver(siguiente(leer(filas)));
console.log("wrong:"); ver(malo(leer(filas)));

With the same three cells, the blinker comes out right with a new board and a different shape comes out if you change the same one: the cell born above already counts as a neighbor for the ones below.

Still, spinning and walking

That rule gives you three kinds of shapes:

  • Still lifes: they don't change, like the block.
  • Oscillators: they come back to the same shape every so many generations, in the same place, like the blinker.
  • Spaceships: they come back to the same shape, but somewhere else. The smallest is the glider, with five cells: every four generations it's one cell lower and one to the right.

The program runs each shape until it repeats, and says how often and how far it moved.

// the eight around it
const ocho = (y, x) => [[y - 1, x - 1], [y - 1, x], [y - 1, x + 1], [y, x - 1],
                        [y, x + 1], [y + 1, x - 1], [y + 1, x], [y + 1, x + 1]];

function siguiente(m) {
  return m.map((fila, y) =>
    fila.map((viva, x) => {
      let n = 0;
      for (const [i, j] of ocho(y, x))
        n += m[i]?.[j] ?? 0;
      if (n === 3) return 1;
      return viva && n === 2 ? 1 : 0;
    }));
}

// puts the shape on a 20 x 20 board, with its corner at (6, 6)
function poner(filas) {
  const m = Array.from({ length: 20 }, () => Array(20).fill(0));
  filas.forEach((f, y) => [...f].forEach((c, x) => { if (c === "O") m[y + 6][x + 6] = 1; }));
  return m;
}

// the shape without its place, and its corner
function forma(m) {
  const vivas = m.flatMap((f, y) => f.flatMap((v, x) => (v ? [[y, x]] : [])));
  const y0 = Math.min(...vivas.map((c) => c[0])), x0 = Math.min(...vivas.map((c) => c[1]));
  return { clave: vivas.map(([y, x]) => (y - y0) + "," + (x - x0)).join(" "), y0, x0 };
}

const figuras = {
  block: ["OO", "OO"],
  blinker: ["OOO"],
  toad: [".OOO", "OOO."],
  glider: [".O.", "..O", "OOO"],
  spaceship: [".O..O", "O....", "O...O", "OOOO."],
};

for (const nombre in figuras) {
  let m = poner(figuras[nombre]);
  const a = forma(m);
  for (let g = 1; g <= 20; g++) {
    m = siguiente(m);
    const b = forma(m);
    if (b.clave === a.clave) {
      console.log(nombre + ": repeats every", g, "| moved", b.y0 - a.y0, "down and", b.x0 - a.x0, "right");
      break;
    }
  }
}
  • The block repeats every 1 (it never changes); the blinker and the toad, every 2, without moving.
  • The glider and the spaceship repeat every 4, but somewhere else. A negative number means up or to the left.

The gun and the computer

Conway offered 50 dollars to whoever could show, before the end of 1970, whether a shape could grow without end. A team from MIT led by Bill Gosper won it in November, with a glider gun: it fires the first one on generation 15 and then one every 30, forever.

With streams of gliders that crash into each other you can make "and", "or" and "not", which is what computers are made of. So the Game of Life can compute anything a computer can, and people have in fact built programmable computers inside it: one runs Tetris.

// the eight around it
const ocho = (y, x) => [[y - 1, x - 1], [y - 1, x], [y - 1, x + 1], [y, x - 1],
                        [y, x + 1], [y + 1, x - 1], [y + 1, x], [y + 1, x + 1]];

function siguiente(m) {
  return m.map((fila, y) =>
    fila.map((viva, x) => {
      let n = 0;
      for (const [i, j] of ocho(y, x))
        n += m[i]?.[j] ?? 0;
      if (n === 3) return 1;
      return viva && n === 2 ? 1 : 0;
    }));
}

const pistola = [
  "........................O...........",
  "......................O.O...........",
  "............OO......OO............OO",
  "...........O...O....OO............OO",
  "OO........O.....O...OO..............",
  "OO........O...O.OO....O.O...........",
  "..........O.....O.......O...........",
  "...........O...O....................",
  "............OO......................",
];

// on a big board, so the gliders don't reach the edge
let m = Array.from({ length: 70 }, () => Array(90).fill(0));
pistola.forEach((f, y) => [...f].forEach((c, x) => { if (c === "O") m[y + 2][x + 2] = 1; }));

const vivas = () => m.flat().reduce((a, v) => a + v, 0);
for (let g = 0; g <= 120; g++) {
  if (g % 30 === 0) console.log("generation", String(g).padStart(3), "alive", vivas());
  m = siguiente(m);
}

Every 30 generations the gun is back to the same shape and there are five more alive: a new glider on its way. That's how it grows without end.

Only the ones that matter

siguiente looks at the eight neighbors of every cell, even though almost all of them are dead: on a 100 × 100 board that's 80,000 looks per generation, for a glider of five. It's O(n) with n cells.

It works better the other way around: let each live one add one to its eight neighbors. You only touch what's next to a live cell, and the board no longer has edges, because you don't store it: you store the live ones, in a Set, and the counts, in a Map.

// the eight around it
const ocho = (y, x) => [[y - 1, x - 1], [y - 1, x], [y - 1, x + 1], [y, x - 1],
                        [y, x + 1], [y + 1, x - 1], [y + 1, x], [y + 1, x + 1]];

let miradas = 0;
function siguienteVivas(vivas) {
  const cuenta = new Map();
  for (const c of vivas) {
    const [y, x] = c.split(",").map(Number);
    for (const [i, j] of ocho(y, x)) {
      const k = i + "," + j;
      cuenta.set(k, (cuenta.get(k) ?? 0) + 1);
      miradas++;
    }
  }
  const nuevas = new Set();
  for (const [k, n] of cuenta)
    if (n === 3 || (n === 2 && vivas.has(k))) nuevas.add(k);
  return nuevas;
}

let planeador = new Set(["0,1", "1,2", "2,0", "2,1", "2,2"]);
planeador = siguienteVivas(planeador);
console.log("looks in one generation:", miradas);

for (let g = 1; g < 400; g++) planeador = siguienteVivas(planeador);
console.log("400 generations later:", [...planeador].sort().join("  "));
  • 40 looks (five live cells times eight) instead of 80,000.
  • In 400 generations the glider walks 100 cells diagonally, and it's still the same: 0,1 became 100,101.

Practice with a video challenge

Further reading