HTML and CSS Reference
In-Depth Information
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 keyup event. When a key is pressed, the eventKeyPressed event handler is
called to test the letter pressed:
window.addEventListener("keyup",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("keyup",eventKeyPressed,true);
drawScreen();
}
The eventKeyPressed() Function
This function, called when the player presses a key, contains most of the action in this
game. Every event handler function in JavaScript is passed an event object that has
information about the event that has taken place. We use the e argument to hold that
object.
The first test we make is to see whether the gameOver variable is false . If so, we continue
to test the key that was pressed by the player; the next two lines of code are used for
that purpose. The first line of code gets the key-press value from the event, and converts
it to an alphabetic letter that we can test with the letter stored in letterToGuess :
var letterPressed = String.fromCharCode(e.keyCode);
The next line of code converts the letter to lowercase so that we can test uppercase
letters if the player unintentionally has Caps Lock on:
letterPressed = letterPressed.toLowerCase();
Next, we increase the guesses count to display, and use the Array.push() method to
add the letter to the lettersGuessed array:
guesses++;
lettersGuessed.push(letterPressed);
Search WWH ::




Custom Search