Created
November 16, 2014 07:23
-
-
Save auxiliary-character/a49f4e09461e731b2c6c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isAlive(state, x, y) { | |
var count=0; | |
for(var i=-1;i<=1;i++){ | |
for(var j=-1;j<=1;j++){ | |
if(!(j===0&&i===0)){ | |
var xIndex = (i+x+state.length)%(state.length); | |
var yIndex = (j+y+state[xIndex].length)%(state[xIndex].length); | |
if(state[xIndex][yIndex]){ | |
count++; | |
} | |
} | |
} | |
} | |
if(state[x][y]){ | |
if(count<2){ | |
return false; | |
} | |
else if(count<4){ | |
return true; | |
} | |
else{ | |
return false; | |
} | |
} | |
else{ | |
if(count===3){ | |
return true; | |
} | |
else{ | |
return false; | |
} | |
} | |
} | |
function calcState(state){ | |
var newState=[] | |
for(var x=0;x<state.length;x++){ | |
newState[x]=[] | |
for(var y=0;y<state[x].length;y++){ | |
newState[x][y]=isAlive(state,x,y); | |
} | |
} | |
return newState; | |
} | |
function init(evnt){ | |
var o=evnt.target; | |
var doc=o.ownerDocument; | |
var root=doc.documentElement; | |
var width=parseInt(root.getAttribute("width")); | |
var height=parseInt(root.getAttribute("height")); | |
var xcells=50; | |
var ycells=50; | |
var state=[]; | |
var cells=[]; | |
function rectangle(x,y,width,height){ | |
var s = doc.createElementNS("http://www.w3.org/2000/svg","rect"); | |
s.setAttribute("x",x); | |
s.setAttribute("y",y); | |
s.setAttribute("width",width); | |
s.setAttribute("height",height); | |
s.setAttribute("stroke","#000"); | |
s.setAttribute("fill","none"); | |
return s; | |
} | |
for(x=0;x<xcells;x++){ | |
state[x]=[]; | |
cells[x]=[]; | |
for(y=0;y<ycells;y++){ | |
cells[x][y]=rectangle((x/xcells)*width, | |
(y/ycells)*height, | |
width/xcells, | |
height/ycells); | |
if(Math.random()>0.5){ | |
state[x][y]=true; | |
cells[x][y].setAttribute("fill","#000") | |
} | |
else{ | |
state[x][y]=false; | |
} | |
} | |
} | |
function loop(){ | |
state = calcState(state); | |
for(x=0;x<xcells;x++){ | |
for(y=0;y<ycells;y++){ | |
if(state[x][y]){ | |
cells[x][y].setAttribute("fill","#000"); | |
} | |
else{ | |
cells[x][y].setAttribute("fill","none"); | |
} | |
root.appendChild(cells[x][y]); | |
} | |
} | |
window.setTimeout(loop,15); | |
} | |
window.setTimeout(loop,0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment