[Transfer] AS3 Game Timer Management

2011-01-13  来源:本站原创  分类:Flash  人气:144 

Because the work takes some time to write a game timer management AS3

In the game development process will find a lot of places will be applied to the timer functions such as upgrading a construction forces arrived how much time a city, etc. If you need a timer in each action on both the new Timer timer if too many eat your CPU will cause a little card is not smooth (the experience from the development of the game last year)

So no matter how many places we only need to use the timer to a new Timer class can be a time to beat the timer is a standard is carried out by the second player

Unit conversion such as: 1 hour = 60 minutes
1 hour = 3600 seconds
1 minute = 60 seconds
1 second = 1 / 60
1 second = 1 / 3600 hours
1 second = 1000 milliseconds;

Cases such as a single class that encapsulates the two methods

public function regTimer (_timeItem: String = null, _timeNum: int = 0, _timeTxt: TextField = null, _fun: Function = null): void

Parameters:

_timeItem: String is the only one up to a timer identifier

_timeNum: int a countdown to the number of seconds

_timeTxt: TextField object is a text box

_fun: Function in the countdown to the callback method when the need

public function removeTimer (_timeItem: String): void

Parameters:

_timeItem: String up the timer to remove the identifier (unique)

package myapp.utility.common{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.utils.Timer;
import myapp.utility.common.debug.Debug;
import myapp.utility.myevents.GameTimeEvent;
/**
* @author silva
*   Implementation
* regTimer(_timeItem:String, _timeNum:int, _timeTxt:TextField):void
* // After the countdown finished up the time to delete registered objects on their own     Out of the queue
*   Game Timer Manager
*/
public class GameTime extends Sprite {
   private var timer:Timer;
   public static var TIMEOVER:String = "GameTime::timerover";
   private static var _class:GameTime;
   private var timeListArr:Array = new Array();
   public function GameTime():void {
    if (_class != null) throw Error("  Please do not instantiate such  ");
    return;
   }
   /**
   *   A single case of this kind is made to be static     Static class can not broadcast the event because
   * @return GameTime
   */
   public static function getInstance():GameTime {
    if (_class == null) return _class = new GameTime();
    return _class;
   }
   /**
   *   Up timer
   */
   private function initTimer():void {
    if (timer == null) {
     timer = new Timer(1000);
    }
    if (timer.running == false ) {
     timer.addEventListener(TimerEvent.TIMER, timerHandler);
     timer.start()
    }
   }
   /**
   *   Please note that labels a queue to increase the uniqueness of character
   * @param _timeItem   Up time identifier
   * @param _timeNum   Time in seconds
   * @param _timeTxt   Display converted text box of time
   */
   public function regTimer(_timeItem:String=null, _timeNum:int=0, _timeTxt:TextField=null,_fun:Function=null):void {
    var len:int = timeListArr.length;
    var regBoo:Boolean = false;
    for (var i = 0; i < len; i++) {
     if (timeListArr[i]["timeItem"] == _timeItem) {
      //  Registered timer
      regBoo = true;
      break;
     }
    }
    if (regBoo==false) {
     //  Write timing is not up to the queue
     timeListArr.push( { timeItem:_timeItem, timeNum:_timeNum, textfiled:_timeTxt,fun:_fun } );
    }
    initTimer();
   }
   /**
   *   Delete a queue
   *   Up in the queue to delete the corresponding time tag identifier
   * @param _timeItem   Up time identifier
   */
   public function removeTimer(_timeItem:String):void {
    var len:int = timeListArr.length;
    for (var i = 0; i < len; i++) {
     //Debug.error(timeListArr[i]["timeItem"] +" - "+_timeItem);
     if (timeListArr[i]["timeItem"] == _timeItem) {
       var temArr:Array = timeListArr.splice(i, 1);

      break;
     }
    }
   }
   /**
   *   Run timer
   */
   private function runTimer():void {
    var len:int = timeListArr.length;
    Debug.error("  Time line-up   - " + len);
    if (len == 0) {
     stopTimer();
     return;
    }
    for (var i = 0; i < len; i++) {
     var temNum:int = int(timeListArr[i]["timeNum"]);
     temNum--;
     if (timeListArr[i]["textfiled"] != null) {
      timeListArr[i]["textfiled"].text = ConvertTime(temNum);
      timeListArr[i]["timeNum"] = temNum;
     }
     ///
     try {
      if (timeListArr[i]["fun"] != null) {
       var funs:Function = timeListArr[i]["fun"];
       funs();
      }
     }catch (e:Error) {
      Debug.error(e.toString());
     }
     //Debug.error(fun)
     if (temNum == 0) {
      dispatchEvent(new GameTimeEvent(TIMEOVER,timeListArr[i]["timeItem"]));
      removeTimer(timeListArr[i]["timeItem"]);
      if (len == 1) {
       stopTimer();
      }
     }
    }
   }
   /**
   *   Stop the timer
   */
   private function stopTimer():void {
    Debug.warning("  Stop the clock  ")
    timer.stop();
    timer.removeEventListener(TimerEvent.TIMER, timerHandler);
   }
   /**
   * TimerEvent  Event listener to achieve
   * @param e
   */
   private function timerHandler(e:TimerEvent):void {
    runTimer();
   }
   /**
   *   The second data format into   00:00:00  Format
   * @param _timeNum
   * @return String
   */
   private function ConvertTime(_timeNum:int):String {
    return (int(_timeNum / 3600).toString() + ":" + int(_timeNum % 3600 / 60).toString() + ":"+ int(_timeNum % 3600 % 60).toString() + "");
   }
}
}

  Timer event class  :

