Displaying Time After the Game Is Over as3 - actionscript-3

hey i am new with ac3.
this is my code for the timer:
its started in frame 1
in the end of the game it's continue to frame 3.
i dont know how to show the timer there...
var timer:Timer = new Timer(100);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 0;
function timerTickHandler(Event:TimerEvent):void
{
timerCount += 100;
toTimeCode(timerCount);
}
function toTimeCode(milliseconds:int) : void {
//create 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+"";
}

The Timer function isn't what you want. That's for a countdown. You just want to count up, which requires recording when you started, and deducting that from the current runtime.
import flash.utils.*;
var start:Number = flash.utils.getTimer();
function showElapsedTime():void {
trace(toTimeCode(flash.utils.getTimer() - start));
}

Related

AS3 How to Set Up A Max Time Count Up

I have the following count up code, but am not sure how I would be able to include an if else statement to have the count-up stop at 15 seconds for example.
Here is the code:
var timer:Timer = new Timer(100);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 0;
function timerTickHandler(Event:TimerEvent):void{
timerCount += 100;
toTimeCode(timerCount);
}
function toTimeCode(milliseconds:int) : void {
//create 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+"." + miliseconds;
}
First, for efficiency, you can use the timers built in currentCount property to know how much time has elapsed (instead of making a timerCount var to that end)
To stop the timer after 15 seconds, simply set the appropriate repeat count so it ends at 15 seconds, or stop it in the tick handler after 15 seconds have past:
var timer:Timer = new Timer(100,150); //adding the second parameter (repeat count), will make the timer run 150 times, which at 100ms will be 15 seconds.
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, timerFinished); //if you want to call a function when all done
function timerTickHandler(Event:TimerEvent):void{
toTimeCode(timer.delay * timer.currentCount); //the gives you the amount of time past
//if you weren't using the TIMER_COMPLETE listener and a repeat count of 150, you can do this:
if(timer.delay * timer.currentCount >= 15000){
timer.stop();
//do something now that your timer is done
}
}

Blinking Random Number Generator ActionScript3

I need a random number generator on AS3 that blinks on a screen one random number per second (1-9). The random number is fine but I'm having a problem with the blinking part. It just stays permanent on the screen instead of blinking the number.
The dynamic textbox is called myNumbers. I've tried using myNumbers.visible = !myNumbers.visible on the event handler, but it didn't work.
My code:
var mytimer:Timer = new Timer(1000,10);
mytimer.addEventListener(TimerEvent.TIMER, timerHandler);
mytimer.start();
function timerHandler(event:TimerEvent):void{
var numbers:Number = Math.floor(Math.random() * (9 - 1 + 1) + 1);
myNumbers.text = numbers+"";
}
Any help is appreciated!
You can use the same Timer to generate a number (every second) and blinks your text field (every 0.5 second).
Take this code :
var number:int = 0;
var timer:Timer = new Timer(500);
timer.addEventListener(TimerEvent.TIMER, timerHandler);
timer.start();
function timerHandler(event:TimerEvent):void{
if(timer.currentCount % 2 == 0){
text_field.alpha = 0.2; // you can use text_filed.visible = false;
} else {
text_field.alpha = 1; // you can use text_filed.visible = true;
number = Math.floor(Math.random() * 9) + 1;
text_field.text = String(number); // you can also write it : number.toString();
}
}
Which will give you something like this :
Hope that can help.
Hide the myNumbers before start a timer:
myNumbers.visible = false;
In the timerHandler add:
myNumbers.visible = true;
setTimeout(hideText, 500);
Add hideText function:
function hideText()
{
myNumbers.visible = false;
}

Ajusting as3 code to trigger on mouse event

Hi I found this really useful code for a timer counter, however it starts when I play the file. What I need is a way to change this into a MouseEvent.CLICK so it starts when the user presses a button and it stops when the uses presses another button. Is this do able?
import flash.utils.Timer;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.globalization.DateTimeFormatter;
var timer:Timer = new Timer(100);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 0;
function timerTickHandler(Event:TimerEvent):void
{
timerCount += 100;
toTimeCode(timerCount);
}
function toTimeCode(milliseconds:int) : void {
//create a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
//define minutes/seconds/mseconds
var hours:String = String(time.hours);
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
hours = (hours.length != 2) ? '0'+hours : hours;
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 = hours + ":" + minutes + ":" + seconds+"." + miliseconds;
}
The easiest thing to do would be to use timer.stop() and timer.start(). This won't be perfectly accurate, as calling stop() and start() basically restarts the current delay (100ms), but if that's good enough then it should work.
Also note that the timer code isn't perfectly accurate as is, since Timer events are dispatched with slight offsets based on framerate and script execution time. For an accurate timer you need to poll getTimer(), but pausing and resuming becomes a little more complicated to implement.

Timer to load random frame not working

I have three frames with "800", "450", and "635"
I updated the codes and its just jumps to frame to frame every 1 seconds now. Thats not what I need. I need the counter to reach to 0 and it jumps to ONE frame and stops right there. Thats it.
[UPDATED 2] See banner - http://magnixsolutions.com/clients/OT/9995MB-Scoreboard-April-160x600.swf
AS3 -
var fromFrame:int = 1;
var myTimer:Timer = new Timer(1000, nCount);
var frameNum:int = Math.ceil(Math.random() * mcYourScore.totalFrames)
timer_txt.text = nCount.toString();
myTimer.start();
myTimer.addEventListener(TimerEvent.TIMER, countdown);
function getRandomFromRange(minValue:Number, maxValue:Number):int {
return Math.round(minValue + Math.random() * (maxValue - minValue));
}
function countdown(e:TimerEvent):void {
//Display countdown
timer_txt.text = String(myTimer.repeatCount - myTimer.currentCount);
//if End of countdown, start from 2 frame
fromFrame = (myTimer.repeatCount == myTimer.currentCount) ? 2 : 1;
mcYourScore.gotoAndStop(getRandomFromRange(fromFrame, mcYourScore.totalFrames));
}
Math.round(Math.random()) doesn't have any sense, it will return only 0 or 1 values.
var frameNum:int = Math.round(1 + Math.random() * (mcYourScore.totalFrames-1));
If you want to visit random frame on every tick, this construction should help you:
var seconds:int;
function getRandomFromRange(minValue:Number, maxValue:Number):int {
return Math.round(minValue + Math.random() * (maxValue - minValue));
}
function countdown(e:TimerEvent):void {
//Display countdown
seconds = myTimer.repeatCount - myTimer.currentCount;
timer_txt.text = seconds.toString();
//if End of countdown, start from 2 frame
mcYourScore.gotoAndStop(getRandomFromRange(((seconds == 0) ? 2 : 1), mcYourScore.totalFrames));
}
If you want to visit random frame only at the end of countdown, you could use TimerEvent.TIMER_COMPLETE event handler, or change countdown logic:
function countdown(e:TimerEvent):void {
//Display countdown
timer_txt.text = String(myTimer.repeatCount - myTimer.currentCount);
//if End of countdown, pick random frame, from 2 frame
if(myTimer.repeatCount == myTimer.currentCount){
mcYourScore.gotoAndStop(getRandomFromRange(2, mcYourScore.totalFrames));
}
}

calculate minutes left between hours actionscript 3

