HTML and CSS Reference
In-Depth Information
finalCol
The final column-resting place of the piece when the puzzle is complete. We use
this value to figure out what part of the video cut out to make this piece.
finalRow
The final row-resting place of the piece when the puzzle is complete. We use this
value to figure out what part of the video cut out to make this piece.
selected
A Boolean that is initially set to false . We will use this to see whether we should
highlight a piece or switch two pieces when the user clicks a piece.
Notice that we use two nested for:next loops to fill the board array with these objects.
Familiarize yourself with this construct because we use it many times in this game. Two
nested loops used like this are particularly useful for games and apps that require a 2D
grid in order to be displayed and manipulated:
for (var i = 0; i < cols; i++) {
board[i] = new Array();
for (var j =0; j < rows; j++) {
board[i][j] = { finalCol:i,finalRow:j,selected:false };
}
}
Now that we have the board array initialized, we call randomizeBoard() (we will discuss
this function shortly), which mixes up the puzzle by randomly placing the pieces on
the screen. We finish the setup section of the game by adding an event listener for the
mouseup event (when the user releases the mouse button), and by setting an interval to
call drawScreen() every 33 milliseconds:
board = randomizeBoard(board);
theCanvas.addEventListener("mouseup",eventMouseUp, false);
setInterval(drawScreen, 33);
Randomizing the puzzle pieces
The randomizeBoard() function requires you to pass in the board variable so we can
operate on it. We've set up the function this way so it will be portable to other
applications.
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 purpose 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 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 required to randomize the pieces:
Search WWH ::




Custom Search