我正在为一个项目制作一个Hangman类型的游戏,并且在进行错误的猜测并将它们放入“错误的字母”库中时遇到了很多麻烦,不允许再次猜到它们。
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
var guess; //user guess
var letters = []; //correctly guessed letters
var wrongLetters = []; //incorrectly guessed letters
var counter = 0; //counts correct letters
var lives; //counts users lives
var wordList = ["cat", "dog", "wolf", "laser", "carrol"]; //FILL LIST LATER!!
//randomly chooses a word from wordList
var word = wordList[Math.floor(Math.random() * wordList.length)];
//choosen word is replaced with
function start() {
for (i = 0; i < word.length; i++) {
letters[i] = "__";
}
document.getElementById("answer").innerHTML = letters.join(" ");
console.log(word);
}
function checkLetter() {
document.onkeyup = function(event) {
guess = event.key.toLowerCase();
for (i = 0; i < word.length; i++) {
if (guess === word[i]) {
letters[i] = guess;
document.getElementById("answer").innerHTML = letters.join(" ");
}
}
}
}
start();
checkLetter();
<h1>Hangman!</h1>
<p>
<font size="+3"><span id="answer"></span></font>
</p>
<p id="counter"></p>
<p id="wrongGuesses"></p>
这是我到目前为止所拥有的。它基本上从数组中选取一个随机字,并在字母的位置显示下划线。如果你猜一个正确的字母,下划线将被替换。正如我之前所说,我现在需要它来跟踪我不正确的猜测。我知道这很模糊,但任何帮助都会非常感激!!
答案 0 :(得分:0)
这是您的代码段,经过修改后可以捕获错误的猜测。
我已经为代码添加了评论,因为我已经改变了。
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
var guess; //user guess
var letters = []; //correctly guessed letters
var wrongLetters = []; //incorrectly guessed letters
var counter = 0; //counts correct letters
var lives; //counts users lives
var wordList = ["cat", "dog", "wolf", "laser", "carrol"]; //FILL LIST LATER!!
//randomly chooses a word from wordList
var word = wordList[Math.floor(Math.random() * wordList.length)];
//choosen word is replaced with
function start() {
for (i = 0; i < word.length; i++) {
letters[i] = "__";
}
document.getElementById("answer").innerHTML = letters.join(" ");
console.log(word);
}
function checkLetter() {
document.onkeyup = function(event) {
guess = event.key.toLowerCase();
var found = false; //lets use bool to check if a letter was found
for (i = 0; i < word.length; i++) {
if (guess === word[i]) {
letters[i] = guess;
document.getElementById("answer").innerHTML = letters.join(" ");
found = true;
}
}
//now all letters have been checked, was any found
if (found) return; //if yes return
//wrong, lets also see if
//it's not already logged, if not add it
//you could also then use wrongLetters.length
//for working out if gueses area all used up.
if (wrongLetters.indexOf(guess) < 0) {
wrongLetters.push(guess);
document.getElementById("wrongGuesses").innerHTML = wrongLetters.join(" ");
}
}
}
start();
checkLetter();
<h1>Hangman!</h1>
<p>
<font size="+3"><span id="answer"></span></font>
</p>
<p id="counter"></p>
<p id="wrongGuesses"></p>