Conway's Game of Life as a data uri

A while ago I came across a post on Hacker News that showed a version of the game "snake" that someone had built to work from a data uri. When I initially saw it I became obsessed because I though it was pretty neat (and because there wasn't much code). Fast forward a few months and I came up with the idea to attempt the same sort of thing except with Conway's Game of Life.

It's implemented in javascript using the canvas element and requestAnimationFrame (instead of setTimeout or setInterval). Also instead of using a 2d array I've used a 1d array (no lazy dead edges though, it still wraps).

Here's the copy and paste version:
data:text/html,<script>var r=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame;document.addEventListener('DOMContentLoaded',function(){for(var e,f,b=256,c=256,d=[],g=2,h=null,i=function(a){(!h||a-h>41.7)&&(f.setTransform(1,0,0,1,0,0),f.fillStyle='#333',f.fillRect(0,0,e.width,e.height),f.scale(g,g),f.fillStyle='#0c0',d=d.map(function(a,c,d){var e=0,g=(c+d.length-b)%d.length,h=(c+b)%d.length,i=c%b?0:b,j=c%b==b-1?b:0;return a&&f.fillRect(c%b,Math.floor(c/b),1,1),e+=d[g-1+i],e+=d[g],e+=d[g+1-j],e+=d[c-1+i],e+=d[c+1-j],e+=d[h-1+i],e+=d[h],e+=d[h+1-j],1==a&&e>1&&4>e||0==a&&3==e?1:0}),h=a),r(i)},j=0;b*c>j;j++)d.push(Math.floor(2*Math.random()));e=document.createElement('canvas'),document.body.appendChild(e),e.width=b*g,e.height=c*g,f=e.getContext('2d'),r(i)});</script>

And a quick link for the lazy...

A more readable version is available here.

Tested working in IE10 and the latest versions of Chrome and Firefox.

Comments

  1. Very neat. Nice touch setting height/width and calculating the offsets between rows/1D mapping.

    I changed b (width) = 1024, c (height) = 512 and g (scale) = 1.0 and it's quite interesting to watch.

    ReplyDelete

Post a Comment

Popular posts from this blog

Brainfuck interpreter in javascript