自定義五子棋View代碼

/**

  • Created by malei on 2017/6/5.
    */

public class GameView extends View{

private static final int MAX_LINES = 10;  //畫線數(shù)目
private final Context mContext;
private Paint mPaint;  //格子筆
private Paint mTextPaint; //提示字筆
private Paint mWinPaint;  //贏了
private int mWidth;  //組件當(dāng)前寬度
private int mHeight; //組件當(dāng)前高度
private int viewWidth;
private int viewHeight;
private int mGridPad;   //每個(gè)格子的寬度
private Bitmap mWhiteChess;  //白棋子
private Bitmap mBlackChess;  //黑棋子
private ArrayList<Point> mWhiteList = new ArrayList<>();//白棋子數(shù)據(jù)boo
private ArrayList<Point> mBlackList = new ArrayList<>();//黑棋子數(shù)據(jù)boo
private boolean isBlackStep;  //黑棋子走 true 是黑走
private boolean isGameOver;


public GameView(Context context) {
    this(context,null);
}

public GameView(Context context, AttributeSet attrs) {
    this(context, attrs,0);
}

public GameView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    mContext = context;
    init();
}


//悔棋
public void backOff(){
    if(isGameOver) return;
    if(!isBlackStep){
        isBlackStep = true;
        if(!mBlackList.isEmpty()){
            mBlackList.remove(mBlackList.size()-1);
        }
    }else {
        isBlackStep = false;
        if(!mWhiteList.isEmpty()){
            mWhiteList.remove(mWhiteList.size()-1);
        }
    }
    invalidate();
}

public void reStart(){
    mWhiteList.clear();
    mBlackList.clear();
    isGameOver = false;
    invalidate();
}

//初始化要畫筆
private void init() {
    mPaint = new Paint();
    mPaint.setColor(Color.BLUE);
    mTextPaint = new Paint();
    mTextPaint.setColor(Color.RED);
    mTextPaint.setTextSize(20);
    mWinPaint = new Paint();
    mWinPaint.setColor(Color.RED);
    mWinPaint.setTextSize(100);
    mWhiteChess = BitmapFactory.decodeResource(getResources(), R.mipmap.white);
    mBlackChess = BitmapFactory.decodeResource(getResources(), R.mipmap.black);

}

//繪制組件
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    LogUtils.i("onDraw");
    drawChessBoard(canvas);
    drawChesses(canvas);
    drawTipText(canvas); //繪制提示字
    checkGameResult(canvas);//游戲結(jié)束處理
}

private void drawTipText(Canvas canvas) {

    String text = "";
    if(isBlackStep){
        text = "黑棋走";
    }else{
        text = "白棋走";
    }
    canvas.drawText(text, mGridPad/4, mGridPad/2, mTextPaint);
}

//判斷游戲結(jié)果
private void checkGameResult(Canvas canvas) {
    boolean isBlackWin = checkResult(mBlackList);
    boolean isWhiteWin = checkResult(mWhiteList);
    if(isBlackWin || isWhiteWin){
        isGameOver = true;
        if(isWhiteWin){
            canvas.drawText("白色贏了",mGridPad*2 , mGridPad*5, mWinPaint);;
        }else {
            canvas.drawText("黑色贏了",mGridPad*2 , mGridPad*5, mWinPaint);;
        }
    }
}

private boolean checkResult(ArrayList<Point> pointList) {
    for (Point p : pointList){
        int x = p.x;
        int y = p.y;
        //水平檢測(cè)
        boolean win = checkHorizontal(x, y, pointList);
        if(win){
            return true;
        }
        //垂直檢測(cè)
        win = checkVertical(x, y, pointList);
        if (win) {
            return true;
        }
        win = checkLeftSlant(x, y, pointList);
        if (win) {
            return true;
        }
        win = checkRightSlant(x, y, pointList);
        if (win) {
            return true;
        }
    }
    return false;

}


//繪制棋子
private void drawChesses(Canvas canvas) {
    //繪制白棋
    int wSize = mWhiteList.size();
    for(int i = 0; i < wSize; i++){
        Point wp = mWhiteList.get(i);
        LogUtils.i(wp.x+"");
        canvas.drawBitmap(mWhiteChess,
                wp.x * mGridPad - mWhiteChess.getHeight()/2,
                wp.y * mGridPad - mWhiteChess.getHeight()/2,
                null);
    }

    //繪制黑棋子
    int bSize = mBlackList.size();
    for(int i = 0; i < bSize; i++){
        Point wp = mBlackList.get(i);
        LogUtils.i(wp.x+"");
        canvas.drawBitmap(mBlackChess,
                wp.x * mGridPad - mBlackChess.getHeight()/2,
                wp.y * mGridPad - mBlackChess.getHeight()/2,
                null);
    }
}

//繪制棋盤(10*10網(wǎng)格)
private void drawChessBoard(Canvas canvas) {
    int startX=0,startY = 0,stopX=0,stopY =0;
    LogUtils.i("viewWidth="+viewWidth);
    for (int i = 0 ; i < MAX_LINES; i++){
        //繪制橫線
        canvas.drawLine(0, startY, viewWidth, stopY, mPaint);
        startY = startY + mGridPad;
        stopY = stopY + mGridPad;

        //繪制豎線
        canvas.drawLine(startX, 0, stopX, viewWidth, mPaint);
        startX = startX + mGridPad;
        stopX = stopX + mGridPad;
    }
}

//View本身大小多少
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    LogUtils.i("onMeasure");
    //寬度設(shè)置
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);//組件寬度大小
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);//組件寬度測(cè)量模式
    if (widthMode == MeasureSpec.AT_MOST) {  //wrap_content 跟父組件關(guān)系密切
        viewWidth = widthSize;
    }else if(widthMode == MeasureSpec.EXACTLY){  //精確尺寸 fill_parent或者50dp
        viewWidth = widthSize;
    }else if(widthMode == MeasureSpec.UNSPECIFIED){ //基本不用
    }
    //高度設(shè)置
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);//高度大小
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);//高度測(cè)量模式
    if (heightMode == MeasureSpec.AT_MOST) {  //wrap_content 跟父組件關(guān)系密切
        viewHeight = heightSize;
    }else if(heightMode == MeasureSpec.EXACTLY){  //精確尺寸 fill_parent或者50dp
        viewHeight = heightSize;
    }else if(heightMode == MeasureSpec.UNSPECIFIED){ //基本不用
    }
    //返回小的值
    int width = Math.min(viewWidth, viewHeight);
    //設(shè)置大小
    setMeasuredDimension(width, width);
    mGridPad = width/10;
}



@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    LogUtils.i("onSizeChanged");
    LogUtils.i("width="+w+" height="+h);
    mWidth = w; //組件可用寬度
    mHeight = h; //組件可用寬度
}

@Override
public boolean onTouchEvent(MotionEvent event) {

    if(isGameOver){
        return false;
    }
    if(event.getAction() == MotionEvent.ACTION_UP){
        int x = (int) event.getX();
        int y = (int) event.getY();
        LogUtils.i("點(diǎn)擊 x="+x+" y="+y);
        Point p = getValidPoint(x, y);
        if (mWhiteList.contains(p) || mBlackList.contains(p)) {
            LogUtils.i("已經(jīng)被占位了");
            return false;
        }
        if(isBlackStep){ //是黑走
            mBlackList.add(p);
        }else{ //白走
            mWhiteList.add(p);
        }

        invalidate();
        isBlackStep = !isBlackStep;
    }

    return true;
}

private Point getValidPoint(int x, int y) {
    return new Point((int) (x / mGridPad), (int) (y / mGridPad));
}

private boolean checkRightSlant(int x, int y, List<Point> pointList) {
    int count = 1;
    for (int i = 1; i < LINE_MAX_NUMS; i++) {
        if (pointList.contains(new Point(x - i, y - i)) || pointList.contains(new Point(x + i, y + i))) {
            count++;
        } else {
            break;
        }
    }
    if (count == LINE_MAX_NUMS) {
        return true;
    }
    return false;
}


private boolean checkLeftSlant(int x, int y, List<Point> pointList) {
    int count = 1;
    for (int i = 1; i < LINE_MAX_NUMS; i++) {
        if (pointList.contains(new Point(x - i, y + i)) || pointList.contains(new Point(x + i, y - i))) {
            count++;
        } else {
            break;
        }
    }
    if (count == LINE_MAX_NUMS) {
        return true;
    }
    return false;
}

//垂直已經(jīng)連成5個(gè)
private boolean checkVertical(int x, int y, ArrayList<Point> pointList) {
    int count = 1;
    for (int i = 1; i < LINE_MAX_NUMS; i++) {
        if (pointList.contains(new Point(x, y - i)) || pointList.contains(new Point(x, y + i))) {
            count++;
        } else {
            break;
        }
    }
    if (count == LINE_MAX_NUMS) {
        return true;
    }
    return false;
}

private final static int LINE_MAX_NUMS = 5;//同色五子成線表示結(jié)束
//橫向已經(jīng)連成5個(gè)
private boolean checkHorizontal(int x, int y, ArrayList<Point> pointList) {
    int count = 1;
    for (int i = 1; i < LINE_MAX_NUMS; i++) {
        //左邊或者右邊判斷
        if(pointList.contains(new Point(x-i,y)) || pointList.contains(new Point(x+i,y))){
            count++;
        }else{
            break;
        }
        if(count == LINE_MAX_NUMS){
            return true;
        }
    }
    return false;
}

//保存界面數(shù)據(jù)(比如來電,李橫豎屏切換等)


//以下幾個(gè)常量是為了保存界面數(shù)據(jù)
private final static String GOBANG_INSTANCE = "gobang_instance";
private final static String GAME_OVER = "game_over";
private final static String WHITE_DATA = "white_data";
private final static String BLACK_DATA = "black_data";

//保存界面數(shù)據(jù)(比如來電,李橫豎屏切換等)
@Override
protected Parcelable onSaveInstanceState() {
    Bundle bundle = new Bundle();
    bundle.putParcelable(GOBANG_INSTANCE, super.onSaveInstanceState());
    bundle.putBoolean(GAME_OVER, isGameOver);
    bundle.putParcelableArrayList(WHITE_DATA, mWhiteList);
    bundle.putParcelableArrayList(BLACK_DATA, mBlackList);
    return super.onSaveInstanceState();
}

/**
 * 取用保存的數(shù)據(jù)
 */
@Override
protected void onRestoreInstanceState(Parcelable state) {
    if (state instanceof Bundle) {
        Bundle bundle = (Bundle) state;
        isGameOver = bundle.getBoolean(GAME_OVER);
        mWhiteList = bundle.getParcelableArrayList(WHITE_DATA);
        mBlackList = bundle.getParcelableArrayList(BLACK_DATA);
        super.onRestoreInstanceState(bundle.getParcelable(GOBANG_INSTANCE));
    }
    super.onRestoreInstanceState(state);
}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容