Reputation: 21
I am trying to run a program that makes the user guess the word by typing in the letter. The same letter should not be allowed to be inputted twice. I was thinking of storing each letter inputted in a list and then I would loop through the list checking each element against the user input. If it is inputted twice and error message like try again will occur. This is what I have so far.
var x = ["Football", "Pie", "Red", "Amber", "Purple", "Blue"];
var y = x[Math.floor(Math.random() * x.length)].toLowerCase();
var answerArray = [];
var lettersUsed = [];
var numberOfGuesses = 10;
for (var i = 0; i < y.length; i++)
{
answerArray[i] = "_";
}
var remainingLetters = y.length;
while (remainingLetters > 0 && numberOfGuesses > 0)
{
console.log(answerArray.join(" "));
var guess = prompt("Guess a letter\n");
if (guess === null)
{
console.log("Game over");
break;
}
else if (guess.length !== 1)
{
console.log("Enter a single letter\n");
}
else
{
numberOfGuesses--;
lettersUsed.push(guess);
for (var j = 0; j < y.length; j++)
{
if (y[j] === guess.toLowerCase() && answerArray[j] === "_")
{
answerArray[j] = guess.toLowerCase();
remainingLetters--;
}
}
}
}
console.log(answerArray.join(" "));
if (numberOfGuesses > 0)
{
console.log("Well done! You've won! Your stick guy has been saved!\n");
}
else
{
console.log("Game over! The word was " + y);
}
///console.log(lettersUsed);
How do I write the for loop? Any help would be appreciated.
Upvotes: 0
Views: 64
Reputation: 444
You can use the Array.includes(item)
method. It will return true
if the item is in the array. For example:
let lettersUsed = ['a', 'b', 'c'];
let newLetter = 'b';
if (lettersUsed.includes(newLetter)) {
console.log('letter already used');
} else {
console.log('letter not used yet');
}
Edit in response to question from OP:
You could add this after you check the input length:
else if (guess.length !== 1)
{
console.log("Enter a single letter\n");
}
else if (lettersUsed.includes(guess))
{
console.log('Letter already used');
}
else
{
numberOfGuesses--;
Upvotes: 2