国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > Android > 正文

Android五子棋游戲程序完整實(shí)例分析

2019-12-12 06:32:35
字體:
供稿:網(wǎng)友

最近學(xué)習(xí)了五子棋的課程,感覺挺不錯(cuò)。然后自己寫了個(gè)關(guān)于五子棋的android程序,從中還是能夠?qū)W習(xí)到很多東西的。現(xiàn)在我們開始今天五子棋程序的編寫歷程。

好了,我們現(xiàn)在開始一步步的構(gòu)建出項(xiàng)目來,首先是如下的項(xiàng)目結(jié)構(gòu)圖:

運(yùn)行的效果圖:

一些前期做準(zhǔn)備的代碼

1、 主活動(dòng)類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、常量類便于維護(hù)管理:Constants

public class Constants { // 五子連珠 public final static int MAX_COUNT_IN_LINE = 5; // 棋盤的行數(shù) final static int MAX_LINE = 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="http://schemas.android.com/apk/res/android" xmlns:tools="http://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="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/action_setting" android:title="再來一局" android:orderInCategory="100" android:showAsAction="never" tools:ignore="AppCompatResource" /></menu>

自定義棋盤的View

ChessBoardView類,是整個(gè)程序比較核心的部分。

1、初始化工作,程序中用到的變量也放在下面的代碼中:

// 棋盤的寬度,也是長(zhǎng)度private int mViewWidth;// 棋盤每格的長(zhǎng)度private float maxLineHeight;private Paint paint = new Paint();// 定義黑白棋子的Bitmapprivate Bitmap mwhitePiece, mblackPiece;private float ratioPieceOfLineHeight = 3 * 1.0f / 4;// 判斷當(dāng)前落下的棋子是否是白色的private boolean mIsWhite = true;// 記錄黑白棋子位置的列表private ArrayList<Point> mwhiteArray = new ArrayList<>();private ArrayList<Point> mblackArray = new ArrayList<>();// 游戲是否結(jié)束private boolean mIsGameOver;// 游戲結(jié)束,是否是白色方勝利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方法,測(cè)量View的大小,使View的長(zhǎng)寬一致。

@Overrideprotected 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);} 

2、onSizeChanged方法在布局的階段,如果View的大小發(fā)生改變,此方法得到調(diào)用。

@Overrideprotected 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方法中處理我們下棋子的位置:

@Overridepublic 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方法做棋盤的繪制工作:

@Overrideprotected void onDraw(Canvas canvas) { super.onDraw(canvas); // 繪制棋盤的網(wǎng)格 drawBoard(canvas); // 繪制棋盤的黑白棋子 drawPieces(canvas); // 檢查游戲是否結(jié)束 checkGameOver();}

6、接下來,我們按上面的流程,一個(gè)個(gè)的做詳細(xì)的解釋:

繪制棋盤的網(wǎng)格:

// 繪制棋盤的網(wǎng)線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); }}

繪制棋盤的黑白棋子:

// 根據(jù)黑白棋子的數(shù)組繪制棋子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); }}

檢查游戲是否已經(jīng)結(jié)束:

// 檢查游戲是否結(jié)束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(); }}

保存殘局并恢復(fù)棋局

1、 保存殘局,例如切換橫堅(jiān)屏?xí)r:

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";@Overrideprotected 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中恢復(fù)棋局:

@Overrideprotected 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);} 

3、 增加再來一局游戲的邏輯:

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

判斷游戲是否結(jié)束的算法

在CheckWinner中,對(duì)棋盤中的棋子做”米“字型的檢查是否五子連珠:

1、 check方法中,針對(duì)不同的方向,做判斷:

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; } } if (count == Constants.MAX_COUNT_IN_LINE) { return true; } return false;}

2、 做四個(gè)方向檢查:

// 橫向判斷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、 做具體的判斷,是否游戲結(jié)束:

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;}

源碼下載:Android五子棋游戲程序

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家學(xué)習(xí)Android軟件編程有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 临汾市| 罗田县| 二连浩特市| 巴马| 泰安市| 油尖旺区| 鄂伦春自治旗| 波密县| 关岭| 海安县| 乌鲁木齐市| 修武县| 平泉县| 凭祥市| 西青区| 广饶县| 黑水县| 东丰县| 宜丰县| 贡觉县| 凤翔县| 贡嘎县| 巴青县| 和田县| 石柱| 革吉县| 思茅市| 电白县| 新建县| 内丘县| 明星| 徐闻县| 襄汾县| 桐柏县| 汽车| 和林格尔县| 丽江市| 海原县| 墨竹工卡县| 和政县| 亚东县|