var g_squares=[];
var g=10;
function setup() {
  var id=0;
  for (var row=0;row<g;row++) {
    document.write("<div class='row'>");
    for (var col=0;col<g;col++) {
      document.write("<div class='square' id='"+id+"' onClick='square_clicked(this);'></div>");
      id++;
    }
    document.write("</div>");
  }
  clear_grid();
}
function clear_grid() {
  for (var id=0;id<g*g;id++) g_squares[id]=0;
}
function draw() {
  for (var id=0;id<g*g;id++) {
    var el=document.getElementById(id);
    if (g_squares[id]==1) {
      el.style.backgroundColor='red';
    } else {
      el.style.backgroundColor='white';
    }
  }
}  
function rc2id(r,c) {
  return r*g+c;
}
function set(row,col) {
  var id=rc2id(row,col);
  g_squares[id]=1;
}
function neighbours(row,col) {
  var n=0;
  for (var r=row-1;r<row+2;r++) {
    for (var c=col-1;c<col+2;c++) {
      var id=rc2id(r,c);
      n+=g_squares[id];
    }
  }
  id=rc2id(row,col);
  n-=g_squares[id];
  return n;
}
function gen() {
  var temp=[];
  for (var id=0;id<g*g;id++) temp[id]=0;
  for (var row=1;row<g-1;row++) {
    for (var col=1;col<g-1;col++) {
      var n=neighbours(row,col);
      var id=rc2id(row,col);
      var v=g_squares[id];
      if (v==0) { // dead
        if (n==3) v=1;
      } else { // alive
        if (n<2) v=0;
        if (n>3) v=0;
      }
      temp[id]=v;
    }
  }
  for (var id=0;id<g*g;id++) g_squares[id]=temp[id];
}
function one_step() {
  gen();
  draw();
}
function glider() {
  set(1,2);
  set(2,3);
  set(3,1);
  set(3,2);
  set(3,3);
}
function demo() {
  clear_grid();
  glider();
  draw();
  setTimeout(demo1,1000,20);
}
function demo1(n) {
  if (n>0) {
    n--;
    one_step();
    setTimeout(demo1,150,n);
  }
}
