Cellular Automaton (Game of Life) - Phone friendly and fast
The Game of Life is a "cellular automaton" which has been studied by computer scientists since the 1970s.
Here's my take on it, where I produce randomly "alive" cells, and where the main aim has been to produce the quickest animation possible.
The "Game"
This uses setInterval
for slow time intervals, and uses requestAnimationFrame
for the "maximum" animation speed.
When using requestAnimationFrame
, we cannot animate faster than the refresh rate of the monitor.
Your monitor refresh rate is: 00 Hz
Actual: 0.00 FPS.
Timer method:
Status:
Generations = 0
Explanation - the "Game"
The cells in the Game of Life behave as follows for each new "generation":
- Any live cell with two or three live neighbours survives (safety in numbers).
- Any dead cell with three live neighbours becomes a live cell (reproduction).
- All other live cells die in the next generation (due to under- or overpopulation). Similarly, all other dead cells stay dead.
(See more on John Horton's Game of Life).
Explanation - coding
The SVG is created via JSXGraph (although it could have been done independently by just writing the SVG element in the HTML).
To achieve very fast animation, we:
- Created our points (circles) directly (independent of JSXGraph), using
var ell = document.createElementNS("http://www.w3.org/2000/svg", "circle");
. - The points are only created when we need them
- If a cell "dies", we just change the colour of the circle, using
ele.setAttribute("fill", "#bbb");
- If a cell is "reborn", we change it back to magenta using
ele.setAttribute("fill", "#f0f");
In this way, we avoid the overhead of JSXGraph point creation and manipulation, which involves a lot of updating, timers and unnecessary creation of DIVs.
The "Actual" framerate is higher than the set FPS when using setInterval
since it's indicating the effective screen update rate, not the rate that the points are changing position.
The framerate drops in cases where there is a "local infinite loop", that is, where a pattern of dots interchanges with another pattern of dots over and over. This involves a lot of CPU drain.