[Android][五子棋]⑥--再來(lái)一局

res-menu-menu.main

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/action_settings"
        android:title="重來(lái)一局"
        android:orderInCategory="100"
        app:showAsAction="never"/>
</menu>

WuziqiPanel

 public WuziqiPanel(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        //setBackgroundColor(0x44ff0000);

      ....

    }
 public void start(){
        mWhiteArray.clear();
        mBlackArray.clear();
        mIsGameOver=false;
        mIsWhiteWinner=false;
        invalidate();
    }

MainActivity

public class MainActivity extends AppCompatActivity {

    private WuziqiPanel wuziqiPanel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wuziqiPanel= (WuziqiPanel) findViewById(R.id.wuziqi);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main,menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id=item.getItemId();

        if(id==R.id.action_settings){
            wuziqiPanel.start();
            return true;
        }


        return super.onOptionsItemSelected(item);
    }
}

完整代碼

package myapplication4.xt.com.wuziqidemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by TONG on 2017/6/7.
 */

public class WuziqiPanel extends View {

    //棋盤(pán)寬度
    private int mPanelWidth;

    //每格行高
    private float mLineHeight;

    //格子數(shù)
    private int MAX_LINE=10;

    private Paint mPaint=new Paint();

    private Bitmap mWhitePiece;

    private  Bitmap mBlackPiece;

    //棋子的大小比例
    private float ratioPieceOfLineHeigh=3*1.0f/4;

    //白棋先走,當(dāng)前輪到白棋
    private boolean mIsWhite=true;
    private ArrayList<Point> mWhiteArray=new ArrayList<>();
    private ArrayList<Point> mBlackArray=new ArrayList<>();

    private boolean mIsGameOver;
    private boolean mIsWhiteWinner;

    private int MAX_COUNT_IN_LINE=5;



    public WuziqiPanel(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        //setBackgroundColor(0x44ff0000);

        //初始化
        init();

    }

    private void init() {
        mPaint.setColor(0x88000000);
        //抗鋸齒
        mPaint.setAntiAlias(true);
        //防抖動(dòng)
        mPaint.setDither(true);
        //畫(huà)筆為空心
        mPaint.setStyle(Paint.Style.STROKE);

        mWhitePiece= BitmapFactory.decodeResource(getResources(),R.drawable.stone_w2);
        mBlackPiece=BitmapFactory.decodeResource(getResources(),R.drawable.stone_b1);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize=MeasureSpec.getSize(widthMeasureSpec);
        int widthMode=MeasureSpec.getMode(widthMeasureSpec);

        int heightSize=MeasureSpec.getSize(heightMeasureSpec);
        int heightMode=MeasureSpec.getMode(heightMeasureSpec);

        int width=Math.min(widthSize,heightSize);

        //嵌套在scrollow中寬度或高度不確定
        if(widthMode==MeasureSpec.UNSPECIFIED){
            width=heightSize;
        }else if(heightMode==MeasureSpec.UNSPECIFIED){
            width=widthSize;
        }

        setMeasuredDimension(width,width);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        //設(shè)置棋盤(pán)寬度
        mPanelWidth=w;
        //設(shè)置格子線的高度
        mLineHeight=mPanelWidth*1.0f/MAX_LINE;

        //棋子寬度
        int pieceWidth= (int) (mLineHeight*ratioPieceOfLineHeigh);
        mWhitePiece=Bitmap.createScaledBitmap(mWhitePiece,pieceWidth,pieceWidth,false);
        mBlackPiece=Bitmap.createScaledBitmap(mBlackPiece,pieceWidth,pieceWidth, false);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if(mIsGameOver) return false;

        int action = event.getAction();
        //不能ACTION_DOWN 因?yàn)槿绻灞P(pán)是可滾動(dòng)的 在滾動(dòng)過(guò)程中也會(huì)執(zhí)行此事件
        if(action==MotionEvent.ACTION_UP){

            int x= (int) event.getX();
            int y= (int) event.getY();


            Point p=getValidPoint(x,y);

            if(mWhiteArray.contains(p)||mBlackArray.contains(p)){
                return false;
            }

            if(mIsWhite){
                mWhiteArray.add(p);
            }else {
                mBlackArray.add(p);
            }

            invalidate();
            mIsWhite=!mIsWhite;

            return true;
        }
        return true;
    }

