基于android实现五子棋开发

 更新时间:2020年02月04日 14:30:57   作者:hahayixiao1  
这篇文章主要为大家详细介绍了基于android实现五子棋开发,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

基于Android的五子棋的开发,供大家参考,具体内容如下

需求分析

1 棋盘和棋子绘制
2 按照五子棋的规则制定游戏胜负规则 
3 鼠标响应 在对战中 需要通过鼠标点击下棋 进行游戏的基本操作
4 游戏模式 双人对战 两人交替落子 双方孰先孰后随机决定
5 棋子的形式和作用 棋子分为黑白两种棋子 双方各持一种棋子 通过黑先白后的方式来进行对局
6 通过棋子完成五连珠结束游戏

流程图

android stdio中的基本架构

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

@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);
 // 绘制棋盘的网格
 drawBoard(canvas);
 // 绘制棋盘的黑白棋子
 drawPieces(canvas);
 // 检查游戏是否结束
 checkGameOver();
}
// 检查游戏是否结束
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 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 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;
 // 棋盘的行数
 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被调用");
 mp.start();
 return null;
 }

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

 public void onDestroy() {
 Log.e("Service", "onDestroy被调用");
 mp.stop();
 super.onDestroy();
 }

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

 public boolean onUnbind(Intent intent) {
 Log.e("Service", "onUnbind被调用");
 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"
 style="?android:attr/buttonStyleSmall"
 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>

运行结果

悔棋由于没时间所以没实现,如果有问题希望大家帮忙改正。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • listview 选中高亮显示实现方法

    listview 选中高亮显示实现方法

    当点击左侧ListView后,选中的一行就会一直呈高亮状态显示,图中选中行字的颜色显示为蓝色(注意:是选中行后一直高亮,而不是只是点击时高亮),如果再次点击另外的一行, 则新的那一行就高亮,下面就来实现这个高亮效果的显示
    2012-11-11
  • Android程序打开和对输入法的操作(打开/关闭)

    Android程序打开和对输入法的操作(打开/关闭)

    整理了一下Android下对输入法的操作:打开输入法窗口、关闭出入法窗口、如果输入法打开则关闭,如果没打开则打开、获取输入法打开的状态
    2013-05-05
  • Android编程动态修改RelativeLayout宽高的方法

    Android编程动态修改RelativeLayout宽高的方法

    这篇文章主要介绍了Android编程动态修改RelativeLayout宽高的方法,涉及Android动态布局的相关技巧,需要的朋友可以参考下
    2015-12-12
  • Android Studio 全局查找问题

    Android Studio 全局查找问题

    这篇文章主要介绍了Android Studio 全局查找问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-01-01
  • 详解如何在Flutter中使用媒体播放器

    详解如何在Flutter中使用媒体播放器

    现在的app功能越来越强大,除了基本的图文之外,还需要各种各样的其他的功能,比如视频,和直播,那么如何在flutter中使用媒体播放器呢?一起来看看吧
    2023-03-03
  • Android ViewFlipper翻转视图使用详解

    Android ViewFlipper翻转视图使用详解

    这篇文章主要为大家详细介绍了Android ViewFlipper翻转视图的使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-05-05
  • Android 自定义View实现任意布局的RadioGroup效果

    Android 自定义View实现任意布局的RadioGroup效果

    这篇文章主要介绍了Android 自定义View实现任意布局的RadioGroup,需要的朋友可以参考下
    2018-11-11
  • Android使用OKHttp库实现视频文件的上传到服务器功能

    Android使用OKHttp库实现视频文件的上传到服务器功能

    这篇文章主要介绍了Android使用OKHttp库实现视频文件的上传到服务器功能,需要的朋友可以参考下
    2018-03-03
  • Android编程之分辨率处理相关代码段合集

    Android编程之分辨率处理相关代码段合集

    这篇文章主要介绍了Android编程之分辨率处理相关代码段合集,涉及Android针对分辨率的计算与转换等相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-11-11
  • Android 再按一次返回键退出程序实现思路

    Android 再按一次返回键退出程序实现思路

    用户退出应用前给出一个提示是很有必要的,因为可能是用户并不真的想退出,而只是一不小心按下了返回键,大部分应用的做法是在应用退出去前给出一个Dialog提示框;个人觉得再按一次返回键退出程序很有必要,接下来介绍一些简单实现
    2013-01-01

最新评论