Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 五子棋完整實作:自訂棋盤 View、落子判斷與四方向勝負演算法

編輯:關於 Android 程式設計

近來學了五子棋相關的課程,收穫不少,於是動手做了一個 Android 版本。這個題目看似簡單,卻很適合練習自訂 View、事件處理、狀態保存與演算法設計,能學到的東西比預期多得多。以下把整個建構過程拆開來講。

一、專案結構與執行結果

專案結構:

執行畫面:

二、前期準備程式碼

1. MainActivity:選單中加入「再來一局」

 public class MainActivity extends AppCompatActivity {

    private ChessBoardView chessBoardView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        chessBoardView = (ChessBoardView) findViewById(R.id.boardView);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_setting) {   // 再來一局
            chessBoardView.start();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
} 

2. Constants:把魔法數字集中管理

 public class Constants {
    public final static int MAX_COUNT_IN_LINE = 5;   // 五子連珠
    final static int MAX_LINE = 15;                  // 棋盤 15 路
    final static int HORIZONTAL = 0;                 // 檢查方向
    final static int VERTICAL = 1;
    final static int LEFT_DIAGONAL = 2;
    final static int RIGHT_DIAGONAL = 4;
} 

3. activity_main.xml:放入自訂棋盤 View

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@mipmap/bg"
    tools:context="com.example.linux.mygobang.MainActivity">

    <com.example.linux.mygobang.ChessBoardView
        android:id="@+id/boardView"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout> 

4. menu_main.xml:再來一局的選單項

 <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="https://schemas.android.com/tools"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:id="@+id/action_setting"
        android:title="再來一局"
        android:orderInCategory="100"
        android:showAsAction="never"
        tools:ignore="AppCompatResource" />
</menu> 

三、自訂棋盤 ChessBoardView

這是整個專案的核心。

1. 初始化與成員變數

 private int mViewWidth;                                    // 棋盤寬度(同時也是長度)
    private float maxLineHeight;                               // 每格線段長度
    private Paint paint = new Paint();

    private Bitmap mwhitePiece, mblackPiece;                   // 黑白棋子圖
    private float ratioPieceOfLineHeight = 3 * 1.0f / 4;       // 棋子直徑佔格寬比例

    private boolean mIsWhite = true;                           // 目前輪到白棋
    private ArrayList<Point> mwhiteArray = new ArrayList<>();   // 白棋位置
    private ArrayList<Point> mblackArray = new ArrayList<>();   // 黑棋位置

    private boolean mIsGameOver;                               // 遊戲是否結束
    private boolean mIsWhiteWinner;                            // 是否白棋獲勝

    public ChessBoardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint.setColor(0x88000000);
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setStyle(Paint.Style.STROKE);   // 只畫輪廓,用來畫棋盤線
        mwhitePiece = BitmapFactory.decodeResource(getResources(), R.mipmap.stone_w2);
        mblackPiece = BitmapFactory.decodeResource(getResources(), R.mipmap.stone_b1);
    } 

2. onMeasure:讓 View 保持正方形

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthModel = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightModel = MeasureSpec.getMode(heightMeasureSpec);

        int width = Math.min(widthSize, heightSize);
        if (widthModel == MeasureSpec.UNSPECIFIED) {
            width = heightSize;
        } else if (heightModel == MeasureSpec.UNSPECIFIED) {
            width = widthSize;
        }
        setMeasuredDimension(width, width);   // 取長寬較小值,強制正方形
    } 

3. onSizeChanged:尺寸確定後才適合做縮放

 @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mViewWidth = w;
        maxLineHeight = mViewWidth * 1.0f / Constants.MAX_LINE;
        int pieceWidth = (int) (maxLineHeight * ratioPieceOfLineHeight);
        mwhitePiece = Bitmap.createScaledBitmap(mwhitePiece, pieceWidth, pieceWidth, false);
        mblackPiece = Bitmap.createScaledBitmap(mblackPiece, pieceWidth, pieceWidth, false);
    } 

4. onTouchEvent:把觸摸座標吸附成棋盤格點

 @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mIsGameOver) {
            return false;
        }
        int action = event.getAction();
        if (action == MotionEvent.ACTION_UP) {
            int x = (int) event.getX();
            int y = (int) event.getY();

            Point point = getValidPoint(x, y);   // 換算成最近的棋盤交叉點
            if (mwhiteArray.contains(point) || mblackArray.contains(point)) {
                return false;                    // 該點已有棋子,忽略
            }
            if (mIsWhite) {
                mwhiteArray.add(point);
            } else {
                mblackArray.add(point);
            }
            invalidate();
            mIsWhite = !mIsWhite;                // 交換落子方
        }
        return true;
    } 

5. onDraw:三步驟完成畫面

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBoard(canvas);      // 畫棋盤網格
        drawPieces(canvas);     // 畫黑白棋子
        checkGameOver();        // 檢查是否結束
    } 

四、各段繪製邏輯

畫棋盤網格

 // 繪製棋盤網線
    private void drawBoard(Canvas canvas) {
        int w = mViewWidth;
        float lineHeight = maxLineHeight;
        for (int i = 0; i < Constants.MAX_LINE; i++) {
            int startX = (int) (lineHeight / 2);
            int endX = (int) (w - lineHeight / 2);
            int y = (int) ((0.5 + i) * lineHeight);
            canvas.drawLine(startX, y, endX, y, paint);   // 橫線
            canvas.drawLine(y, startX, y, endX, paint);   // 豎線
        }
    } 

線段從半格處起訖,讓棋盤上下左右各留半格邊距,棋子才不會被裁掉。

畫棋子

 // 依黑白棋子陣列繪製棋子
    private void drawPieces(Canvas canvas) {
        for (int i = 0, n = mwhiteArray.size(); i < n; i++) {
            Point whitePoint = mwhiteArray.get(i);
            float left = (whitePoint.x + (1 - ratioPieceOfLineHeight) / 2) * maxLineHeight;
            float top = (whitePoint.y + (1 - ratioPieceOfLineHeight) / 2) * maxLineHeight;
            canvas.drawBitmap(mwhitePiece, left, top, null);
        }
        for (int i = 0, n = mblackArray.size(); i < n; i++) {
            Point blackPoint = mblackArray.get(i);
            float left = (blackPoint.x + (1 - ratioPieceOfLineHeight) / 2) * maxLineHeight;
            float top = (blackPoint.y + (1 - ratioPieceOfLineHeight) / 2) * maxLineHeight;
            canvas.drawBitmap(mblackPiece, left, top, null);
        }
    } 

(1 - ratio) / 2 這個位移讓棋盤交叉點正好落在棋子中心,而不是左上角。

檢查勝負

 // 檢查遊戲是否結束
    private void checkGameOver() {
        CheckWinner checkWinner = new CheckWinner();
        boolean whiteWin = checkWinner.checkFiveInLineWinner(mwhiteArray);
        boolean blackWin = checkWinner.checkFiveInLineWinner(mblackArray);
        if (whiteWin || blackWin) {
            mIsGameOver = true;
            mIsWhiteWinner = whiteWin;
            String text = mIsWhiteWinner ? "白棋勝利" : "黑棋勝利";
            Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
        }
    } 

五、保存與恢復棋局

1. 保存殘局(例如旋轉螢幕時)

 private static final String INSTANCE = "instance";
    private static final String INSTANCE_GAME_OVER = "instance_game_over";
    private static final String INSTANCE_WHITE_ARRAY = "instance_white_array";
    private static final String INSTANCE_BLACK_ARRAY = "instance_black_array";

    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE, super.onSaveInstanceState());
        bundle.putBoolean(INSTANCE_GAME_OVER, mIsGameOver);
        bundle.putParcelableArrayList(INSTANCE_BLACK_ARRAY, mblackArray);
        bundle.putParcelableArrayList(INSTANCE_WHITE_ARRAY, mwhiteArray);
        return bundle;
    } 

2. 從 Bundle 恢復

 @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            mIsGameOver = bundle.getBoolean(INSTANCE_GAME_OVER);
            mwhiteArray = bundle.getParcelableArrayList(INSTANCE_WHITE_ARRAY);
            mblackArray = bundle.getParcelableArrayList(INSTANCE_BLACK_ARRAY);
            super.onRestoreInstanceState(bundle.getParcelable(INSTANCE));
            return;
        }
        super.onRestoreInstanceState(state);
    } 

能這樣存是因為 Point 本身實作了 Parcelable。若棋盤要做得更完整,還應該把「輪到誰」與勝負結果一起存起來。

