为什么我的程序跳过游戏部分?

时间:2015-02-10 23:10:49

标签: javascript html

我写了一个非常基本的刽子手游戏,但它跳过了实际的刽子手部分。它会显示警告这个单词你按下了多久然后它显示完成消息没有游戏部分我无法找出原因 请告诉我有什么问题                    刽子手     

<body>
    <h1>Hangman!</h1>


    <script>
    var words = [
        "javascript",
        "monkey",
        "amazing",
        "pancake",
      ];
      var word = words[Math.floor(Math.random() * words.length)];
      var answerArray = [];
      for (var i = 0; i < word.length; i++) {
        answerArray[i] = "_"
      }

      var remainingLetters = word.length

      while (remainingLetters < 0) {

      alert(answerArray.join(" "));

      var guess = prompt("Guess a letter, or click Cancel to stop playing>");
      if (guess === null) {
            break;
      } else if (guess.length !== 1) {
      alert("Please enter a single letter.");    
      } else {
            //update the game state with a guess
      for (var j = 0; j < word.length; j++) {
        if (word[j] === guess) { 
          answerArray[j] = guess;
          remainingLetters--;
         } 
        }
       }
      }
      alert(answerArray.join(" "));
      alert("Good Job! The answer was " + word);
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

while (remainingLetters < 0) {应为while (remainingLetters > 0) {

另外,正如Pluto提到它(好抓!),你可以一遍又一遍地输入相同的字母作弊。要解决这个问题,您可以将猜测的字母存储在一个字符串中并检查它是否在之前被猜到(并且不会增加分数)。

另一项调整,如果用户点击取消(想要退出),我在末尾添加了if语句,以便不再显示警报。

var words = ["javascript", "monkey", "amazing", "pancake"];
var word = words[Math.floor(Math.random() * words.length)];
var answerArray = [];
// Storing the letters already guessed
var guessedLetters = "";
for (var i = 0; i < word.length; i++) {
    answerArray[i] = "_"
}

var remainingLetters = word.length;

while (remainingLetters > 0) {

    alert(answerArray.join(" "));

    var guess = prompt("Guess a letter, or click Cancel to stop playing>");
    if (guess === null) {
        break;
    } else if (guess.length !== 1) {
        alert("Please enter a single letter.");
    } else {
        // if the letter was already guessed
        if (guessedLetters.indexOf(guess) > -1) {
            // skip
            continue;
        }
        //update the game state with a guess
        for (var j = 0; j < word.length; j++) {
            if (word[j] === guess) {
                answerArray[j] = guess;
                // add the letter to the guessed letters
                guessedLetters += guess;
                remainingLetters--;
            }
        }
    }
}
// if there are no remaining letters (if the user cancelled,
// no need to show these).
if( !remainingLetters) {
    alert(answerArray.join(" "));
    alert("Good Job! The answer was " + word);
}

JS Fiddle Demo