Friday, October 3rd, 2008
Life: The game in Canvas
<p>
Kyle McGregor took a look at the JavaScript games for Life out there and decided to write a Canvas version that ends up being a lot snappier. The entire game is pretty small:
-
-
var counterface = 0;
-
var oInstance;
-
var Game = Class.create();
-
-
Game.prototype = {
-
'working': false,
-
'map': '',
-
'interval_id': '',
-
'initialize': function()
-
{
-
-
//generate map
-
var startmap = [];
-
-
for(var y = 0; y <90; y++)
-
{
-
var row = [];
-
-
for(var x = 0; x <90; x++)
-
{
-
var state = Math.random();
-
state = (state> 0.8)? 1:0;
-
row[x] = state;
-
}
-
-
startmap[y] = row;
-
}
-
-
this.map = startmap;
-
-
oInstance=this;
-
this.interval_id = setInterval(function(){oInstance.loop()}, 100);
-
},
-
'loop': function()
-
{
-
if (document.getElementById('frame').getContext)
-
{
-
// drawing code here
-
if(this.working == false)
-
{
-
this.working = true;
-
this.draw();
-
this.step();
-
this.working = false;
-
}
-
}
-
else
-
{
-
// canvas-unsupported code here
-
}
-
},
-
'draw': function()
-
{
-
var ctx = document.getElementById('frame').getContext('2d');
-
ctx.save();
-
ctx.clearRect(0,0,450,450);
-
ctx.fillStyle = "rgb(0,0,0)";
-
-
for(var y = 0; y <90; y++)
-
{
-
for(var x = 0; x <90; x++)
-
{
-
if(this.map[y][x] == 1)
-
{
-
ctx.fillRect (x*5, y*5, 5, 5);
-
}
-
}
-
}
-
-
ctx.restore();
-
ctx.fill();
-
},
-
'step': function()
-
{
-
var output = '';
-
supercount = 0;
-
-
var tempmap = [];
-
-
for(var y = 0; y <90; y++)//work around for arrays passing by reference.
-
{
-
var row = [];
-
-
for(var x = 0; x <90; x++)
-
{
-
row[x] = this.map[y][x];
-
}
-
-
tempmap[y] = row;
-
}
-
-
for(var y = 0; y <90; y++)
-
{
-
for(var x = 0; x <90; x++)
-
{
-
var countme = this.getNeighborCount(y,x);
-
-
if ( this.map[y][x] == 0 ) // dead cell
-
{
-
if ( countme == 3 )
-
{
-
tempmap[y][x] = 1;
-
}
-
}
-
else
-
{
-
if ( ( countme == 2 ) || ( countme == 3) )
-
{
-
tempmap[y][x] = 1;
-
}
-
else
-
{
-
tempmap[y][x] = 0 ;
-
}
-
}
-
}
-
}
-
counterface++;
-
this.map = tempmap;
-
},
-
'getNeighborCount': function(starty,startx)
-
{
-
var count = 0;
-
-
for(var y = starty-1; y <= starty+1; y++)
-
{
-
for(var x = startx-1; x <= startx+1; x++)
-
{
-
if(y>= 0 && y <90 && x>= 0 && x <90)
-
{
-
if(startx != x || starty != y)
-
{
-
if(this.map[y][x] == 1)
-
{
-
count++;
-
}
-
}
-
}
-
}
-
}
-
-
return count;
-
}
-
}
-
Related Content:











Brilliant. I love succinct code.
I made an implementation of Life using canvas as well, back a couple of months ago. Left it as a comment too, on another post. :)
http://www.randomthink.net/canvas/life.html
http://sircambridge.net/conwayGameOfLife3.html#
load an example to start – has a few examples loaded from life initial condition libraries using rsh compression