The initGame() Function
The initGame()
function
sets up the game for the player. The two most important
blocks of code are as follows. This code finds a random letter from the
letters array and stores it in the letterToGuess
variable:
var
letterIndex
=
Math
.
floor
(
Math
.
random
()
*
letters
.
length
);
letterToGuess
=
letters
[
letterIndex
];
This code adds an event listener to the window
object of the DOM to listen for the
keyboard keydown
event. When a key is
pressed, the eventKeyPressed
event
handler is called to test the letter pressed:
window
.
addEventListener
(
"keydown"
,
eventKeyPressed
,
true
);
Here is the full code for the function:
function
initGame
()
{
var
letterIndex
=
Math
.
floor
(
Math
.
random
()
*
letters
.
length
);
letterToGuess
=
letters
[
letterIndex
];
guesses
=
0
;
lettersGuessed
=
[];
gameOver
=
false
;
window
.
addEventListener
(
"keydown"
,
eventKeyPressed
,
true
);
drawScreen
();
}
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.