Personalized user-customizable Countdown Timer through flash/actionscript - actionscript-3

To be honest, I have no experience in flash. So if anyone can point me to the necessary direction. That would be great. I was tasked to build a countdown timer with all the features that can be found on http://www.online-stopwatch.com/
You might argue that why don't I use the one found in the link I provided but I was tasked to create a personalized one with background and layout that will be completely different from the one in the link.
I've looked at some tutorials but none can point me to the direction that's needed. Thank you for the help.

This is not really a question that can be answered in one answer, its more like you need to completely learn action-script 3.0 and then use that knowledge to write this program.
Here is a link to a book that i found great for learning action-script 3.0 and flash in general. IF you don't want to learn everything about action-script 3.0 then consider looking up tutorials on the basics of it and then specifically on the Timer Class. If you want a good program that has everything that the website you cited has, then you should probably just read the Essential Actin script 3 book, but if your pressed for time you can quickly learn the basics and try and throw something together, but it won't be very good.

Normally a question on SO that shows no attempt on the OP's part to solve their issue would get little attention, but I just happen to have this around from helping someone else with it so you're in luck! I can't help you learn how to use Flash per se, put this is the logic you'll need.
The following class should take care of what you're looking for:
myClockMC is a movieclip with five textfields in it, days, hours, minutes, seconds and milliseconds.
You might need to adjust names and paths within this class to get it working with your construct.
Use this signature to instantiate:
var myClock:CountdownClock = new CountdownClock( myClockMC, 2014, 8, 20 );
package
{
import flash.display.MovieClip;
import flash.events.Event;
public class CountdownClock extends MovieClip
{
public function CountdownClock( clip:MovieClip, targetMonth:Number, targetDay:Number, targetYear:Number )
{
trace('new CountdownClock');
addEventListener( Event.ENTER_FRAME, update );
}
private function update( evt:Event ):void
{
var date:Date = new Date();
var targetDate:Date = new Date( targetYear, targetMonth, targetDay );
var currentYear:Number = date.getFullYear();
var currentTime:Number = date.getTime();
var targetTime:Number = targetDate.getTime();
var diff:Date = new Date( targetDate - date );
var timeLeft:Number = targetTime - currentTime;
var millSecs:Number = diff.getMilliseconds();
var seconds:Number = Math.floor(timeLeft / 1000);
var minutes:Number = Math.floor(seconds / 60);
var hours:Number = Math.floor(minutes / 60);
var days:Number = Math.floor(hours / 24);
seconds = String(seconds % 60);
if (seconds.length < 2)
{
seconds = "0" + seconds;
}
minutes = String(minutes % 60);
if (minutes.length < 2)
{
minutes = "0" + minutes;
}
hours = String(hours % 24);
if (hours.length < 2)
{
hours = '0' + hours;
}
days = String(days);
if (days.length < 2)
{
days = '0' + days;
}
clip.daysWindow.text = days;
clip.hoursWindow.text = hours;
clip.minutesWindow.text = minutes;
clip.secondsWindow.text = seconds;
clip.millSecsWindow.text = millSecs;
if(days == '00' && hours == '00' && minutes == '00' && seconds == '00')
{
updateAfterReachingDate( clip );
}
}
private function updateAfterReachingDate( mc:MovieClip ):void
{
removeEventListener( Event.ENTER_FRAME, update );
// handle timer target reached
}
}
}

Related

How do i set Time as high score?

