Simple, Sexy Cellular Autonoma with the Terra.js Library

terrajs

I’m absolutely fascinated with cellular autonoma simulations like Conway’s Game of Life. So much so, I spent several days building a game of life simulation for this year’s JS1k competition:

 

And while I think what I built is pretty cool, it took me several days and several hundred lines of code to figure out. Terra.js is a library that simplifies building these sorts of simulations. For example, here’s all the code necessary to run a game of life simulation:

var gameOfLife = new terra.Terrarium(25, 25, {
  trails: 0.9,
  periodic: true,
  background: [22, 22, 22]
});
terra.registerCA({
  type: 'GoL',
  colorFn: function () { return this.alive ? this.color + ',1' : '0,0,0,0'; },
  process: function (neighbors, x, y) {
    var surrounding = neighbors.filter(function (spot) {
      return spot.creature.alive;
    }).length;
    this.alive = surrounding === 3 || surrounding === 2 && this.alive;
    return true;
  }
}, function () {
  this.alive = Math.random() < 0.5;
});
gameOfLife.grid = gameOfLife.makeGrid('GoL');
gameOfLife.animate();

Compared to the several hundred lines of code I originally wrote for my simulation, this is a piece of cake.

Check out Terra on GitHub and the example site. Go forth and build awesome.

Rob

Rob has been building websites for more than half of his life. You'd think that'd make all this less interesting, but nope! There's a lot of awesome stuff going on webwards, and canvas is definitely one of them.

You may also like...

Leave a Reply

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