編輯:關於 Android 程式設計
這個系列的最終目標是做出可以操作的打飛機:控制小飛機左右移動、閃避子彈、擊倒 Boss。本文完成第一步——開始選單介面。
先把圖片資源整個複製進來。接著,任何一個遊戲動畫的起點都是「狀態」:目前是在選單、在戰鬥、還是已經結算?把狀態切乾淨,後續的繪製、輸入、邏輯才有地方分流。
// 遊戲狀態常量
public static final int GAME_MENU = 0; // 遊戲選單
public static final int GAMEING = 1; // 遊戲中
public static final int GAME_WIN = 2; // 遊戲勝利
public static final int GAME_LOST = 3; // 遊戲失敗
public static final int GAME_PAUSE = -1; // 暫停
// 當前遊戲狀態,預設停在選單
public static int gameState = GAME_MENU;
定義好狀態後,在繪圖方法、實體按鍵的按下與抬起方法、觸屏監聽、邏輯方法這幾處都加上同一個 switch,讓每個狀態各自分流:
switch (gameState) {
case GAME_MENU: break;
case GAMEING: break;
case GAME_WIN: break;
case GAME_LOST: break;
case GAME_PAUSE: break;
default: break;
}
接著宣告需要用到的資源。用一個 Resources 實例來載入圖片,再把每張圖都宣告成 Bitmap 欄位:
// 便於載入圖片
private Resources res = this.getResources();
private Bitmap bmpBackGround; // 遊戲背景
private Bitmap bmpBoom; // 爆炸效果
private Bitmap bmpBoosBoom; // Boss 爆炸效果
private Bitmap bmpButton; // 開始按鈕
private Bitmap bmpButtonPress; // 開始按鈕(被按下)
private Bitmap bmpEnemyDuck; // 怪物鴨子
private Bitmap bmpEnemyFly; // 怪物蒼蠅
private Bitmap bmpEnemyBoos; // Boss 豬頭
private Bitmap bmpGameWin; // 勝利背景
private Bitmap bmpGameLost; // 失敗背景
private Bitmap bmpPlayer; // 主角飛機
private Bitmap bmpPlayerHp; // 主角血量
private Bitmap bmpMenu; // 選單背景
public static Bitmap bmpBullet; // 子彈
public static Bitmap bmpEnemyBullet; // 敵機子彈
public static Bitmap bmpBossBullet; // Boss 子彈
資源在 surfaceCreated() 中載入。這個回呼同時負責記錄螢幕尺寸、初始化遊戲、啟動繪圖執行緒:
/** SurfaceView 建立時呼叫 */
@Override
public void surfaceCreated(SurfaceHolder holder) {
screenW = this.getWidth();
screenH = this.getHeight();
initGame();
flag = true;
// 建立並啟動執行緒
th = new Thread(this);
th.start();
}
/** 載入遊戲資源 */
private void initGame() {
bmpBackGround = BitmapFactory.decodeResource(res, R.drawable.background);
bmpBoom = BitmapFactory.decodeResource(res, R.drawable.boom);
bmpBoosBoom = BitmapFactory.decodeResource(res, R.drawable.boos_boom);
bmpButton = BitmapFactory.decodeResource(res, R.drawable.button);
bmpButtonPress = BitmapFactory.decodeResource(res, R.drawable.button_press);
bmpEnemyDuck = BitmapFactory.decodeResource(res, R.drawable.enemy_duck);
bmpEnemyFly = BitmapFactory.decodeResource(res, R.drawable.enemy_fly);
bmpEnemyBoos = BitmapFactory.decodeResource(res, R.drawable.enemy_pig);
bmpGameWin = BitmapFactory.decodeResource(res, R.drawable.gamewin);
bmpGameLost = BitmapFactory.decodeResource(res, R.drawable.gamelost);
bmpPlayer = BitmapFactory.decodeResource(res, R.drawable.player);
bmpPlayerHp = BitmapFactory.decodeResource(res, R.drawable.hp);
bmpMenu = BitmapFactory.decodeResource(res, R.drawable.menu);
bmpBullet = BitmapFactory.decodeResource(res, R.drawable.bullet);
bmpEnemyBullet = BitmapFactory.decodeResource(res, R.drawable.bullet_enemy);
bmpBossBullet = BitmapFactory.decodeResource(res, R.drawable.boosbullet);
}

