我正在创建一个西蒙游戏,它可以在第一轮上运行,但是一旦你的每一轮第二轮它立即说不正确。
我重置了轮次之间的所有变量,但它似乎仍然保存它们,因为它立刻说“游戏结束!”
JS:
function makeGuess() {
...
var checkForComplete = setInterval(function () {
if (yourAnswer.length >= round) {
clearInterval(checkForComplete);
yourString = yourAnswer.toString();
correctString = correctAnswer.toString();
if (yourString === correctString) {
alert('Correct');
round++;
yourAnswer = [];
correctAnswer = [];
yourString = "";
correctString = "";
playSimon();
}
else {
alert("Game Over!");
}
}
}, 500)
这是playSimon()函数:
function playSimon() {
setTimeout(function () {
color = Math.floor(Math.random() * 4);
if (color == 0) {
correctAnswer.push(0);
$('#redButton').addClass('lightOn');
setTimeout(function () {
$('#redButton').removeClass('lightOn');
}, 500);
}
else if (color == 1) {
correctAnswer.push(1);
$('#blueButton').addClass('lightOn');
setTimeout(function () {
$('#blueButton').removeClass('lightOn');
}, 500);
}
else if (color == 2) {
correctAnswer.push(2);
$('#greenButton').addClass('lightOn');
setTimeout(function () {
$('#greenButton').removeClass('lightOn');
}, 500);
}
else if (color == 3) {
correctAnswer.push(3);
$('#yellowButton').addClass('lightOn');
setTimeout(function () {
$('#yellowButton').removeClass('lightOn');
}, 500);
}
i++;
if (i <= round) {
playSimon();
}
else {
makeGuess();
}
}, 700);
}
为什么第2轮会立即警告Game Over?
答案 0 :(得分:1)
因为您多次绑定点击事件:
function makeGuess() {
$('#redButton').click(function() {
yourAnswer.push(0);
});
$('#blueButton').click(function() {
yourAnswer.push(1);
});
$('#greenButton').click(function() {
yourAnswer.push(2);
});
$('#yellowButton').click(function() {
yourAnswer.push(3);
});
...
}
每次调用makeGuess()时,按钮都绑定了另一个click事件监听器。第一次完成(第一级),只有1个事件监听器,所以它正常工作,但从第二级开始,每个按钮都绑定了2个相同的点击监听器,当播放器单击一个按钮,该函数被调用两次=&gt; yourAnswer立即被推两次,导致答案错误=&gt;游戏结束。
快速修复unbind 4个按钮上的所有点击事件,然后再次将它们全部绑定,最好在调用下一个playSimon()之前。
if (yourString === correctString) {
alert('Correct');
round++;
yourAnswer = [];
correctAnswer = [];
yourString = "";
correctString = "";
$('#redButton').unbind( "click" );
$('#blueButton').unbind( "click" );
$('#greenButton').unbind( "click" );
$('#yellowButton').unbind( "click" );
playSimon();
} else {
alert("Game Over!");
}
JsFiddle:https://jsfiddle.net/dfk2am7e/1/
答案 1 :(得分:0)
AVAVT是正确的,但不是取消绑定,而只是将事件绑定一次。
我已经更新了你的JSFiddle并对你的代码进行了一些优化。
https://jsfiddle.net/dfk2am7e/3/
// Run this when the page has loaded to ensure HTML is there.
$(function(){
$('#redButton').click(function() {
yourAnswer.push(0);
});
$('#blueButton').click(function() {
yourAnswer.push(1);
});
$('#greenButton').click(function() {
yourAnswer.push(2);
});
$('#yellowButton').click(function() {
yourAnswer.push(3);
});
});