Reputation: 11
I'm doing a hangman game, this is my progress. So the computer chooses a random word, prints out as many underscores as there are letters in the word. Now I need to check if a input letter matches any of the letters in the random word. I've tried this so far.
var wordList = new Array("duck","cat","dog","carpet","pants","computer","book");
var randomWord = wordList[Math.floor(Math.random()* wordList.length)];
var underscore = function(randomWord) {
for (i = 0; i < randomWord.length; i++) {
document.write("_" + " " + " ");
}
};
underscore(randomWord);
var guessLetter= prompt("Guess a letter");
var positions = function (randomWord, guessLetter){
for (var i = 0; i < randomWord.length ; i++) {
}
}
Now I am completely stuck, any help?
Upvotes: 1
Views: 603
Reputation: 242
The following code returns all the positions matched by a letter in a word :
function checkLetterInWord(word, letter) {
var positions = [];
for(var i=0; i<word.length; i++)
if(word.charAt(i) == letter)
positions.push(i);
return positions;
}
var word2guess = "hangman";
var pos = checkLetterInWord(word2guess, "a");
for(var i=0; i<word2guess.length; i++) {
if(pos.indexOf(i) === -1)
document.write("_");
else
document.write(word2guess[i]);
}
Upvotes: 0
Reputation: 820
The following suggestion would be what you are looking for, it will return a bool;
bool isItThere = randomWord.Contains('guessletter');
if you want the position of the characters see @guy777's answer.
Upvotes: 1