Game of Life by Ninjihaku

HTML5 Game of Life

by Dr. Ninjimonimous

HTML

<body>
<center><canvas id="myCanvas" width="500" height="500" style="border: 1px solid #000;"></canvas></center>
<center><input type="button" value="Start" id="start"/><input type="button" value="Clear" id="clear"/></center><br/>
<center>Grid size: <input type="range" id="csz" min="1" max="100"/> <label id="zoom">5</label></center><br/>
<center>Timer: <input type="range" id="tmr" min="20" max="2000" interval="100"/> <label id="tmrz">100</label></center>
<center><form>
<input type="checkbox" id="sgrd" checked>Show grid<br>
</form></center>
</body>

JavaScript

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var dimensions = 500;
var ced = 10;
var ls = Math.ceil(dimensions / ced);
var squares = Math.pow(Math.ceil(dimensions / ced),2);
var cells = new Array(squares);
var first = true;
var simulating = false;
var times = 100;
var showgrid = true;

function createArray(length) {
    var arr = new Array(length || 0),
        i = length;

    if (arguments.length > 1) {
        var args = Array.prototype.slice.call(arguments, 1);
        while(i--) arr[length-1 - i] = createArray.apply(this, args);
    }

    return arr;
}

var cells = createArray(ls, ls);

function drawbackground()
{
	ctx.fillStyle = "#00343e";
	ctx.fillRect(0,0,dimensions,dimensions);
	ctx.strokeStyle = "#004c99";
  if(showgrid)
    for(var i = 1; i < ls; i++)
    {
      ctx.beginPath();
      ctx.moveTo(ced*i,0);
      ctx.lineTo(ced*i,dimensions);
      ctx.stroke();
      ctx.beginPath();
      ctx.moveTo(0,ced*i);
      ctx.lineTo(dimensions, ced*i);
      ctx.stroke();
    }
	
}

function drawcell(posx, posy)
{
	ctx.fillStyle = "#009592";
	ctx.strokeStyle = "#007cb9";
	ctx.fillRect(posx*ced,posy*ced,ced,ced);
	ctx.strokeRect(posx*ced,posy*ced,ced,ced);
}

function drawcells()
{
for(var y = 0; y < ls; y++)
	for(var x = 0; x < ls; x++)
		if(cells[x][y]>0)
			drawcell(x,y);
}

function modcell(posx, posy, value)
{
	if(posx >= ls || posy >= ls)
  	return;
	cells[posx][posy] = value;
}

function clearcells()
{
for(var y = 0; y < ls; y++)
	for(var x = 0; x < ls; x++)
		cells[x][y] = 0;
    drawbackground();
    drawcells(); //Theorically not necessary, but proves it is clear indeed.
}

function checkPopulation(px, py)
{
		var result = 0;
		
		//console.log("Population check: " + px + " " + py + ":" + cells[px][py]);
		
		if(px < 0 || py < 0 || px >= ls || py >= ls)
		{
			console.log("Warning: cells["+px+"]["+py+"] out of range");
			return 0;
		}
			
		if(cells[px][py] == null)
		{
			console.log("Warning: cells["+px+"]["+py+"]...