
 /*
 
 File:Puzzler.js
 
 Abstract: JavaScript properties for the Puzzler sample
 
 Version: <1.0>
 
 Disclaimer: IMPORTANT:  This Apple software is supplied to you by 
 Apple Inc. ("Apple") in consideration of your agreement to the
 following terms, and your use, installation, modification or
 redistribution of this Apple software constitutes acceptance of these
 terms.  If you do not agree with these terms, please do not use,
 install, modify or redistribute this Apple software.
 
 In consideration of your agreement to abide by the following terms, and
 subject to these terms, Apple grants you a personal, non-exclusive
 license, under Apple's copyrights in this original Apple software (the
 "Apple Software"), to use, reproduce, modify and redistribute the Apple
 Software, with or without modifications, in source and/or binary forms;
 provided that if you redistribute the Apple Software in its entirety and
 without modifications, you must retain this notice and the following
 text and disclaimers in all such redistributions of the Apple Software. 
 Neither the name, trademarks, service marks or logos of Apple Inc. 
 may be used to endorse or promote products derived from the Apple
 Software without specific prior written permission from Apple.  Except
 as expressly stated in this notice, no other rights or licenses, express
 or implied, are granted by Apple herein, including but not limited to
 any patent rights that may be infringed by your derivative works or by
 other works in which the Apple Software may be incorporated.
 
 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
 MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
 THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
 FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
 OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
 
 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
 MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
 AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
 STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 
 Copyright (C) 2007 Apple Inc. All Rights Reserved.
 
 */ 

/********************
Modified November 2007 by Beth Katz
- making numberOfBallChoices a variable instead of hard-coded 5
- made prefix of files a variable so that it can be easily changed
- added score field and calculation
- added a button to make it easier or harder toggling between 4 and 5
  ball choices
*********************/

 
//Puzzler draws a grid with 7 columns and 6 rows
var numberOfColumns = 7;
var numberOfRows = 6;

//The grid array contains numbers ranging from 1 to numberOfBallChoices, 
//which represent the different available ball images.
//1 = yellow ball
//2 = light blue ball
//3 = green ball
//4 = dark blue ball 
//5 = red ball

var grid = [];
var numberOfBallChoices = 5;
var lessVariety = 4;
var moreVariety = 5;
var filePrefix = "ball-";

//The selected array contains either true or false. True indicates that 
//the current cell is selected (a user clicked on the ball)
var selected = [];

//The dirty array contains either true or false values. True indicates 
//that the current cell contains a grey ball
var dirty = [];
var allowClicks = true;

//Score rewards larger blocks being removed
var score = 0;

//Remove all the DOM (document object model) elements of the grid
function removeAllChildren (parent)
{
    while (parent.hasChildNodes()) 
    {
        parent.removeChild(parent.firstChild);
    }
}

// resets score to zero
function resetScore( )
{
    score = 0;
    document.score.field.value = score;
}

//adds amount to score
function updateScore(amount)
{
    score += amount;
    document.score.field.value = score;
}

//Initialize or Reinitialize the grid. Remove all balls on the grid.
function resetGrid()
{
    grid = new Array(numberOfColumns);
    selected = new Array(numberOfColumns);
    dirty = new Array(numberOfColumns);
    
    for( var column=0; column< numberOfColumns; column++ )
    {
          grid[column] = new Array(numberOfRows);
          selected[column] = new Array(numberOfRows);
          dirty[column] = new Array(numberOfRows);
          
          for( var row=0; row < numberOfRows; row++ )
          {
              //Generate numbers ranging from 1 to numberOfBallChoices randomly. 
              var ballNumber= 1 + 
                  Math.floor(Math.random() * numberOfBallChoices);
              grid[column][row] = ballNumber;
              
              //No ball is selected initially
              selected[column][row] = false;
              
              //The grid does not contain any grey balls initially
              dirty[column][row] = false;
          }
    }
    resetScore();
}


