HTML and CSS Reference
In-Depth Information
Note
You'll later add logic to handle promoting a piece to a king.
eXerCISe 14-5. eNFOrCING the rULeS
1.
Implement the isValidMove() function by adding the code shown in Listing 14-6 to
the existing script element.
Listing 14-6. Implementing the isValidMove() function
function isValidMove(source, target, drop) {
// Get the piece prefix and location
var startPos = source.id.substr(1, 2);
var prefix = source.id.substr(0, 1);
// Get the drop location
var endPos = target.id;
// You can't drop on the existing location
if (startPos === endPos) {
return false;
}
// You can't drop on occupied square
if (target.childElementCount != 0) {
return false;
}
// Compute the x and y coordinates
var xStart = parseInt(startPos.substr(0, 1));
var yStart = parseInt(startPos.substr(1, 1));
var xEnd = parseInt(endPos.substr(0, 1));
var yEnd = parseInt(endPos.substr(1, 1));
switch (prefix) {
// For white pieces...
case "w":
if (yEnd <= yStart)
return false; // Can't move backwards
break;
// For black pieces...
case "b":
if (yEnd >= yStart)
return false; // Can't move backwards
break;
}
 
 
Search WWH ::




Custom Search