Description
Game of Life is a cellular automation devised by John Conway in 1970. My application puts the game on screen as a Windows Form application. It was written in C++ for a first-year university assignment. The application uses the standard rules:
- Any live cell with fewer than two live neighbours dies, as if by underpopulation.
- Any live cell with two or three live neighbours lives on to the next generation.
- Any live cell with more than three live neighbours dies, as if by overpopulation.
- Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
Development
GeeksforGeeks has a great tutorial which explains how you could code this application in a variety of languages. I based my code on this and added functions for loading from and saving to a CSV file. There are a few important things to consider:
- Saving the future state of the grid in a separate array before overwriting the current one prevents destructive mutations (I learned this one the hard way!).
- A discrete function for counting neighbours for a given cell simplifies the main loop.
- In the original simulation, the edges of the grid do not wrap. I chose to wrap the edges so that simple starting states last longer or even indefinitely.
int countNeighbours(bool boolArray[][gridSize], int x, int y) {
int count = 0;
for (int i(-1); i < 2; ++i) { //for every row before and after the passed position
for (int j(-1); j < 2; ++j) { //for every column before and after the passed position
int checkX = x + i;
int checkY = y + j;
//edge cases - wrap coordinates around the grid
if (checkX < 0) {
checkX = gridSize-1;
}
else if (checkX >= gridSize) {
checkX = 0;
}
if (checkY < 0) {
checkY = gridSize-1;
}
else if (checkY >= gridSize) {
checkY = 0;
}
//add to neighbours if not checking self and checked cell is true (alive)
if ( !(i == 0 && j == 0) && (boolArray[checkX][checkY] == true)) {
++count;
}
}
}
return count;
}
When the project was first set there was no requirement for a GUI, so I output the simulation in the terminal.
Features
- Interactive GUI, step through iterations manually or automatically
- Pre-made patterns, glider and 10 cell row
- Toggle the state of any cell by clicking on it
- Load/save the current state to CSV
- Wrap grid edges
- Change cell color
- Compile the application with different grid sizes
This video has no sound