Action Script 3. Restore timer to 0 after game restart - actionscript-3

I'm creating flash game, here is timer which counts how long player playing at current level. And here is "Restart" button, I need to restart timer (count from 0) after this button is clicked.
Here is my timer's code:
public function MemoryGame()
{
addChild(CardContainer);
tryAgain.addEventListener(MouseEvent.CLICK, restartGame);
timer = new Timer(1000); //create a new timer that ticks every second.
timer.addEventListener(TimerEvent.TIMER, tick, false, 0, true); //listen for the timer tick
txtTime = new TextField();
addChild(txtTime);
tmpTime = timer.currentCount;
timer.start();
}
private function tick(e:Event):void {
txtTime.text = showTimePassed(timer.currentCount - tmpTime);
var format:TextFormat = new TextFormat();
format.font = "Verdana";
format.color = 0xFF0000;
format.size = 16;
format.bold = true;
//txtTime.x = 250;
txtTime.width/2;
var stageCenter_x:Number = stage.stageWidth/2;
var stageCenter_y:Number = stage.stageHeight/2;
var textCenter_x:Number = txtTime.width/2;
var textCenter_y:Number = txtTime.height/2;
txtTime.x = stageCenter_x - textCenter_x;
txtTime.autoSize = TextFieldAutoSize.CENTER;
txtTime.defaultTextFormat = format;
}
function showTimePassed(startTime:int):String {
var leadingZeroMS:String = ""; //how many leading 0's to put in front of the miliseconds
var leadingZeroS:String = ""; //how many leading 0's to put in front of the seconds
var leadingZeroM:String = "";
var time = getTimer() - startTime; //this gets the amount of miliseconds elapsed
var miliseconds = (time % 1000); // modulus (%) gives you the remainder after dividing,
if (miliseconds < 10) { //if less than two digits, add a leading 0
leadingZeroMS = "0";
}
var seconds = Math.floor((time / 1000) % 60); //this gets the amount of seconds
if (seconds < 10) { //if seconds are less than two digits, add the leading zero
leadingZeroS = "0";
}
var minutes = Math.floor((time / (60 * 1000) ) );
if (minutes < 10) { //if seconds are less than two digits, add the leading zero
leadingZeroM = "0";
}
//60 seconds times 1000 miliseocnds gets the minutes
return leadingZeroM + minutes + ":" + leadingZeroS + seconds + "" + leadingZeroMS ;
}
When I use: removeChild(txtTime); and later addChild(txtTime); timer not restarting just removing for the time, later adding again and continue time counting. How to restore timer to 0? Any ideas? Thank you very much.
EDIT:
Timer must resets when restartGame() function is used.
When I use this - nothing happens.
public function MemoryGame()
{
addChild(CardContainer);
tryAgain.addEventListener(MouseEvent.CLICK, restartGame);
timer = new Timer(1000); //create a new timer that ticks every second.
timer.addEventListener(TimerEvent.TIMER, tick, false, 0, true); //listen for the timer tick
timer.addEventListener(TimerEvent.TIMER, resetTimer);
txtTime = new TextField();
addChild(txtTime);
tmpTime = timer.currentCount;
timer.start();
}
function restartGame(e:MouseEvent):void
{
timer.addEventListener(TimerEvent.TIMER, resetTimer);
}
function resetTimer(event:TimerEvent):void{
timer.reset();
timer.start();
}
When I use this - timer stops and continue counting, but not reseting.
function restartGame(e:MouseEvent):void
{
timer.reset();
timer.start();
}
What's wrong?

You can use
timer.reset();
to reset it and then start it again with:
timer.start();
See docs for more info

Related

Restarting timer in action script 3 function resetClock

I'm new to action script 3 so i will be picking your brains I lot.
I'm making a simple 5 min scoreboard for my workplace to use and now im stuck on making the reset button work.
I have made 3 buttons with instance of (start-btn, stop_btn and reset_btn) but I can't figure out the function code for the reset_btn. I need it to go back to 5:00 and stop so you can press start and begin counting from (5:00 or in my case 300) again.
This is my code so far:
import flash.events.TimerEvent;
import flash.utils.Timer;
var timeRemaining:int = 300;
showTime.text = formatTimeRemaining();
var timer:Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, onTimer);
timer.stop();
start_btn.addEventListener(MouseEvent.CLICK, startClock);
function startClock(event:MouseEvent):void
{
timer.start();
}
stop_btn.addEventListener(MouseEvent.CLICK, stopClock);
function stopClock(event:MouseEvent):void
{
timer.stop();
}
reset_btn.addEventListener(MouseEvent.CLICK, resetClock);
function resetClock(event:MouseEvent):void
{
timer.reset();
showTime.text = "300";
}
function onTimer( ev:TimerEvent ):void
{
timeRemaining--;
if (timeRemaining < 0)
{
timeRemaining = 0;
loseGame();
}
else
{
showTime.text = formatTimeRemaining();
}
}
function formatTimeRemaining():String
{
var mins : int = int (timeRemaining / 60);
var minstr:String = mins < 10 ? "0" + mins:"" + mins;
var secs:int = timeRemaining % 60;
var secstr:String = secs < 10 ? "0" + secs:"" + secs;
return minstr+":"+secstr;
}
function loseGame():void
{
timer.stop();
trace("Countdown is finished.");
showTime.text = formatTimeRemaining() + (" Time's Up!");
}
function resetClock(event:MouseEvent):void
{
timer.stop();
timeRemaining = 300;
showTime.text = formatTimeRemaining();
}
Simply stop the timer, reset the timeRemaining variable then display it.

Stop clock on pause button

I have a "clock" counting down the time of the game (from 9 seconds to 0 seconds). I have a button that pauses the game, so I want to freeze de clock and when I click to play, the game continuos from that second that I frozen. But I don't have any idea how to do this! Can you help me please?
this.addEventListener(Event.ENTER_FRAME, updateTimer);
function updateTimer(e:Event){
var t:uint = getTimer();
var dt:uint = 9000 - t;
var totseconds:uint = Math.floor(dt/1000);
var minutes:uint = Math.floor(totseconds/60);
var seconds:uint = Math.floor(totseconds%60);
var minsWithZ = minutes < 10 ? "0" + minutes : minutes;
var secsWithZ = seconds < 10 ? "0" + seconds : seconds;
var time = minsWithZ + ":" + secsWithZ;
this.tempo_txt.text = time;
}
pausa.addEventListener(MouseEvent.MOUSE_UP, menuPause);
function menuPause(e:MouseEvent){
...somegame code...
voltar.addEventListener(MouseEvent.MOUSE_UP, play);
}
function play (e:MouseEvent){
...some game code
}
You have two choices at least:
1-Andre's answer;
2-my answer:
import flash.events.Event;
var dt:int = 9000
var diff:Number=0;
var prevDiff:Number=0;
var currentTime:Number=0;
var t:uint=0;
var totseconds:int=0;
var minutes:int=0;
var seconds:int=0;
var minsWithZ;
var secsWithZ;
var running:Boolean=true;
var time;
this.addEventListener(Event.ENTER_FRAME, updateTimer);
function updateTimer(e:Event){
if(dt<1){dt=1;menuPause(null)}
trace(running);
totseconds= Math.floor(dt/1000);
minutes= Math.floor(totseconds/60);
seconds= Math.floor(totseconds%60);
minsWithZ = minutes < 10 ? "0" + minutes : minutes;
secsWithZ = seconds < 10 ? "0" + seconds : seconds;
time = minsWithZ + ":" + secsWithZ;
this.tempo_txt.text = time;
if(running){
t= getTimer()-diff-prevDiff;
dt=5000- t;
}else{
diff=getTimer()-currentTime;
}
}
pausa.addEventListener(MouseEvent.MOUSE_UP, menuPause);
voltar.addEventListener(MouseEvent.MOUSE_UP, reset);
function menuPause(e:Event){
running=false;
currentTime=getTimer();
prevDiff+=diff;
}
function menuPlay (e:Event){
running=true;
}
function reset(){
running=true;
prevDiff+=9000;
}
A little explaination on code:
getTimer() returns the miliseconds from when you opened the app and
You can't Pause "getTimer()"
but you can get the time that game is paused and subtract from getTimer().
variable "diff" does that here.
and "currentTime" is when you paused the game.
Andre's answer is more easy;
my answer is more accurate.
because getTimer() returns real miliseconds but timer is not ticking exactly accurate.ENTER_FRAME event and setInterval are also same as timer.
that means if you want a more simple code, use Andre's and if you want an accurate Timer, use Mine.
and removing eventListener (3vilguy's answer) is not enough
because getTimer won't Pause !
I hope my answer be useful.
Better using the Timer- Object
var seconds=9;
var t:Timer=new Timer(1000,seconds);
t.addEventListener(TimerEvent.TIMER, updateTimer);
t.addEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteHandler);
updateTimer();
t.start();
function updateTimer(e:TimerEvent=null){
var t:uint = t.currentCount;
var dt:uint = seconds - t;
var totseconds:uint = dt;
var minutes:uint = Math.floor(totseconds/60);
var sec:uint = Math.floor(totseconds%60);
var minsWithZ = minutes < 10 ? "0" + minutes : minutes;
var secsWithZ = sec < 10 ? "0" + sec : sec;
var time = minsWithZ + ":" + secsWithZ;
this.tempo_txt.text = time;
}
function timerCompleteHandler(e:TimerEvent):void{
trace("Timer complete");
}
pausa.addEventListener(MouseEvent.MOUSE_UP, menuPause);
function menuPause(e:MouseEvent){
t.stop();
voltar.addEventListener(MouseEvent.MOUSE_UP, play);
}
function play (e:MouseEvent){
t.start();
}
Greetings

Timer in as3 initial value

I have a timer counting up in as3. I am trying to simulate a clock counting up from 07:30 to 12:00. The functionality of the counting is working. How would i set an initial start value and a stop value?
Here is my code:
var timer:Timer = new Timer(100, 50);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 10;
function timerTickHandler(Event:TimerEvent):void
{
timerCount += 10000;
toTimeCode(timerCount);
}
function toTimeCode(milliseconds:int) : void
{
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
var seconds:String = String(time.seconds);
var miliseconds:String = String(Math.round(time.milliseconds)/100);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+minutes : minutes;
seconds = (seconds.length != 2) ? '0'+seconds : seconds;
//display elapsed time on in a textfield on stage
timer_txt.text = minutes + ":" + seconds;
}
There are a few ways you can do this. I'll share 2 of them.
Initialize a date object to your starting time: (before your timer starts ticking)
var time:Date = new Date();
time.setHours(7, 30);
Then append your milliseconds to the time every timer interval:
time.time += milliseconds;
This would be a good way to go if you needed to stop the clock for some reason.
If you don't need to stop the clock ever (and wanted an accurate clock), you could do the following:
var time:Date = new Date();
time.setHours(7,30);
var offset:Number = flash.utils.getTimer(); //this gets the amount of milliseconds elapsed since the application started;
Then in your interval method:
time.time += flash.utils.getTimer() - offset;

Unknown error in Flash CS6 AS3 code

I am trying to build a countdown timer that uses a time that is contained in a text document called ResponseTime.txt. I am getting no error messages however it is not working. I can't find the problem.
{
addEventListener('enterframe', callback_handler)
function callback_handler(e:Event):void {
var StartTime:URLLoader = new URLLoader();
StartTime.dataFormat=URLLoaderDataFormat.VARIABLES;
StartTime.addEventListener(Event.COMPLETE, onLoaded);
function onLoaded(e:Event):void {
StartTime.load(new URLRequest("ResponseTime.txt"));
var today:Date = new Date();
var currentTime = today.getTime();
var targetDate:Date = new Date();
var timeLeft = StartTime.data - currentTime;
var sec = Math.floor(timeLeft/1000);
var min = Math.floor(sec/60);
sec = String(sec % 60);
if(sec.length < 2){
sec = "0" + sec;
}
min = String(min % 60);
if(min.length < 2){
min = "0" + min;
}
if(timeLeft > 0 ){
var counter:String = min + ":" + sec;
time_txt.text = counter;
}else{
var newTime:String = "00:00";
time_txt.text = newTime;
}
}
}
}
Thanks.
You're calling the load method in onLoaded which is the callback for when it finishes loading. So the loader never actually starts loading.
function onLoaded(e:Event):void {
StartTime.load(new URLRequest("ResponseTime.txt"));
}
Just start the load outside the callback.

AS3 / Stopping timer at a Vector?

How do i start my timer at vector[2] and stop it at vec[13]. myTimer.stop();
I have done that the vector jumps to the next vector every 10 seconds (timerevent). The timer and vector will continue to count and then goes back to the vec[0]
If possible, I would like to start my timer at a later vector. And that the timer stops at the end.
var myTimer:Timer = new Timer(1000);
myTimer.repeatCount = 13;
myTimer.delay = 1000;
myTimer.addEventListener(TimerEvent.TIMER, countdownHandler);
function countdownHandler(event:TimerEvent):void
{
countdown.text = 0+myTimer.currentCount+" s remaining";
countdown2.text = 0+myTimer.currentCount+" s remaining";
if(myTimer.currentCount==10)
{
myTimer.reset();
myTimer.start();
}
}
myTimer.start();
&
function timerfunctie(event:TimerEvent)
{
for(var i:int = 0; i < vec.length; i++)
{
if (vec[i].parent) if (myTimer.currentCount == 9)
{
removeChild(vec[i]);
var next2:int = i+1;
if(next2 == vec.length) next2 = 0;
addChild(vec[next2]);
break;
}
}
}
Not sure where timerfunctie is called, but this code should detect when the currentCount of the timer is 2 and 13. If you want the Timer to run the full 13 iterations, you do not want to reset it at iteration 10.
function countdownHandler(event:TimerEvent):void
{
countdown.text = 0+myTimer.currentCount+" s remaining";
countdown2.text = 0+myTimer.currentCount+" s remaining";
if (myTimer.currentCount==2) {
// start with vector[2]
} else if (myTimer.currentCount==13) {
// end with vector[13]
}
}