Background
A while ago, I discovered Jonh Conway’s Game of Life. Game of Life is a cellular automaton invented by the British mathematician John Horton Conway in 1970.
A cellular automaton is an array (of one or more dimensions) of cells in which each cell has a finite number of conditions. An example of a finite number of conditions is “on” and “off”, or “empty”, “half full” and “full”.
A set rules determines, based on the current condition of the cells and each cell’s neighbours, what the next condition of each cell will be.
By applying these rules repeatedly, certain patterns or movements come to exist. Depending on the rules, these movements can closely resemble what happens spontaneously in nature.
Conway’s Game of Life is an example of such a cellular automaton. The cells can either be dead or alive and within the automaton, the following rules apply:
- Every living cell with less than two living neighbours dies as if by underpopulation
- Every living cell with more than three living neighbours dies as if by overpopulation
- Every living cell with exactly two or three living neighbours continues to live
- Every dead cell with exactly three living cells comes back to life
By applying these rules multiple times per second, the cells will switch state and this can, depending on the formations of living cells, lead to interesting movements.
I thought this was so intersting that I decided to build my own implementation of Conway’s Game of Live. Using Javascript.
My implementation
Because Conway’s Game of Life takes place inside a two dimensional grid of cells, it seemed logical to use a <table> for this. In my first version I tried to get everything working without using any extra variables in Javascript by keeping everything inside attributes of the <td>’s. This worked, the performance was so horrible that I had to find another way.
In my second (and current) version, I ended up creating three classes in Javascript:
- A class Cell that, of course, represents a cell.
- A class GameOfLifeRenderer that is responsible for creating a <table> with a certain amount of cells. The condition of the cells is saved in a two dimensional array of the type Cell.
- A class GameOfLifeLogic that implements the rules of the game.
The logics work like this:
- Loop over the two dimensional array of Cells and calculate the amount of living neighbours for each cell.
- Determine for each cell what its next condition will be.
- Loop over the two dimensional array a second time. If the current condition of a cell if different from its next condition, change the current condition and give the <td> the correct color.
Here you can find my version of Conway’s Game of Life I have also provided a browser friendly version of my Javascript code.
Nice!
cool