龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > JAVA开发 >

J2ME游戏开发中时钟的简单实现

时间:2009-12-23 15:42来源:未知 作者:admin 点击:
分享到:
在游戏开发中,有时候我们需要一个时钟来记录游戏的时间,假如时间结束则结束游戏。本文介绍如何在J2ME中使用Timer和TimerTask来实现这样一个时钟,并给出具体代码实例。 在Java.uti

  在游戏开发中,有时候我们需要一个时钟来记录游戏的时间,假如时间结束则结束游戏。本文介绍如何在J2ME中使用Timer和TimerTask来实现这样一个时钟,并给出具体代码实例。

  在Java.util包中有一个TimerTask类,你可以扩展这个类并且实现他的run()方法,在run()方法中编写我们的逻辑代码。假如我们想制作一个游戏时钟,那么非常简单我们编写一个GameClock类扩展TimerTask,GameClock需要维持一个实例变量timeLeft,这样我们就可以记录游戏剩余的时间了,在每次run()运行的时候把timeLeft减1就可以了。有时候我们需要始终暂停以及重新启动,这并不复杂,在GameClock中添加一个boolean类型的标记就可以了。下面给出GameClock的代码:
  
  /*
   * GameClock.java
   *
   * Created on 2005年7月18日, 上午11:00
   *
   * To change this template, choose Tools Options and locate the template under
   * the Source Creation and Management node. Right-click the template and choose
   * Open. You can then make changes to the template in the Source Editor.
   */

  package com.j2medev.gameclock;
  import java.util.TimerTask;
  /**
   *
   * @author Administrator
   */
  public class GameClock extends TimerTask{
     
      private int timeLeft = 60;//时钟的默认时间
      private boolean pause = false;
      /** Creates a new instance of GameClock */
      public GameClock() {
      }
     
      public GameClock(int value){
          timeLeft = value;
      }
     
      public void run(){
          if(!pause){
              timeLeft--;
          }
      }
     
      public void pause(){
          pause = true;
      }
     
      public void resume(){
          pause = false;
      }
     
      public int getTimeLeft(){
          return timeLeft;
      }
     
      public void setTimeLeft(int _value){
          this.timeLeft = _value;
      }
  }

  
  

精彩图集

赞助商链接