Android五子棋游戏程序完整实例分析
程序员文章站
2024-03-01 15:17:34
最近学习了五子棋的课程,感觉挺不错。然后自己写了个关于五子棋的android程序,从中还是能够学习到很多东西的。现在我们开始今天五子棋程序的编写历程。程序的源码请参见友情链...
最近学习了五子棋的课程,感觉挺不错。然后自己写了个关于五子棋的android程序,从中还是能够学习到很多东西的。现在我们开始今天五子棋程序的编写历程。程序的源码请参见友情链接:
好了,我们现在开始一步步的构建出项目来,首先是如下的项目结构图:
运行的效果图:
一些前期做准备的代码
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; // 检查的方向 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类,是整个程序比较核心的部分。
1、初始化工作,程序中用到的变量也放在下面的代码中:
// 棋盘的宽度,也是长度 private int mviewwidth; // 棋盘每格的长度 private float maxlineheight; private paint paint = new paint(); // 定义黑白棋子的bitmap 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的大小,使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); }
2、onsizechanged方法在布局的阶段,如果view的大小发生改变,此方法得到调用。
@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(); }
6、接下来,我们按上面的流程,一个个的做详细的解释:
绘制棋盘的网格:
// 绘制棋盘的网线 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); } }
检查游戏是否已经结束:
// 检查游戏是否结束 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); }
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; } } if (count == constants.max_count_in_line) { return true; } return false; }
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; }
源码下载:android五子棋游戏程序
以上就是本文的全部内容,希望对大家学习android软件编程有所帮助。