How do i set Time as high score? - actionscript-3

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é

Related

Simple (maybe antiquated) AS3 script stops after 30 seconds

Designing some lessons in AS3 for the HS multimedia class I teach.
I haven't tried to teach this in my class in a few years, so I'm a bit rusty. It's also possible my script is not as smooth as it could be as I've based it on some AS2 work I did quite sometime ago.
That said, this little bit of code runs for about thirty seconds and then stops. No error, no feedback outside the trace command I put in to track array length.
This is part of a lesson series for getting the kids in the direction of writing some games in AS3. In this one we're looking at creating random timing and random placement. We've already covered motion, properties, variables, listeners, and functions.
Here's the code:
import flash.events.Event;
var firstMeteor:Number = 1;
var timeSinceLast:Number = 0;
var lastMeteor:Number = 0;
var totalMeteors = 60;
var metProp=.08;
var rocksBox:Array = new Array;
var dropSpeed:Number = 15;
var lowLimit:Number = 350;
stage.addEventListener(Event.ENTER_FRAME,dropRocks);
stage.addEventListener(Event.ENTER_FRAME,moveRocks);
function dropRocks(e:Event):void{
if(lastMeteor<totalMeteors) {
if(Math.random() < metProp) {
lastMeteor++;
var rock:meteor = new meteor;
addChild(rock);
rocksBox.push(rock);
rock.x = Math.random()*500;
rock.y = 20;
timeSinceLast = 0;
}
}
timeSinceLast++;
}
function moveRocks(e:Event):void {
for(var i:int = rocksBox.length-1; i>=0; i--) {
rocksBox[i].y += dropSpeed;
if(rocksBox[i].y>lowLimit) {
removeChild(rocksBox[i]);
rocksBox.splice(i,1);
trace(rocksBox.length);
}
}
}
In your code, you drop a rock only when the total count of the meteors created so far (i.e: the lastMeteor), has not yet reached the maximum amount of totalMeteors you specified! When it reached the maximum, then if(lastMeteor<totalMeteors) won't let any other "meteor" creation happen!!

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

Flex 4 timers keep Firing

I'm trying to create a simple flex4 project which involves some timers that trigger other functions.
I don't have much experience with Action Script and even less with timer events.
Here is a bit of my code it seems to be working for the most part but you lines were I'm adding up the total score (score = score +1;) seems to just keep adding and adding when I test the application. I think its because the timers keep firing the function but I'm not sure.
private var score:int = 0;
private function submit():void {
this.currentState = 'loading';
var timer:Timer = new Timer(2200);
timer.addEventListener(TimerEvent.TIMER, removeLoading);
timer.start();
}
private function removeLoading(event:TimerEvent):void{
removeloading.play();
var timer1:Timer = new Timer(1000);
timer1.addEventListener(TimerEvent.TIMER, viewResults);
timer1.start();
this.currentState = 'results';
}
private function viewResults(event:TimerEvent):void{
if (q1_t.selected == true){
answer1m.text = 'You Answer the Question Correctly.';
score = score +1;
} else {
answer1m.text ='The Correct answer was: '+ q1_t.label;
}
if (q2_f.selected == true){
answer2m.text = 'You Answer the Question Correctly.';
score = score +1;
} else {
answer2m.text ='The Correct answer was: '+ q2_f.label;
}
finalscore.text = score.toString();
}
So I did a bit more research and turns out I hadn't included the second timer parameter.
The second parameter is the number of times that the TimerEvent.TIMER event will be dispatched before stopping. If you set the second parameter to 0 (zero) or omitted it completely, the timer would run forever (or until you called the stop() method on the timer instance.
Since I only want to run the event once I need to add 1.
From this:
var timer:Timer = new Timer(2200);
To this:
var timer:Timer = new Timer(2200,1);