简体   繁体   English

在js中创建简单的刽子手游戏并且无法正确读取if语句

[英]Creating Simple Hangman Game in js and Can't get if statement read correctly

In the code below, I can not get the code to execute if the players guess of a letter is not in the secret word chosen.在下面的代码中,如果玩家猜测的字母不在所选的秘密单词中,我将无法执行代码。 I have it set so when the submit button is hit, we first check to see if the letter guessed is in the puzzle word, if it is the letter is turned over, then I am trying to say if it is not in the word take a life away from the player.我已经设置了所以当点击提交按钮时,我们首先检查猜出的字母是否在拼图单词中,如果是字母被翻转,然后我试图说如果它不在单词中远离玩家的生活。 I've tried several ways but can not get the program to read the second if statement correctly.我尝试了几种方法,但无法让程序正确读取第二个 if 语句。

submit.addEventListener('click', function(){
    console.log("clicked");
    usedLetters.innerHTML += playersLetter.value + ' '

    for(i=0; i<checkWord.length; i++){
      console.log(wordLife)

      if(playersLetter.value == (checkWord[i])){
        console.log('in if#1')
        console.log(playersLetter.value)
        var answerLetter = document.getElementsByClassName('letter')[i]
        answerLetter.innerHTML = playersLetter.value
        wordLife--
      }
    }

  function scoreLetter(value){// To check if the letter is actually in the word
  for(let i = 0; i < checkWord.length; i++){
    if(value == (checkWord[i])){
      return true
    }else {
      return false
    }
  }
}
console.log('read function')

 if(scoreLetter(playersLetter.value) == false){
   console.log('in 2nd if')
   playerLife--

console.log(playerLife)
}    
})

Your scoreLetter function is wrong, you are only checking the first letter and returning false if the value in not in the first position.您的 scoreLetter 函数是错误的,您只检查第一个字母,如果值不在第一个位置,则返回 false。 Try this ... to check if the letter is in the array试试这个……检查字母是否在数组中

 function scoreLetter(value){
      return (checkWord.indexOf(value) === -1) ? false : true;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM