The Game Of Life, is a cellular automation devised by the British mathematician John Horton Conway in 1970.
The so-called game has no players, it's evolution being determined by its initial state, being required no more inputs. The objective is to see how an initial grid-based configuration evolves based on some conditions that are pre-implemented inside it.
Even if it may seem hard at the beginning, it's one of the fastest-to-implement and easy-to-understand visualizations.
How are we making it?
All we need is C++, SFML Library (for graphics, of course, who would like to see a game in a Terminal?) and a little bit of patience.
We start with a two-dimensional orthogonal grid array of cells (which are going to represent our life forms), being implemented in their own class, with not-so-many methods (all they have to do is to be able to draw themselves to the window, die, be born, and changing states in the initial-setup part of the game).
Cell's components:
- isAlive() > return if the cell is alive or not
- getX(), getY() > get cell's coordinates
- draw() > draw the cell on screen
- setPosition() > set position on screen
- kill(), born() > change cell's state to alive or not alive
- update() > get cell's input from window (change state on click)
After we implemented the cell class, the rest of the game is easier than you might think. In the game-loop, all we have to do is just follow 3 steps:
- Clone the grid in a gridCopy.
- Traverse the grid and update the gridCopy based on the current conditions (we have to update them in the gridCopy, because once we kill/create a new cell in the main grid, number of neighbors of the next cell will be smaller than real) a) Any live cell with fewer than two live neighbors dies, as if by underpopulation. b) Any live cell with two or three live neighbors lives on to the next generation. c) Any live cell with more than three live neighbors dies, as if by overpopulation. d) Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
- Move the gridCopy into the main grid.
You can see the full code on GitHub and the practical demo of the application on YouTube. Have fun coding and, until next time, keep smiling, life is too short to have bugs!
Top comments (0)