Quick HTML5 App: Conway’s Game of Life

Now, if you’ve read a few of my previous posts you will of seen that I am very interested in Cellular Automata (I did two articles on them, here and here). And in another post I showed off the HTML5 canvas tag some JavaScript for making a binary clock and my previous post was on a simple HTML5 application that retrieved people’s Minecraft skins.

So I thought that I might be able to combine the two topics and implement a cellular automata using the canvas and some JavaScript. And I did! You can view it in action here.

The code itself isn’t the nicest so I won’t go into big details of it, feel free to check it out though through Viewing the Pages’ source.

 

As a little bonus; if you click anywhere on the canvas it adds a Glider!

As a little bonus; if you click anywhere on the canvas it adds a Glider!

I learnt a bit more about arrays in JavaScript from my research for this project. One thing I learnt was how to make a 2 dimensional array (thanks to an answer on Stack Overflow):

function Create2DArray(rows) {
  var arr = [];
  for (var i=0;i<rows;i++) {
     arr[i] = [];
  }
  return arr;
}

And a lot more from this good blog post on arrays.

One part of the code that I really want to improve if I ever come back to it is the getLiveNeighbours function, it just seems needlessly long:

function getLiveNeighbours(x, y) {
    var live = 0;
    if(x < SIZE-1 && grid[x+1][y] == true) {
	// right
	live ++;
    }
    if(x > 0 && grid[x-1][y] == true) {
	// left
	live ++;
    }
    if(y < SIZE-1 && grid[x][y+1] == true) {
	// up
	live ++;
    }
    if(y > 0 && grid[x][y-1] == true) {
	// down
	live ++;
    }
    if(y < SIZE-1 && x < SIZE-1 && grid[x+1][y+1] == true) {
	// top right
	live ++;
    }
    if(y > 0 && x < SIZE-1 && grid[x+1][y-1] == true) {
	// bottom right
	live ++;
    }
    if(y < SIZE-1 && x > 0 && grid[x-1][y+1] == true) {
	// top left
	live ++;
    }
    if(y > 0 && x > 0 && grid[x-1][y-1] == true) {
	// bottom left
	live ++;
    }
    return live;
}

 

I’ve also learnt that I should be using the functions addEventListner and attachEvent instead of just setting attributes of elements. The Mozilla Developer Network had this snippet that I used for them:

function attachEvent(element, event, callbackFunction) {
    if(element.addEventListener) {
      element.addEventListener(event, callbackFunction, false);
    } 
    else if(element.attachEvent)  {
      element.attachEvent('on' + event, callbackFunction);
    }
}

One last thing I learnt making this is that while fast, I would still need to optimise the Game Of Life code in order to run it on a larger grid as I was getting slow downs in a 300×300 pixel grid.

Leave a Reply