HTML and CSS Reference
In-Depth Information
shuffling/
) explaining the
Fisher-Yates algorithm
. The strategy of this algorithm is to make a random
determination for each position in the deck, starting from the end and working toward the start. The
calculation determines a random position in the deck from 0 up to and including the current position and
does a swap. The main shuffle function follows:
function shuffle() {
var i = deck.length - 1;
var s;
while (i>0) {
s = Math.floor(Math.random()*(i+1));
swapindeck(s,i);
i--;
}
}
Recall that
Math.random() * N
returns a number from zero up to but not including
N
. Taking
Math.floor
of the result returns an integer from zero up to
N
. So if we want a number from
0
to
i
, we need to write
Math.floor(Math.random()*(i+1))
. To make the
shuffle
function easier to read, I made a separate
function called
swapindeck
that swaps the two cards that are located at the positions indicated by the
parameters to the function. To perform a swap, an extra place is needed and this is the variable
hold
. This
extra place is needed because the two assignment statements cannot be accomplished at the same time.
function swapindeck(j,k) {
var hold = new MCard(deck[j].num,deck[j].suit,deck[j].picture.src);
deck[j] = deck[k];
deck[k] = hold;
}
Capturing key presses
The use of the arrow keys was described in the maze game in Chapter 7. This essentially is a repeat of
that explanation.
Detecting that a key on the keyboard has been pressed and determining which key is termed
capturing
the key strokes
. The code must set up the response to a key event and is analogous to setting up a
response to a mouse event. The coding starts with invoking the
addEventListener
method, this time for
the
window
for this application.
window.addEventListener('keydown',getkey,false);
This means the
getkey
function will be invoked if and when a key is pressed.
Note: There also are
keyup
and
keypress
events. The
keydown
and
keyup
fire only once. The
keypress
event will occur again after some amount of time if the player holds down the key.
Now, as you may expect at this point, the coding to get the information for which key involves code for
different browsers. The following code, with two ways to get the number corresponding to the key, works
for Chrome, Firefox, and Safari:
if(event == null)