Conway's Game of Life

Conway's Game of Life

🌐 Auf Deutsch lesen
📅 2026-12-03 ✍️ Andreas Wittmann 👁️ ... algorithm graphics computer-graphics cellular-automaton

The flood fill and maze articles worked on a grid of cells, where each cell only cares about its direct neighbors. Conway's Game of Life takes that idea and removes everything else: no seed cell, no goal, no player. A grid of cells, each alive or dead, and a single rule that decides from a cell's neighbors whether it is alive in the next generation. Apply the rule to every cell at once, again and again, and watch what happens.

The mathematician John Conway designed it in 1970, and it became famous when Martin Gardner described it in his "Mathematical Games" column in Scientific American that October. It is the best-known example of a cellular automaton, and it is a "game" only in the sense that you set up the starting position and then watch.

The rules

Every cell has eight neighbors: the cells directly next to it, horizontally, vertically, and diagonally. To get the next generation, count the live neighbors of each cell:

cell is live neighbors next generation
alive 0 or 1 dies (loneliness)
alive 2 or 3 survives
alive 4 or more dies (overcrowding)
dead exactly 3 comes to life
dead anything else stays dead

That is all. Life enthusiasts write the rule as B3/S23: born with 3 neighbors, survives with 2 or 3.

Implementation

#include "plot.hpp"

// false: a random start ("soup"), true: Gosper's glider gun
const bool GLIDER_GUN = false;

// true: the grid wraps around at the edges (a torus),
// false: everything outside the grid is dead
const bool WRAP = true;

const int DENSITY = 30;  // percent of cells alive in the random start
const int SEED = 1;      // a different seed gives a different soup
const int SPEED = 4;     // frames per generation

const int CELL = 8;
const int TOP = 24;                // room for the status line
const int W = 640 / CELL;          // 80 columns
const int H = (480 - TOP) / CELL;  // 57 rows

// Two grids: the next generation is computed entirely from the current
// one, then the two are swapped.
unsigned char grid[H][W];
unsigned char next[H][W];
unsigned char born[H][W];  // only for drawing: new in this generation

int generation = 0;
int tick = 0;

// A small xorshift generator, so the soup is the same everywhere.
unsigned int rng = 2463534242u + SEED;
unsigned int random_number() {
    rng ^= rng << 13;
    rng ^= rng >> 17;
    rng ^= rng << 5;
    return rng;
}

bool alive(int x, int y) {
    if (WRAP) {
        x = (x + W) % W;
        y = (y + H) % H;
    } else if (x < 0 || x >= W || y < 0 || y >= H) {
        return false;
    }
    return grid[y][x];
}

int neighbors(int x, int y) {
    int n = 0;
    for (int dy = -1; dy <= 1; dy++) {
        for (int dx = -1; dx <= 1; dx++) {
            if ((dx != 0 || dy != 0) && alive(x + dx, y + dy)) n++;
        }
    }
    return n;
}

// The rules: a live cell with 2 or 3 live neighbors survives,
// a dead cell with exactly 3 live neighbors comes to life,
// every other cell is dead in the next generation.
void step() {
    for (int y = 0; y < H; y++) {
        for (int x = 0; x < W; x++) {
            int n = neighbors(x, y);
            next[y][x] = grid[y][x] ? (n == 2 || n == 3) : (n == 3);
            born[y][x] = next[y][x] && !grid[y][x];
        }
    }
    for (int y = 0; y < H; y++) {
        for (int x = 0; x < W; x++) grid[y][x] = next[y][x];
    }
    generation++;
}

const char* gun[] = {
    "........................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......................",
};

void setup() {
    PlotCanvas(640, 480);

    if (GLIDER_GUN) {
        for (int y = 0; y < 9; y++) {
            for (int x = 0; gun[y][x]; x++) grid[y + 2][x + 2] = gun[y][x] == 'O';
        }
    } else {
        for (int y = 0; y < H; y++) {
            for (int x = 0; x < W; x++) grid[y][x] = random_number() % 100 < DENSITY;
        }
    }
}

void frame() {
    if (++tick >= SPEED) {
        tick = 0;
        step();
    }

    PlotBackground(250, 250, 250);

    int population = 0;
    for (int y = 0; y < H; y++) {
        for (int x = 0; x < W; x++) {
            if (!grid[y][x]) continue;
            population++;
            if (born[y][x]) PlotColor(220, 60, 60);  // just born
            else            PlotColor(70, 170, 90);  // survived
            PlotFilledRectangle(x * CELL + 1, TOP + y * CELL + 1,
                                x * CELL + CELL - 1, TOP + y * CELL + CELL - 1);
        }
    }

    PlotColor(40, 44, 52);
    PlotLine(0, TOP - 1, 640, TOP - 1);
    PlotText(10, 4, "generation %d   population %d", generation, population);
}
Open in full editor →

