在遊戲開發中,有時候我們需要一個時鐘來記錄遊戲的時間,如果時間結束則結束遊戲。本文介紹如何在J2ME中使用Timer和TimerTask來實現這樣一個時鐘,並給出具體代碼實例。
幸運好時機,註冊贏手機 2005 三星yepp夏季數碼旅遊風 |
在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;
}
}
當我們使用這個時鐘的時候,隻需要把它的一個實例作為參數傳給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 | 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.Timer;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.*;
/**
*
* @author Administrator
*/
public class ClockCanvas extends GameCanvas implements Runnable {
private Timer timer = new Timer();
private GameClock clock = null;
private boolean going = true;
int timeLeft = 0;
/** Creates a new instance of ClockCanvas */
public ClockCanvas() {
super(false);
}
public void run(){
clock = new GameClock(30);
timer.schedule(clock,0,1000);
while(going){
verifyGameState();
userInput();
repaint();
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
&n