我正在研究一个有趣的项目:一个“热或冷”游戏应用程序,但似乎无法理解某些东西。
问题在于,当有正确的猜测时,我设置的用于注册猜测的标志不会永久地记录变化(由正确的猜测引起)并且用户可以继续猜测。
当用户做出正确的猜测时,我会更改全局变量winflag的值,但由于某种原因,它会返回false(即尚未猜测)并继续游戏。
任何人都可以指出为什么会发生这种情况?
//INSIDE DOCUMENT.READY
//global variable declaration
var winflag=false;
//event handler for click on guess button
$('#guessButton').click(function(){
event.preventDefault();
if(!winflag) {
console.log("calling guessfunction")
guessfunction();
}
else {
alert("Game is over");
}
});
//END OF DOCUMENT READY
var guessfunction = function () {
//guesscount++ -- write guesscount in #count
guesscount++;
console.log("guesscount is " + guesscount);
//current guess cguess=get the input from the text box
var tcguess = $('#userGuess').val();
var cguess = +tcguess;
//if cguess>100 - alert "not valid input"
if (cguess>100) {
return alert("Not a valid input");
}
else {
//append cguess in #guessList
$('#guessList').append('<li>'+tcguess+'</li>');
//calculatefeedback(solution,cguess)
calculatefeedback(solution,cguess);
console.log("calculated feedback");
}}
var calculatefeedback = function(sol,guess) {
//difference=absolute value(solution-guess)
var difference = Math.abs(solution-guess);
//if difference=>70 --- return you're freezing
if (difference >= 70) {
winflag=false;
return alert("You're freezing!");
}
//else if difference=>30 --- return youre cold
else if (difference >= 30) {
winflag=false;
return alert("You're cold!");
}
//else if difference=>15 --- return youre warm
else if (difference >= 15) {
winflag=false;
return alert("You're warm!");
}
//else if difference=>5 --- return hot
else if (difference >= 5) {
winflag=false;
return alert("You're hot!");
}
//else if difference>=1 --- return burning
else if (difference >= 1) {
winflag=false;
return alert("You're burning!");
}
//else if difference=0 --- return GUESSED
else if (difference == 0) {
winflag=true;
return alert("You guessed!");
}
//else alert "not valid input"
else {
return alert("Not a valid input");
}
//end game
}
答案 0 :(得分:1)
如果您在var winflag=false;
内设置$(document).ready(function() {})
,则不会在全局范围内设置winflag
。 window.winflag=false
正在准备好的文档范围内。您需要像{{1}}一样设置它。