The grid has 80 × 57 cells of 8 × 8 pixels, with a status line above it. neighbors counts the live cells around a position, and step applies the rules to every cell. Red cells were born in the current generation, green cells survived from the one before. The starting position is a random "soup": every cell is alive with a probability of DENSITY percent. As in the maze article, the program uses its own small xorshift random generator with a fixed SEED, so the soup looks the same in every browser and on every system; change SEED for a different one.

The grid is finite, so something has to happen at the edges. With WRAP = true, the grid wraps around like a torus: a cell on the right edge counts the cells on the left edge as its neighbors, and the same for top and bottom. With WRAP = false, everything outside the grid counts as dead.

Why two grids

step does not change grid while it is counting. It writes every new state into a second array, next, and only copies it back once all cells have been computed. This matters: the rules describe what all cells do at the same time. If you update the grid in place, the cells further down and to the right already see some neighbors from the next generation instead of the current one.

The difference is not subtle. The simplest oscillator, three cells in a row, should flip between horizontal and vertical forever. Updated in place, it turns into a 2 × 2 block after two generations and stays that way. The glider, the famous pattern described below, also collapses into a block. And the random soup from the sample, which correctly settles at 104 live cells, still has 1,838 after 1,000 generations of in-place updates, a dense pattern of stripes that has nothing to do with Life.

Still lifes, oscillators, spaceships

Watch the soup for a while and the same small shapes keep appearing. They fall into three groups:

still lifes      oscillator        spaceship
                 (period 2)        (period 4)

 OO     .OO.     ...    .O.        .O.
 OO     O..O     OOO    .O.        ..O
        .OO.     ...    .O.        OOO
block  beehive    blinker          glider

From chaos to order

A random soup does not stay random. With the default settings, 1,402 of the 4,560 cells are alive at the start. After 10 generations, 1,006 are left, after 100 generations 430, after 500 generations 192. In generation 966, the soup has settled for good: 104 live cells in still lifes and blinkers, repeating every two generations from then on.

That is not a peculiarity of this one soup. Here are 200 different seeds per starting density on the same 80 × 57 torus. "Settled" means the grid has started to repeat itself with a period of at most 60 generations:

live at start settled after (average) live at the end
10 % 915 generations 2.6 %
20 % 1,273 generations 3.0 %
30 % 1,252 generations 3.0 %
50 % 1,319 generations 3.0 %
70 % 1,150 generations 2.7 %

Whether a fifth or seven tenths of the cells start alive, roughly 3 % are left at the end. Extreme starts are evened out right away: at 70 %, overcrowding kills so many cells that only 5.5 % are still alive after a single generation, and at 10 %, loneliness halves the population to 4.8 %. After that, every soup is the same kind of chaotic mixture, which takes about a thousand generations to burn out. Almost every final state has a period of exactly two, because somewhere a blinker is left over. Only a handful of the 1,400 soups was still changing after 6,000 generations.

The glider gun

When Conway published the game, he offered a prize of 50 dollars for a starting pattern that grows forever, and suspected that none existed. A group around Bill Gosper at MIT won the prize the same year with the glider gun: a pattern of 36 cells that produces a new glider every 30 generations and sends it off diagonally. On an infinite grid, the number of live cells therefore grows forever.

Set GLIDER_GUN = true in the sample to see it. On the torus it does not last long: the gliders travel off the bottom of the grid, come back in at the top, and after about 240 generations the first one crashes into the gun and wrecks it. With WRAP = false as well, the gun keeps firing forever. The first glider to reach the bottom edge cannot leave and turns into a block; the next glider runs into that block and both disappear; the one after that becomes a new block, and so on, a cycle that repeats every 60 generations.

The infinite grid

Conway's grid is infinite, and every array is not. Wrapping around and treating the outside as dead are both compromises, and as the glider gun shows, they can change what a pattern does. Serious Life programs therefore store only the live cells, or, like the Hashlife algorithm, store repeating blocks of the grid only once and skip ahead through billions of generations. For an animation that shows what happens on screen, a plain array is all you need.

Conclusion

The Game of Life is the shortest program in this series, and in some ways the deepest one. One rule about counting neighbors produces still lifes, oscillators, and spaceships, turns random noise into the same 3 % of order every time, and, as was proven later, can even be arranged into patterns that compute anything a computer can. Change DENSITY and SEED in the sample, or draw your own starting pattern into setup, and see what it turns into.