// Pisolo ringrazia  Carlo "Sauron" Pelliccia
var matrice = new Array();
matrice[1] = new Array();
matrice[2] = new Array();
matrice[3] = new Array();
var ok = true;

for (r=1;r<=3;r++)
  for (c=1;c<=3;c++) 
    matrice[r][c] = '#';

function tris(id) {
  for (k=1;k<=3;k++)
   for (h=1;h<=3;h++) 
    if (matrice[k][h]==id) {
      if (matrice[1][h]==id && matrice[2][h]==id && matrice[3][h]==id) return true;
      if (h==1 && matrice[k][2]==id && matrice[k][3]==id) return true;
      if (k==2 && h==2 && matrice[1][1]==id && matrice[3][3]==id) return true;
      if (k==2 && h==2 && matrice[1][3]==id && matrice[3][1]==id) return true;     
    }
  return false;
}

function clic(i,j) {
  if (!ok) return;
  if (matrice[i][j]!='#') return;
  matrice[i][j] = 'x';
  eval('document.m'+i+j).src = 'x.gif';
  if (tris('x')) {
    alert('Sei proprio bravo, hai vinto!');
    if (confirm('Altra partitina?')) location.reload();
    ok = false;
    return;
  }
  ok = false;
  var id = setTimeout('computer()',1000);
}

function computer() {
  var r = 0;
  var c = 0;

  // mossa vincente
  for (x=1;x<=3;x++) 
   for (y=1;y<=3;y++) 
    if (matrice[y][x]=='#') {
      matrice[y][x] = 'o';
      if (tris('o')) {
        r = y;
        c = x;
      }
      matrice[y][x] = '#';
    }

  // mossa bloccante
  if (r==0) {
  for (x=1;x<=3;x++)
   for (y=1;y<=3;y++)
    if (matrice[y][x]=='#') {
      matrice[y][x] = 'x';
      if (tris('x')) {
        var r = y;
        var c = x;
      }
      matrice[y][x] = '#';
    }
  }

  // mossa casuale
  if (r==0) {
   var pos = new Array();
   var t = 0;
   for (x=1;x<=3;x++)
    for (y=1;y<=3;y++)
     if (matrice[y][x]=='#') pos[t++] = '' + y + x;
   if (t==0) {
     alert('Partita finita pari');
     if (confirm('Altra partitina?')) location.reload();
     ok = false;
     return;
   }
   var cas = Math.floor(Math.random()*t);
   r = parseInt(pos[cas].charAt(0));
   c = parseInt(pos[cas].charAt(1));
  }

  matrice[r][c] = 'o';
  eval('document.m'+r+c).src = 'o.gif';
  if (tris('o')) {
     alert('Sei proprio una schiappa, hai perso');
     if (confirm('Vuoi riprovarci?')) location.reload();
     ok = false;
     return;
  }
  ok = true;
}
