我的目标是在以前使用过键时停止打印键,并在显示所有字母时停止游戏(赢得比赛)。
解决:对于那些有同样问题的人:添加此功能将会 做这个工作:
//check if key is used function checkKey(charStr) { if (keyStore.includes(charStr)) { return false; } else { //record pressed key keyStore.push(charStr); if (nameChosen.toLowerCase().includes(charStr)) { display(charStr); } else { attempt--; //print out wrong-guess key document.getElementById("wrongGuess").innerHTML = document.getElementById("wrongGuess").innerHTML + charStr + " "; } } }
并将该函数放入keypress事件中。
这是我的旧代码:
var names = ["Adam Red", "Bob Green", "Chris Blue"];
var nameChosen = names[Math.floor(Math.random() * names.length)];
var nameSplit = nameChosen.split("");
var updated = [];
var attempt = nameChosen.length - 2;
function display(char) {
//replace each of the letters with underscore and space with dash
char = char || "_"; // set to default when no char given
var nameDisplayed = [];
for (var i = 0; i < nameSplit.length; i++) {
if (updated[i] || (char.toLowerCase() === nameSplit[i].toLowerCase())) {
nameDisplayed += nameSplit[i] + " ";
updated[i] = true;
}
else if (nameSplit[i] == " ") {
nameDisplayed += "- ";
}
else {
nameDisplayed += "_ ";
}
}
document.getElementById("nameDisplay").innerHTML = nameDisplayed;
}
// need function for game won <===============
function gameLost() {
document.getElementById("container").style.backgroundColor = "red";
document.getElementById("notice").innerHTML = "SORRY, YOU'VE LOST THE GAME!";
document.getElementById("notice").style.fontWeight = "bold";
document.getElementById("notice").style.color = "white";
}
document.getElementById("attempt").innerHTML = attempt;
//get key pressed by user
document.addEventListener("keypress", function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
console.log("key pressed: ", charStr);
if (nameChosen.toLowerCase().includes(charStr)) {
display(charStr);
}
else {
attempt--;
document.getElementById("wrongGuess").innerHTML = document.getElementById("wrongGuess").innerHTML + charStr + " ";
// print out key pressed continuously <==================
};
if (attempt == 0) {
gameLost();
};
document.getElementById("attempt").innerHTML = attempt;
});
display(); // call onload
我尝试过:添加新的var并将其设置为true / false并放入循环中,创建一个新函数但仍然无法实现。
答案 0 :(得分:1)
看起来你正在建造一个挂人的游戏?
尝试搜索nameDisplayed变量并查看其中的任何字符是否与“_”匹配
如果他们不这样做,你就会揭开所有角色并赢得比赛! 如果它仍然有一个'_'字符,则必须有另一个字符可供查找。
按下全局按键数组,并在按下新按键后搜索该按键可以帮助重复按键。
至于获胜时停止键输入,请对removeEventListener函数进行一些研究,你可以删除键击,甚至是侦听器。
希望有所帮助!
答案 1 :(得分:0)
解决问题的方法:
//check if key is used
function checkKey(charStr) {
if (keyStore.includes(charStr)) {
return false;
}
else {
//record pressed key
keyStore.push(charStr);
if (nameChosen.toLowerCase().includes(charStr)) {
display(charStr);
}
else {
attempt--;
//print out wrong-guess key
document.getElementById("wrongGuess").innerHTML = document.getElementById("wrongGuess").innerHTML + charStr + " ";
}
}
}