1

I am new to java and am trying to create a game that simulates hangman. I am trying to get the letters from the user after they input on keyboard. However, when I type something it doesn't make any difference, it doesn't output whether it is correct or incorrect. I think I may not be using the event in my guessLetter() function correctly, any help would be greatly appreciated.

window.addEventListener("DOMContentLoaded", function() {
      var word = ['taco'];

      let randNum = Math.floor(Math.random() * word.length);
      let chosenWord = word[randNum];
      let underScore = [];

      let docUnderScore = document.getElementsByClassName('underScore');
      let docRightGuess = document.getElementsByClassName('rightGuess');
      let docWrongGuess = document.getElementsByClassName('wrongGuess');

      console.log(chosenWord); //lets grader cheat

      let generateUnderscore = () => {
        for (let i = 0; i < chosenWord.length; i++) {
          underScore.push('_');
        }
        return underScore;
      }


      document.onkeyup = function guessLetter(event) {
        let letter = String.fromCharCode(event.keyCode || event.code).toLowerCase();

        if (chosenWord.indexOf(letter) > -1) {
          rightWord.push(letter);
          underScore[chosenWord.indexOf(letter)] = letter;
          docUnderScore[0].innerHTML = underScore.join(' ');
          docRightGuess[0].innerHTML = rightWord;
          if (underScore.join('') === chosenWord) {
            alert('CONGRATS! YOU WIN!!!');
          } else {
            wrongWord.push(letter);
            docWrongGuess[0].innerHTML = wrongWord;
          }
        }
        underScore[0].innerHTML = generateUnderscore().join(' ');

      }
    });
<!DOCTYPE html>
<html>

<head>
  <h1> Hangman </h1>
  <div id="guesses">
    <div class="letter" id="letter" </div>
    </div>
</head>

<body>
</body>
<div class="container">
  <div class="underScore">_ _ _ _</div>
  <div class="rightGuess"> right guess </div>
  <div class="wrongGuess"> wrong guess </div>
</div>

</html>

1
  • Check out your console log. Your code is trying to use some undefined variables including rightWord and wrongWord (so either define them or use existing variables.) Commented Mar 9, 2019 at 3:49

2 Answers 2

1

In the JS console, ReferenceErrors are being thrown as a result of the fact that the rightWord and wrongWord variables have not been defined.

Sign up to request clarification or add additional context in comments.

1 Comment

I copied and pasted the code wrong, it still doesn't behave correctly.. any ideas?
1

You are writing the in head tag why ? it doesn't shown in your web page , place the html tags within body.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.