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
neighbors(grid, x, y)returns how many of the 8 cells around(x, y)are alive. Don't count the cell itself.- Cells outside the grid count as dead. Grids can be any size. The program paints a heat map: more neighbours, hotter colour.
neighbors(grid, x, y)returns how many of the 8 cells around(x, y)are alive. Don't count the cell itself.- Cells outside the grid count as dead. Grids can be any size. The program paints a heat map: more neighbours, hotter colour.
main.py Python sleeping
Press Run to try your code, then Check to test it.