HTML and CSS Reference
In-Depth Information
When you redraw a piece in its new location, it is still visible in the old location as well. Also, if you were to
capture a piece by moving a piece in the same square as another, you would end up with two pieces in the same
square. You could implement some complex logic to clear the square and redraw a red or white square before
moving the piece. However, for this demonstration you will simply clear the entire canvas and redraw the board
and all of the pieces.
To implement the automation, you'll create a makeNextMove() function. This will adjust the x and y positions
of a chess piece and then redraw the board and all of the pieces. You'll use the setInterval() function to call this
repeatedly so the pieces will move in succession.
eXerCISe 10-4. aNIMatING the CheSS pIeCeS
Add the following variables shown in bold near the beginning of the script element:
// Define an array to store 32 pieces
var pieces = new Array(32);
var moveNumber = −1;
var timer;
Implement the makeNextMove() function shown in Listing 10-6. This code “moves”
a piece by adjusting its x and y properties. It keeps track of the move number and
uses this to adjust the appropriate piece. The 7th move captures a piece and sets
its killed property. since this ends the animation, the 7th move also uses the
clearTimer() function so no more timer events will occur. After each move, the
board and all the pieces are re-drawn. After the 7th move, this function also uses the
fillText() method, which is used to write text to the canvas.
Listing 10-6. The makeNextMove implementation
function makeNextMove() {
function inner() {
if (moveNumber === 1) {
if (moveNumber === 2) {
pieces[4].y += 2;
if (moveNumber === 3) {
pieces[29].y = 4;
pieces[29].x = 2;
if (moveNumber === 4) {
if (moveNumber === 5) {
pieces[30].x = 5;
pieces[30].y = 5;
Search WWH ::

Custom Search