Actionscript 3.0 timer to save time - actionscript-3

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

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é

AS3 display final time

I have a function that keeps track of the time elapsed in my main game file that looks like this:
public function timeElapsed(milliseconds:int):void
{
var time:Date = new Date(milliseconds);
var minutes:String = String(time.minutes);
var seconds:String = String(time.seconds);
var miliseconds:String = String(Math.round(time.milliseconds)/100);
if(minutes.length != 2)
{
minutes = '0' + minutes;
}
if(seconds.length != 2)
{
seconds = '0' + seconds;
}
trace(minutes + ":" + seconds + "." + miliseconds);
}
What I'm trying to figure out now is how to get it to display the FINAL time, when the player is killed. I have functions handling calls to other files for various events, but at the moment I'm drawing a complete blank on how to get the time to go from here, to displaying on the game over screen, which is it's own separate file.
Any thoughts?
For calculation of time elapsed in the game, you don't need Date class. You should use getTimer() - used to compute relative time. At the start of game register current time elapsed, and format difference as you want.
var start: int = getTimer();
//later, check difference
myTextField.text = timeElapsed(start);
function timeElapsed(start : int):String{
var dt: int = getTimer() - start;
//format result as you wish
return someFormatResult;
}
Display final time, do you want visualise result of time formatting? You could use simple TextField.

Show my timer time during my basic game

Im doing a little game in actionscript, and i have a timer that starts when the gamer starts and end when the game ends.
But i want to show in a textfield the value of my timer during the game like 1,2,3,4,5,6, etc.
How can i can acess that timer propriety to get the value?
My timer code is this:
startTime = (new Date().time);
endTime = (new Date().time);
public function testTime():void
{
const 5_min = 5 * 60 * 1000;
const 2_min = 2 * 60 * 1000;
var timeDiff:Number = endTime - startTime;
if (timeDiff < 2_min) {
trace("Good!");
} else {
trace("Bad!");
}
}
And here (above) i create a txt field. Now, how i can show the timer value while playing the game?
var timer_txt:TextField;
pontuacao = new TextField();
timeDiff = 0;
timer_txt = new TextField();
timer_txt.text = String(timeDiff);
stage.addChild(timer_txt);
timer_txt.x = 470;
timer_txt.y = 320;
Well, first of all, in AS you cannot begin your variable names with a number, therefore this code should absolutely not compile (5_min, 2_min = WRONG!).
You have your startTime, which is ok. Now you will have to check the current time in some kind of event (Timer, EnterFrame) or interval (setInterval) and update the endTime value accordingly. Once you have it, you just count the difference and divide it by 1000 (I assume you don't want to show it in millis)
Something like this:
import flash.utils.setInterval;
var s:Number = new Date().getTime(); //start time
var e:Number; //end time
var d:Number; //difference
setInterval(function () {
e = new Date().getTime();
var oldDiff:Number = d;
d = int((e - s) / 1000);
if(oldDiff != d) trace(d + " seconds since launch");
},
100
);

Personalized user-customizable Countdown Timer through flash/actionscript

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

How to only execute something every 30 frames

My question is this, I want to add a rock every second (30 frames per second), I have different levels, this means I have different amounts of rocks in each level and I have different amount of speeds, so I want to add 10 rocks in a total of 30 seconds in level 1
in level 2 it's 20 rocks in a total of 20 seconds etc. I'm open to completly changing it, I just want the best solution. I want it to be dynamic so I can make a lot of levels. How should I got about doing this
I don't want to keep a counter and every time it's at 30 then add a rock and reset it.
Thank you in advance
switch(difficulty)
{
case 1:
timer = 30;
numberOfRocks = 10;
break;
case 2:
timer = 20;
numberOfRocks = 20;
break;
case 3:
timer = 10;
numberOfRocks = 30;
break;
case 4:
timer = 5;
numberOfRocks = 40;
break;
}
addEventListener(Event.ENTER_FRAME, loop)
}
private function loop(e:Event):void
{
for (var i:int = 0; i < (timer * 30); i++)
{
a_bitmap = new a_class();
a_bitmap.x = 750;
a_bitmap.y = Math.ceil(Math.random() * (600 - a_bitmap.height));
a_bitmap.height = 35;
a_bitmap.width = 35;
addChild(a_bitmap);
a_bitmap.name = "astroid" + i + "";
myArray.push(true);
}
}
A Timer may work better for you're needs than a frame handler. I'd recommend using math to calculate your level parameters instead of hard-coded switch statements, then you can add as many levels as you'd like (or have your game go indefinitely)
var rockLoadTimer:Timer;
function gameInit():void {
//your games initialization code here
//create a timer that fires every second when running
rockLoadTimer = new Timer(1000);
//the function to call every time the timer fires. You could also listen for TIMER_COMPLETE is wanted to run a function once all rocks are loaded
rockLoadTimer.addEventListener(TimerEvent.TIMER, addNextRock);
}
function startLevel(difficulty:int = 1):void {
//your code here to clear the level
//repeat count is used as the amount of rocks to load this level - level number times 10
rockLoadTimer.repeatCount = difficulty * 10;
//the delay time is how quickly you want the rocks to load. this is 5 seconds divided by the difficulty level
//so the first level would be every 5 seconds, second would be every 2 and a half seconds, third level would be every second and two thirds. etc.
rockLoadTimer.delay = Math.round(5000 / difficulty);
rockLoadTimer.reset();
rockLoadTimer.start();
}
function addNextRock(e:Event = null):void {
//your rock creation code here
}
You can use a Timer, and create an instance of a_class during each tick:
var timer:Timer = new Timer(1000, 30); // One per second for 30 seconds
timer.addEventListener(TimerEvent.TIMER, addAsteroid);
timer.start();
function addAsteroid():void {
a_bitmap = new a_class();
// etc.
}
The timer delay is "asteroids per millisecond", so if you want to create 10 over 30 seconds you would set it to 30000/10 = 3000.
However, this approach works best when there is a smooth framerate- it will execute once per second, but the number of frames of animation can vary if Flash is running at less than 30fps. If your game works how I think it does, this could result in asteroids being "bunched up". So, keeping a counter might be the better solution here, unless you plan on handling the rest of your game logic (i.e. asteroid movement speed) in a way that can account for variations in frame rate.
If you want to use a counter:
var creationCounter:Number = 0; // put this at class level
// Then in the ENTER_FRAME event:
creationCounter += asteroids_per_second / 30;
while (creationCounter-- >= 1) {
a_bitmap = new a_class();
// etc.
}
You can also use flash.utils.setInterval function .
setInterval(trace , 1000 , "trace message once per second");
If you use TweenLite, you can use the delayedCall function, it can use time or frames,
// delayedCall(delay:Number, onComplete:Function, onCompleteParams:Array = null, useFrames:Boolean = false):TweenMax
TweenLite.delayedCall(30, addAstroid, null, true);
More info, see the docs: http://www.greensock.com/as/docs/tween/com/greensock/TweenMax.html#delayedCall()