作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我写了一个非常基本的刽子手游戏,但它跳过了实际的刽子手部分。它将显示该词有多长的警报,然后按“确定”,然后显示完成消息,没有游戏部分,我不知道为什么请告诉我出了什么问题 刽子手
<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);
}
关于javascript - 为什么我的程序会跳过游戏部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28443673/
我是一名优秀的程序员,十分优秀!