溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

基于android實(shí)現(xiàn)五子棋開發(fā)

發(fā)布時(shí)間:2020-10-20 11:25:06 來源:腳本之家 閱讀:176 作者:hahayixiao1 欄目:移動(dòng)開發(fā)

基于Android的五子棋的開發(fā),供大家參考,具體內(nèi)容如下

需求分析

1 棋盤和棋子繪制
2 按照五子棋的規(guī)則制定游戲勝負(fù)規(guī)則 
3 鼠標(biāo)響應(yīng) 在對(duì)戰(zhàn)中 需要通過鼠標(biāo)點(diǎn)擊下棋 進(jìn)行游戲的基本操作
4 游戲模式 雙人對(duì)戰(zhàn) 兩人交替落子 雙方孰先孰后隨機(jī)決定
5 棋子的形式和作用 棋子分為黑白兩種棋子 雙方各持一種棋子 通過黑先白后的方式來進(jìn)行對(duì)局
6 通過棋子完成五連珠結(jié)束游戲

流程圖

基于android實(shí)現(xiàn)五子棋開發(fā)

android stdio中的基本架構(gòu)

基于android實(shí)現(xiàn)五子棋開發(fā)

CheckWinner.java

 package com.example.wuziqi;
 import android.graphics.Point;
 import java.util.List;
/**
 * Created by Linux on 2016/4/8.
 */
public class CheckWinner {
 private Point point1, point2;
 private int checkModel = Constants.HORIZONTAL;
 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;
 }
 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;
 }
 // 橫向判斷
 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);
 }

}

ChessBoardView.java

package com.example.wuziqi;

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.media.MediaPlayer;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;

public class ChessBoardView extends View {
 // 棋盤的寬度,也是長(zhǎng)度
 private int mViewWidth;
 // 棋盤每格的長(zhǎng)度
 private float maxLineHeight;
 private Paint paint = new Paint();
 // 定義黑白棋子的Bitmap
 private 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);
}

@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);
}
@Override
protected void onDraw(Canvas canvas) {
 super.onDraw(canvas);
 // 繪制棋盤的網(wǎng)格
 drawBoard(canvas);
 // 繪制棋盤的黑白棋子
 drawPieces(canvas);
 // 檢查游戲是否結(jié)束
 checkGameOver();
}
// 檢查游戲是否結(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();
 }
}
// 根據(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);
 }
}
// 繪制棋盤的網(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);
 }
}
@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);
}
@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;
}
private Point getValidPoint(int x, int y) {
 int validX = (int) (x / maxLineHeight);
 int validY = (int) (y / maxLineHeight);
 return new Point(validX, validY);
}
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;
}
@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();
}
}

Constants.java

package com.example.wuziqi;

/**
 * Created by Linux on 2016/4/8.
 */
public class Constants {

 // 五子連珠
 public final static int MAX_COUNT_IN_LINE = 5;
 // 棋盤的行數(shù)
 final static int MAX_LINE = 25;

 // 檢查的方向
 final static int HORIZONTAL = 0;
 final static int VERTICAL = 1;
 final static int LEFT_DIAGONAL = 2;
 final static int RIGHT_DIAGONAL = 3;
}

MainActivity.java

package com.example.wuziqi;

import android.content.Intent;
import android.os.Bundle;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

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);
}
public void doClick(View v) {
 Intent intent = new Intent(MainActivity.this, MusicServer.class);
 switch (v.getId()) {
 case R.id.button1:
 this.startService(intent);
 break;
 case R.id.button2:
 this.stopService(intent);
 break;
 }
}
@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;
}

MusicServers.java

package com.example.wuziqi;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class MusicServer extends Service {
 private MediaPlayer mp;
 public IBinder onBind(Intent intent) {
 Log.e("Service", "onBind被調(diào)用");
 mp.start();
 return null;
 }

 public void onCreate() {
 Log.e("Service", "onCreate被調(diào)用");
 mp = MediaPlayer.create(this, R.raw.yinyue);
 super.onCreate();
 }

 public void onDestroy() {
 Log.e("Service", "onDestroy被調(diào)用");
 mp.stop();
 super.onDestroy();
 }

 public int onStartCommand(Intent intent, int flags, int startId) {
 Log.e("Service", "onStartCommand被調(diào)用");
 mp.start();
 return super.onStartCommand(intent, flags, startId);
 }

 public boolean onUnbind(Intent intent) {
 Log.e("Service", "onUnbind被調(diào)用");
 mp.stop();
 return super.onUnbind(intent);
 }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.wuziqi">

<application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:supportsRtl="true"
 android:theme="@style/AppTheme">

 <activity android:name=".MainActivity">
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>

 </activity>
 <service
 android:name=".MusicServer"
 android:enabled="true"
 android:exported="true"></service>
</application>
</manifest>

activity_main.xml

<?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/bg1"
 tools:context="com.example.wuziqi.MainActivity">

 <com.example.wuziqi.ChessBoardView
 android:id="@+id/boardView"
 android:layout_centerInParent="true"
 android:layout_width="match_parent"
 android:layout_height="match_parent" />

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/textView"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="16dp"
 android:onClick="doClick"
 android:text="開啟音樂" />

 <Button
 android:id="@+id/button2"
 
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/button1"
 android:layout_alignStart="@+id/button1"
 android:layout_marginStart="94dp"
 android:layout_marginTop="-48dp"
 android:onClick="doClick"
 android:text="停止音樂" />

</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" />
 <item android:id="@+id/action_setting1"
 android:title="悔棋"
 android:orderInCategory="100"
 android:showAsAction="never"
 tools:ignore="AppCompatResource" />
</menu>

運(yùn)行結(jié)果

基于android實(shí)現(xiàn)五子棋開發(fā)

悔棋由于沒時(shí)間所以沒實(shí)現(xiàn),如果有問題希望大家?guī)兔Ω恼?/p>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI