-1

I'm currently building a Tron canvas game based on this code. it works kinda good, but if I restart the game, two values are getting passed via e.which.

Try to show main code:

function loadGame() {
    var e;
    document.onkeydown=function(event){e=event};

    function intervall() {
        function check() { 
           //Function for drawing Tron
        }
        var key = e.which;
        if(key == 87) { //W and so one
            check();
        }
    }
    var timer = setInterval(intervall,900)
}

If I lose, and call loadGame() again, it works great. It does not if I call loadGame() while Game is still running.

I uploaded a live demo here: http://wernersbacher.de/tron.html

Thanks for any help!

Standard
  • 1,450
  • 17
  • 35
  • There's not really enough here to tell what is going wrong. What is loadGame supposed to do? – Matt R Aug 15 '14 at 21:29

1 Answers1

1

You're getting two values because when you restart the game, the old interval loop is still running when you start a new one.

I see you're trying to stop the old loop here:

if(hard) {
    clearInterval(timer);
}

However, because the variable 'timer' was declared in a different invocation of the loadGame function, this newly invoked loadGame function has no access to it.

You can see this in action by logging the variable to the console from the new loadGame invocation:

function loadGame(hard) {
    if(hard) {
        console.log(timer);
    }

You'll see it returns undefined.

If any of this sounds confusing to you, you might want to learn more about Function scope.

A solution is to declare the 'time' variable outside the loadGame function, in the global scope:

var time;
function loadGame(hard) {
    /* the rest of your code */
    timer = setInterval(intervall,9)
}

That way, the new instance of the loadGame function which is called when you press the 'Load game' button has access to the old timer and can stop it before starting a new one.

Incidentally, completely reloading everything, including creating a new canvas element and destroying the old one, seems a bit unnecessary. Why not simply clear() the canvas and reset the player position to the start position? You don't even need to restart the timer using that method.

Zekko
  • 73
  • 6