遊戲核心在於動畫。MIDP 2.0 javax.microedition.game 套件提供雙緩衝、精靈、圖層管理等基礎設施。本文展示兩個核心類別:TimerTaskManager (單例計時器) 與 Game (動畫主邏輯)。
public class TimerTaskManager {
private Timer timer;
private static TimerTaskManager instance;
public static TimerTaskManager getInstance() {
if (instance == null) instance = new TimerTaskManager();
return instance;
}
public TimerTask add(Runnable task, long period) {
TimerTask tt = new RunnableTimerTask(task);
timer.schedule(tt, period, period);
return tt;
}
public void close() {
if (timer != null) { timer.cancel(); timer = null; }
}
private Timer getTimer() {
if (timer == null) timer = new Timer();
return timer;
}
static class RunnableTimerTask extends TimerTask {
private final Runnable runnable;
RunnableTimerTask(Runnable r) { runnable = r; }
public void run() { runnable.run(); }
}
}
public class Game extends Canvas implements Runnable {
private Image source;
private Image[] frames = new Image[10];
private int bgColor = 0x209C00;
private TimerTask animTask;
private static int frameIndex = 0;
public Game() {
try { source = Image.createImage("/action.png"); }
catch (IOException e) { e.printStackTrace(); }
// 從單張大圖切割 10 個影格 (5 格跑步 + 5 格雷電)
for (int i = 0; i < 5; i++)
frames[i] = Image.createImage(source, 96*i, 0, 96, 60, 0);
for (int j = 5; j < 10; j++)
frames[j] = Image.createImage(source, 96*(j-5), 102, 96, 80, 0);
// 每 150ms 切換一次影格
animTask = TimerTaskManager.getInstance().add(this, 150);
}
protected void paint(Graphics g) {
fillScreen(g);
paintAction(g);
}
private void fillScreen(Graphics g) {
g.setColor(0xFFFFFF);
g.fillRect(0, 0, getWidth(), getHeight());
}
private void paintAction(Graphics g) {
if (frameIndex == 10) frameIndex = 0;
// 雷電動作 (索引 5-9) 期間,保持跑步第 5 格 (索引 4) 不動
if (frameIndex >= 5)
g.drawImage(frames[4], 40, 0, Graphics.LEFT | Graphics.TOP);
g.drawImage(frames[frameIndex], frameIndex*10, 0, Graphics.LEFT | Graphics.TOP);
frameIndex++;
}
public void run() { repaint(); } // Timer 呼叫
}
Image.createImage(source, x, y, w, h, transform) 切割,減少檔案數與載入開銷。TimerTaskManager 封裝 Timer,避免重複建立計時器,統一管理週期任務。Canvas 繼承自 GameCanvas 可啟用雙緩衝 (setFullScreenMode),消除閃爍。frameIndex 循環 0-9,雷電階段固定顯示跑步末影格,形成「跑步→雷電→跑步」循環。掌握「圖集切割 + Timer 週期觸發 + 影格索引邏輯」即可實現流暢 2D 動畫,為進階遊戲開發 (精靈、碰撞、圖層) 打下基礎。