HTML and CSS Reference
In-Depth Information
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
testthekeythatwaspressedbytheplayer;thenexttwolinesofcodeareusedforthatpurpose.
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:
var
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 );
Nowitistime totestthecurrentgamestate togivefeedback totheplayer.First,wetesttosee
whether letterPressed is equal to letterToGuess . If so, the player has won the game:
iif ( letterPressed == letterToGuess ) {
gameOver = true
true ;
If the player has not won, we need to get the index of letterToGuess and the index of let-
terPressed in the letters array. We are going to use these values to figure out whether we
should display “Higher,” “Lower,” or “That is not a letter.” To do this, we use the indexOf()
arraymethodtogettherelative indexofeachletter.Because wealphabetized theletters inthe
array, it is very easy to test which message to display:
} else
else {
letterIndex = letters . indexOf ( letterToGuess );
guessIndex = letters . indexOf ( letterPressed );
Now we make the test. First, if guessIndex is less than zero, it means that the call to in-
dexOf() returned −1 , and the pressed key was not a letter. We then display an error message:
iif ( guessIndex < 0 ) {
higherOrLower = "That is not a letter" ;
Search WWH ::




Custom Search