package myapp.utility.myevents{
import flash.events.Event;
/**
* @author silva
*   Timer management event class
*/
public class GameTimeEvent extends Event{
   private var info:String;
   public function GameTimeEvent(type:String, eventInfo:String, bubbles:Boolean = false, cancelable:Boolean = false):void{
     super(type, bubbles, cancelable);
     info = eventInfo;
     }
   /**
   *   The timing of the timer identifier returned
   */
     public function get eventInfo():Object{
     return info;
     }
}
}

Such as: 1 hour = 60 minutes

1 hour = 3600 seconds

1 minute = 60 seconds

1 second = 1 / 60

1 second = 1 / 3600 hours

1 second = 1000 milliseconds;

Such as: 1 hour = 60 minutes

1 hour = 3600 seconds

1 minute = 60 seconds

1 second = 1 / 60

1 second = 1 / 3600 hours

1 second = 1000 milliseconds;

相关文章
  • [Transfer] AS3 Game Timer Management 2011-01-13

    Because the work takes some time to write a game timer management AS3 In the game development process will find a lot of places will be applied to the timer functions such as upgrading a construction forces arrived how much time a city, etc. If you n

  • Transfer from Business Rule Management (Business Rules Management, referred to as BRM) 2011-04-29

    Transfer from Business Rule Management (Business Rules Management, referred to as BRM) Company's business rules are very abstract for most people, even if decision makers can not tell their own enterprise in the end the number of business rules Is in

  • [Transfer] as3 resource management and GC in 2010-12-31

    http://nianshi.javaeye.com/blog/816476 1, as3 in both ordinary object, or displayobejct alike 2, fp9 used in two ways gc memory clean-up a, reference count reference count, by definition, according to the number of times the object is referenced, if

  • [Transfer] AS3 garbage collection Detailed 2011-01-04

    AS3 function relative to the previous version of the much enhanced, when the task entrusted to it, it must also pay a price: the garbage collector will not support automatic garbage collection for you. This article, I compiled some information for ev

  • (Transfer) AS3 RPG game engine: to understand and RPG games 2010-06-04

    RPG game background ├ │ ├ │ ├ Map prospects: building, mountain, river, tree, etc. │ ├ │ │ ├-oriented players, coordinate │ │ └ actions: stop, walking, running, jumping and other actions such as attacks │ ├ NPC: │ ├ items with the players: drop thing

  • [Transfer] AS3.0 page class 2010-10-29

    This component is written with 3.0 6DN, flip action is very smooth, but the original version has a big problem is that this class does not provide control of incoming loaded child movie features, but only a page After onPageEnd this method, the start

  • [Transfer] AS3 method overloading 2011-01-13

    Method overloading AS3 authors: dmh2002 Posted on :2008-2-20 Category: AS3 experience / skills / game Views: 115 First, the need to affirm is this: in the As3.0 still does not support method overloading, we can only be achieved through simple overloa

  • [Transfer] AS3 Code Libraries (APIs) 2011-05-05

    http://www.adrianparr.com/?p=83 Here is a round up of some of the most popular ActionScript 3.0 (AS3) libraries out there to use. Let me know if I have missed an important one off. NOTE: This List was originally for My Personal use (that I thought I

  • [Transfer] AS3 XML in the new approach - E4X 2010-10-15

    Today we take a look at the new AS3 XML approach: E4X, until now, ECMA scripting language specification (ECMA-262) - AscriptScript 3.0 core foundation, and did not provide any of the XML data processing class or method. AcriontScript the previous ver

  • [Transfer] IBM release case management tools to improve workflow automation 2010-10-31

    From: SAN Abstract: According to foreign media reports, IBM released a software tool to help manage the business and allow continued growth of unstructured data is automatically incorporated into the workflow process steps. IBM case management softwa

  • [Transfer] as3 the cookies to access 2010-11-07

    http://www.imemment.com/post/86.html FLASH There are 2 cookies A traditional browser cookies One is the AS3 Following the above two kinds of Cookies class publishing at Very useful Browser COOKIES package { import flash.external.ExternalInterface; pu

  • [Transfer] AS3 container properties to achieve the principle scrollrect 2010-11-17

    http://www.asarea.cn/showdiary.jsp?id=160 The so-called container, does not mean displayobjectcontainer, but the child display object that can carry and the size of the container and the scroll bar to display the child display object container, such

  • [Transfer] AS3 difference in the Object with the Dictionary 2010-11-18

    Dictionary class in AS3 (flash.utils.Dictionary) is a new AS class. Object Dictionary class and the only difference is: Dictionary objects can use non-strings as the keys on the key, Object can only use strings as keys for the key. The following two

  • [Transfer] AS3 copy visual objects 2010-12-19

    AS3 copy visual objects A copy of the editing stage Method 1 - reflection method: var ClassRef: Class = getDefinitionByName (getQualifiedClassName (t_mc)) as Class; var clone_mc: DisplayObject = new ClassRef (); addChild (clone_mc); Method 2 - constr

  • [Transfer] iPhone Development Memory Management Considerations 2010-12-30

    1. Through distribution or copying of objects created to keep count of 1; 2. To assume that any other method to get the object to keep count of 1, and the automatic release of the pool, in order to perform outside the scope of the current use of the

  • [Transfer] AS3 fast random number generation does not repeat 2011-01-05

    http://bbs.9ria.com/viewthread.php?tid=71711&extra=page% 3D1% 26amp; orderby% 3Ddateline% 26amp; filter% 3D86400 See article FlashAS3 random green milk will not repeat the method is just to AS3 Array recent review of the function usually less So it i

  • [Transfer] AS3 Socket-depth study of Chinese character display 2011-01-10

    http://happear.javaeye.com/blog/714928 As the saying goes seeing is believing and hearsay is true, the program development time, listen to what others have to say that their own verification. Because the network this thing, follow the trend of too ma

  • [Transfer] as3 Optimization Summary 2011-01-11

    http://hi.baidu.com/artgou/blog/item/5a02c1136e48928d6538db3c.html 1. Using multiplication instead of division (when the divisor can be transformed into a limited number of times.) For example var n: Number = value * 0.5; than var n: Number = value /

  • [Transfer] AS3 forced to implement the abstract run-time class 2011-01-13

    Read this article good, you can learn some skills, record what the original: Runtime Enforcement of Abstract Classes in AS3 To implement an abstract class need to meet two requirements: 1. Abstract class can not be instantiated 2. Subclasses must imp

  • (Transfer) AS3 data access mode Efficiency 2011-01-14

    AS3 Tutorials (13): AS3 in the Efficiency of data access methods December 1, 2008 Monday 16:33 Today there is another friend and I chatted on MSN AS3 efficient access to data in the topic, suddenly remembered previous forum in blueidea discussed . St