I'm using AS3 to pull XML data, one field is a time field in the XML and displays an hour. I'm getting the date and then the AS3 loads the proper node based on teh time set in the XML. This is all working perfect - I have two times as variables, one is the system time (which is set in UTC time) the other is one hour ahead.
The two variables are currentHour and newHour - it's doing everything I want however I'd like to now create a countdown between these two hours and display time remaining in the minutes.
Here is the complete code for that.
Get the time from XML using AS3
These seems straight forward but I'm having a hard time. I've tried this:
var data:Array = [currentHour, newHour];
var aDate:String = data[0].split(" ")[0];
var dateElements:Array = aDate.split("-");
var date1:Date = new Date();
date1.setMinutes(int(data[0].split(" ")[1].split(":")[0]));
dateElements = data[1].split(" ")[0].split("-");
var date2:Date = new Date();
date2.setMinutes(int(data[1].split(" ")[1]));
var elapse:Number = date2.getTime() - date1.getTime();
trace("minutes: " + date2.getMinutes());
But that isn't right, so I tried this:
if(currentHour < newHour)
{
var dayDiff:Number = newHour-currentHour;
// make sure it’s in the future
if (dayDiff > 0)
{
var seconds:Number = dayDiff / 1000;
var minutes:Number = seconds / 60;
}
trace(minutes, seconds);
}
If someone could help me get unstuck that would be amazing. Thank you!
Created a new answer which didn't contain the spam from previous one where I tried to figure out what the actual issue was and what the expectations of the program was. Anyways to summarize:
User wanted to, given a specific date/time, find out how long until the next complete hour, so for instance given the time 4:47pm wanted to find out how many minutes and seconds left until 5:00pm.
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.globalization.NumberFormatter;
import flash.utils.getTimer;
import flash.utils.Timer;
var timer:Timer = new Timer(250);
var my_date:Date = new Date();
var targetDate:Date = new Date();
//calculate how many total milliseconds left until next whole hour since that is how as3 is using Date-objects
var timeUntilWholeHourMS:Number = (60 - my_date.getMinutes()) * 60 * 1000;
targetDate.setTime(my_date.getTime() + timeUntilWholeHourMS);
//clear the "second and milliseconds" part of the new time since we want the whole hours
targetDate.setSeconds(0, 0);
var secondsLeft:Number = (targetDate.time - new Date().time) / 1000;
//make sure it is in the future
if (secondsLeft > 0) {
timer.addEventListener(TimerEvent.TIMER, onTimer);
timer.start();
}
function onTimer(e:flash.events.TimerEvent):void {
secondsLeft = (targetDate.time - new Date().time)/1000;
if (secondsLeft > 0) {
var minutes:Number = Math.floor(secondsLeft/60);
var seconds:Number = Math.floor(secondsLeft%60);
trace("minutes left: " + minutes, ", seconds left: " + seconds);
} else {
//time limit reached
timer.removeEventListener(TimerEvent.TIMER, onTimer);
timer.stop();
trace("Time limit reached!");
}
}
I'd reccomend you using Timer. At first declare a variable seconds (between currentHour and newHour):
private var seconds:int;
Then assign it value
seconds = (newHour - currentHour) * 3600;
Then declare a timer which will tick every second (second parameter tells how much times will it tick):
var timer:Timer = new Timer(1000, seconds)
timer.addEventListener(TimerEvent.TIMER, timerHandler);
timer.start();
And then create timerHandler that will make all necessary updates:
function func(e:TimerEvent):void {
--seconds;
//if you have some textfield that shows minutes left, update it's text here
//timeTextfieldText.text = int(seconds / 60) + " minutes left";
trace(int(seconds / 60));
}
A bit unclear on how you want to present the data, but this is how to get it working at least. You need to replace "currentHour & newHour" with actual hours. And then handle the cases inside onTimer with approriate code.
The thing that differentiates this code towards the other solutions are that this takes a timestamp when you start and then whenever a timer event occurs it will check the current time against that timestamp. Meaning it doesn't matter if the flash timer is off by a couple of milliseconds etc.
import flash.events.TimerEvent;
import flash.globalization.NumberFormatter;
import flash.utils.getTimer;
import flash.utils.Timer;
var timer:Timer = new Timer(250);
var currentHour:Number = 14;
var newHour:Number = 15;
var totalSeconds:Number = 0;
var timestampStart:Number = 0;
if(currentHour < newHour) {
totalSeconds = (newHour - currentHour) * 3600;
if (totalSeconds > 0) {
timestampStart = getTimer();
timer.addEventListener(TimerEvent.TIMER, onTimer);
timer.start();
}
}
function onTimer(e:flash.events.TimerEvent):void {
var secondsRunning:Number = (getTimer() - timestampStart) / 1000;
var secondsLeft:Number = totalSeconds - secondsRunning;
if (secondsLeft > 0) {
var minutes:Number = Math.floor(secondsLeft/60);
var seconds:Number = Math.floor(secondsLeft%60);
trace("minutes left: " + minutes, ", seconds left: " + seconds);
} else {
//time limit reached
timer.removeEventListener(TimerEvent.TIMER, onTimer);
timer.stop();
trace("Time limit reached!");
}
}
You need to add an enterFrame event hanler
private var frameCount:int = 0;
private var diff:int = 3600;//the seconds between the two hours, you could set it here
this.addEventListener(Event.ENTER_FRAME, handler);
private function handler(event:Event):void {
frameCount++;
if (frameCount >= stage.frameRate) {
frameCount = 0;
diff--;
if (diff < 0) {
this.removeEventListener(Event.ENTER_FRAME, handler);
}
}
var minutes:int = diff/60;
}