Conway's Game of Life
Conway’s Game of Life
In 1970, British mathematician John Horton Conway invented a cellular automaton called The Game of Life. This simple game is governed by its initial cellular state and four simple rules:
- Any live cell with fewer than two live neighbors dies, as if caused by underpopulation.
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by overpopulation.
- Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The rules are applied to all the cells in the grid, starting with the initial grid populated with the starting live cells. After many iterations, the grid comes to an end-state which can be unexpected given the initial seed state.
To make this cellular automaton more interesting, I’ve forked and modified a gist that uses pygames, a nice python module that aids in the development of python-based interactive visual games.
Here’s the gist for the code. I won’t go through it line-by-line, as it’s pretty obvious, but a few points worth mentioning. Take a lool at how the Ben Nuttall (the person from whom I forked the initial code) solves the neighbor index bounds problem. It’s novel. There are three ways count neigbors.
- wrap the grid with an outward perimeters of zeros that are not visible so that the bounds of all eight neighbors will be valid and will not result in an index bounds error
- preceed each of the eight neighbors with a conditional statement verifies the bounds are valid
- use a
try
andexcept
clause to attempt to index our grid andpass
if the resulting index would cause an index bounds error.
Take a look:
def count_neighbors(grid, position):
x,y = position
neighbour_cells = [(x - 1, y - 1), (x - 1, y + 0), (x - 1, y + 1),
(x + 0, y - 1), (x + 0, y + 1),
(x + 1, y - 1), (x + 1, y + 0), (x + 1, y + 1)]
count = 0
for x,y in neighbour_cells:
if x >= 0 and y >= 0:
try:
count += grid[x][y]
except:
pass
return count
Pretty cool. He creates a list of neighbors enumerating all eight (and leaving a blank in the middle where we live!) We then iterate
over the list by x
and y
coordinates and attempt to index grid[x][y]
inside a try
clause. if the resulting indexing is
invalid it throws an except and it’s simply ignored.
The foked version that I created parameterizes a few things and adds a title screen that dynamically shows the current iteration.
Have some fun and experiment with big and little numbers for block_size. The bigger the block_size, the less number of cells on the grid. Also experiment with different sizes for iteration count. The larger the number, the higher the probability that you’ll exhaust the cellular state from its initial seed state.
Installation Instructions
Here’s a quick summary of how to setup your environment to run the gist:
python3 -m venv sandbox
source sandbox/bin/activate
pip install pygame
Next copy the raw file below into conway.py
: