Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

2048 遊戲完整源碼解析:MainView 與 MainGame 的分工

編輯:Android 開發實例

2048 是一款規則極簡、實作卻很能磨練功力的遊戲。開源自 2048 的專案不少,本文以 iQuick 版本為例,拆解它的架構設計:畫面繪製與遊戲邏輯如何拆分、動畫如何與狀態同步、以及最高分如何持久化。原始碼位址在文末。

專案結構

MainView:遊戲畫面的呈現層

MainView 負責資源載入、字型與顏色設定、以及整個棋盤的繪製。它在建構時就完成資源準備並啟動新局,同時掛上觸碰監聽器。

// 初始化:載入資源、字型與顏色,並開始新遊戲
public MainView(Context context) {
    super(context);
    Resources resources = context.getResources();
    game = new MainGame(context, this);
    try {
        backgroundRectangle = resources.getDrawable(R.drawable.background_rectangle);
        lightUpRectangle = resources.getDrawable(R.drawable.light_up_rectangle);
        fadeRectangle = resources.getDrawable(R.drawable.fade_rectangle);
        TEXT_WHITE = resources.getColor(R.color.text_white);
        TEXT_BLACK = resources.getColor(R.color.text_black);
        TEXT_BROWN = resources.getColor(R.color.text_brown);
        this.setBackgroundColor(resources.getColor(R.color.background));

        Typeface font = Typeface.createFromAsset(
                resources.getAssets(), "ClearSans-Bold.ttf");
        paint.setTypeface(font);
        paint.setAntiAlias(true);
    } catch (Exception e) {
        System.out.println("Error getting assets?");
    }
    setOnTouchListener(new InputListener(this));
    game.newGame();
}

// 尺寸改變時重算版面並重建背景快取
@Override
protected void onSizeChanged(int width, int height, int oldw, int oldh) {
    super.onSizeChanged(width, height, oldw, oldh);
    getLayout(width, height);
    createBitmapCells();
    createBackgroundBitmap(width, height);
    createOverlays();
}

值得注意的一點是 createBackgroundBitmap():它把靜態的棋盤背景預先繪製成 Bitmap,之後每帧只需貼圖加上動態方塊,大幅降低 onDraw 的負擔。這是在自訂 View 上做遊戲時相當實用的優化手法。

MainGame:遊戲規則與狀態的核心

邏輯層獨立成一個純 Java 類別,不依賴任何 View,因此可單獨測試。以下節錄幾個關鍵部分。

package com.tpcstld.twozerogame;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MainGame {

    public static final int SPAWN_ANIMATION = -1;
    public static final int MOVE_ANIMATION = 0;
    public static final int MERGE_ANIMATION = 1;
    public static final int FADE_GLOBAL_ANIMATION = 0;

    public static final long MOVE_ANIMATION_TIME = MainView.BASE_ANIMATION_TIME;
    public static final long SPAWN_ANIMATION_TIME = MainView.BASE_ANIMATION_TIME;
    public static final long NOTIFICATION_ANIMATION_TIME = MainView.BASE_ANIMATION_TIME * 5;
    public static final long NOTIFICATION_DELAY_TIME = MOVE_ANIMATION_TIME + SPAWN_ANIMATION_TIME;

    private static final String HIGH_SCORE = "high score";
    public static final int startingMaxValue = 2048;
    public static int endingMaxValue;

    // 奇數 = 非進行中,偶數 = 進行中;贏/輸狀態各再加一
    public static final int GAME_WIN = 1;
    public static final int GAME_LOST = -1;
    public static final int GAME_NORMAL = 0;
    public static final int GAME_NORMAL_WON = 1;
    public static final int GAME_ENDLESS = 2;
    public static final int GAME_ENDLESS_WON = 3;

    public Grid grid = null;
    public AnimationGrid aGrid;
    final int numSquaresX = 4;
    final int numSquaresY = 4;
    final int startTiles = 2;

    public int gameState = 0;
    public boolean canUndo;
    public long score = 0;
    public long highScore = 0;
    public long lastScore = 0;
    public int lastGameState = 0;

    private long bufferScore = 0;
    private int bufferGameState = 0;
    private Context mContext;
    private MainView mView;

    public MainGame(Context context, MainView view) {
        mContext = context;
        mView = view;
        endingMaxValue = (int) Math.pow(2, view.numCellTypes - 1);
    }

    /** 開新局 */
    public void newGame() {
        if (grid == null) {
            grid = new Grid(numSquaresX, numSquaresY);
        } else {
            prepareUndoState();
            saveUndoState();
            grid.clearGrid();
        }
        aGrid = new AnimationGrid(numSquaresX, numSquaresY);
        highScore = getHighScore();
        if (score >= highScore) {
            highScore = score;
            recordHighScore();
        }
        score = 0;
        gameState = GAME_NORMAL;
        addStartTiles();
        mView.refreshLastTime = true;
        mView.resyncTime();
        mView.invalidate();
    }

    private void addStartTiles() {
        for (int xx = 0; xx < startTiles; xx++) {
            this.addRandomTile();
        }
    }

    /** 隨機生成新方塊:九成機率為 2,一成為 4 */
    private void addRandomTile() {
        if (grid.isCellsAvailable()) {
            int value = Math.random() < 0.9 ? 2 : 4;
            Tile tile = new Tile(grid.randomAvailableCell(), value);
            spawnTile(tile);
        }
    }

    private void spawnTile(Tile tile) {
        grid.insertTile(tile);
        aGrid.startAnimation(tile.getX(), tile.getY(),
                SPAWN_ANIMATION, SPAWN_ANIMATION_TIME, MOVE_ANIMATION_TIME, null);
    }

    private void recordHighScore() {
        SharedPreferences settings =
                PreferenceManager.getDefaultSharedPreferences(mContext);
        SharedPreferences.Editor editor = settings.edit();
        editor.putLong(HIGH_SCORE, highScore);
        editor.commit();
    }

    private long getHighScore() {
        SharedPreferences settings =
                PreferenceManager.getDefaultSharedPreferences(mContext);
        return settings.getLong(HIGH_SCORE, -1);
    }

    /** 撤銷功能:把當前狀態存進 buffer */
    private void prepareUndoState() {
        grid.prepareSaveTiles();
        bufferScore = score;
        bufferGameState = gameState;
    }

    private void saveUndoState() {
        grid.saveTiles();
        canUndo = true;
        lastScore = bufferScore;
        lastGameState = bufferGameState;
    }

    public void revertUndoState() {
        if (canUndo) {
            canUndo = false;
            aGrid.cancelAnimations();
            grid.revertTiles();
            score = lastScore;
            gameState = lastGameState;
            mView.refreshLastTime = true;
            mView.invalidate();
        }
    }

    public boolean gameWon() {
        return (gameState > 0 && gameState % 2 != 0);
    }

    public boolean gameLost() {
        return (gameState == GAME_LOST);
    }

    public boolean isActive() {
        return !(gameWon() || gameLost());
    }

    /** 移動主邏輯:0 上、1 右、2 下、3 左 */
    public void move(int direction) {
        aGrid.cancelAnimations();
        if (!isActive()) {
            return;
        }
        prepareUndoState();

        Cell vector = getVector(direction);
        List<Integer> traversalsX = buildTraversalsX(vector);
        List<Integer> traversalsY = buildTraversalsY(vector);

        boolean moved = false;
        prepareTiles();

        for (int xx : traversalsX) {
            for (int yy : traversalsY) {
                Cell cell = new Cell(xx, yy);
                Tile tile = grid.getCellContent(cell);
                if (tile != null) {
                    Cell[] positions = findFarthestPosition(cell, vector);
                    Tile next = grid.getCellContent(positions[1]);
                    if (next != null && next.getValue() == tile.getValue()
                            && next.getMergedFrom() == null) {
                        // 合併
                        Tile merged = new Tile(positions[1], tile.getValue() * 2);
                        Tile[] temp = {tile, next};
                        merged.setMergedFrom(temp);
                        grid.insertTile(merged);
                        grid.removeTile(tile);

                        // 讓兩塊磚先聚攏,再播放合併動畫
                        tile.updatePosition(positions[1]);
                        int[] extras = {xx, yy};
                        aGrid.startAnimation(merged.getX(), merged.getY(),
                                MOVE_ANIMATION, MOVE_ANIMATION_TIME, 0, extras);
                        aGrid.startAnimation(merged.getX(), merged.getY(),
                                MERGE_ANIMATION, SPAWN_ANIMATION_TIME,
                                MOVE_ANIMATION_TIME, null);

                        score = score + merged.getValue();
                        highScore = Math.max(score, highScore);

                        // 達成 2048
                        if (merged.getValue() >= winValue() && !gameWon()) {
                            gameState = gameState + GAME_WIN;
                            endGame();
                        }
                    } else {
                        // 單純移動
                        moveTile(tile, positions[0]);
                        int[] extras = {xx, yy, 0};
                        aGrid.startAnimation(positions[0].getX(), positions[0].getY(),
                                MOVE_ANIMATION, MOVE_ANIMATION_TIME, 0, extras);
                    }
                    if (!positionsEqual(cell, tile)) {
                        moved = true;
                    }
                }
            }
        }

        if (moved) {
            saveUndoState();
            addRandomTile();
            checkLose();
        }
        mView.resyncTime();
        mView.invalidate();
    }

    private void checkLose() {
        if (!movesAvailable() && !gameWon()) {
            gameState = GAME_LOST;
            endGame();
        }
    }

    private void endGame() {
        aGrid.startAnimation(-1, -1, FADE_GLOBAL_ANIMATION,
                NOTIFICATION_ANIMATION_TIME, NOTIFICATION_DELAY_TIME, null);
        if (score >= highScore) {
            highScore = score;
            recordHighScore();
        }
    }

    private Cell getVector(int direction) {
        Cell[] map = {
            new Cell(0, -1),   // 上
            new Cell(1, 0),    // 右
            new Cell(0, 1),    // 下
            new Cell(-1, 0)    // 左
        };
        return map[direction];
    }

    private List<Integer> buildTraversalsX(Cell vector) {
        List<Integer> traversals = new ArrayList<Integer>();
        for (int xx = 0; xx < numSquaresX; xx++) {
            traversals.add(xx);
        }
        if (vector.getX() == 1) {
            Collections.reverse(traversals);   // 向右時要從右側開始掃
        }
        return traversals;
    }

    private List<Integer> buildTraversalsY(Cell vector) {
        List<Integer> traversals = new ArrayList<Integer>();
        for (int xx = 0; xx < numSquaresY; xx++) {
            traversals.add(xx);
        }
        if (vector.getY() == 1) {
            Collections.reverse(traversals);   // 向下時要從下側開始掃
        }
        return traversals;
    }

    /** 找出沿著 vector 方向能推到的最遠位置 */
    private Cell[] findFarthestPosition(Cell cell, Cell vector) {
        Cell previous;
        Cell nextCell = new Cell(cell.getX(), cell.getY());
        do {
            previous = nextCell;
            nextCell = new Cell(previous.getX() + vector.getX(),
                                previous.getY() + vector.getY());
        } while (grid.isCellWithinBounds(nextCell) && grid.isCellAvailable(nextCell));
        return new Cell[] {previous, nextCell};
    }

    private boolean movesAvailable() {
        return grid.isCellsAvailable() || tileMatchesAvailable();
    }

    /** 是否還有可合併的相鄰同值磚 */
    private boolean tileMatchesAvailable() {
        Tile tile;
        for (int xx = 0; xx < numSquaresX; xx++) {
            for (int yy = 0; yy < numSquaresY; yy++) {
                tile = grid.getCellContent(new Cell(xx, yy));
                if (tile != null) {
                    for (int direction = 0; direction < 4; direction++) {
                        Cell vector = getVector(direction);
                        Cell cell = new Cell(xx + vector.getX(), yy + vector.getY());
                        Tile other = grid.getCellContent(cell);
                        if (other != null && other.getValue() == tile.getValue()) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    private boolean positionsEqual(Cell first, Cell second) {
        return first.getX() == second.getX() && first.getY() == second.getY();
    }

    private int winValue() {
        return canContinue() ? startingMaxValue : endingMaxValue;
    }

    public void setEndlessMode() {
        gameState = GAME_ENDLESS;
        mView.invalidate();
        mView.refreshLastTime = true;
    }

    public boolean canContinue() {
        return !(gameState == GAME_ENDLESS || gameState == GAME_ENDLESS_WON);
    }
}

幾個值得學的設計細節

掃描順序會影響結果:buildTraversalsX/Y 在方向為正向時把索引清單反轉,確保每次都從「移動方向的那一端」開始處理。少了這一步,往右或往下移動時合併結果就會出錯——這是實作 2048 最容易忽略的地方。

合併只做一次:透過 getMergedFrom() == null 的檢查,避免同一帧內新產生的方塊又被合併一次(例如四個 2 不該一次變成 8)。

動畫與邏輯分離:AnimationGrid 獨立記錄每個動畫的型別、時間與附加參數,邏輯層只負責下指令,View 依時間軸播放。這種切分讓規則調整不會牽動繪製細節。

最高分持久化:用 SharedPreferences 存 high score,簡單有效。若換成 DataStore 會更合適,但對這種單一數值場景而言差異不大。

如何整合廣告

若要把這個專案變成可上架的產品,作者示範了接入第三方廣告的方式。首先在 AndroidManifest.xml 中加入必要權限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<supports-screens android:anyDensity="true" />

接著註冊廣告 SDK 的元件:

<!-- 酷果廣告元件 -->
<activity android:name="com.phkg.b.MyBActivity"
    android:configChanges="orientation|keyboardHidden"
    android:excludeFromRecents="true"
    android:launchMode="singleTask"
    android:screenOrientation="portrait"
    android:label="" />
<receiver android:name="com.phkg.b.MyBReceive">
    <intent-filter>
        <action android:name="android.intent.action.PACKAGE_ADDED" />
        <data android:scheme="package" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

<!-- 有米廣告元件 -->
<activity android:name="net.youmi.android.AdBrowser"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
    android:theme="@android:style/Theme.Light.NoTitleBar" />
<service android:name="net.youmi.android.AdService" android:exported="false" />
<receiver android:name="net.youmi.android.AdReceiver">
    <intent-filter>
        <action android:name="android.intent.action.PACKAGE_ADDED" />
        <data android:scheme="package" />
    </intent-filter>
</receiver>

並在 MainView 中載入廣告條:

// 有米廣告
private void loadYMAds() {
    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.FILL_PARENT,
            FrameLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.gravity = Gravity.BOTTOM | Gravity.RIGHT;   // 右下角
    AdView adView = new AdView(this, AdSize.FIT_SCREEN);
    adView.setAdListener(new YMAdsListener());
    this.addContentView(adView, layoutParams);
}

// 酷果廣告
private void loadKGAds() {
    BManager.showTopBanner(MainActivity.this, BManager.CENTER_BOTTOM,
            BManager.MODE_APPIN, Const.COOID, Const.QQ_CHID);
    BManager.setBMListner(new ADSListener());
}

別忘了把 Const 類別中的 AppKey 換成自己申請的值。作者推薦的平台為有米(https://www.youmi.net/)與酷果(https://www.kuguopush.com/)。

這裡要補充一句:範例中 GET_TASKS、SYSTEM_ALERT_WINDOW 這類權限在後續 Android 版本已大幅受限或列入敏感權限,Google Play 也有相應政策規範,如今上架時應改用官方廣告 SDK(如 AdMob)並遵循平台政策,避免直接沿用舊寫法導致審核被拒。

匯入專案

Android Studio 可直接 Import。若使用 Eclipse,做法是新建一個相同包名的專案,把原工程的 src 與 libs 內容複製到新專案對應目錄,再用原工程的 AndroidManifest.xml 覆蓋新專案的版本,即可完成遷移。

轉換成自己的專案時,務必記得兩件事:改掉包名,以及把 Const 類別中的廣告 AppKey 換成自己的。

原始碼位址:https://github.com/iQuick/2048

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved