Skip to content

Instantly share code, notes, and snippets.

@fffaraz
Created July 4, 2017 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fffaraz/e8cc547a6d99cef91e219d2774025651 to your computer and use it in GitHub Desktop.
Save fffaraz/e8cc547a6d99cef91e219d2774025651 to your computer and use it in GitHub Desktop.
Conway's Game of Life
<!-- saved from http://www.cc.gatech.edu/grads/b/bhroleno/ -->
<html>
<title>Conway's Game of Life</title>
<head>
<style type="text/css">
body{ font-family: serif; font-size:1.00em; text-align: center; margin: 10px 0 30px 0; virtical-align: middle }
</style>
<script type="text/javascript">
var cells = new Array(40);
var tmpCells = new Array(40);
var canvas;
var ctx;
var speed = 100;
var liveProb = 0.1;
function drawCells(){
updateCells();
for(var x=0;x<40;x++){
for(var y=0;y<17;y++){
if(cells[x][y])
ctx.fillStyle = "rgb(255,255,255)";
else
ctx.fillStyle = "rgb(0,0,0)";
ctx.fillRect((x*20),(y*20),20,20);
}
}
setTimeout('drawCells()',speed);
}
function aliveNeighbors(x,y){
var neighbors=0;
if(x>0){
if(y>0 && cells[x-1][y-1]) neighbors++;
if(cells[x-1][y]) neighbors++;
if(y<16 && cells[x-1][y+1]) neighbors++;
}
if(y>0 && cells[x][y-1]) neighbors++;
if(y<16 && cells[x][y+1]) neighbors++;
if(x<39){
if(y>0 && cells[x+1][y-1]) neighbors++;
if(cells[x+1][y]) neighbors++;
if(y<16 && cells[x+1][y+1]) neighbors++;
}
return neighbors;
}
function updateCells(){
for(var x=0;x<40;x++){
for(var y=0;y<17;y++){
var neighbors = aliveNeighbors(x,y);
if(neighbors < 2 || neighbors > 3)
tmpCells[x][y] = false;
else if(cells[x][y] || neighbors == 3)
tmpCells[x][y] = true;
}
}
var foo = cells;
cells = tmpCells;
tmpCells = foo;
}
function ca(){
for(var x=0; x<40;x++){
cells[x] = new Array(17);
tmpCells[x] = new Array(17);
for(var y=0; y<17; y++){
if(Math.random()<liveProb)
cells[x][y] = true;
else
cells[x][y] = false;
}
}
canvas = document.getElementById('banner');
ctx = canvas.getContext('2d');
drawCells();
}
</script>
</head>
<body onload="ca();">
<canvas id="banner" width="800" height="340"></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment