Add or remove time from a countdown - actionscript-3

I have a timer script:
import flash.utils.Timer;
import flash.events.TimerEvent;
var secs:Number = 30;//second
var mins:Number = 2;//minute
var sec_t:String;
var min_t:String;
var my_timer:Timer = new Timer(1000);
my_timer.addEventListener(TimerEvent.TIMER, timerHandler);
my_timer.start();
showTimer.text = "02:30";
function timerHandler(event:TimerEvent):void
{
if (secs == 0)
{
if (mins == 0)
{
my_timer.stop();
trace("Countdown is finished.");
showTimer.text =String(min_t+sec_t)+" Times Up";
return;
}
else
{
--mins;
secs = 59;
}
}
else
{
--secs;
}
sec_t = (secs < 10) ? "0" + String(secs):String(secs);
min_t = (mins < 10) ? "0" + String(mins) + ":":String(mins) + ":";
trace(min_t+sec_t);
showTimer.text =String(min_t+sec_t);
}
wrongBtn.addEventListener(MouseEvent.CLICK, wrongClick);
function wrongClick(event:MouseEvent):void
{
secs = secs - 10;
}
correctBtn.addEventListener(MouseEvent.CLICK, correctClick);
function correctClick(event:MouseEvent):void
{
secs = secs + 10;
}
There are two buttons, wrongBtn and correctBtn.
wrongBtn will decrease time by 10 seconds, correctBtn will increase time by adding 10 seconds.
But when the timer second is around 2:05 and I press wrongBtn, the time is displayed incorrectly, like this: "2:0-5". Likewise, when the time is around 2:55 and I press the correctBtn, the time will be displayed as "2:65"...
How can I get this working, so that the output is displayed correctly?

Keep one timer count instead of separate minutes and seconds. You can safely increase and decrease it, and always keep the correct time. To make it readable, just format the output:
import flash.events.TimerEvent;
import flash.utils.Timer;
var timeRemaining:int = 150; // 150 seconds => 2:30 mins
showTime.text = formatTimeRemaining();
var timer : Timer = new Timer (1000);
timer.addEventListener (TimerEvent.TIMER, onTimer);
timer.start();
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!");
}
wrongBtn.addEventListener(MouseEvent.CLICK, wrongClick);
function wrongClick(event:MouseEvent):void
{
timeRemaining -= 10;
}
correctBtn.addEventListener(MouseEvent.CLICK, correctClick);
function correctClick(event:MouseEvent):void
{
timeRemaining += 10;
}

Related

Countdown Timer in AS3

