Code

Count the Neighbours

The Game of Life (invented by John Conway in 1970) is a world of cells on a grid. Each cell is alive (1) or dead (0). What happens next depends on how many neighbours are alive: the 8 cells touching it, including diagonals.

. . .
. X .    X has 8 neighbours (the dots)
. . .

Visit them with two small loops from -1 to 1, skipping the cell itself:

for ny in range(y - 1, y + 2):
    for nx in range(x - 1, x + 2):
        if (nx, ny) != (x, y):
            ...

Cells beyond the edge count as dead. Careful: in Python grid[-1] is the last row, not an error! Check 0 <= nx < width and 0 <= ny < height before you look.

Remember: rows come first, so the cell is grid[y][x].

Assignment

  1. neighbors(grid, x, y) returns how many of the 8 cells around (x, y) are alive. Don't count the cell itself.
  2. Cells outside the grid count as dead. Grids can be any size. The program paints a heat map: more neighbours, hotter colour.