//Set up the game on the page using DOM elements
function setup()
{
    resetGrid();
    resetScore();
    
    var gridTable = document.getElementById('grid');
    //Remove any current ball on the grid 
    removeAllChildren(gridTable);
    
    //Loop thru the grid, Create numberOfRows rows, add them to the grid.
    //For each row, generate numberOfColumns columns that contain each an image
    for( var row=0; row < numberOfRows; row++ ) 
    {
        //Create a row 
        var gridRow = document.createElement('tr'); 
        
        //Create columns for the row generated above
        for( var column=0; column< numberOfColumns; column++ )
        {
              //Create a new column 
              var gridColumn = document.createElement('td');  
              
              //Create a new image 
              var img = document.createElement('img');        
              
              //Set the image attributes
              img.setAttribute("onclick", "click("+column+","+row+")");
              img.setAttribute("src", filePrefix+grid[column][row]+".png");
              img.setAttribute("id", column+"_"+row);
              img.setAttribute("numberOfColumns", 32);
              img.setAttribute("numberOfRows", 32);
              img.setAttribute("width", 40);
              img.setAttribute("height", 40);
              
              //Append the new image to this column 
              gridColumn.appendChild(img); 
              
              //Add this column to the curent row 
              gridRow.appendChild(gridColumn);          
        }
        //Add this row to the grid 
        gridTable.appendChild(gridRow);   
    }
}


// changes number of balls easier or harder
function changeDifficulty()
{
   if (numberOfBallChoices == lessVariety) {
      numberOfBallChoices = moreVariety;
      document.score.difficulty.value = "Easier";
   } else {
      numberOfBallChoices = lessVariety;
      document.score.difficulty.value = "Harder";
   }
   setup( );
}

//Update image at position represented by (column,row)
function updateCell(column,row)
{
    var newSrc;
    
    //Append a grey ball at the position given by (column, row) 
    //if the current ball is selected
    if( selected[column][row] )
    {
        newSrc = filePrefix+"sel.png";
    }    
    else 
    {
        //Append a ball at the position given by (column, row) 
        //if the current ball is not selected
        //The color of the ball is determined by grid[column][row], 
        //which returns a number ranging from 1 to 5
        newSrc = filePrefix+grid[column][row]+".png"
    }        
    document.images[column+"_"+row].src = newSrc;
    }


//Update all images on the grid 
function updateAllCells()
{
     //Loop thru all rows and columns, then update each image at position 
     //specified by column and row
    for( var row=0; row< numberOfRows; row++ ) 
    {
        for( var column= 0; column< numberOfColumns; column++ ) 
        {
            updateCell(column,row);
        }
    }
}


//Check the dirty array for any true value, if true is found at a position(column,row), update the associated cell
function updateAllDirtyCells()
{
    for( var row=0; row< numberOfRows; row++ )
    {
        for( var column=0; column< numberOfColumns; column++ )
        {
            if( dirty[column][row] ) 
            {
                //Place a grey ball at this position
                updateCell(column, row);
                dirty[column][row]= false;
            }
        }
    }
}


//Remove all selected balls on the grid 
function removeSelectedCells()
{
    var numRemoved = 0;

    for( var row=0; row< numberOfRows; row++ ) 
    {
        for( var column=0; column< numberOfColumns; column++ )
        {
            if( selected[column][row] ) 
            {
                //Remove the ball at this position
                grid[column][row] = 0;
                selected[column][row] = false;
                dirty[column][row] = true;
                numRemoved++;
            }
        }
    }
    updateScore(numRemoved*numRemoved);
}


//Look for empty cells along the vertical axis on the grid 
function fallDown()
{
    var fallTo,foundGap;
    for( var column= numberOfColumns-1; column >= 0; column-- ) 
    {
        //Indicate whether a ball at a given position is grey 
        foundGap = false;
        for( var row= numberOfRows-1; row >= 0; row-- )
        {
             //Check if cell at position(column,row) is empty
            if( grid[column][row] == 0 ) 
            {
                if( ! foundGap )
                {
                    //Get position (along the vertical axis) of the cell 
                    //that contains a grey ball 
                    fallTo = row;
                    foundGap = true;
                }
            }
            else 
            { 
                 //If cell contains a ball, check if the ball is grey 
                if( foundGap ) 
                {
                    //Insert a new ball at this position  
                    grid[column][fallTo] = grid[column][row];
                    grid[column][row] = 0;
                    dirty[column][fallTo] = true;
                    dirty[column][row] = true;
                    fallTo -= 1;
                }
            }
        }
    }
}


