Reputation: 189
I am working on s atudent project: a 'hot or cold' game app but can't seem to understand something.
The problem is that when there is a correct guess, the flag I have setup to register the guess does not register the change (caused by the correct guess) permanently and the user can continue guessing.
I change the value of the global variable winflag when the user makes the correct guess but for some reason it goes back to false (i.e. no guess yet) and continues the game.
Can anyone please point out why is this happening?
//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
}
Upvotes: 0
Views: 1273
Reputation: 809
If you are setting var winflag=false;
inside a $(document).ready(function() {})
then it is not being set on the global scope. The winflag
is being set within the scope of the document ready. You need to set it like so window.winflag=false
.
Upvotes: 1