HTML and CSS Reference
In-Depth Information
// These rule apply to all pieces
if (yStart === yEnd || xStart === xEnd)
return false; // Move must be diagonal
if (Math.abs(yEnd - yStart) > 2 || Math.abs(xEnd - xStart) > 2)
return false; // Can't move more than two spaces
// If moving two spaces, find the square that is jumped
if (Math.abs(xEnd - xStart) === 2) {
var pos = ((xStart + xEnd) / 2).toString() +
((yStart + yEnd) / 2).toString();
var div = document.getElementById(pos);
if (div.childElementCount === 0)
return false; // Can't jump an empty square
var img = div.children[0];
if (img.id.substr(0, 1).toLowerCase() === prefix.toLowerCase())
return false; // Can't jump a piece of the same color
// If this function is called from the drop event
// Remove the jumped piece
if (drop) {
div.removeChild(img);
}
}
return true;
}
2.
The parameters to the isValidMove() function include the source and target
elements. Remember the source is an img element and its id attribute is a
combination of the color (“w” or “b”) and the x and y coordinates. The target is a
div element and its id attribute is just the x and y coordinates. I've added lots of
comments to this code so it should be fairly self-explanatory but I will point out a
couple of the more interesting points.
To determine if a square is occupied, you can simply check the
childElementCount property. This will be 0 for empty squares.
For white pieces, moving forward means the y coordinate is increasing but for
black pieces the opposite is true. To handle this, the function uses a switch
statement to apply a different rule for each.
If the piece is moving two spaces then the function needs to check the square
that is being jumped. Its location is determined by averaging the starting and
ending positions.
If the square is occupied then the code checks to see if the piece is the same
color. The code first gets the child element, which will be the img on that
square. The color is determined by the prefix of the id attribute. The code
converts the prefix to lowercase before comparing. I'll explain that later.
 
Search WWH ::




Custom Search