canvas-kit-1
by rajeshpillai
HTML
<input type="button" id="btnGenerate" value="Generate Life"/>
<br>
<canvas id ="canbg" width="400" height="400">Please go get a better browser </canvas>
CSS
#canbg {
background-color: white;
}
JavaScript
var Cell = function (x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.isAlive = false;
this.draw = function (ctx) {
ctx.save();
ctx.strokeStyle = "black";
if (this.isAlive === true) {
ctx.fillStyle = "green";
}
else {
ctx.fillStyle = "white";
}
ctx.fillRect(this.x, this.y, this.width, this.height);
ctx.rect(this.x,this.y, this.width, this.height);
ctx.stroke();
ctx.restore();
};
};
var GameOfLife = function (can) {
var self = this;
this.canvas = can;
this.ctx = this.canvas.getContext('2d');
this.width = this.canvas.width;
this.height = this.canvas.height;
this.grid = new Grid(this.width, this.height);
$('#btnGenerate').on('click', function (e) {
self.beginLife();
self.draw();
});
};
GameOfLife.prototype.beginLife = function () {
this.play();
};
GameOfLife.prototype.draw = function () {
this.grid.draw(this.ctx);
};
GameOfLife.prototype.play = function () {
var that = this;
that.prepareNextGen();
that.renderNextgen();
setTimeout(that.play.bind(that), 200);
that.draw();
};
GameOfLife.prototype.prepareNextGen = function () {
for(var y = 0; y < this.cellsY; y++) {
for(var x = 0; x < this.cellsX; x++)
{
var cell = this.grid.getCell(x, y);
var neighbours = this.grid.getLiveNeighboursCount(x,y);
console.log('Neighbours: ' + neighbours);
cell.living = false;
if (this.grid.isCellAlive(x,y)) {
if (neighbours === 2 || neighbours === 3) {
cell.living = true;
}
}
else if (neighbours === 3){
cell.living = true;
}
}
}
};
...