選單要負責的事只有兩件:把背景與按鈕畫出來,以及判斷使用者有沒有按到按鈕。把它獨立成一個類別,MySurfaceView 就能保持乾淨。
package com.gsf;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.MotionEvent;
public class GameMenu {
private Bitmap bmpMenu; // 選單背景
private Bitmap bmpButton, bmpButtonPress; // 按鈕的未按下 / 按下圖
private int btnX, btnY; // 按鈕座標
private Boolean isPress; // 是否按下
public GameMenu(Bitmap bmpMenu, Bitmap bmpButton, Bitmap bmpButtonPress) {
this.bmpMenu = bmpMenu;
this.bmpButton = bmpButton;
this.bmpButtonPress = bmpButtonPress;
// X 軸置中,Y 軸貼齊螢幕底部
btnX = MySurfaceView.screenW / 2 - bmpButton.getWidth() / 2;
btnY = MySurfaceView.screenH - bmpButton.getHeight();
isPress = false;
}
public void draw(Canvas canvas, Paint paint) {
// 先畫背景
canvas.drawBitmap(bmpMenu, 0, 0, paint);
// 依按壓狀態決定用哪張按鈕圖
if (isPress) {
canvas.drawBitmap(bmpButtonPress, btnX, btnY, paint);
} else {
canvas.drawBitmap(bmpButton, btnX, btnY, paint);
}
}
public void onTouchEvent(MotionEvent event) {
int pointX = (int) event.getX();
int pointY = (int) event.getY();
// 按下或移動中:更新按鈕的視覺狀態
if (event.getAction() == MotionEvent.ACTION_DOWN
|| event.getAction() == MotionEvent.ACTION_MOVE) {
if (pointX > btnX && pointX < btnX + bmpButton.getWidth()) {
if (pointY > btnY && pointY < btnY + bmpButton.getHeight()) {
isPress = true;
} else {
isPress = false;
}
} else {
isPress = false;
}
// 抬起:只有在按鈕範圍內才觸發開始遊戲
} else if (event.getAction() == MotionEvent.ACTION_UP) {
if (pointX > btnX && pointX < btnX + bmpButton.getWidth()) {
if (pointY > btnY && pointY < btnY + bmpButton.getHeight()) {
isPress = false; // 還原為未按下狀態
// 切換到遊戲中
MySurfaceView.gameState = MySurfaceView.GAMEING;
}
}
}
}
}
這裡有個細節值得注意:判定抬手位置而不是按下位置。這樣可以避免使用者按下滑出按鈕再放開時被誤判為點擊。
把前面宣告的 gameMenu 實例化,並在繪圖與觸屏處把它接上:
public class MySurfaceView extends SurfaceView implements Callback, Runnable {
private SurfaceHolder sfh;
private Paint paint;
private Thread th;
private boolean flag;
private Canvas canvas;
// 1. 遊戲狀態常量
public static final int GAME_MENU = 0;
public static final int GAMEING = 1;
public static final int GAME_WIN = 2;
public static final int GAME_LOST = 3;
public static final int GAME_PAUSE = -1;
// 當前遊戲狀態,預設在選單
public static int gameState = GAME_MENU;
private Resources res = this.getResources();
private Bitmap bmpBackGround;
private Bitmap bmpBoom;
private Bitmap bmpBoosBoom;
private Bitmap bmpButton;
private Bitmap bmpButtonPress;
private Bitmap bmpEnemyDuck;
private Bitmap bmpEnemyFly;
private Bitmap bmpEnemyBoos;
private Bitmap bmpGameWin;
private Bitmap bmpGameLost;
private Bitmap bmpPlayer;
private Bitmap bmpPlayerHp;
private Bitmap bmpMenu;
public static Bitmap bmpBullet;
public static Bitmap bmpEnemyBullet;
public static Bitmap bmpBossBullet;
public static int screenW;
public static int screenH;
private GameMenu gameMenu;
public MySurfaceView(Context context) {
super(context);
sfh = this.getHolder();
sfh.addCallback(this);
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
setFocusable(true);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
screenW = this.getWidth();
screenH = this.getHeight();
initGame();
flag = true;
th = new Thread(this);
th.start();
}
private void initGame() {
bmpBackGround = BitmapFactory.decodeResource(res, R.drawable.background);
bmpBoom = BitmapFactory.decodeResource(res, R.drawable.boom);
bmpBoosBoom = BitmapFactory.decodeResource(res, R.drawable.boos_boom);
bmpButton = BitmapFactory.decodeResource(res, R.drawable.button);
bmpButtonPress = BitmapFactory.decodeResource(res, R.drawable.button_press);
bmpEnemyDuck = BitmapFactory.decodeResource(res, R.drawable.enemy_duck);
bmpEnemyFly = BitmapFactory.decodeResource(res, R.drawable.enemy_fly);
bmpEnemyBoos = BitmapFactory.decodeResource(res, R.drawable.enemy_pig);
bmpGameWin = BitmapFactory.decodeResource(res, R.drawable.gamewin);
bmpGameLost = BitmapFactory.decodeResource(res, R.drawable.gamelost);
bmpPlayer = BitmapFactory.decodeResource(res, R.drawable.player);
bmpPlayerHp = BitmapFactory.decodeResource(res, R.drawable.hp);
bmpMenu = BitmapFactory.decodeResource(res, R.drawable.menu);
bmpBullet = BitmapFactory.decodeResource(res, R.drawable.bullet);
bmpEnemyBullet = BitmapFactory.decodeResource(res, R.drawable.bullet_enemy);
bmpBossBullet = BitmapFactory.decodeResource(res, R.drawable.boosbullet);
// 選單類別實例化
gameMenu = new GameMenu(bmpMenu, bmpButton, bmpButtonPress);
}
/** 遊戲繪圖 */
public void myDraw() {
try {
canvas = sfh.lockCanvas();
if (canvas != null) {
canvas.drawColor(Color.WHITE);
// 依遊戲狀態決定畫什麼
switch (gameState) {
case GAME_MENU: gameMenu.draw(canvas, paint); break;
case GAMEING: break;
case GAME_WIN: break;
case GAME_LOST: break;
case GAME_PAUSE: break;
default: break;
}
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if (canvas != null) sfh.unlockCanvasAndPost(canvas);
}
}
/** 觸屏事件 */
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (gameState) {
case GAME_MENU: gameMenu.onTouchEvent(event); break;
case GAMEING: break;
case GAME_WIN: break;
case GAME_LOST: break;
case GAME_PAUSE: break;
}
return true;
}
/** 按鍵按下 */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (gameState) {
case GAME_MENU: break;
case GAMEING: break;
case GAME_WIN: break;
case GAME_LOST: break;
case GAME_PAUSE: break;
}
return super.onKeyDown(keyCode, event);
}
/** 按鍵抬起 */
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (gameState) {
case GAME_MENU: break;
case GAMEING: break;
case GAME_WIN: break;
case GAME_LOST: break;
case GAME_PAUSE: break;
}
return super.onKeyUp(keyCode, event);
}
/** 遊戲邏輯 */
private void logic() {
switch (gameState) {
case GAME_MENU: break;
case GAMEING: break;
case GAME_WIN: break;
case GAME_LOST: break;
case GAME_PAUSE: break;
}
}
/** 主迴圈:繪圖與邏輯交替執行,以 50ms 為一幀 */
@Override
public void run() {
while (flag) {
long start = System.currentTimeMillis();
myDraw();
logic();
long end = System.currentTimeMillis();
try {
if (end - start < 50) {
Thread.sleep(50 - (end - start));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { }
/** SurfaceView 銷毀時停止執行緒 */
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
flag = false;
}
}
執行結果如下:

選單頁完成,按下按鈕即可切換到遊戲狀態。下一步就是在此框架下補上主角移動、子彈與碰撞偵測。
Android 主題切換(二):用獨立 APK 實作插件式換膚
上一篇講的是內建 style 方案,本篇來看第二種:把皮膚打包成一個獨立的 apk,主程式在執行期把它載入來用。這也是「插件化」思路最直觀的入門形式。步驟一:建立皮膚 a
Android Studio 性能調優(六):GPU Monitor 使用指南
Android Monitor 中包含了 GPU Monitor,它能夠以圖形化的方式直觀地展示窗體的渲染耗時。借助 GPU Monitor,你可以: 迅速查看 UI 窗
Android 開發筆記(一百一十一):用 Socket 打造聊天室
Socket 通信 基本概念 對程式開發來說,網路通信的地基就是 Socket。但正因為它是地基,用起來反而不容易上手。今天就來把 Socket 通信談清楚。 計算機網路
Android RecyclerView 點擊事件實作解析
一、為什麼要用 RecyclerView 自從 Android L 問世,RecyclerView 就逐步取代 ListView 成為展示大量資料的首選。相比 ListV