Game of Life

<script>
 var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
 document.addEventListener('DOMContentLoaded', function(event){
  var width = 256, height = 256, state = [], canvas, context , scale = 2, timer = null, generation = 0, livecells = 0, tick = function(frametime){
   if(!timer || frametime - timer > 41.7){
    context.setTransform(1, 0, 0, 1, 0, 0);
    context.fillStyle = '#333';
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.scale(scale,scale);
    context.fillStyle = '#0c0';
    generation++;
    livecells = 0;
    state = state.map(function(value, index, array){
     var l = 0, r1 = (index + array.length - width) % array.length, r2 = (index + width) % array.length, c1 = index % width ? 0 : width, c2 = index % width == width - 1 ? width : 0;
     value && context.fillRect(index % width, Math.floor(index / width), 1, 1);
     l += array[r1 - 1 + c1]; 
     l += array[r1]; 
     l += array[r1 + 1 - c2];
     l += array[index - 1 + c1];
     l += array[index + 1 - c2];
     l += array[r2 - 1 + c1];
     l += array[r2];
     l += array[r2 + 1 - c2];
     if((value == 1 && l > 1 && l < 4) || (value == 0 && l == 3)){
      livecells++;
      return 1;
     }
     return 0;
    });
    timer = frametime;
   }
   requestAnimationFrame(tick);
  };
  for(var i = 0; i < width * height; i++)
   state.push(Math.floor(Math.random() * 2));
  canvas = document.createElement('canvas');
  document.body.appendChild(canvas);
  canvas.width = width * scale;
  canvas.height = height * scale;
  context = canvas.getContext('2d');
  requestAnimationFrame(tick);
 });
</script>

Popular posts from this blog

Conway's Game of Life as a data uri

Brainfuck interpreter in javascript