    /**
     * 獲取點(diǎn)擊在合理范圍的點(diǎn)
     * @param x
     * @param y
     * @return
     */
    private Point getValidPoint(int x, int y) {
        return new Point((int)(x/mLineHeight),(int)(y/mLineHeight));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBoard(canvas);

        drawPiece(canvas);

        checkGameOver();
    }


    private void checkGameOver() {
        boolean whiteWin=checkFiveInLine(mWhiteArray);
        boolean blackWin=checkFiveInLine(mBlackArray);

        if(whiteWin||blackWin){
            mIsGameOver=true;
            mIsWhiteWinner=whiteWin;

            String text=mIsWhiteWinner?"白棋勝利":"黑棋勝利";
            Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();

        }
    }

    private boolean checkFiveInLine(List<Point> points) {

        for(Point p:points){
            int x=p.x;
            int y=p.y;

            boolean win=checkHorizontal(x,y,points);
            if(win) return true;
            win=checkVertical(x,y,points);
            if(win) return true;
            win=checkLeftDiagonal(x,y,points);
            if(win) return true;
            win=checkRightDiagonal(x,y,points);
            if(win) return true;
        }


        return false;
    }

    /**
     * 判斷x,y位置的棋子礁凡,是否橫向有相鄰的五個(gè)一致
     * @param x
     * @param y
     * @param points
     * @return
     */
    private boolean checkHorizontal(int x, int y, List<Point> points) {
        int count=1;
        //左邊
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x-i,y))){
                count++;
            }else {
                break;
            }
        }

        //右邊
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x+i,y))){
                count++;
            }else {
                break;
            }
        }

        if(count==MAX_COUNT_IN_LINE) return true;

        return false;
    }

    /**
     * 判斷x,y位置的棋子,是否縱向有相鄰的五個(gè)一致
     * @param x
     * @param y
     * @param points
     * @return
     */
    private boolean checkVertical(int x, int y, List<Point> points) {
        int count=1;
        //上
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x,y-i))){
                count++;
            }else {
                break;
            }
        }

        //下
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x,y+i))){
                count++;
            }else {
                break;
            }
        }

        if(count==MAX_COUNT_IN_LINE) return true;

        return false;
    }

    /**
     * 判斷x,y位置的棋子涯肩,是否左斜有相鄰的五個(gè)一致
     * @param x
     * @param y
     * @param points
     * @return
     */
    private boolean checkLeftDiagonal(int x, int y, List<Point> points) {
        int count=1;
        //上
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x-i,y+i))){
                count++;
            }else {
                break;
            }
        }

        //下
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x+i,y-i))){
                count++;
            }else {
                break;
            }
        }

        if(count==MAX_COUNT_IN_LINE) return true;

        return false;
    }

    /**
     * 判斷x,y位置的棋子撒汉,是否右斜有相鄰的五個(gè)一致
     * @param x
     * @param y
     * @param points
     * @return
     */
    private boolean checkRightDiagonal(int x, int y, List<Point> points) {
        int count=1;
        //上
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x-i,y-i))){
                count++;
            }else {
                break;
            }
        }

        //下
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x+i,y+i))){
                count++;
            }else {
                break;
            }
        }

        if(count==MAX_COUNT_IN_LINE) return true;

        return false;
    }


    private void drawPiece(Canvas canvas) {
        for(int i=0,n=mWhiteArray.size();i<n;i++){
            Point whitePoint=mWhiteArray.get(i);
            canvas.drawBitmap(mWhitePiece,
                    (whitePoint.x+(1-ratioPieceOfLineHeigh)/2)*mLineHeight,
                    (whitePoint.y+(1-ratioPieceOfLineHeigh)/2)*mLineHeight,null);
        }

        for(int i=0,n=mBlackArray.size();i<n;i++){
            Point blackPiece=mBlackArray.get(i);
            canvas.drawBitmap(mBlackPiece,
                    (blackPiece.x+(1-ratioPieceOfLineHeigh)/2)*mLineHeight,
                    (blackPiece.y+(1-ratioPieceOfLineHeigh)/2)*mLineHeight,null);
        }

    }

    private void drawBoard(Canvas canvas) {
        int w=mPanelWidth;
        float lineHeight=mLineHeight;

        for(int i=0;i<MAX_LINE;i++){
            int startX= (int) (lineHeight/2);
            int endX= (int) (w-lineHeight/2);

            int y= (int) ((0.5+i)*lineHeight);

            //畫(huà)豎線
            canvas.drawLine(startX,y,endX,y,mPaint);
            //畫(huà)橫線
            canvas.drawLine(y,startX,y,endX,mPaint);


        }

    }

    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_WHITE_ARRAY,mWhiteArray);
        bundle.putParcelableArrayList(INSTANCE_BLACK_ARRAY,mBlackArray);
        return 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();
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末沟优,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子睬辐,更是在濱河造成了極大的恐慌挠阁,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,946評(píng)論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件溯饵,死亡現(xiàn)場(chǎng)離奇詭異侵俗,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)丰刊,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,336評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)隘谣,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人啄巧,你說(shuō)我怎么就攤上這事寻歧。” “怎么了秩仆?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,716評(píng)論 0 364
  • 文/不壞的土叔 我叫張陵码泛,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我澄耍,道長(zhǎng)噪珊,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 60,222評(píng)論 1 300
  • 正文 為了忘掉前任逾苫,我火速辦了婚禮卿城,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘铅搓。我一直安慰自己,他們只是感情好搀捷,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,223評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布星掰。 她就那樣靜靜地躺著,像睡著了一般嫩舟。 火紅的嫁衣襯著肌膚如雪氢烘。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 52,807評(píng)論 1 314
  • 那天家厌,我揣著相機(jī)與錄音播玖,去河邊找鬼。 笑死饭于,一個(gè)胖子當(dāng)著我的面吹牛蜀踏,可吹牛的內(nèi)容都是我干的维蒙。 我是一名探鬼主播,決...
    沈念sama閱讀 41,235評(píng)論 3 424
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼果覆,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼颅痊!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起局待,我...
    開(kāi)封第一講書(shū)人閱讀 40,189評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤斑响,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后钳榨,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體舰罚,經(jīng)...
    沈念sama閱讀 46,712評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,775評(píng)論 3 343
  • 正文 我和宋清朗相戀三年薛耻,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了沸停。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,926評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡昭卓,死狀恐怖愤钾,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情候醒,我是刑警寧澤能颁,帶...
    沈念sama閱讀 36,580評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站倒淫,受9級(jí)特大地震影響伙菊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜敌土,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,259評(píng)論 3 336
  • 文/蒙蒙 一镜硕、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧返干,春花似錦兴枯、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,750評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至癌淮,卻和暖如春躺坟,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背乳蓄。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,867評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工咪橙, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,368評(píng)論 3 379
  • 正文 我出身青樓美侦,卻偏偏與公主長(zhǎng)得像产舞,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子音榜,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,930評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容

  • ¥開(kāi)啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開(kāi)一個(gè)線程庞瘸,因...
    小菜c閱讀 6,451評(píng)論 0 17
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,336評(píng)論 25 707
  • 原文地址:http://www.android100.org/html/201606/06/241682.html...
    AFinalStone閱讀 947評(píng)論 0 1
  • 給我1000W 來(lái)吧~有想做的私聊,我還你一片天空 看看一個(gè)普通人的生活將會(huì)有怎樣的變化赠叼。而人格擦囊,心理,交友圈等等...
    我很黑但也很白閱讀 197評(píng)論 0 0
  • 歡愉嫌夜短嘴办,天蒙蒙亮了瞬场,嚴(yán)如斯一夜未眠。高漲的情緒冷靜下來(lái)了涧郊,她側(cè)臥著身子贯被,看著身邊熟睡的鄭毅。 鄭毅天生有些自來(lái)...
    樵砥閱讀 282評(píng)論 0 1