Good Morning Friends,
I am brand new to JavaScript and have been studying it using many platforms, including the "JavaScript For Kids". In this book, I am now on "Chapter 7: Creating a Hangman Game"…and on the "Programming Challenges", I was able to complete the first three challenges. The fourth one that I’m totally stuck on is "Fixing a Bug". It states that there is a "bug in the game" and that "if you keep guessing the same correct letter, "remainingLetters" will keep decrementing. Can you fix it?". It says that you can add another condition to check whether a value in answerArray is still an underscore. If it’s not an underscore, then that letter must have been guessed already. I’m not sure where to even start with this…
Please see code below. I’m not sure where to go from here. I tried googling it, but still, I’m not getting it.
<script>
//Set a maximum number of tries
var maximumTries = 10;
// Create an array of words
var words = [
"quail",
"chicken",
"kookaburra",
"parrot"
];
// Pick a random word
var word = words[Math.floor(Math.random() * words.length)];
// Set up the answer array
var answerArray = [];
for (var i = 0; i < word.length; i++) {
answerArray[i] = "_";
}
var remainingLetters = word.length;
// This will hold all the letters tried
var guessAll = "";
// The game loop
while (remainingLetters >= 0 && guessAll.length < maximumTries) {
// Show the player their progress
alert(answerArray.join(" "));
// Get a guess from the player
var guess = prompt("Guess a letter, or click Cancel to stop playing.");
guessAll += guess;
guess = guess.toLowerCase();
if (guess === null) {
// Exit the game loop
break;
} else if (guess.length !== 1) {
alert("Please enter a single letter.");
} else {
for (var j = 0; j < word.length; j++) {
if (word[j] === guess) {
answerArray[j] = guess;
remainingLetters--;
}
}
}
// The end of the game loop
}
//Show the answer and congratulate the player
alert(answerArray.join(" "));
alert("Good job! The answer was " + word);
</script>
2
Answers
Let’s go through the hints they gave:
Yes, that is true. When
guess
is the same as a previous guess, then still the followingif
condition will be true and its code block will execute:We don’t want a repeated guess to have any effect on the
remainingLetters
countdown. It should remain unchanged.That is a good hint, because the first time that guess was made, we had replaced an underscore with
guess
:So… if the same guess is made again, the character at
answerArray[j]
will no longer be an underscore, but the guessed letter. Therefore it would be a good idea to first check what the character is atanswerArray[j]
before we decide to enter thatif
block.Does this help to find out what you should do?
If not, here is the solution as a spoiler