3. 重新開局

 // 再來一局
    public void start() {
        mwhiteArray.clear();
        mblackArray.clear();
        mIsGameOver = false;
        mIsWhiteWinner = false;
        invalidate();
    } 

六、勝負判斷演算法

CheckWinner 以「米」字型的四個方向檢查是否五子連珠。

1. check 方法:以落子點為中心,同時往正反兩側延伸計數

 private boolean check(int x, int y, List<Point> points, int checkOri) {
        int count = 1;   // 含自己
        // 往負方向數
        for (int i = 1; i < Constants.MAX_COUNT_IN_LINE; i++) {
            switch (checkOri) {
                case Constants.HORIZONTAL:    point1 = new Point(x - i, y);     break;
                case Constants.VERTICAL:      point1 = new Point(x, y - i);     break;
                case Constants.LEFT_DIAGONAL: point1 = new Point(x - i, y + i); break;
                case Constants.RIGHT_DIAGONAL:point1 = new Point(x + i, y + i); break;
            }
            if (points.contains(point1)) {
                count++;
            } else {
                break;
            }
        }
        // 往正方向數
        for (int i = 1; i < Constants.MAX_COUNT_IN_LINE; i++) {
            switch (checkOri) {
                case Constants.HORIZONTAL:    point2 = new Point(x + i, y);     break;
                case Constants.VERTICAL:      point2 = new Point(x, y + i);     break;
                case Constants.LEFT_DIAGONAL: point2 = new Point(x + i, y - i); break;
                case Constants.RIGHT_DIAGONAL:point2 = new Point(x - i, y - i); break;
            }
            if (points.contains(point2)) {
                count++;
            } else {
                break;
            }
        }
        return count == Constants.MAX_COUNT_IN_LINE;
    } 

2. 四個方向的包裝方法

 // 橫向
    private boolean checkHorizontal(int x, int y, List<Point> points) {
        checkModel = Constants.HORIZONTAL;
        return check(x, y, points, checkModel);
    }

    // 縱向
    private boolean checkVertical(int x, int y, List<Point> points) {
        checkModel = Constants.VERTICAL;
        return check(x, y, points, checkModel);
    }

    // 左斜
    private boolean checkLeftDiagonal(int x, int y, List<Point> points) {
        checkModel = Constants.LEFT_DIAGONAL;
        return check(x, y, points, checkModel);
    }

    // 右斜
    private boolean checkRighttDiagonal(int x, int y, List<Point> points) {
        checkModel = Constants.RIGHT_DIAGONAL;
        return check(x, y, points, checkModel);
    } 

3. 主判斷

 private Point point1, point2;
    private int checkModel = -1;

    public boolean checkFiveInLineWinner(List<Point> points) {
        for (Point point : points) {
            int x = point.x;
            int y = point.y;
            if (checkHorizontal(x, y, points)) {
                return true;
            } else if (checkVertical(x, y, points)) {
                return true;
            } else if (checkLeftDiagonal(x, y, points)) {
                return true;
            } else if (checkRighttDiagonal(x, y, points)) {
                return true;
            }
        }
        return false;
    } 

七、可以優化的地方

  • 只檢查最後一手就夠了。目前每次都掃過全部棋子再跑四方向,其實只要檢查剛落下的那一子即可,運算量能省下幾十倍。
  • 方向常數用位元旗標更直覺。把 HORIZONTAL=1、VERTICAL=2、LEFT_DIAGONAL=4、RIGHT_DIAGONAL=8 之後,就能用位元運算一次檢查多個方向。
  • 用陣列取代 ArrayList<Point>。棋盤只有 15×15,用二維陣列記錄棋色,查詢是 O(1),也不需要每次 new Point。
  • 棋譜還可以存更多狀態。例如目前輪誰、是否已結束、勝方,才能完整還原中斷的對局。
  • 加一個簡單的 AI。先從「能贏就贏、對手要贏就擋」的啟發式規則開始,再進到 Minimax 加 Alpha-Beta 剪枝,是理解博弈搜尋很好的練習。

以上就是五子棋的完整實作。自訂 View 的度量、事件、繪製三件套,加上一個直觀的四方向檢查演算法,一個能玩的小遊戲就完成了。

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