HTML and CSS Reference
In-Depth Information
This appears in the init function. The choose function must contain code to determine which card we
choose to shuffle. The program must also return the coordinates of the mouse when the player clicks on
the canvas. The methodology for obtaining mouse coordinates is also the same as that covered in
Chapter 4.
Unfortunately, different browsers implement handling of mouse events in different ways. I discussed this
in Chapter 4 , and I repeat the explanation here. The following works in Chrome, Firefox, and Safari.
if ( ev.layerX || ev.layerX==0) {
mx= ev.layerX;
my = ev.layerY;
}
else if (ev.offsetX || ev.offsetX==0 ) {
mx = ev.offsetX;
my = ev.offsetY;}
This works because if ev.layerX doesnt exist, it will be assigned a value of false . If it does exist but
has value 0, the value will also be interpreted as false, but ev.layerX==0 will be true. So if theres a
good ev.layerX value, the program uses it. Otherwise, the code looks at ev.offsetX . If neither works,
mx and my wont get set.
Because the cards are rectangles, going through the deck and doing compare operations is relatively
easy using the mouse cursor coordinates ( mx , my ), the location of the upper-left corner, and the width and
height of each card. Heres how we construct the if condition:
if ((mx>card.sx)&&(mx<card.sx+card.swidth)&&(my>card.sy)&&(my<card.sy+card.sheight))
{
,
Note: The next chapter, which describes the way you create HTML markup at runtime
shows how to
set up event handling for specific elements positioned on the screen as opposed to using the whole
canvas element.
We clear the variable firstpick and initialize it as true , which indicates that this is the first of two picks
by a player. The program changes the value to false after the first pick and back to true after the
second. Variables like this, which flip back and forth between two values, are called flags or toggles .
Note that the specifics of this section apply just to these memory games, but the general lesson holds for
building any interactive application. There are at least two ways a player can thwart the game. Clicking
twice on the same card is one; clicking on a region where a card has been removed (that is, the board has
been painted over) is another.
Preventing certain types of cheating
To deal with the first case, after the if-true clause that determines whether the mouse is over a certain
card, insert the if statement
if ((firstpick) || (i!=firstcard)) break;
 
Search WWH ::




Custom Search