我正在尝试制作一个刽子手游戏,如果选择了错误的字母,它会为刽子手模型添加一个正文部分。我希望它显示左臂显示后,右臂显示在下一个字母条目上。然而,他们都出现在第一个错误的条目
//JavaScript document
var answer = ['h', 'a', 'n', 'g', 'm', 'a', 'n'];
var wrong= ['b' ,'c' ,'d', 'e' ,'f' ,'i' ,'j' ,'k' ,'l','o' ,'p', 'q', 'r', 's' ,'t', 'u', 'v' ,'w', 'x' ,'y' ,'z'];
var letters = /^[a-zA-Z]*$/;
var answerLetter = document.getElementsByClassName("answer_char");
var letterpool= ['a ' ,'b ' ,'c ' ,'d ', 'e ' ,'f' ,'g ' ,'h ' ,'i ' ,'j ' ,'k ' ,'l ', 'm ' ,'n ' ,'o ' ,'p ', 'q ', 'r ', 's ' ,'t ', 'u ', 'v ' ,'w ', 'x ' ,'y ' ,'z '];
var leftarm = false
onload = init;
function init(){
updateDisplay()
document.getElementById("guess_button").onclick = function enter() {
var userGuess = document.getElementById("guess_text").value;
// This uses String.prototype.match() used too see if its both a letter and a single entry
if(userGuess.match(letters) && userGuess.length === 1) {
for (var i = 0; i < answer.length; i++) {
if (userGuess === answer[i])
// answer[i] correlates to answerLetter[i].
answerLetter[i].innerHTML = userGuess;
}
if(userGuess.match(letters) && userGuess.length === 1) {
for (var i = 0; i < wrong.length; i++) {
if (userGuess === wrong[i])
document.getElementsByTagName("img")[1].src="img/leftarm_on.png";
leftarm = true;
}
if(leftarm= true){
document.getElementsByTagName("img")[3].src="img/rightarm_on.png";
}
}
}else {
window.alert('please enter one letter, numbers need not apply .');
}
}
}
答案 0 :(得分:1)
if (userGuess === wrong[i]) document.getElementsByTagName("img")[1].src="img/leftarm_on.png"; leftarm = true; } if(leftarm= true){ document.getElementsByTagName("img")[3].src="img/rightarm_on.png"; }
你在这里相互测试条件 - 当你在第一个中设置leftarm
时,它在第二个中已经为真。顺便说一句,您没有使用==
比较,而是使用=
作业;实际上根本没有必要进行这种比较。它应该是
if (userGuess === wrong[i]) {
if (!leftarm) {
document.getElementsByTagName("img")[1].src="img/leftarm_on.png";
leftarm = true;
} else if (leftarm) {
document.getElementsByTagName("img")[3].src="img/rightarm_on.png";
}
}
答案 1 :(得分:0)
在代码中查看此逻辑:
for (var i = 0; i < wrong.length; i++) {
if (userGuess === wrong[i])
document.getElementsByTagName("img")[1].src="img/leftarm_on.png";
leftarm = true;
}
if(leftarm= true){
document.getElementsByTagName("img")[3].src="img/rightarm_on.png";
}
将左臂设置为真后立即检查是否为真,如果是,则打开右臂。