OGEngine 是一款開源 Android 2D 遊戲引擎,基於 OpenGL ES 封裝,提供精靈、場景、物理、音頻等模組。本文展示如何用 OGEngine 快速構建 2048 遊戲主場景(GameScene)。
private void initView() {
// 1. 遊戲背景
AnimatedSprite game_bg = new AnimatedSprite(0, 0, Res.GAME_BG, getVertexBufferObjectManager());
this.attachChild(game_bg);
// 2. 中央遊戲主體組 (4x4 格子容器)
mGameGroup = new GameGroup(this);
mGameGroup.setCentrePosition(this.getCameraCenterX(), this.getCameraCenterY());
this.attachChild(mGameGroup);
// 3. 2048 LOGO
AnimatedSprite game_logo = new AnimatedSprite(20, 20, Res.GAME_LOGO, getVertexBufferObjectManager());
this.attachChild(game_logo);
// 4. 最高分背景板 (右上角)
bestScoreBg = new AnimatedSprite(0, 20, Res.GAME_SCORE_BG_BEST, getVertexBufferObjectManager());
bestScoreBg.setRightPositionX(this.getCameraRightX() - 20);
this.attachChild(bestScoreBg);
tBestScore = new Text(0, bestScoreBg.getY() + 50,
FontRes.getFont(ConstantUtil.FONT_SCORE_NUM),
SharedUtil.getBestScore(getActivity()) + "", 4,
getVertexBufferObjectManager());
tBestScore.setCentrePositionX(bestScoreBg.getCentreX());
this.attachChild(tBestScore);
// 5. 當前分背景板 (最高分左側)
currScoreBg = new AnimatedSprite(0, bestScoreBg.getY(), Res.GAME_SCORE_BG_NOW, getVertexBufferObjectManager());
currScoreBg.setRightPositionX(bestScoreBg.getLeftX() - 20);
this.attachChild(currScoreBg);
tCurrScore = new Text(0, currScoreBg.getY() + 50,
FontRes.getFont(ConstantUtil.FONT_SCORE_NUM),
"0", 4, getVertexBufferObjectManager());
tCurrScore.setCentrePositionX(currScoreBg.getCentreX());
this.attachChild(tCurrScore);
// 6. 新遊戲/撤銷按鈕等其他 UI 元素...
// initButtons();
}
AnimatedSprite:帶動畫支持的精靈,構造參數 (x, y, TextureRegion, VertexBufferObjectManager)。GameGroup:自定義組件,封裝 4×4 格子邏輯、滑動合並動畫、分數更新回調。Text:字體渲染組件,需預載字體紋理 (FontRes)。Res / FontRes / ConstantUtil / SharedUtil:資源常量、字體管理、配置常量、SharedPreferences 封裝。getCameraCenterX/Y(), getCameraRightX():場景相機座標輔助方法,實現自適應佈局。File → New → Import Module 選擇引擎目錄,或將 JAR 放入 libs/ 並 implementation files('libs/ogengine.jar')。AndroidManifest.xml 添加 OpenGL ES 2.0 特性聲明:<uses-feature android:glEsVersion="0x00020000" android:required="true" />BaseGameActivity (引擎提供),實現 onCreateEngineOptions(), onCreateResources(), onCreateScene()。int[][] grid = new int[4][4]。MoveModifier 或 ScaleModifier 實現格子平滑移動/縮放。scene.updateScore(newScore) 更新 tCurrScore 文本,破紀錄同步 tBestScore 並持久化。| 資源類型 | 示例文件名 | 用途 |
|---|---|---|
| 背景圖 | game_bg.png | 場景底圖 |
| LOGO | game_logo.png | 標題 |
| 分數板 | score_bg_best.png, score_bg_now.png | UI 面板 |
| 數字塊 | tile_2.png ~ tile_2048.png | 格子紋理 |
| 字體 | font_score.png + .fnt | BMFont 位圖字體 |
| 音效 | move.wav, merge.wav, win.wav | 操作反饋 |
OGEngine 以聲明式 API 簡化 OpenGL ES 開發,initView() 中的鏈式調用(attachChild, setCentrePosition)直觀表達場景樹結構。配合 GameGroup 封裝遊戲核心邏輯,可快速完成 2048 原型並擴展更多功能。