I'm testing the opposite script as a countdown timer, and there's a type error:
TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::Event#33d6b881f29 to flash.events.TimerEvent.
var goalTimerScore: int = Math.floor(Math.random() * 101) + 20;
var Minutes:Number = Math.floor(Math.random() * 11);
var Seconds:Number = Math.floor(Math.random() * 60);
timerMin_txt.text = String(Seconds);
timerSec_txt.text = String(Minutes);
timerWatch.addEventListener(Event.ENTER_FRAME, countTimer);
timerWatch.play();
function countTimer(e:TimerEvent):void {
if (timerWatch.currentFrame == 61) {
Seconds--;
if (Seconds > 59) {
Seconds = 0;
timerSec_txt.text = "0" + Seconds;
Minutes--;
if (Minutes > 10) {
timerMin_txt.text = "" + Minutes;
} else {
timerMin_txt.text = "0" + Minutes;
}
if (Minutes == 0 && Seconds == 0) {
timerWatch.removeEventListener(Event.ENTER_FRAME, countTimer);
timer.stop();
gotoAndPlay("gameover_Hidden3");
return;
}
}
else {
if (Seconds >= 10) {
timerSec_txt.text = "" + Seconds;
} else {
timerSec_txt.text = "0" + Seconds;
}
}
}
}
Any ideas how to solve this?
You have the wrong function parameters, they should be:
function countTimer(e:Event):void {
As a suggestion, running a timer off the frame rate can be pretty inconsistent as it relies on a constant frame rate. Probably better to use a time based approach.
You can use the Timer class for a basic approach. There is an example in the asdocs of a count down.
https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/Timer.html
function countTimer(e: Event): void {
if (timerWatch.currentFrame == 61) {
Seconds--;
if (Seconds < 0) {
Minutes--;
Seconds = 59;
}
if (Minutes == 0 && Seconds == 0) {
timerWatch.removeEventListener(Event.ENTER_FRAME, countTimer);
timerWatch.stop();
gotoAndPlay("gameover_Hidden3");
return;
}
if (Minutes >= 1 && Seconds == 0) {
if (Minutes == 0) {
timerMin_txt.textColor = 0xFF0000;
timerSec_txt.textColor = 0xFF0000;
}
}
}
if (Seconds < 10) {
timerSec_txt.text = "0" + Seconds;
} else {
timerSec_txt.text = "" + Seconds;
}
if (Minutes < 10) {
timerMin_txt.text = "0" + Minutes;
} else {
timerMin_txt.text = "" + Minutes;
}
}
A crucial thing for timer accuracy is the stage.frameRate property. Without maxing it out, accuracy will be multiples of 60 Hz.
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.getTimer;
import flash.utils.Timer;
stage.frameRate = 1000;
const t:Timer = new Timer(0);
t.addEventListener(TimerEvent.TIMER, t_h);
t.delay = 10000; //10 seconds
timestamp = getTimer();
t.start();
public function t_h(e:TimerEvent):void {
trace("countdown complete")
trace(getTimer() - timestamp)
t.stop();
}

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.

Timer related error in flash, TypeError #1009

I used a timer in my flash application, and I have this particular error below:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at FlashGame_fla::MainTimeline/toTimeCode()
at FlashGame_fla::MainTimeline/timerTickHandler()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
Below is my code for this particular flash game application. It's a game where the player collects as many items as possible within a specific time:
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.geom.Rectangle;
menuButton.addEventListener(MouseEvent.CLICK, evilToMenu);
rulesButton.addEventListener(MouseEvent.CLICK, toggleRule);
gameRules.addEventListener(MouseEvent.CLICK, toggleRule);
gameRules.visible = false;
gameRules.buttonMode = true;
evilGameOverMC.visible = false;
evilWinLose.visible = false;
playAgainBtn.visible = false;
toMenuBtn.visible = false;
var pLives:int = 3;
var pEvilScore:int = 0;
var pItems:int = 10;
var daveMC:MovieClip;
var cGameObjs:Array = new Array();
var timer:Timer = new Timer(100, 300);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 15000;
//var cPlayerData:Object;
//var cSavedGameData:SharedObject;
addCharacter();
addBots();
addItems();
scoreDisplay.text = "" + pEvilScore;
livesDisplay.text = pLives + " lives";
function evilToMenu(Event:MouseEvent):void
{
removeLeftovers();
removeChild(daveMC);
timer.stop();
gotoAndStop("menu");
}
function timerTickHandler(Event:TimerEvent):void
{
timerCount -= 100;
toTimeCode(timerCount);
if (timerCount <= 0)
{
gameOver(false);
}
}
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
timerDisplay.text = minutes + ":" + seconds;
}
function addCharacter():void
{
trace("Adding the character, Dave")
//set the initial values
var myBorder:Rectangle = new Rectangle(355,145,395,285);
var myXY:Array = [355,430];
var myChar:int = Math.ceil(Math.random() * 3);
var myKeys:Array = [37,39,38,40];
var myDistance:int = 7;
// create and add a new player object to the stage
daveMC = new Character(myBorder,myXY,myKeys,myChar,myDistance);
addChild(daveMC);
}
function addBots():void
{
trace("Adding the bots..");
// set the initial values (adapt to suit your game)
var myBorder:Rectangle = new Rectangle(355,145,395,285);
var myMaxBots:int = 5;// simulation
// add bots one at a time via a loop
for (var i:int = 0; i < myMaxBots; i++)
{
// create a new bot object and name it
var thisBot:Bot = new Bot(myBorder, daveMC);
thisBot.name = "bot" + i;
cGameObjs.push(thisBot);
// add it to the stage
addChild(thisBot);
}
}
function addItems():void
{
trace("Adding the items..");
//set the initial values
for (var i:int = 0; i < 10; i++)
{
// create a new bot object and name it
var thisItem:Item = new Item(daveMC);
thisItem.name = "item" + i;
cGameObjs.push(thisItem);
// add it to the stage
addChild(thisItem);
}
}
function updateLives(myBot:MovieClip):void
{
// update the player's LIVES and score
pLives--;
pEvilScore -= 30;
var myIndex:int = cGameObjs.indexOf(myBot);
cGameObjs.splice(myIndex,1);
// check for a LOST GAME
if (pLives > 0)
{
updateScores();
}
else
{
gameOver(false);
}
}
function updateItems(myItem:MovieClip):void
{
// update the player's LIVES and score
pItems--;
pEvilScore += 20;
var myIndex:int = cGameObjs.indexOf(myItem);
cGameObjs.splice(myIndex,1);
// check for a LOST GAME
if (pItems > 0)
{
updateScores();
}
else
{
gameOver(true);
}
}
function gameOver(myFlag:Boolean):void
{
updateScores();
if (myFlag)
{
// player wins
msgDisplay.text = "YAY! PAPPLE FOR \nEVERYBODY!";
removeLeftovers();
evilWinLose.text = "Weee!! We've got papples for Gru! \nYour Score: " + pEvilScore;
}
else
{
// player loses
msgDisplay.text = "OH NO! NOT \nENOUGH PAPPLES";
removeLeftovers();
evilWinLose.text = "Boo!! Not enough papples for Gru! \nYour Score: " + pEvilScore;
}
timerDisplay.text = "";
removeChild(daveMC);
evilGameOverMC.visible = true;
evilWinLose.visible = true;
toMenuBtn.visible = true;
playAgainBtn.visible = true;
toMenuBtn.addEventListener(MouseEvent.CLICK, Click_backtoMain);
playAgainBtn.addEventListener(MouseEvent.CLICK, backToEvil);
}
function updateScores():void
{
scoreDisplay.text = "" + pEvilScore;
livesDisplay.text = pLives + " lives";
msgDisplay.text = pItems + " papples more to \ncollect..";
}
function removeLeftovers():void
{
// check each BOT/ITEM in array
for each (var myObj in cGameObjs)
{
myObj.hasHitMe();
myObj = null;
}
}
function backToEvil(event:MouseEvent):void
{
pEvilScore = 0;
pLives = 3;
pItems = 3;
gotoAndStop("menu");
gotoAndStop("evil");
}
Anyone can help me out with this? Thank you alot! :)
Replace your toTimeCode function code by :
function toTimeCode(milliseconds:int): void
{
trace(1);
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
trace(2);
//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
trace(3);
var seconds:String = String(time.seconds);
trace(4);
var miliseconds:String = String(Math.round(time.milliseconds)/100);
trace(5);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+minutes : minutes;
trace(6);
seconds = (seconds.length != 2) ? '0'+seconds : seconds;
trace(7);
//display elapsed time on in a textfield on stage
timerDisplay.text = minutes + ":" + seconds;
trace(8);
}
Please, change the timerDisplay line to this one... The problem will be in the toTimeCode method. The error say that you are trying to call a method from a var wich is not (yet) an object...
if(null != timerDisplay)
timerDisplay.text = minutes + ":" + seconds;
You have to find an object wich is null! Add this :
function toTimeCode(milliseconds:int): void
{
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
trace("Time: " + time);

AS3 Simple timer with alarm?

I have been looking for an example code to create a simple countdown timer .
It would display the time in "Hours : Minutes : Seconds" and I would have the ability to set the time to 10 min, 30 min, 1 hour, 2 hour , etc.
When the timer hits zero, it would do a function. Your help is greatly appreciated. The only stuff I could find online was for counting down to a specific date.
Making a timer is very simple. You can read more on the AS3 Timer Class. Displaying the time as HH:MM:SS is a little bit of work. I use this class when I need to do that:
package com.dop.utils
{
public class Timecodes
{
public function Timecodes()
{
}
public static function timecodeToSeconds(tcStr:String):Number
{
var t:Array = tcStr.split(":");
return (t[0] * 3600 + t[1] * 60 + t[2] * 1);
}
public static function secondsToTimecode(seconds:Number):String
{
var minutes:Number = Math.floor(seconds/60);
var remainingSec:Number = seconds % 60;
var remainingMinutes:Number = minutes % 60;
var hours:Number = Math.floor(minutes/60);
var floatSeconds:Number = Math.floor((remainingSec - Math.floor(remainingSec))*100);
remainingSec = Math.floor(remainingSec);
return getTwoDigits(hours) + ":" + getTwoDigits(remainingMinutes) + ":" + getTwoDigits(remainingSec);
}
private static function getTwoDigits(number:Number):String
{
if (number < 10)
{
return "0" + number;
}
else
{
return number + "";
}
}
}
}
I made a little example that you can see here using this class: http://ronnieswietek.com/cc/alarm/alarm.swf
(and source here: http://ronnieswietek.com/cc/alarm/alarm.fla)
The code I used that utilizes the Timer class is here:
import com.dop.utils.Timecodes;
import flash.events.*;
import fl.controls.*;
import fl.data.*;
import flash.utils.Timer;
var timer:Timer = new Timer(1000); //-- run once a second
timer.addEventListener(TimerEvent.TIMER, onTimer);
var countdown:Number = 0;
var durations:Array = [
{label:'1 minute',time:1},
{label:'5 minutes',time:5},
{label:'10 minutes',time:10},
{label:'30 minutes',time:30},
{label:'1 hour',time:60},
{label:'2 hours',time:120},
{label:'3 hours',time:180}
];
durationBox.dataProvider = new DataProvider(durations);
timerButton.addEventListener(MouseEvent.CLICK, timerHandler);
function timerHandler(e:MouseEvent):void
{
if (!timer.running)
{
var selectedTime:Number = durationBox.selectedItem.time * 60;
countdown = selectedTime;
timeText.text = Timecodes.secondsToTimecode(countdown);
timer.start();
timerButton.label = "Stop";
}
else
{
countdown = 0;
timeText.text = Timecodes.secondsToTimecode(countdown);
timer.stop();
timer.reset();
timerButton.label = "Start";
}
}
function onTimer(e:TimerEvent):void
{
timeText.text = Timecodes.secondsToTimecode(countdown);
countdown--;
if (countdown == 0)
{
timer.stop();
timer.reset();
timeText.text = "ALARM!!!";
}
}
Where accuracy is required you can't rely on the Timer class alone to give you a precise passage of time. Especially if the Flash Player is doing a lot of other work. This is because the Timer classes interval is actually a request and not a guarantee. Let's take a look, start with a trivial implementation of a timer ticking once a second (1000 milliseconds):
private var startTime:uint;
private var ticks:int;
protected function start():void
{
var t:Timer = new Timer( 1000 );
t.addEventListener( TimerEvent.TIMER, timerTick );
t.start();
startTime = getTimer();
}
protected function timerTick( event:TimerEvent ):void
{
trace( 'Ideal: ' + (++ticks) + ' Actual: ' + (getTimer()-startTime)/1000 );
}
Using getTimer (get familiar with getTimer) to measure the actual time we can see within 20 seconds the Timer class is a half a second behind. This drift will vary each time this is run:
Expected: 1 Actual: 1.043
Expected: 2 Actual: 2.083
Expected: 3 Actual: 3.082
…
Expected: 18 Actual: 18.417
Expected: 19 Actual: 19.457
Expected: 20 Actual: 20.5
That's where implementing a Stopwatch comes in handy for measuring time more precisely:
import flash.utils.getTimer;
public class Stopwatch
{
private var startStamp:Number;
private var stopStamp:Number;
private var runTime:Number;
private var _countdownDuration:Number;
private var started:Boolean;
private var stopped:Boolean;
private var paused:Boolean;
function Stopwatch( startNow:Boolean = true ):void
{
if ( startNow )
start();
}
public function start():void
{
runTime = 0;
startStamp = getTimer();
_countdownDuration = 0;
started = true;
stopped = false;
paused = false;
}
public function startCountdown( milliseconds:Number ):void
{
start();
_countdownDuration = milliseconds;
}
public function pause():void
{
if ( started && ! stopped )
{
runTime += getTimer() - startStamp;
paused = true;
}
}
public function resume():void
{
if ( started && paused )
{
startStamp = getTimer();
paused = false;
}
}
public function stop():void
{
if ( started && ! stopped )
{
if ( ! paused )
runTime += getTimer() - startStamp;
stopped = true;
paused = false;
}
}
public function set elapsed( value:uint ):void
{
runTime = value;
if ( running )
startStamp = getTimer();
}
public function get elapsed():uint
{
if ( running )
return ( getTimer() - startStamp ) + runTime;
return runTime;
}
public function get running():Boolean
{
return ( started && ! paused && ! stopped );
}
public function get countdownDuration():Number
{
return _countdownDuration;
}
public function set countdownDuration( value:Number ):void
{
_countdownDuration = value;
}
public function get remaining():int
{
if ( ! _countdownDuration )
return 0;
else if ( _countdownDuration - elapsed < 0 )
return 0;
return _countdownDuration - elapsed;
}
}
Extending the first example with Stopwatch you can effectively measure the passage of time very simply (just remember stopwatch.elapsed is in milliseconds so we'll divide by 1000 for seconds):
private var stopwatch:Stopwatch;
protected function start():void
{
var t:Timer = new Timer( 1000 );
t.addEventListener( TimerEvent.TIMER, timerTick );
t.start();
stopwatch = new Stopwatch;
stopwatch.start();
}
protected function timerTick( event:TimerEvent ):void
{
trace( stopwatch.elapsed/1000 + ' seconds have elapsed',
(60 * 10) - stopwatch.elapsed/1000 + ' seconds remain' );
}
Since stopwatch.elapsed is in milliseconds, you'll want to convert that quantity to different time increments. Following the Single Responsibility Principle we'll make a reusable general use class called StopwatchFormatter to help us consolidate these calculations and expose a readable API:
public class StopwatchFormatter
{
private var elapsed:Number;
public var paddedSize:int;
public var cappedDecimalLength:int;
function StopwatchFormatter( paddedSize:Number = 2, cappedDecimalLength:Number = 1, elapsed:Number = 0 )
{
this.elapsed = elapsed;
this.paddedSize = paddedSize;
this.cappedDecimalLength = cappedDecimalLength;
}
// INPUTS
public function setTimeAsGroup( hours:Number, minutes:Number = 0, seconds:Number = 0, milliseconds:Number = 0 ):StopwatchFormatter
{
elapsed = ( hours * 60 * 60 * 1000 ) + ( minutes * 60 * 1000 ) + ( seconds * 1000 ) + milliseconds;
return this;
}
public function set totalMilliseconds( value:Number ):void
{
elapsed = value;
}
public function set totalSeconds( value:Number ):void
{
elapsed = value * 1000;
}
public function set totalMinutes( value:Number ):void
{
elapsed = value * 1000 * 60;
}
public function set totalHours( value:Number ):void
{
elapsed = value * 1000 * 60 * 60;
}
// CLOCK LIKE
// (converting to int will drop the decimal place)
public function get milliseconds():int
{
return elapsed % 1000;
}
public function get seconds():int
{
return ( elapsed / 1000 ) % 60;
}
public function get minutes():int
{
return ( elapsed / 1000 / 60 ) % 60;
}
public function get hours():int
{
return ( elapsed / 1000 / 60 / 60 ) % 24;
}
// CLOCK PADDED (zeroes in the front)
// 5 becomes "05" , 10 becomes "10" where _paddedSize is 2
public function get millisecondsPadded():String
{
return frontPad( milliseconds );
}
public function get secondsPadded():String
{
return frontPad( seconds );
}
public function get minutesPadded():String
{
return frontPad( minutes );
}
public function get hoursPadded():String
{
return frontPad( hours );
}
// TOTAL
public function get totalMilliseconds():Number
{
return elapsed;
}
public function get totalSeconds():Number
{
return elapsed / 1000;
}
public function get totalMinutes():Number
{
return elapsed / 1000 / 60;
}
public function get totalHours():Number
{
return elapsed / 1000 / 60 / 60;
}
// TOTAL CAPPED
// 3.134 becomes 3.1 where _cappedDecimalLength is 1
public function get totalMillisecondsCapped():Number
{
return capped( totalMilliseconds );
}
public function get totalSecondsCapped():Number
{
return capped( totalSeconds );
}
public function get totalMinutesCapped():Number
{
return capped( totalMinutes );
}
public function get totalHoursCapped():Number
{
return capped( totalHours );
}
// TOTAL CAPPED + PADDED (zeroes in the back and one zero in the front for values less than 0)
// 3.101 becomes "3.10" where _cappedDecimalLength is 2
public function get totalSecondsCappedPadded():String
{
return capped( totalSeconds ).toFixed( cappedDecimalLength );
}
public function get totalMinutesCappedPadded():String
{
return capped( totalMinutes ).toFixed( cappedDecimalLength );
}
public function get totalHoursCappedPadded():String
{
return capped( totalHours ).toFixed( cappedDecimalLength );
}
// UTILITY FUNCTIONS
private function frontPad( n:int ):String
{
var s:String = n.toString();
if ( s.length < paddedSize )
{
var i:int = 0;
var len:int = paddedSize - s.length;
for ( ; i < len; i++ )
{
s = "0" + s;
}
}
return s;
}
private function capped( input:Number ):Number
{
if ( cappedDecimalLength == 0 )
return Math.floor( input );
var decimalFactor:Number = Math.pow( 10, cappedDecimalLength );
return Math.floor( input * decimalFactor ) / decimalFactor;
}
}
Pulling it all together with these two classes and a Timer we have a trivial way to countdown:
private var stopwatch:Stopwatch;
private var time:StopwatchFormatter;
protected function start():void
{
var t:Timer = new Timer( 1000 );
t.addEventListener( TimerEvent.TIMER, timerTick );
t.start();
stopwatch = new Stopwatch;
stopwatch.startCountdown( new StopwatchFormatter().setTimeAsGroup( 1, 10, 30 ).totalMilliseconds );
time = new StopwatchFormatter;
}
protected function timerTick( event:TimerEvent ):void
{
time.totalMilliseconds = stopwatch.elapsed;
var elapsed:String = time.hoursPadded + ':' + time.minutesPadded + ':' + time.secondsPadded + ':' + time.millisecondsPadded;
time.totalMilliseconds = stopwatch.remaining;
var remainig:String = time.hoursPadded + ':' + time.minutesPadded + ':' + time.secondsPadded + ':' + time.millisecondsPadded;
trace( 'Elapsed:', elapsed, "Remaining:", remainig );
}

gotoandstop problems actionscript 3

I have a memory game program and when the timer runs out, I want it to go to frame 3 where it displays the "game failed" page.
I have it all set up, except when the game runs out of time, the frame just appears to overlap the original frame, instead of going to a completely separate page.
Can anyone help me?
Here is my code:
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.display.MovieClip;
import flash.text.TextField;
public class MemoryGame extends MovieClip{
private var firstTile:cards;
private var secondTile:cards;
private var pauseTimer:Timer;
private var score:int;
private var cardCount:int;
var seconds:Number;
var minutes:Number;
var numberDeck:Array = new Array(1,1,2,2,3,3,4,4,5,5,6,6);
public function MemoryGame(){
//TIMER FUNCTION
var levelTimer:Timer = new Timer(1000, 180);
levelTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteHandler);
levelTimer.addEventListener(TimerEvent.TIMER, timerHandler);
// LEVEL FUNCTION
easyBtn.addEventListener(MouseEvent.CLICK, easyButtonClicked);
medBtn.addEventListener(MouseEvent.CLICK, medButtonClicked);
hardBtn.addEventListener(MouseEvent.CLICK, hardButtonClicked);
score = 0;
txtScore.text=""+score;
//Level button events
function easyButtonClicked(e:MouseEvent):void{
removeChild(levelText);
trace("easy button clicked!");
seconds = 0;
minutes = 1;
txtTime.text = "1:00";
levelTimer.start();
setupTiles();
}
function medButtonClicked(e:MouseEvent):void{
removeChild(levelText);
trace("medium button clicked!");
seconds = 30;
minutes = 0;
txtTime.text = "0:30";
levelTimer.start();
setupTiles();
}
function hardButtonClicked(e:MouseEvent):void{
removeChild(levelText);
trace("hard button clicked!");
seconds = 15;
minutes = 0;
txtTime.text = "0:15";
levelTimer.start();
setupTiles();
}
//Timer handlers
function timerHandler(e:TimerEvent):void {
if (seconds > 00) {
seconds -=1;
}
else {
if (minutes > 0) {minutes -=1;seconds = 59;}
}
txtTime.text = minutes+":"+(seconds >= 10 ? seconds : "0"+seconds);
}
function timerCompleteHandler(e:TimerEvent):void {
e.target.reset();
e.target.stop();
trace("game over!");
}
//Tiles set up
function setupTiles(){
for(x=1; x<=4; x++) {
for (y=1; y<=3; y++){
var randomCard = Math.floor(Math.random()*numberDeck.length);
var tile:cards = new cards();
tile.card = numberDeck[randomCard];
numberDeck.splice(randomCard,1);
tile.gotoAndStop(9);
tile.x = (x-1) * 150;
tile.y = (y-1) * 200;
tile.addEventListener(MouseEvent.CLICK,tileClicked);
addChild(tile);
cardCount = cardCount + 1
}
}
}
}
public function tileClicked(event:MouseEvent) {
var clicked:cards = (event.currentTarget as cards);
if (firstTile == null){
firstTile = clicked;
firstTile.gotoAndStop(clicked.card);
}
else if (secondTile == null && firstTile != clicked){
secondTile = clicked;
secondTile.gotoAndStop(clicked.card);
if (firstTile.card == secondTile.card){
pauseTimer = new Timer(1000, 1);
pauseTimer.addEventListener(TimerEvent.TIMER_COMPLETE,removeCards);
pauseTimer.start();
}
else {
pauseTimer = new Timer(1000, 1);
pauseTimer.addEventListener(TimerEvent.TIMER_COMPLETE,resetCards);
pauseTimer.start();
}
}
if (seconds == 0){
this.gotoAndStop(2);
pauseTimer.stop();
//levelTimer.stop();
}
}
public function resetCards(event:TimerEvent) {
firstTile.gotoAndStop(9);
secondTile.gotoAndStop(9);
firstTile = null;
secondTile = null;
pauseTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,resetCards);
score = score - 2;
txtScore.text=""+score;
}
public function removeCards(event:TimerEvent){
removeChild(firstTile);
removeChild(secondTile);
firstTile = null;
secondTile = null;
pauseTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,removeCards);
score = score + 10;
txtScore.text=""+score;
cardCount = cardCount - 2;
trace("Cardcount: " + cardCount);
if (cardCount == 0){
this.gotoAndStop(2);
txtFinalScore.text=" "+score;
pauseTimer.stop();
}
}
}
}
Thank you so much!
When you add an object using addChild(object) it isn't associated with keyframes along the timeline.
So what you need to do is rather than jumping to frame 2, removeChild(object) or object.visible = false all children you don't want and addChild(object) your 'out of time' assets.
A good work ethic is to create destroy() functions that remove and null any unwanted assets. This way you can easily remove unwanted items and free up memory.