HTML and CSS Reference
In-Depth Information
Listing 11-10.
Implementing the movePiece() function
function movePiece(oStart, startID, end, pieceStore) {
computeRowColumn(oStart, end);
var startUpdateReq = pieceStore.put(oStart, startID);
startUpdateReq.onsuccess = function (event) {
moveNumber++;
drawBoard();
drawAllPieces();
if (moveNumber > 7) {
clearInterval(timer);
chessContext.font = "30pt Arial";
chessContext.fillStyle = "black";
chessContext.fillText("Checkmate!", 200, 220);
}
}
}
This code first computes the
row
and
column
properties using the
computeRowColumn()
function that you
created earlier. It then updates the object. In the
onsuccess
event handler it increments the
moveNumber
variable
and draws the board and all of the pieces using the existing functions. Finally, if this is the last move, the timer is
cleared and the “Checkmate!” text is drawn on the canvas.
Starting the Animation
The last step is to start the timer that will cause the
makeNextMove()
function to be called. You'll do this in the
onsuccess
event handler for the
open()
call. Add the code shown in bold:
var request = dbEng.open("Chess", 2);
request.onsuccess = function (event) {
db = event.target.result;
// Add the pieces to the board
resetBoard();
// Draw the pieces in their initial positions
drawAllPieces();
// Start the animation
timer = setInterval(makeNextMove, 2000);
}
Save your changes and press F5 to start the application. You should see the alert letting you know that the
database is being configured since you changed the database version. After a series of moves you should see the
completed board shown in Figure
11-5
.