码迷,mamicode.com
首页 > 移动开发 > 详细

android程序---->android五子棋的实现

时间:2016-04-08 21:38:25      阅读:389      评论:0      收藏:0      [点我收藏+]

标签:

在慕课网上学习了五子棋的课程,感觉挺不错。然后自己写了个关于五子棋的android程序,从中还是能够学习到很多东西的。现在我们开始今天五子棋程序的编写历程。程序的源码请参见友情链接:

 

目录导航

  1.   一些前期做准备的代码
  2.   自定义棋盘的View
  3.   保存残局并恢复棋局
  4.   判断游戏是否结束的算法
  5.   友情链接

 

好了,我们现在开始一步步的构建出项目来,首先是如下的项目结构图:

技术分享

 运行的效果图:

技术分享

一些前期做准备的代码

 一、 主活动类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;
    }
}

 

二、 常量类便于维护管理: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;
}

 

三、 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>

 

四、 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类,是整个程序比较核心的部分。

一、 初始化工作,程序中用到的变量也放在下面的代码中:

// 棋盘的宽度,也是长度
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);
}

 

二、 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);
}

 

三、 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);
}

 

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

 

五、 在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);
    }
}

检查游戏是否已经结束:

// 检查游戏是否结束
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();
    }
}

 

保存残局并恢复棋局

一、 保存残局,例如切换横坚屏时:

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

 

二、 从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);
}

 

三、 增加再来一局游戏的逻辑:

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

 

判断游戏是否结束的算法

在CheckWinner中,对棋盘中的棋子做”米“字型的检查是否五子连珠:

一、 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);
                point2 = new Point(x + i, y);
                break;
            case Constants.VERTICAL:
                point1 = new Point(x, y - i);
                point2 = new Point(x, y + i);
                break;
            case Constants.LEFT_DIAGONAL:
                point1 = new Point(x - i, y + i);
                point2 = new Point(x + i, y - i);
                break;
            case Constants.RIGHT_DIAGONAL:
                point1 = new Point(x + i, y + i);
                point2 = new Point(x - i, y - i);
                break;
        }
        if (points.contains(point1) || points.contains(point2)) {
            count++;
        } else {
            break;
        }
    }
    if (count == Constants.MAX_COUNT_IN_LINE) {
        return true;
    }
    return false;
}

 

二、 做四个方向检查:

// 横向判断
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);
}

 

三、 做具体的判断,是否游戏结束:

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五子棋的实现

标签:

原文地址:http://www.cnblogs.com/huhx/p/MyAndroidgobang.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!