HTML and CSS Reference
In-Depth Information
To randomize the puzzle pieces, we first need to set up an array named newBoard that will
hold the randomized puzzle pieces. newBoard will be what we call a parallel array . Its pur-
pose is to become the original array—but randomized. We then create a local cols variable
and initialize it to the length of the board array that was passed in to the function, and we
create a local rows variable, initialized to the length of the first column— board[0] —in the
array. This works because all of our rows and columns are the same length, so the number of
rows in the first column is the same as all the others. We now have the building blocks re-
quired to randomize the pieces:
function randomizeBoard ( board ) {
var newBoard = new
new Array ();
var cols = board . length ;
var rows = board [ 0 ]. length
Nextweloopthrougheverycolumnandrow,randomlychoosingapiecefromthe board array
and moving it into newBoard :
for ( var
var i = 0 ; i < cols ; i ++ ) {
We use two nested for:next loops here, once again.
Every time we come to an iteration of the outer nested loop, we create a new array that we
will fill up in the second nested loop. Then we drop into that nested loop. The found variable
will be set to true when we have found a random location to place the piece in the newBoard
array. The rndRow and rndCol variables hold the random values that we will create to try and
find a random location for the puzzle pieces:
newBoard [ i ] = new
new Array ();
for ( var
var j = 0 ; j < rows ; j ++ ) {
var found = false
false ;
var rndCol = 0 ;
var rndRow = 0 ;
Now we need to find a location in newBoard in which to put the puzzle piece from the board
array. We use a while() loop that continues to iterate as long as the found variable is false .
To find a piece to move, we randomly choose a row and column and then use them to see
whether that space ( board[rndCol][rndRow] ) is set to false . If it is not false , we have
found a piece to move to the newBoard array. We then set found equal to true so that we can
get out of the while() loop and move to the next space in newBoard that we need to fill:
Search WWH ::

Custom Search