user3548246
user3548246

Reputation: 9

Check letter in word [hangman]

I'm new in programming.I have to write hangman game i javascript and have a big problem :D This is my function.The problem is : when user enter right letter it is appears in Wrong Guess too and I don't know why.

function IsLetterInWord(letter)
{
    for(i = 0; i< Word.length; i++)
        {
        if(letter == Word[i])
        {
            secretword[i] == letter;
            RightGuess += letter;
            var el = document.getElementById("right");
            el.innerHTML = "Your right guesses are:" + RightGuess;
            win();
        }

        }
if (letter != Word[i]){
            WrongGuess += letter;
            var e = document.getElementById("wrong");
            e.innerHTML = "Your wrong guesses are:" + WrongGuess;
    }
}

Upvotes: 0

Views: 1869

Answers (2)

ebohlman
ebohlman

Reputation: 15003

You've got a problem with your logic: you're treating a letter as wrong if it doesn't match every letter in the target, whereas it should only count as wrong if it doesn't match any letter. Also, a wrong letter should only count once, whereas a right letter should count for each match.

Just as a matter of developing good habits (though it makes no real difference in something as small as this), try not to repeat DOM operations unnecessarily since they're fairly slow. Things like

var el = document.getElementById("right");

should be done before a loop rather than inside it (the identity of the element plainly isn't going to change) and things like

el.innerHTML = "Your right guesses are:" + RightGuess;

should only be done after the loop finishes (the browser has to redraw part of the screen each time it's called).

Upvotes: 0

bobthedeveloper
bobthedeveloper

Reputation: 3783

You should use of the indexOf() method.The method returns the first index at which a given element can be found in the array, or -1 if it is not present. Link to docs

"string".indexOf("r") > -1;

You also need to use single equals on line #7:

secretword[i] = letter; // instead of ==

Upvotes: 1

Related Questions