Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 49 ยท Projects

Project: Conway's Game of Life

Build Conway's Game of Life with NumPy: count neighbors with np.roll, apply the rules in one expression, wrap the edges, run generations and print glider and blinker.

Conway's Game of Life is a "game" with no players. You draw a grid of cells, each alive or dead, press go, and the grid evolves by four simple rules. From those rules emerge blinking lights, still blocks, and little creatures called gliders that crawl across the grid forever. It is a favourite beginner project because the rules fit in two lines, and a favourite NumPy project because the obvious solution, two nested loops over every cell, can be replaced by a handful of whole-array operations.

In this project you will represent the board as a 2D array, count every cell's neighbors at once with np.roll, apply the rules with boolean masks, run many generations, and print text frames to watch a blinker and a glider. You will also compare three different ways to count neighbors and see why they agree. You need slicing, boolean masks and joining and splitting arrays.

The rules

The board is a grid. Each cell has eight neighbors (the cells touching it, including diagonals). Every generation, all cells change at the same moment according to the number of living neighbors:

  1. A live cell with 2 or 3 live neighbors survives.
  2. A live cell with any other count dies (loneliness or overcrowding).
  3. A dead cell with exactly 3 live neighbors comes alive.
  4. Everything else stays dead.

Rules 1 to 4 combine into one boolean formula. If board is 1 for alive and 0 for dead and n is the neighbor count:

next = (n == 3) | (board == 1) & (n == 2)

A cell with three neighbors is alive next time whatever it was before; a cell with two neighbors keeps its current state. That is the whole game.

flowchart LR
    A["board<br/>(0 and 1)"] --> B["count neighbors<br/>for all cells"]
    B --> C["apply rules<br/>with masks"]
    C --> D["new board"]
    D -->|"repeat"| A

One generation: count, apply the rules, replace the board.

Counting neighbors without loops

To count the neighbors of every cell at once, imagine eight copies of the board, each shifted by one step in a different direction: up, down, left, right and the four diagonals. If you stack the eight copies and add them, the value at each position is the number of live neighbors of that cell.

np.roll(board, shift=(dy, dx), axis=(0, 1)) does the shifting. It moves the content by dy rows and dx columns, and cells that fall off one edge re-enter at the opposite edge. That is a useful accident: it makes the board a torus (like the screen in the game Asteroids), so a glider leaving on the right appears on the left, and no cell needs special edge handling.

flowchart TD
    A["board"] --> S1["roll (-1, -1)"]
    A --> S2["roll (-1, 0)"]
    A --> S3["roll (-1, +1)"]
    A --> S4["roll (0, -1)"]
    A --> S5["roll (0, +1)"]
    A --> S6["roll (+1, -1)"]
    A --> S7["roll (+1, 0)"]
    A --> S8["roll (+1, +1)"]
    S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 --> T["add all eight: neighbor counts"]

Eight shifted copies of the board add up to the neighbor count of every cell. The shift (0, 0), the cell itself, is left out.

Python Neighbor counts with np.roll

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The loop runs only 8 times, regardless of how large the board is. Each iteration is one vectorized operation over the entire grid. Look at the numbers: the cell above and below the middle of the blinker each see 3 live neighbors (so they will be born), the two end cells see only 1 (so they will die), and the centre cell sees 2 (so it survives).

The counts use uint8, which is plenty for numbers up to 8 and uses little memory. Adding eight boards of 0s and 1s can never overflow it. If you used bool arrays instead, += would not count, because True + True is still True in boolean arithmetic.

Applying the rules and running generations

With the neighbor counts the step function is one line. Notice how & and | need parentheses (see boolean masks), and how astype(np.uint8) turns the final boolean mask back into 0s and 1s.

Python The blinker and the glider

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The blinker is an oscillator with period 2: a horizontal bar becomes a vertical bar and back again. The glider is a spaceship: after four generations it has the same shape, shifted one cell down and to the right. On an 8 by 8 torus it needs 8 shifts of 4 generations each, so 32 generations, to return to where it started. If you had used a bounded board (dead outside), the glider would crash into the wall and turn into a still 2 by 2 block.

