繁体   English   中英

简单的刽子手游戏尝试次数不起作用

[英]Simple hangman game number of tries doesn't work

我从一本书中学习本教程,如果猜测结果不正确,我会尝试添加。 在开始时,我将此变量设置为4。

现在我的猜测是 - 减少到很多数字一次所以我不知道如何修复它只减少一次尝试从4,直到guessesNr <0。有人可以告诉我该怎么做吗?

 var words = [ "javascript", "monkey", "amazing", "pancake" ]; var word = words[Math.floor(Math.random() * words.length)]; //create an empty array called answerArray and fill it //with underscores (_) to match the number //of letters in the word var answerArray = []; for( var i=0; i < word.length; i++) { answerArray[i] = "_"; } //every time the player guesses a //correct letter, this value will //be decremented (reduced) by 1 var remainingLetters = word.length; var guessesNr = 4; while((remainingLetters > 0) && (guessesNr > 0)) { // Show the player their progress alert("The word is from " + word.length + " letters " + answerArray.join(" ")); // Take input from player var guess = prompt("Guess a letter"); // if the player clicks the Cancel button, then guess will be null if(guess===null) { // break to exit the loop break; //ensuring that guess is exactly one letter } else if(guess.length !== 1) { alert("Please enter a single letter!"); } else { for(var j = 0; j < word.length; j++) { if(word[j] === guess) { // sets the element at index j, from word, // of answerArray to guess answerArray[j] = guess; remainingLetters--; } else { //guessesNr--; //console.log("guessesNr", guessesNr); } } } } //alert(answerArray.join(" ")); alert("Great job! The answer was " + word); 
 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript" src="hangman-test1.js"></script> </body> </html> 

guessesNrfor循环中递减,因此对于单词中的每个字母,它会减少1。 你需要在循环之外移动guessesNr--

我还没有检查过其他问题。

一旦你知道他们已经进行了合理的猜测,你只需要递减:

        var isHit = false;
        for(var j = 0; j < word.length; j++) {
            if(word[j] === guess) {
                // sets the element at index j, from word, 
                // of answerArray to guess
                remainingLetters--;
                isHit = true;
            }
        }
        if (!isHit) {
            guessesNr--;
        }

暂无
暂无

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

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