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

时间:2017-02-21 01:38:10

标签: javascript

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

一旦你知道他们已经做出合理的猜测,你只需要减少:

df$match <- Reduce("|", lapply(patterns, grepl, df$trans))
df
#   id              trans match
# 1  1   1-IA-45045000100  TRUE
# 2  2   2-IA-23003001801 FALSE
# 3  3 3-LITP-01001000100 FALSE
# 4  4  4-OTP-06006000606  TRUE
# 5  5  4-OTP-06010001001  TRUE
# 6  6   1-IA-45001010002  TRUE
# 7  7   2-IA-45045000101 FALSE
# 8  8 2-LITP-23005005002  TRUE