Three ways to count neighbors

np.roll is short, but it is not the only option. Each of the following produces the same counts, and each teaches a different NumPy idea:

  • Padded slices. Pad the board by one cell on every side (np.pad(board, 1, mode="wrap")), then add the eight slices padded[dy:dy+h, dx:dx+w]. No wrapping inside the sum, no copies of the whole board.
  • Window sums. Use sliding_window_view to see every 3 by 3 block, sum each block, and subtract the cell itself. This is a convolution with a 3 by 3 kernel of ones, the same operation behind the image filters in the next projects. See memory layout and strides.
  • Rolling. The method above.
Python Three neighbor counters agree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The three methods give identical results on the torus. Changing mode="wrap" to mode="constant" pads with zeros, so cells on the border lose the neighbors that were wrapping around, and the first row gets lower counts. Choose wrapping when you want an "infinite" feeling on a small board and zero padding when you want walls.

A random soup and long-term behaviour

Real Life boards start random. A "soup" with about 25 percent live cells usually loses cells for a few dozen generations, then settles into still lifes, blinkers and a few gliders. Fixed seeds make the experiment repeatable. Because the board is a NumPy array, you can detect a repeating state by storing board.tobytes() in a dictionary.

Python Population counts and cycle detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The soup starts with 617 live cells and shrinks gradually. The 12 by 12 board ends in a state that repeats with period 1, which means a still life: nothing changes any more. The R-pentomino is famous because five cells expand into dozens of live cells and take over a thousand generations to stabilise on an unbounded board; on our 30 by 30 torus the wrapped edges eventually interfere, so do not expect the textbook numbers.

Speed and extensions

Each generation costs eight array additions plus a few comparisons, all in compiled code, so a 1000 by 1000 board runs in milliseconds per step. A pure Python loop over each cell, with eight neighbor lookups, would be hundreds of times slower. Compare with the tuning advice in writing fast NumPy code.

Ideas to try next:

  • Add a function that stamps a pattern into a larger board at a chosen position (slice assignment).
  • Draw frames with matplotlib.pyplot.imshow(board, cmap="gray_r") using arrays as images.
  • Change the rules. "HighLife" adds one rule: a dead cell with 6 neighbors is also born, which you can write as born = ((n == 3) | (n == 6)) & (board == 0) and survive = ((n == 2) | (n == 3)) & (board == 1), then born | survive. Edit the mask formula and observe.
  • Count how many generations until the population stops changing, and plot the population history.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the vectorized neighbor count, why is the shift (0, 0) skipped?

    The shift (0, 0) returns the board itself. Adding it would count every cell as a neighbor of itself.
  2. 2. What happens to cells that np.roll pushes past the right edge of the board?

    np.roll wraps values around, so no edge handling is needed and the board behaves like a torus.
  3. 3. A live cell has 4 live neighbors. What is its state in the next generation?

    A live cell survives only with 2 or 3 live neighbors. Four is overcrowding, so the cell dies.
  4. 4. Why does the example use dtype uint8 rather than bool for the board?

    In boolean arithmetic True plus True stays True, so the sum of eight neighbor boards would not be a count. uint8 holds numbers from 0 to 255.
  5. 5. Which pattern returns to its starting shape after 2 generations without moving?

    The blinker flips between a horizontal and a vertical bar, so it has period 2. The block never changes, and the glider shifts position.

Summary

  • The board is a 2D uint8 array of 0s and 1s; the next state is (n == 3) | (board == 1) & (n == 2), where n counts live neighbors.
  • Eight np.roll shifts added together count the neighbors of all cells at once and wrap the edges into a torus.
  • Padded slices and sliding_window_view are alternatives that give the same counts and allow dead borders.
  • A blinker oscillates with period 2, a glider moves one cell diagonally every four generations, and board.tobytes() lets you detect repeating states.
  • The whole simulation is vectorized: the cost per generation does not depend on Python loops over cells.

Next: Project: Image Filters from Scratch