Restarting timer in action script 3 function resetClock - actionscript-3

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.

Related

AS3 / Stopping timer at a Vector?

How do i start my timer at vector[2] and stop it at vec[13]. myTimer.stop();
I have done that the vector jumps to the next vector every 10 seconds (timerevent). The timer and vector will continue to count and then goes back to the vec[0]
If possible, I would like to start my timer at a later vector. And that the timer stops at the end.
var myTimer:Timer = new Timer(1000);
myTimer.repeatCount = 13;
myTimer.delay = 1000;
myTimer.addEventListener(TimerEvent.TIMER, countdownHandler);
function countdownHandler(event:TimerEvent):void
{
countdown.text = 0+myTimer.currentCount+" s remaining";
countdown2.text = 0+myTimer.currentCount+" s remaining";
if(myTimer.currentCount==10)
{
myTimer.reset();
myTimer.start();
}
}
myTimer.start();
&
function timerfunctie(event:TimerEvent)
{
for(var i:int = 0; i < vec.length; i++)
{
if (vec[i].parent) if (myTimer.currentCount == 9)
{
removeChild(vec[i]);
var next2:int = i+1;
if(next2 == vec.length) next2 = 0;
addChild(vec[next2]);
break;
}
}
}
Not sure where timerfunctie is called, but this code should detect when the currentCount of the timer is 2 and 13. If you want the Timer to run the full 13 iterations, you do not want to reset it at iteration 10.
function countdownHandler(event:TimerEvent):void
{
countdown.text = 0+myTimer.currentCount+" s remaining";
countdown2.text = 0+myTimer.currentCount+" s remaining";
if (myTimer.currentCount==2) {
// start with vector[2]
} else if (myTimer.currentCount==13) {
// end with vector[13]
}
}

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

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.

Add or remove time from a countdown

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

AS3.0 Two For-loops with a delay

I've got the following code and i would like to add an delay of 200 ms after each trace statement
for (var x_pos:uint = 0; x_pos <= 12; x_pos++){
for (var y_pos:uint = 0; y_pos <=12; y_pos++){
trace("hello world " +"("x_pos+","+y_pos+")");
//CODE FOR DELAY OF 200ms
}
}
The real situation is a bit more complex but kind of the same:
//For each Row
for (var x_pos:uint = 0; x_pos <= tile_amount-1; x_pos++){
//For each column
for (var y_pos:uint = 0; y_pos <= tile_amount-1; y_pos++){
//New tile;
var newtile:Tile = new Tile;
//Set position
newtile.x = ((40*y_pos)-(40*x_pos));
newtile.y = ((20*y_pos)+(20*x_pos));
//Add to stage
addChild(newtile);
}
}
Anyone any suggestions ?
private var x_pos:uint;
private var y_pos:uint;
private var timer:Timer;
public function startLoop():void
{
x_pos = 0;
y_pos = 0;
timer = new Timer(200);
timer.addEventListener(TimerEvent.TIMER, onTick);
timer.start();
}
private function onTick(event:TimerEvent):void
{
trace("hello world " +"("x_pos+","+y_pos+")");
if (++y_pos <= 12)
return;
y_pos = 0;
if (++x_pos <= 12)
return;
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, onTick);
timer = null;
}
You can't stop the execution of code in the middle of a statement like that, your best bet is to use a timer:
package
{
import flash.events.TimerEvent;
public class Foo
{
private var x_pos:uint = 0;
private var y_pos:uint = 0;
private var timer:Timer;
public function Foo()
{
timer = new Timer(200, 0);
timer.addEventListener(TimerEvent.TIMER, handleTick);
timer.start();
}
public function handleTick(e:TimerEvent):void {
trace("hello world " +"("x_pos+","+y_pos+")");
y_pos++;
if(y_pos > 12){
x_pos++;
y_pos = 0;
}
if(x_pos > 12) timer.stop();
}
}
}
Actionscript does not have a blocking timeout system -- you need to do a recursive function of your own. This following perfect, but it is a start.
import flash.utils.setTimeout;
// call the final function.
delayedRecursion(12,12,200,
function(curX:Number, curY:Number):void
{
trace("hello world " +"("+curX+","+curY+")");
});
//This is really a wrapper around delayedRecursionHelper
function delayedRecursion(maxX:Number, maxY:Number,
delay:Number, callback:Function):void
{
delayedRecursionHelper(0,-1,maxX,maxY,delay,callback);
}
// each time you call this, it creates a function which holds the variables
// passed in, but incremented by 1.
function delayedRecursionHelper(
curX:Number, cury:Number,
maxX:Number, maxY:Number,
delay:Number, called:Function ):Function
{
return function():void
{
called(curX, curY);
// Exit condition: nothing to do here!
if( curX == maxX && curY == maxY ) return;
if( curY == maxY )
{
curY = -1;
curX++;
}
curY++;
setTimeout(delayedRecursionHelper(curX, curY, maxX, maxY, delay), delay);
}
}
You can not delay the loops in as3.
For this purpose you need to use timers. Some help for your solution you can find here: How to show the current progressBar value of process within a loop in flex-as3?
At the end you just need to modify the function logic.