Game Of Life
by Nathan Piper
HTML
<canvas id="game" width="2500" height="2500"></canvas>
<canvas id="game2" width="500" height="500"></canvas>
CSS
canvas {
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
width: 500px;
position: absolute;
top: 0;
left: 0;
}
JavaScript
function canvas(id) {
return document.getElementById(id).getContext('2d');
}
var game = canvas("game");
var map = [];
var map2 = [];
var mapSize = 250;
var round = 0;
var squareSize = 10;
var aliveCells = 0;
function square(x, y, alive){
this.x = x*squareSize;
this.y = y*squareSize;
this.size = squareSize;
this.alive = alive;
this.neighbors = [];
this.aliveNeighbors;
this.render = function() {
if(this.alive){
game.fillRect(this.x, this.y, this.size, this.size)
}
}
this.getNeighbors = function() {
this.currentSquare;
this.aliveNeighbors = 0;
var i;
var k;
var j;
var l;
if(this.y == 0){
i = 0;
} else {
i = 1;
}
if(this.y == mapSize*this.size-this.size){
k = -1;
} else {
k = -2;
}
if(this.x == 0){
j = 0;
} else {
j = 1
}
if(this.x == mapSize*this.size-this.size){
l = -1;
} else {
l = -2;
}
for(var ii = i; ii > k; ii--){
for(var jj = j; jj > l; jj--){
this.currentSquare = map2[(this.y/this.size)-ii][(this.x/this.size)-jj];
if(this.currentSquare.alive == true){
this.aliveNeighbors++;
}
}
}
}
this.update = function(){
this.getNeighbors();
if (this.aliveNeighbors == 3 && !this.alive){
this.alive = true;
}
else if (this.alive && (this.aliveNeighbors > 3 || this.aliveNeighbors < 2)){
this.alive = false;
}
else {
this.alive = this.alive;
}
}
}
function setMap() {
var alive;
for(var i=0; i < mapSize; i++){
map.push( [] );
map2.push( [] );
for(var j=0; j < mapSize; j++){
if(Math.round(Math.random()*20) < 2){
alive = true;
} else {
alive = false;
}
map[i].push(new square(j,i,alive));
map2[i].push(new square(j,i,alive));
}
}
}
function main() {
game.clearRect(0,0,squareSize*mapSize,squareSize*mapSize);
map2 = map;
for(var i = 0; i <...