[英]variable doesn't update when function restarts (javascript)
我将尽力在没有大量代码的情况下问这个问题。 基本上我已经写了一个非常简单的数学问答游戏。 在这个游戏中,您选择难度,想要的问题数量,然后游戏开始。 它询问该问题的数量,然后您得到一个分数,然后游戏结束。 但是,您可以重新启动游戏。 重新启动时,它仅使您返回主屏幕,然后您可以再次选择选项。 唯一的问题是,我们需要跟踪测验中剩余的问题数量,这是第一次,效果很好。 我们将numQuestions
传递给游戏功能。 但是,即使我第二次通过numQuestions=10
,该值从我第一次玩游戏起仍为0。 这是游戏功能:
function startGame(difficulty,numQuestions,score){
// begins game, excluded that come its just some acsii art
// asks question
var q = new question(difficulty);
$("#gameInside").html(q.string);
$("#gameInside").data('answer',q.answer);
// gives answer options
for (var ii=0;ii<=3;ii++){
$("#answers").append("<button class='answerButton'>"+q.answerArray[ii]+"</button>")
}
// starts timer
var b = document.getElementById("timer");
timer = new stopWatch(b, {delay: 100});
timer.start();
},5500)
// when answer is clicked, go here
$("#gameScreen").on("click",".answerButton",function() {
// this seems to be the problem: on the second time I play the game, numQuestions remains the value from the first game and continues to go down (-1,-2) and since my selector is (>0), the else statement fires.
numQuestions--;
var time = parseFloat($("#timer span").html());
var correct = parseFloat($("#gameInside").data('answer'));
var userAnswer = parseFloat($(this).html());
if (correct==userAnswer)
tempScore = Math.round(calculateScore(time)*100)/100;
else
tempScore = 0;
score += tempScore;
$("#score").html(Math.round(score*100)/100);
if (numQuestions > 0) {
var q = new question(difficulty);
$("#gameInside").html(q.string);
$("#gameInside").data('answer',q.answer);
$("#answers").empty();
for (var ii=0;ii<=3;ii++){
$("#answers").append("<button class='answerButton'>"+q.answerArray[ii]+"</button>")
}
timer.reset();
} else {
$("#answers").empty();
$("#gameInside").html('Game Over! Thanks for Playing!');
timer.stop();
}
});
}
有任何想法吗? 谢谢
编辑:
$(".numberQButton").click(function(){
numQuestions = parseFloat($(this).html());
$("#numQuestionsScreen").hide();
$("#gameScreen").show();
$("#score").html(0);
startGame(difficulty,numQuestions,score);
});
听起来好像您需要在重新启动游戏时实例化一个新的Game对象。
您的问题(我认为)在于闭包。 当您在javascript中声明函数时,从变量自身作用域之外进行的任何访问都会生成所谓的闭包。 在这种情况下,可以从事件函数内部访问numQuestions
,从而创建一个闭包。 这样做的结果是,事件函数内部对numQuestions
变量的任何访问都引用了该变量,就像从您的javascript解释器遇到事件函数本身(即,您第一次玩游戏)以来一样。
查看这些内容,以了解发生问题的地方。
您在哪里定义点击监听器? 如果两次触发,则好像您是在定义点击监听器,这样,在完成一个游戏并重新开始之后,将注册一个新的监听器,最后得到2个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.