AS3 Increment Timer by User Input - actionscript-3

I am a noob to AS3 so excuse me, please.
I have a timer on my app that I am trying to use as a stop watch, What I would like to do is start it at a specified time not always at 0?
I would like the user to enter in a text box a value of 1 to 99 and the timer starts from there entered value.
Thanks in advance.
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
var customtime:int;
clock.text = "00:00";
var myTimer:Timer = new Timer(1000,0);
myTimer.addEventListener(TimerEvent.TIMER, stopwatch);
function stopwatch(event:TimerEvent):void
{
clock.text = convert_time(myTimer.currentCount);
}
start_btn.addEventListener(MouseEvent.CLICK, startClock);
stop_btn.addEventListener(MouseEvent.CLICK, stopClock);
reset_btn.addEventListener(MouseEvent.CLICK, resetClock);
setTime_btn.addEventListener(MouseEvent.CLICK, setCustomTime);
function startClock(evt:MouseEvent):void
{
myTimer.start();
}
function stopClock(evt:MouseEvent):void
{
myTimer.stop();
}
function resetClock(evt:MouseEvent):void
{
myTimer.reset();
clock.text = "00:00";
}
function setCustomTime(evt:MouseEvent)
{
var t1:int = int(setTimeTxt.text)*60;
clock.text = convert_time(t1);
customtime = t1;
}
function time_update(t1:int):int
{
var t2:int=t1*60;
return t2;
}
function convert_time(currentAmountSecs:int):String
{
var minutes:int = Math.floor(currentAmountSecs / 60);
var seconds:int = currentAmountSecs % 60;
var prependString:String = "";
if ( minutes < 10 )
{
prependString = "0";
}
var prependStringsec:String = "";
if ( seconds < 10 )
{
prependStringsec = "0";
}
return prependString + minutes + ":" + prependStringsec + seconds;
}

Well you can't change Timer/currentCount but you can store a start count and display startCount + myTimer.currentCount:
var startCount:int = 100;
clock.text = convert_time(startCount + myTimer.currentCount);
As for how to determine the startCount from a user text input: you can use parseInt to convert text to an integer. You should also restrict the text input to numbers, and you can enforce a range of 0-99 using Math.min and Math.max:
// restrict input characters to numbers
input.restrict = "0-9";
// update the `startCount` any time user input changes
input.addEventListener(Event.CHANGE, inputChange);
function inputChange(e:Event):void {
// parse an integer from the text input
startCount = parseInt(input.text);
// limit the range to 0-99
startCount = Math.max(0, Math.min(startCount, 99));
// make sure the input text displays the in-range value
if (input.text != String(startCount))
input.text = String(startCount);
}

Related

Restarting timer in action script 3 function resetClock

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.

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

Action Script 3. How to count game time?

I'm creating Flash "memory" game, Idea to discover 2 equal cards. I need to add "Timer" in top of window which count in how many seconds all cards will be descovered.
Here is my code:
package
{
import flash.display.MovieClip;
import Card;
import Boarder;
import BlueBoard;
import flash.events.MouseEvent;
import RedBoard;
import Snow;
public class MemoryGame extends MovieClip
{
private var _card:Card;
private var _boarder:Boarder;
private var _blueBoard:BlueBoard;
private var _cardX:Number;
private var _cardY:Number;
private var _firstCard:*;
private var _totalMatches:Number;
private var _currentMatches:Number;
private var _redBoard:RedBoard;
private var _snow:Snow;
private var _cards:Array;
public var _message:String;
public function MemoryGame()
{
_cards = new Array();
_totalMatches = 4;
_currentMatches = 0;
createCards();
}
private function createCards():void
{
_cardX = 45;
_cardY = 10;
for(var i:Number = 0; i < 2; i++)
{
_card = new Card();
addChild(_card);
_boarder = new Boarder();
_card.setType(_boarder);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
for(var j:Number = 0; j < 2; j++)
{
_card = new Card();
addChild(_card);
_blueBoard = new BlueBoard();
_card.setType(_blueBoard);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
_cardX = 45;
_cardY = _card.height + 30;
for(var k:Number = 0; k < 2; k++)
{
_card = new Card();
addChild(_card);
_redBoard = new RedBoard();
_card.setType(_redBoard);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
for(var l:Number = 0; l < 2; l++)
{
_card = new Card();
addChild(_card);
_snow = new Snow();
_card.setType(_snow);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
randomizeCards(_cards);
}
private function checkCards(event:MouseEvent):void
{
event.currentTarget.removeEventListener(MouseEvent.CLICK, checkCards);
if(_firstCard == undefined)
{
_firstCard = event.currentTarget;
}
else if(String(_firstCard._type) == String(event.currentTarget._type))
{
trace("match");
_message = "match";
message_txt.text = _message;
_firstCard = undefined;
_currentMatches ++;
if(_currentMatches >= _totalMatches)
{
trace("YOU WIN !!!");
_message = "YOU WIN !!!";
message_txt.text = _message;
}
}
else
{
trace("wrong");
_message = "wrong";
message_txt.text = _message;
_firstCard.gotoAndPlay("flipBack");
event.currentTarget.gotoAndPlay("flipBack");
_firstCard.addEventListener(MouseEvent.CLICK, checkCards);
event.currentTarget.addEventListener(MouseEvent.CLICK, checkCards);
_firstCard = undefined;
}
}
private function randomizeCards(cards:Array):void
{
var randomCard1:Number;
var randomCard2:Number;
var card1X:Number;
var card1Y:Number;
for(var i:Number = 0; i < 10; i++)
{
randomCard1 = Math.floor(Math.random() * cards.length);
randomCard2 = Math.floor(Math.random() * cards.length);
card1X = cards[randomCard1].x;
card1Y = cards[randomCard1].y;
cards[randomCard1].x = cards[randomCard2].x;
cards[randomCard1].y = cards[randomCard2].y
cards[randomCard2].x = card1X;
cards[randomCard2].y = card1Y;
}
}
}
}
EDIT:
And I have one more question. When I will add this game to PHP, how can I add username and his time to database? I need write code in Action Script (swf file) or I can do it in php later? I mean in php can I use any method to get time from swf file and write it to database?
Could you help me? Thank you very much.
Here is an example of how to use the Timer class (flash.utils.Timer) to accomplished what you're asking:
var timer:Timer; //import flash.utils.Timer;
var txtTime:TextField;
var tmpTime:Number; //this will store the time when the game is started
//your constructor:
public function MemoryGame()
{
timer = new Timer(1000); //create a new timer that ticks every second.
timer.addEventListener(TimerEvent.TIMER, tick, false, 0, true); //listen for the timer tick
txtTime = new TextField();
addChild(txtTime);
tmpTime = flash.utils.getTimer();
timer.start(); //start the timer
//....the rest of your code
}
private function tick(e:Event):void {
txtTime.text = showTimePassed(flash.utils.getTimer() - tmpTime);
}
//this function will format your time like a stopwatch
function showTimePassed(startTime:int):String {
var leadingZeroMS:String = ""; //how many leading 0's to put in front of the miliseconds
var leadingZeroS:String = ""; //how many leading 0's to put in front of the seconds
var time = getTimer() - startTime; //this gets the amount of miliseconds elapsed
var miliseconds = (time % 1000); // modulus (%) gives you the remainder after dividing,
if (miliseconds < 10) { //if less than two digits, add a leading 0
leadingZeroMS = "0";
}
var seconds = Math.floor((time / 1000) % 60); //this gets the amount of seconds
if (seconds < 10) { //if seconds are less than two digits, add the leading zero
leadingZeroS = "0";
}
var minutes = Math.floor( (time / (60 * 1000) ) ); //60 seconds times 1000 miliseocnds gets the minutes
return minutes + ":" + leadingZeroS + seconds + "." + leadingZeroMS + miliseconds;
}
//in your you-win block of code:
var score = flash.utils.getTimer() - tmpTime; //this store how many milliseconds it took them to complete the game.
This creates a timer that will tick every second, and update a text field with the current amount of seconds elapsed
As per the second part of your request, here is a way you can do this (the database work needs to be done in PHP, this shows you how to send the data to a php page)
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, scoreSaveResponse,false,0,true);
var request:URLRequest = new URLRequest("http://mysite.com/score.php");
var urlVars:URLVariables = new URLVariables();
urlVars.time = flash.utils.getTimer() - tmpTime;
urlVars.userName = "yourUserName";
//add any other parameters you want to pass to your PHP page
request.method = URLRequestMethod.POST;
urlLoader.data = urlVars;
urlLoader.load(request);
function scoreSaveResponse(e:Event):void {
//whatever you return from the php page is found in urlLoader.data
}

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