Dave Hulbert's Today I Learned (TIL)


Conway’s Game of Life in Canvas

date: 2013-01-27 18:14:07

I haven’t done much with Canvas, so I thought I’d experiment by making Conway’s Game of Life with a little JavaScript. Conway’s Game of Life is based on a grid of cells, which are either alive or dead. It has 4 simple rules rules:

  1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overcrowding.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction

These simple rules allow anything to be created. For example:

Gliders

Gliders in Conway’s Game of Life (from Wikipedia)

You can see the code on GitHub. It’s very basic but works OK and isn’t too bad for a couple of hours whilst watching TV (it may eat up your CPU a little, sorry). Pull requests, ideas and suggestions welcome.

You can see it in action in the header of this blog. If you move your mouse over it then it will leave a trail of blocks. Clicking on the canvas will add lots of random cells.