在編寫遊戲邏輯前,構建三個核心工具類:圖片加載器、遊戲對象封裝、位圖字體,為後續開發奠定高效基礎設施。
ImageTools:安全圖片加載統一異常處理,避免 IOException 到處拋出:
public class ImageTools {
private ImageTools() {}
public static Image getImage(String path) {
Image img = null;
try { img = Image.createImage(path); }
catch (Exception ex) { System.out.println("Load img fail: " + path + " " + ex); }
return img;
}
}
GameObject:Sprite 狀態封裝與生命週期核心思想:一個 Sprite 實例可被多個邏輯對象共享 (如子彈群),GameObject 保存單個實體的運行時狀態 (位置、速度、幀、存活、生命週期)。
public class GameObject {
public Sprite sprite; // 共享的 Sprite 實例
public boolean alive; // 存活標記
public int lifetime; // 生命週期 (幀數),0=永久
public int speed; // 動畫幀率 (幀間隔),0=每幀更新
private int lifeCount, aniCount;
public GameObject(Image img, int fw, int fh) {
sprite = new Sprite(img, fw, fh);
reset();
}
public void move(int dx, int dy) { sprite.move(dx, dy); }
public void moveto(int x, int y) { sprite.setPosition(x, y); }
public void update() { // 每幀調用
if (!alive) return;
// 動畫幀更新
if (++aniCount > speed) { aniCount = 0; sprite.nextFrame(); }
// 生命週期
if (lifetime != 0 && ++lifeCount > lifetime) alive = false;
}
public void paint(Graphics g) { if (alive) sprite.paint(g); }
public void reset() { alive = true; lifeCount = 0; aniCount = 0; sprite.setFrame(0); }
}
用法:子彈群創建 new Bullets(...) 內部持有 GameObject,每顆子彈邏輯由數組驅動,繪製時調用 gameObject.sprite.setPosition(x,y); gameObject.paint(g); 復用同一 Sprite。
Font:位圖字體高速渲染J2ME 無系統字體繪製,必須用圖集。Hash 映射 O(1) 查找字符幀索引,避免遍歷數組:
public class Font {
private Sprite sprite;
private int charW, charH;
private int[] charMap; // size 128, ASCII 映射
private Graphics g;
public Font(Graphics g, Image img, int cw, int ch, char[] chars) {
this.g = g;
sprite = new Sprite(img, cw, ch);
this.charW = cw; this.charH = ch;
charMap = new int[128];
Arrays.fill(charMap, -1);
for (int i=0; i= 0) {
sprite.setPosition(x, y);
sprite.setFrame(idx);
sprite.paint(g);
}
}
public void drawString(String str, int x, int y) {
for (int i=0; i
使用:
Font font = new Font(g, ImageTools.getImage("/pic/font.png"), 8, 12,
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray());
font.drawString("SCORE: 1234", 10, 10);
| 類 | 模式 | 核心價值 |
|---|---|---|
| ImageTools | 工廠方法 + 異常屏蔽 | 統一資源加載入口,便於後續加入緩存、預加載 |
| GameObject | 狀態對象 / 享元 | 分離「共享圖形數據」與「實例運行狀態」,支援對象池 |
| Font | 享元 + 直接索引映射 | O(1) 字符查找,固定寬高無換行,極致渲染性能 |
這三個類構成了輕量級「微引擎」核心,後續所有遊戲邏輯均建立於此。