Conway Game of Life

by konijn_gmail_com

JavaScript

/* It is currently working ok with a canvas ov width 300, height 150 and cellsize of 7 (RECH and RECW) and offset between cells of 1 (OFFS). */

var view = 
{
    init : function()
    {
      var canvas = document.createElement("canvas");
      view.ctx = canvas.getContext("2d");
      canvas.width = 300;
      canvas.height = 150;
      document.body.appendChild(canvas);    
      view.clear();
    },
    clear : function()
    {
      view.ctx.fillStyle = "rgb(0, 0, 0)";
      view.ctx.fillRect(0,0,300,150);        
    }
};

/* Cell, should know its' status, location and neighbours 
   Spartan notation : c(olumn) and r(ow)                  */
function Cell( c, r, neighbours )
{
  this.c = c;
  this.r = r;
  this.alive = false;
  this.neighbours = neighbours || [];
}

/* it should also be able to determine whether it should live */
Cell.prototype = 
{
  nextStatus : function()
  {
    var livingNeighbours = 0 , 
        neighbourCount = this.neighbours.length, i;
    for( i = 0 ; i < neighbourCount ; i++ )
      if( this.neigbours[i].alive )
        livingNeighbours++;
    if( this.alive && (this.neighbours < 2 || this.neighbours > 3)  )
      return this.DEAD;
    if( !this.alive && this.neighbours === 3 )
      return this.ALIVE;
    return this.NO_CHANGE;
  },
  NO_CHANGE : 0,      
  DEAD : 1,  
  ALIVE : 2    
};

var model = 
{
  size : { rows :  20 , columns : 40 },
  cellCount : -1,
  cells : [],
  neighbourVectors :   
  [
    { c : +1 , r : +1 },
    { c : +1 , r : +0 },
    { c : +1 , r : -1 },
    { c : -1 , r : +1 },
    { c : -1 , r : +0 },
    { c : -1 , r : -1 },
    { c : +0 , r : +1 },
    { c : +0 , r : -1 },      
  ],
  neighourVectorCount : 8,
  init : function()
  {
    var i, c, r, vectorIndex;
    /* Calc the cellCount*/
    model.cellCount = model.size.columns * model.size.rows;  
    /* Create the cells */
    for( c = 0 ; c < model.size.columns ; c++ )  
      for( r = 0 ; r < model.size.rows ; r++ )
        model.cells.push( new...