我正在编写一个《 Hangman》游戏,即使多次检查都没有发现任何错误,但仍然出现此错误。
我确实在Stack Overflow上阅读了有关此内容的内容,但找不到适合我的特殊情况的解决方案。它不是一个函数,因此应该是一个中断而不是返回。
我的代码:
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="review.css">
<script src="review.js" type="text/javascript"></script>
</head>
<body>
<h2>Hangman</h2>
<script>
// pick our random words for the game & save in an array in a
varibale
var word = [
"school",
"teacher",
"class",
"principal"];
// use this to pick a random word from the array
var word = words[Math.floor(Math.random() * words.length)];
// create an empty array and fill it with underscores to match the number of letters in a word
var answerArray = [];
for (var i = 0; i < word.length; i ++) {
answerArray[i] = "_";
}
// variable set to the length of the secret word; use this to keep track of how many letters are left to guess
var remainingLetters = word.length;
// we will continue to loop as long as the number of letters is greater than zero; once it is zero they have correctly guessed the word; .join changes an array into a string
while (remainingLetters > 0) {
alert(answerArray.join(" "));
}
// prompt takes a guess from the player and saves it to the varible guess; now we must handle 4 separate scenarios: the player does not provide a letter, the letter is greater than 1, the player does it correctly
var guess = prompt("Guess a letter, or click cancel to stop playing.");
if (guess === null) {
// exit the game loop
break;
}else if (guess.length !== 1) {
alert("Please enter a single letter.");
}else {
for (var j =0; j < word.length; j++){
if (word[j] === guess) {
answerArray[j] = guess;
remainingLetters --;
}
}
}
alert(answerArray.join(" "));
alert("Good. The answer was " + word);
</script>
</body>
</html>
答案 0 :(得分:1)
你必须把你的代码放在While循环中……像这样然后中断;会工作,因为它在循环中::::)))
while (remainingLetters > 0) {
alert(answerArray.join(" "));
var guess = prompt("Guess a letter, or click cancel to stop playing.");
if (guess === null) {
// exit the game loop
break;
} else if (guess.length !== 1) {
alert("Please enter a single letter.");
} else {
for (var j =0; j < word.length; j++){
if (word[j] === guess) {
answerArray[j] = guess;
remainingLetters --;
}
}
}
}
alert(answerArray.join(" "));
alert("Good. The answer was " + word);