HTML and CSS Reference
In-Depth Information
Now it is time to test the current game state to give feedback to the player. First, we
test to see whether
letterPressed
is equal to
letterToGuess
. If so, the player has won
the game:
if (letterPressed == letterToGuess) {
gameOver = true;
If the player has not won, we need to get the index of
letterToGuess
and the index of
letterPressed
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()
array method to get the relative index of each letter. Because we
alphabetized the letters in the array, it is very easy to test which message to display:
} 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
indexOf()
returned
-1
, and the key press was not a letter. We then display an error
message:
if (guessIndex < 0) {
higherOrLower = "That is not a letter";
The rest of the tests are simple. If
guessIndex
is greater than
letterIndex
, we set the
higherOrLower
text to “Lower.” Conversely, if
guessIndex
is less than
letterIndex
, we
set the
higherOrLower
test to “Higher”:
} else if (guessIndex > letterIndex) {
higherOrLower = "Lower";
} else {
higherOrLower = "Higher";
}
}
Finally, we call
drawScreen()
to paint the screen:
drawScreen();
Here is the full code for the function:
function eventKeyPressed(e) {
if (!gameOver) {
var letterPressed = String.fromCharCode(e.keyCode);
letterPressed = letterPressed.toLowerCase();
guesses++;
lettersGuessed.push(letterPressed);
if (letterPressed == letterToGuess) {
gameOver = true;
} else {
letterIndex = letters.indexOf(letterToGuess);
guessIndex = letters.indexOf(letterPressed);
Debugger.log(guessIndex);