0

I am creating a game that uses a timer set to a random number. The timer counts up to this number then the game ends. I would like the player to have an option to replay once the timer runs out but I am having trouble determining how to do this. Here is what it looks like now.

var age:int = Math.floor(Math.random()*100)+1;
trace(age);
var upCounter:int = 1;
timer();

//timer
function timer(){
var myTimer:Timer = new Timer(1000, age);
myTimer.addEventListener("timer", timerHandler);
myTimer.start();
}

//displays timer and triggers outcome function
function timerHandler(event:TimerEvent):void{
    if ( upCounter < age) {
          trace(upCounter);
          age_txt.text = String(upCounter);
          upCounter++;
          }
          else{
            outcome();
          }
}

The problem is the "age" and "upCounter" variables are global, and if I put them inside a "startGame" function I can not pass them to the "timerHandler". If I don't put them inside a "startGame" function I don't know how to restart the game. Thanks.

1 Answers1

0

You have defined your timer as iterating the value of age, right ?

So why not just add a TIMER_COMPLETE event ?

myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, outcome);

function outcome(e:TimerEvent):void
{
    var myTimer:Timer = e.target as Timer;
    myTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, outcome);

    // prompt to play again or whatever goes here.
}

In your TIMER event handler, just put the things that need to happen on a timer tick.

prototypical
  • 6,731
  • 3
  • 24
  • 34