2017-02-21 96 views
1

我遵循本教程的一本書,如果猜測不正確,我嘗試添加最後的猜測。在開始時,我將這個變量設置爲4.簡單的hang子手遊戲嘗試次數不起作用

現在我的猜測無 - 減少到許多數字一次所以我不知道如何解決它只減少一個嘗試從4,直到猜測Nr < 0. 可以有人請告訴我該怎麼做?

var words = [ 
 
\t "javascript", 
 
\t "monkey", 
 
\t "amazing", 
 
\t "pancake" 
 
\t ]; 
 

 
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++) { 
 
\t 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)) { 
 
\t // Show the player their progress 
 
\t alert("The word is from " + word.length + " letters " + answerArray.join(" ")); 
 
\t // Take input from player 
 
\t var guess = prompt("Guess a letter"); 
 

 
\t // if the player clicks the Cancel button, then guess will be null 
 
\t if(guess===null) { 
 
\t \t // break to exit the loop 
 
\t \t break; 
 
\t \t //ensuring that guess is exactly one letter 
 
\t } else if(guess.length !== 1) { 
 
\t \t alert("Please enter a single letter!"); 
 
\t } else { 
 
\t \t for(var j = 0; j < word.length; j++) { 
 
\t \t \t if(word[j] === guess) { 
 
\t \t \t \t // sets the element at index j, from word, 
 
\t \t \t \t // of answerArray to guess 
 
       answerArray[j] = guess; 
 
\t \t \t \t remainingLetters--; 
 
\t \t \t 
 
\t \t \t } else { \t 
 
\t \t \t \t //guessesNr--; 
 
\t \t \t \t //console.log("guessesNr", guessesNr); 
 
\t \t \t } 
 
\t \t } 
 
\t } 
 
\t 
 
} 
 

 
//alert(answerArray.join(" ")); 
 
alert("Great job! The answer was " + word);
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
\t <title></title> 
 
</head> 
 
<body> 
 
<script type="text/javascript" src="hangman-test1.js"></script> 
 
</body> 
 
</html>

回答

1

你只需要遞減,一旦你知道他們已經把一個合法的猜測:

 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--; 
     } 
+0

我這樣做,但即使我把正確的信仍然沒有 - 就像我把錯誤的字母。你能檢查我的代碼嗎? –

+0

好的。如果他們沒有得到任何匹配,我編輯的解決方案只會減少。 – rasmeister

0

guessesNrfor循環如此這般下降了1對單詞的每個字母遞減。您需要將guessesNr--移到循環外部。

我還沒有檢查過其他問題。