gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:50:20 25 4
gpt4 key购买 nike

我写了一个非常基本的刽子手游戏,但它跳过了实际的刽子手部分。它将显示该词有多长的警报,然后按“确定”,然后显示完成消息,没有游戏部分,我不知道为什么请告诉我出了什么问题 刽子手

<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>

最佳答案

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

关于javascript - 为什么我的程序会跳过游戏部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28443673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com