//Look for empty cells along the horizontal axis on the grid 
function fallRight()
{
    var fallTo,foundGap;
    for( var row= numberOfRows-1; row >= 0; row-- )
    {
        //Indicate whether a ball at a given position is grey 
        foundGap = false;
        for( var column= numberOfColumns-1; column >= 0; column-- ) 
        {
            //Check if cell at position(column,row) is empty
            if( grid[column][row] == 0 ) 
            {
                if( ! foundGap ) 
                { 
                    // Get position (along the horizontal axis) of the cell 
                    // that contains a grey ball
                    fallTo = column;
                    foundGap = true;
                }
            }
            else 
            { 
                //Check if cell at position(column,row) contains a grey ball
                if( foundGap) 
                {
                    //Insert a new ball at this position  
                    grid[fallTo][row] = grid[column][row];
                    grid[column][row] = 0;
                    dirty[fallTo][row] = true;
                    dirty[column][row] = true;
                    fallTo -= 1;
                }
            }
        }
    }
}


//Unselect all balls on the grid 
function deselectAllCells()
{
    for( var row= 0; row < numberOfRows; row++ ) 
    {
        for( var column= 0; column < numberOfColumns; column++ ) 
        {
            //Remove position from the selected array 
            if( selected[column][row] ) 
            {
                selected[column][row] = false;
                
                //Set value to true, so grey ball can be added at that position
                dirty[column][row] = true;
            }
        }
    }
}


//Determines whether each of the 4 neighbors(top,bottom,left, and right) of a
//cell is equal to that current cell
function cellHasIdenticalNeighbour(column, row)
{
    var cell = grid[column][row];
    if( ( column+1 < numberOfColumns  && cell == grid[column+1][row] )
      || ( column-1 >= 0     && cell == grid[column-1][row] )
      || ( row+1 < numberOfRows && cell == grid[column][row+1] )
      || ( row-1 >= 0     && cell == grid[column][row-1] ) ) 
    {
        return true;
    }
    else 
    {
        return false;
    }
}


//Select all contiguous cells of the same color
function selectCellAndContiguousCells(cell, column, row)
{
    if( column >= 0 && column < numberOfColumns && row >= 0 && row < numberOfRows ) 
    {
        if( cell == grid[column][row] && ! selected[column][row] ) 
        {
            selected[column][row] = true;
            dirty[column][row] = true;
            selectCellAndContiguousCells( cell, column+1, row);
            selectCellAndContiguousCells( cell, column-1, row );
            selectCellAndContiguousCells( cell, column, row+1 );
            selectCellAndContiguousCells( cell, column, row-1 );
        }
    }
}


//Update cells along the horizontal axis
function fallRightAndAllowClicks()
{
    fallRight();
    updateAllDirtyCells();
    allowClicks = true;
}


//Update all cells on the grid
function fallDownThenFallRightAndAllowClicks()
{
    fallDown();
    updateAllDirtyCells();
    fallRightAndAllowClicks();
}


//Handle clicks on the grid 
function click(column, row)
{
    if( ! allowClicks )
    {
        return;
    } 
    
    // if a given cell is selected
    if( selected[column][row] )
    {
        // remove all selected cells
        removeSelectedCells();
        
        //Check the grid for selected values, then add grey balls at their positions
        updateAllDirtyCells();
        
        allowClicks = false;
        setTimeout("fallDownThenFallRightAndAllowClicks();", 100);
    }
    else if( grid[column][row] != 0 )
    {   
        //If a given cell is not selected, but contains a ball, deselect all cells
        deselectAllCells();
        
        //Check whether there is an adjacent cell of the same color
        if( cellHasIdenticalNeighbour(column,row ))
        {
            //select all contiguous cells of the same color
            selectCellAndContiguousCells( grid[column][row], column, row);
        } 
        updateAllDirtyCells();
    }
}

