我对我的游戏有疑问。看起来我只能打印一个字母而不是一个字。例如,"星球大战"看起来像" star wr"。
//array of Star Wars Names
var words = ["star wars",
"senator organa",
"boba fett",
"chewbacca",
"luke skywalker",
"darth vader",
"lando calrissian",
"anakin skywalker",
"padme amidala"
];
//Declared variables
var rightLetter = [];
var wrongLetter = [];
var underScore = [];
var underScore = [];
var randomWords = Math.floor(Math.random() * words.length);
var chosenWords = words[randomWords];
var starWarsNames = document.getElementsByClassName("Star_Wars_words");
var correctGuess = document.getElementsByClassName("rightGuess");
var incorrectGuess = document.getElementsByClassName("wrongGuess");
//random word array
console.log(chosenWords);
function generateUnderscore() {
for (i = 0; i < chosenWords.length; i++) {
underScore.push("_");
}
return underScore;
}
//Game Loop
document.addEventListener("keypress", letterPressed);
//letter function
function letterPressed(event) {
var letter = String.fromCharCode(event.keyCode);
if (chosenWords.indexOf(letter) > -1) {
rightLetter.push(letter);
underScore[chosenWords.indexOf(letter)] = letter;
starWarsNames[0].innerHTML = underScore.join(" ");
correctGuess[0].innerHTML = rightLetter;
if (underScore.join(" ") == chosenWords) {
alert("The force is strong with you!");
}
} else {
wrongLetter.push(letter);
incorrectGuess[0].innerHTML = wrongLetter;
}
}
console.log(rightLetter);
console.log(wrongLetter);
console.log(starWarsNames);
&#13;
<div class="Star_Wars_words">
</div>
<div class="rightGuess">
</div>
<div class="wrongGuess">
</div>
&#13;
答案 0 :(得分:2)
在letterPressed
功能中,您可以重新组织它以检查多个实例。例如:
var idx = 0;
idx = chosenWords.indexOf(letter, idx);
if (idx == -1) {
wrongLetter.push(letter);
incorrectGuess[0].innerHTML = wrongLetter;
return;
}
while (idx > -1) {
rightLetter.push(letter);
underScore[idx] = letter;
starWarsNames[0].innerHTML = underScore.join(" ");
correctGuess[0].innerHTML = rightLetter;
if(underScore.join(" ") == chosenWords) {
alert("The force is strong with you!");
}
idx = chosenWords.indexOf(letter, ++idx);
}
所以不同的是,如果找到一个字母(idx > -1
),那么你将像以前一样处理它,但随后你将使用下一个字母索引更新idx
。