Conway’s Game of Life Code

<html>
<head>
<title>
Conway’s Game of Life
</title>
</head>
<body>

<canvas id=”canvas” width=”600″ height=”600″></canvas>
<script type=”text/javascript”>

var canvas = document.getElementById(“canvas”);
var ctx = canvas.getContext(“2d”);

ctx.canvas.width = window.innerWidth – 20;
ctx.canvas.height = window.innerHeight – 20;

var tileSize = 10;

var grid = [];
for(i=0;i<Math.floor(canvas.width/tileSize)+2;i++){
grid.push([]);
}
for(i=0;i<grid.length;i++){
for(j=0;j<Math.floor(canvas.height/tileSize)+2;j++){
if(Math.random()<0.5){
grid[i].push(0);
}
else{
grid[i].push(1);
}
}
}

var nextGrid = [];
for(i=0;i<Math.floor(canvas.width/tileSize)+2;i++){
nextGrid.push([]);
}
for(i=0;i<nextGrid.length;i++){
for(j=0;j<Math.floor(canvas.height/tileSize)+2;j++){
nextGrid[i].push(0);
}
}

function neighborCount(a,b){

return(grid[a-1][b-1]+grid[a-1][b]+grid[a-1][b+1]+grid[a][b-1]+grid[a][b+1]+grid[a+1][b-1]+grid[a+1][b]+grid[a+1][b+1]);

}

function drawScreen(){

for(i=1;i<grid.length-2;i++){

for(j=1;j<grid[i].length-2;j++){

if(neighborCount(i,j)>3||neighborCount(i,j)<2){
nextGrid[i][j] = 0;
}
if(neighborCount(i,j)==3){
nextGrid[i][j] = 1;
}

}

}
for(y=0;y<nextGrid.length;y++){
for(z=0;z<nextGrid[y].length;z++){
grid[y][z] = nextGrid[y][z];
}
}

for(i=1;i<grid.length-1;i++){

for(j=1;j<grid[i].length-1;j++){

ctx.beginPath();
ctx.fillStyle = “rgba(“+(255-grid[i][j]*255)+”,”+(255-grid[i][j]*255)+”,”+(255-grid[i][j]*255)+”,1)”;

ctx.fillRect((i-1)*tileSize,(j-1)*tileSize,tileSize,tileSize);
ctx.fill();

}

}

}

setInterval(drawScreen,100);

</script>

</body>
</html>