首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

J2ME 2D 遊戲開發入門(二):核心工具類庫構建

     編輯:Java 相關知識

在編寫遊戲邏輯前,構建三個核心工具類:圖片加載器、遊戲對象封裝、位圖字體,為後續開發奠定高效基礎設施。

1. 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;
    }
}

2. 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。

3. 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) 字符查找,固定寬高無換行,極致渲染性能

這三個類構成了輕量級「微引擎」核心,後續所有遊戲邏輯均建立於此。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved