Skip to content

Instantly share code, notes, and snippets.

@jfhbrook
Created June 23, 2010 20:40
Show Gist options
  • Save jfhbrook/450513 to your computer and use it in GitHub Desktop.
Save jfhbrook/450513 to your computer and use it in GitHub Desktop.
Same game of life.
<html>
<head>
<title>Like The Sims, but without the spiralling depression.</title>
<script src="raphael.js" type="text/javascript" charset="utf-8"></script>
</head>
<body style="background-color:#333333;">
<script>
//Trying to implement Conway's Game of Life in js.
//I'm pretty dumb with js though.
//Requires raphael.js.
//I'd love to be able to get the screen size and just fill it.
//Maybe later.
var width=200;
var height=200;
//raphael comes into the picture.
var game = Raphael(0,0,width,height);
//trying to initialize a 2-d array
//No telling if this is good style or not
var state_now = [];
for (i=0;i<width;i++) {
state_now[i] = [];
for (j=0;j<height;j++) {
//This is so nbrs() works propers
state_now[i][j]=0;
}
}
//also need a state_later.
var state_later = state_now;
//drawing a glider the stupid way.
//there must be a better way!
//I'll find it later.
state_now[50][50]=1;
state_now[50][51]=1;
state_now[50][49]=1;
//counts neighbors
function nbrs(game_now,x,y) {
return game_now[x+1][y]+
game_now[x+1][y+1]+
game_now[x][y+1]+
game_now[x-1][y+1]+
game_now[x-1][y]+
game_now[x-1][y-1]+
game_now[x][y-1]+
game_now[x+1][y-1];
}
function update() {
game.clear()
//I think there's some fishy stuff going on with state_now & state_later.
//The board updates as though there are not separate tallys. :(
state_later=state_now;
for (x=1;x<width-1;x++) {
for (y=1;y<height-1;y++) {
if (state_now[x][y]) {
//draw the rectangle
game.rect(2*x,2*y,2,2).attr({fill: "#0f0", "stroke-width": 0, stroke: "#fff"});
//death-logic
if (nbrs(state_now,x,y)!=2 && nbrs(state_now,x,y)!=3) {state_later[x][y]=0; }
} else {
//birth-logic
if (nbrs(state_now,x,y)==3) {state_later[x][y]=1; }
}
}
}
state_now=state_later;
}
//main loop
setInterval(function(){ update(); },800);
</script>
</body>
</html>
@jfhbrook
Copy link
Author

Renders now, but doesn't keep state_now and state_later separate like I'd expect. I'm almost certain this is due to a javascript idiosyncracy combined with my own dumbness.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment