HTML and CSS Reference
In-Depth Information
eXerCISe 11-2. aDDING the MOVeS StOre
1.
Add the following code to the script element just after the existing static data
definitions for the pieceTypes and pieces arrays:
var moves = [
{ id: 1, start: "e2", end: "e3" },
{ id: 2, start: "e7", end: "e5" },
{ id: 3, start: "f1", end: "c4" },
{ id: 4, start: "h7", end: "h6" },
{ id: 5, start: "d1", end: "f3" },
{ id: 6, start: "g7", end: "g6" },
{ id: 7, start: "f3", end: "f7" }
];
2.
Add the following code shown in bold to the end of the configureDatabase()
function. This will create and populate the move store when the database is
configured.
pieceStore.createIndex
("piecePosition", "pos", { unique: true });
// Store the moves
var moveStore = db.createObjectStore
(“move”, { keyPath: “id” });
for (var i in moves) {
moveStore.add(moves[i]);
}
}
On the open() call, change the version to 2 as shown in bold. This will cause the
onupgradeneeded event to be raised the next time the page is loaded.
3.
if (!dbEng)
alert("IndexedDB is not supported on this browser");
else {
var request = dbEng.open("Chess", 2 );
Converting the Position
The objects in the piece store have the row , column , and pos properties. The row and column properties follow
the same convention that was used in Chapter 10, where the top-left square is at 0,0. That is consistent with how
canvas works and simplifies the drawPiece() implementation. In contrast, the pos property uses the notation
widely used in Chess where the columns (files) go from “a” to “h” as you move left to right. The rows (ranks) go
from “1” to “8” as you move from the bottom of the board to the top. Thus “a1” is the bottom-left square.
Before you get into the heavy work of moving the pieces you'll create a function that will convert the pos
property into row and column properties. When a piece is moved to e3 for example, you'll need to convert “e3”
into the corresponding row and column coordinates, which would be 5 (row) and 4 (column). Add the function
shown in Listing 11-8 to the end of the existing script element.
 
Search WWH ::




Custom Search