PYTHON
Recreate the famous Game of Life
Mihalis Tsoukalos casts a light on Python sets and shows how to implement the classic programming exercise the Game of Life in Python.
OUR EXPERT
Mihalis Tsoukalos iis a Systems Engineer and a Technical Writer. He is the author of
Go Systems Programming and
Mastering Go, 3rd edition. You can reach him at
www. mtsoukalos.euand
@mactsouk.
Everyone loves 2D cellular automaton, to explore this exciting subject we’re going to use Game of Life as our working example. This isn’t to be confused with The Game of Life, the family board game that was first produced in 1960 and is still going strong today. So, let’s begin by explaining how Game of Life the non-board game edition works! Before we start you can get the code packs for this tutorial from the LXF Archive here: https://bit.ly/lxf284code.
Game of Life doubles up as both a programming exercise and an introduction to theoretical mathematics and computer science (don’t let that put you off! – Ed), but in this tutorial we’re only dealing with the former. Although it might not seem it, the game is Turing Complete, which means that its data manipulation rules can be used to simulate a Turing Machine (see LXF271). We’ll look at this in more detail later in the article.
Game of Life can have various states, depending on the initial state of the board. Given an initial state, Game of Life doesn’t require any extra input from the user. Put simply, once it has an initial state, Game of Life can operate on its own with the help of its rules.
The patterns of life
Game of Life works by creating patterns. The figure (below) shows an example of patterns in the Game of Life, that displays living and dead cells. It uses black for living cells and white for dead cells, which is the colouring scheme used throughout this tutorial. Once you’ve read the rules of Game of Life, you’ll understand why not all black and white cell combinations are allowed. Hint: when a living cell has too many neighbours, it’s going to die! Bear in mind that there are two kinds of patterns: those that are changing and keep repeating; and patterns that are stable, which means that they’re not being updated.
This shows some stable patterns that might appear in Game of Life. The stability of a pattern depends on the rules. In the case of the square that comprises four cells, no cell dies because each cell has three living neighbours.