im creating a simple game which the objective is to deliver items the fastest as you can.There are no other score points except time, i manage to make the time start as the game begin and stop when the objective is done, but how do i save the time when it stop and make it appear at the home page as the "Best Time"? for now im still using other score points with the time, but im going to delete it and use only Time instead, help me, thanks in advance :)
these are several codes where i manage to stop the time, just write it here in case if it is needed, will write other codes as well if needed.
if (score==15) {
time1.stop();
gotoAndPlay('resultframe')
stop();
time1.stop();
score2_txt.text = String(score);
timeField2.text = String(""+minute+":"+second+"");
response_txt.text = "Well Done! You won!";
var minute = 5;
var second = 59;
var time1:Timer = new Timer (1000);
time1.addEventListener(TimerEvent.TIMER, calcTime);
function calcTime(e:TimerEvent):void {
second -= 1;
if(second == 00){
minute -= 1;
second = 59;
}
timeField.text = String(""+minute+":"+second+"");
}
import flash.utils.getTimer;
var startTime:int;
function chronometerStart():void
{
startTime = getTimer();
}
function chronometerStop():int
{
var now:int = getTimer();
var time:int = now - startTime;
return time;
}
the getTimer()-method returns the number of milliseconds that have elapsed since the swf gegan to run.
Greetings André

How to get a time as a variable in Flash CS6

I am trying to get a time that is in a text document to become a variable in a Flash CS6 AS3 project. I can't seem to find where the problem is and the error messages aren't really helping. The highlighted parts are the changed lines.
Here is the newest code:
this.onEnterFrame = function()
{
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 = e.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;
delete (this.onEnterFrame);
}
}
Newest Error:
1120: Access of undefined property e. (Line 17).
First of all, this does nothing :
var StartTime();
It's not correct AS3 code.
Then, AS3 loaders being asynchronous, you must way for the loader to finish load so you can get your variable. I mean that all your code after StartTime.load(...) must be inside the function onLoaded.
This way, when the loader finish loading, you'll have you variable.
That say, URLVariable is NOT a loader. It is an object you can use to put your variable into, and feed them to a loader.
If you want to download some file, use URLLoader (with URLRequest). On this page, there is a good example on how you can do that (skip the part about the dataFormat, though). The date you're requesting will be available in the data property of the event, eg :
var timeLeft = e.data - currentTime;
I'm not asking where currentTime is from, since it's out of the scope of that question.
Good luck.

Actionscript 3.0 timer to save time

im doing a basic game in action script and now i want to do a timer.
I want that the timer starts count when the game starts and in the end of the game when the player can do ten points i want to say in textfield that if the time was more than 5 minutes it was very bad if the timer was less than 2minutes very good and things like this!
Im trying do this but the timer dont count, anyone can help?
Thanks!
theTime.addEventListener(Event.ENTER_FRAME,showTime);
function showTime(event:Event):void {
var myTime:Date = new Date();
var theMinutes=myTime.getMinutes();
theTime.text =theMinutes;
}
new Date(); gives a Date object which contains the current date and time. To keep track of passed time you need to keep track of start and end time and find their difference. You can do this by using time property. Something like this:
// Do this when you start the game.
var startTime:Number = (new Date()).time;
// Do this when the game is over
var endTime:Number = (new Date()).time;
const MILLI_SECOND_IN_5_MIN:Number = 5 * 60 * 1000;
const MILLI_SECOND_IN_2_MIN:Number = 5 * 60 * 1000;
var timeDiff:Number = endTime - startTime;
if (timeDiff < MILLI_SECOND_IN_2_MIN) {
trace("Good");
} else if (timeDiff > MILLI_SECOND_IN_5_MIN) {
trace("Bad");
}

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;
}

Is this a good implementation of the gameloop

I have implemented a gameloop in Flash/Actionscript/Starling and I want to throw it at you to see if this is a valid implementation.
I wanted to have a variable time step approach.
private var _deltaTime:Number = 0;
private var _lastTime:Number = 0;
private var _speed = 1000 / 40;
private function onEnterFrame() {
var now = new Date().getTime();
var delta = now - _lastTime;
_deltaTime += delta - _speed;
_lastTime = now;
//skip if frame rate to fast
if (_deltaTime <= -_speed) {
_deltaTime += _speed;
return;
}
update();
}
private function update() {
updateGameState();
if (_deltaTime >= _speed) {
_deltaTime -= _speed;
update();
}
}
What I got sofar is that I have a constant speed (more or less).
My question is is there a better approach so that the movements will appear even
smoother.
What is really surprising to me is that even thou the FPS is pretty much constant (60FPS)
the movement is sometimes bumpy yet smoother than with the naive gameloop.
Youre on the right track - assuming that onEnterFrame is triggered in some way by Event.ENTER_FRAME - instead of skipping update, call it on every frame but pass in the time elapsed:
private function onEnterFrame() {
var now = new Date().getTime();
var delta = now - _lastTime;
_lastTime = now;
updateGameState(delta/1000);//divide by 1000 to give time in seconds
}
In updateGameState, you can utilise 'delta' to calculate movement etc, eg:
function updateGameState(timeElapsed:Number):void {
myAlien.x += myAlienSpeedPerSecond*timeElapsed;
}
This way you get smooth movement even when frame rate varies.
from the Starling introduction pages, it shows that time elapsed is built into the EnterFrameEvent class.
// the corresponding event listener
private function onEnterFrame(event:EnterFrameEvent):void
{
trace("Time passed since last frame: " + event.passedTime);
enemy.moveBy(event.passedTime * enemy.velocity);
}
http://wiki.starling-framework.org/manual/animation#enterframeevent