////////////////////////////////////////////////////////////////
// The 15 puzzle
// Written by Konstantin Makarychev
////////////////////////////////////////////////////////////////

//the numbers on the 4x4 board are stored in the following array.
var nArray = new Array (16);

////////////////////////////////////////////////////////////////
// Update (i) updates the value of the cell number i in the 
// html-table
////////////////////////////////////////////////////////////////
function Update (i)
{
   //find the cell html-element with index i
   var cell = document.getElementById ("f"+i);
   if (cell != null)
   {
      //update the value and set focus
      cell.innerHTML = (nArray[i] != 16) ? nArray[i] : "&nbsp;";
      cell.focus ();
   }
}

////////////////////////////////////////////////////////////////
// Swap (i, j) moves the number from the cell i to the cell j
//   if this is possible, return true; otherwise, false
////////////////////////////////////////////////////////////////
function Swap (i, j)
{
   if ((j >= 0) && (j < 16) && //check if j is a valid index
       nArray[j] == 16)        //check if the cell is empty
   {
      //swap the cells and update the values in the html-table
      nArray[j] = nArray[i];
      nArray[i] = 16;
      
      Update (i);
      Update (j);
      
      return (true);
   }
   else
   {
      return false;
   }
}

//////////////////////////////////////////////////////////////// 
// Move (i) moves the number in the cell i to an adjacent empty
// cell, if such a cell exists
//////////////////////////////////////////////////////////////// 
function Move (i)
{
   // try to move the number to all adjacent cells
   if (Swap (i, i + 1) ||
       Swap (i, i - 1) ||
       Swap (i, i + 4) ||
       Swap (i, i - 4))
   {
      return; //do nothing; we are already done!
   }    
}

//////////////////////////////////////////////////////////////// 
// Init ()  initializes the array of cells; all numbers are in
// the correct order except for the numbers 14 and 15
//////////////////////////////////////////////////////////////// 
function Init ()
{

   var i = 0;
   for (i = 0; i < 16; i++)
   {
      nArray[i] = i + 1;
   }
      
   nArray[14] = 14;
   nArray[13] = 15;
}

Init ();   

