Cellular Automata – Conway’s Game of Life in HTML 5

I had to do a school project involving automata so, after searching what this means .. I came to “cellular automaton” and then to the “Conway’s Game of Life” on wikipedia. I remember doing such a project on RentACoder few years ago in Visual Basic but I didn’t knew this fancy name for it … “cellular automata” 🙂

The rules are pretty simple :

  • A cell with 0 or 1 neighbor dies because of underpopulation
  • A cell with 4 or more neighbors dies because of overpopulation
  • If an empty space has exactly 3 cells then a new cell is born in that empty space
  • If none of the above rules apply then the space does not change (a live cell remanins alive, and an empty space is still empty)

For implementing it .. I choosed the canvas object from HTML 5 specs as I wanted to learn a little bit about it.

The first step was writing the canvas tags with a default message in case the user’s browser does not support it.

Your browser does not support canvas.

After this .. came the fun part .. javascript 🙂

The code below is pretty simple :

  • We declare how many cells we want on the X/Y axes, how many pixels wide should be a cell and the delay between drawing the next generation of cells
  • We create 2 arrays, one for storing the initial colony and one for the next generation
  • We randomly fill with live cells the initial colony
  • We draw the initial colony and then we process the colony using the game’s rules

If you have any questions .. feel free to ask 🙂

Click here to see the working project.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.