Sam Creamer
Sam Creamer

Reputation: 5361

variable doesn't update when function restarts (javascript)

I'm going to try my best to ask this question without a huge wall of code. Basically I have written a very simple math quiz game. In this game you select a difficulty, the number of questions you want, and the game starts. It asks that number of questions and then you get a score and then the game is over. However, you can restart the game. When you restart, it simply returns you to the home screen, then you can select your options again. The only problem is, we need to keep track of the number of questions remaining in the quiz, the first time around, it works well. We pass numQuestions to the game function. The second time, however, even if I pass numQuestions=10, the value remains 0 from the first time I played the game. Here is the game function:

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();

        }

    });

}

any ideas? Thanks

edit:

$(".numberQButton").click(function(){
        numQuestions = parseFloat($(this).html());
        $("#numQuestionsScreen").hide();
        $("#gameScreen").show();
        $("#score").html(0);
        startGame(difficulty,numQuestions,score);
});

Upvotes: 0

Views: 214

Answers (3)

CharlyDelta
CharlyDelta

Reputation: 938

Where do you define the on click listener? If it triggers two times, it seems like you are defining the on click listener in such way, that after you completed one game and start all over, a new listener will be registered so you got 2 in the end.

Upvotes: 1

Lawrence Jones
Lawrence Jones

Reputation: 955

You're problem (I think) lies in closures. When you declare a function in javascript, any accessing of a variable from outside it's own scope generates what is called a closure. In this case, numQuestions is accessed from inside your event function, creating a closure. The effect of this is that any accessing of the variable numQuestions inside your event functions references the variable as it was from the moment your javascript interpreter came across the event function itself- ie, the first time you play your game.

Have a look at these to get an idea of where it's going wrong.

Upvotes: 1

Neil Girardi
Neil Girardi

Reputation: 4923

It sounds like you need to instantiate a new Game object when the game is restarted.

Upvotes: 1

Related Questions