I have a confession to make. Although I have a degree in Computer Science, I don’t ever recall implementing John Conway’s Game of Life. The program is less of a game and more about implementing an algorithm with observable results. In this post, we’ll implement Conway’s Game of Life using .NET, C#, and some fun emojis.
What Are The Rules
In 1970, British mathematician John Conway developed a zero-player game designed to mimic the behavior of life itself. Players are required to see the universe with an initial state, and then observe as the rules of life produce an outcome. Each game consists of a two-dimensional grid with a potential state of life or death enhabiting each cell. Each cell has the potential to shift its state based on a set of rules.
What are the rules to play the game of life?
- Any live cell with fewer than two live neighbors dies, as if 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.
For programming, we can reduce these rules to a set of three algorithm steps.
- Any live cell with two or three live neighbors survives.
- Any dead cell with three live neighbors becomes a live cell.
- All other live cells die in the next generation. Similarly, all other dead cells stay dead.
Each generation continues to seed the next generation until the universe reaches an equilibrium. The game is a fun one to watch and hypnotic based on the size of the board.
reference: Wikipedia: Conway’s Game of Life
Game of Life in C#
We’ll be using a C# console application to implement the rules to the Game of Life. For the sake of following along, we’ll paste the app in its entirety below.
Some of the cool things to note in the code above include:
- A variable row and column setup.
- The use of
RandomNumberGenerator
to seed our grid. - Listening for
CancelKeyPress
event to stop the simulation. - The
Print
method builds a single string then writes to the console by repositioning the cursor. - The logic and UI are separated, allowing us to move the logic to another display format.
When we run the program, we see the following.
We can play with the emojis and get different outputs. Here is an example of aliens and astronauts.
Here is an example of cats and mice.
Here is a zombie apocalypse inspired layout.
With emojis and the game of life, the possibilities are endless. What other combinations are possible? Leave them in the comments below. The code is available on GitHub.