JAVA 五子棋 判断输赢的代码实现


	<pre name="code" class="java">//定义棋盘大小,宽w,高h
	int w = 11;
	int h = w;
	//用一个二维数组保存棋盘数据,1代表红棋,2代表黑棋
	int[][] chess = new int[h][w];
	//定义控制循环的布尔变量
	boolean game_over = false;
	boolean win_red = false;
	boolean win_black = false;

 

//判断输赢的函数,传入当前点位置坐标
		public void judge(int y3, int x3) {
			//创建4个StringBuffer对象分别保存横向,纵向,两个斜向棋盘数据
			StringBuffer buf21 = new StringBuffer();
			StringBuffer buf14 = new StringBuffer();
			StringBuffer buf13 = new StringBuffer();
			StringBuffer buf24 = new StringBuffer();
			// 横向数据流
			for (int y = y3, x = 0; x < w; x++) {
				buf21.append(chess[y][x]);
			}
			//System.out.println(buf21);
			
			// 纵向数据流
			for (int y = 0, x = x3; y < h; y++) {
				buf14.append(chess[y][x]);
			}
			//System.out.println(buf14);
			
			// 二四象限数据流
			if (y3 >= x3) {
				for (int y = y3 - x3, x = 0; y < h; y++, x++) {
					buf24.append(chess[y][x]);
				}
			} else {
				for (int y = 0, x = x3 - y3; x < w; y++, x++) {
					buf24.append(chess[y][x]);
				}
			}
			//System.out.println(buf24);

			// 一三象限数据流
			if ((x3 + y3) < h) {
				for (int x = x3 + y3, y = 0; y <= x3 + y3; y++, x--) {
					buf13.append(chess[y][x]);
				}
			} else {
				for (int x = h - 1, y = x3 + y3 - (h - 1); y < h; y++, x--) {
					buf13.append(chess[y][x]);
				}
			}
			//System.out.println(buf13);

			//使用正则表达式匹配数据判断输赢,连续5个1表示红棋赢,连续5个二表示黑棋赢
			if (buf21.toString().matches("\\d*1{5}\\d*")
					|| buf14.toString().matches("\\d*1{5}\\d*")
					|| buf13.toString().matches("\\d*1{5}\\d*")
					|| buf24.toString().matches("\\d*1{5}\\d*")) {
				win_red =true;
			}
			
			if (buf21.toString().matches("\\d*2{5}\\d*")
					|| buf14.toString().matches("\\d*2{5}\\d*")
					|| buf13.toString().matches("\\d*2{5}\\d*")
					|| buf24.toString().matches("\\d*2{5}\\d*")) {
				win_black =true;
			}
			
			if (win_red) {
				JOptionPane.showMessageDialog(null, "红棋赢!");
			} else if (win_black) {
				JOptionPane.showMessageDialog(null, "黑棋赢!");
			}
		}


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值