盾怪网教程:是一个免费提供流行杀毒软件教程、在线学习分享的学习平台!

J2ME游戏开发中时钟的容易完成

时间:2024/12/4作者:未知来源:盾怪网教程人气:

[摘要]Options and locate the template under * the Source Creation and Management node. Right-click the te...
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;
    }
}

  当我们使用这个时钟的时候,只需要把它的一个实例作为参数传给Timer的schedule()方法即可。例如

      clock = new GameClock(30);
      timer.schedule(clock,0,1000);

  接下来我们编写一个简单的游戏界面测试一下时钟。我们在程序启动的时候开始计时,每隔一秒钟timeLeft会减少1,并且在手机屏幕上显示当前剩余的时间。如果timeLeft为0的时候代表游戏已经结束了。因此我们需要这样判断游戏的状态。

    public void verifyGameState(){
        timeLeft = clock.getTimeLeft();
        if(timeLeft == 0){
            going = false;
        }
    }

  为了测试时钟的暂停功能,我们接收用户的按键行为,如果左键被按下,那么调用clock的pause()方法,如果右键被按下则调用clock的resume()方法。

    public void userInput(){
        int keyStates = this.getKeyStates();
        if((keyStates & GameCanvas.LEFT_PRESSED) != 0){
            clock.pause();
        }else if((keyStates & GameCanvas.RIGHT_PRESSED) != 0){
            clock.resume();
        }
           
    }

  下面给出MIDlet和Canvas的代码:

/*
 * ClockCanvas.java
 *
 * Created on 2005年7月18日, 上午11:04
 *
 * To change this template, choose Tools

关键词:J2ME游戏开发中时钟的容易完成




Copyright © 2012-2018 盾怪网教程(http://www.dunguai.com) .All Rights Reserved 网站地图 友情链接

免责声明:本站资源均来自互联网收集 如有侵犯到您利益的地方请及时联系管理删除,敬请见谅!

QQ:1006262270   邮箱:kfyvi376850063@126.com   手机版