編輯:關於 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>
這是整個專案的核心。
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;
}
以上就是五子棋的完整實作。自訂 View 的度量、事件、繪製三件套,加上一個直觀的四方向檢查演算法,一個能玩的小遊戲就完成了。
Android 換膚方案:把皮膚包成獨立 APK 當插件載入
轉載請註明出處:IT_xiao小巫 這篇來分享一個 Android 換膚的 Demo。相關程式碼都整理在 GitHub 上,後續文章涉及的程式碼也會統一放在那邊管理。
Android 開發常見第三方框架與實用元件整理
Android 開發常見第三方框架與實用元件整理 在 Android 開發中,合理選用第三方框架與元件,能有效減少重複工作,提高開發效率。以下依網路請求、快速開發、圖片加
Android 系統開發(3):Makefile 的編寫
Makefile 是什麼? Makefile 的作用主要有兩點: 1、組織工程文件,編譯成複雜的程序;2、安裝及卸載我們的程序。 Makefile 使用示例 在 /hom
微信支付 JSAPI 公眾號支付完整接入實戰教程
開始之前:你需要準備些什麼 這份教程面向已經具備一定基礎的開發者。在動手之前,請確認你已經滿足以下幾個前提條件:拥有一個通過微信認證的服務號,並且該服務號已成功開通微信支