JAVA基础 流程控制 做 五子棋

JAVA基础 流程控制 做 五子棋

package com.lanou.test;
import java.util.Scanner;

public class Wuziqi {
	public static void main(String[] args) {
		int[][] game = new int[16][16];
		boolean isSuccess = false;
		int role = 1;
		while (!isSuccess) {
			// 打印棋盘 遍历二维数组
			for (int[] items : game) {
				for (int item : items) {
					System.out.print(item + " ");
				}
				System.out.println();
			}
			System.out.println("请玩家" + (role == 1 ? "黑棋" : "白棋") + "下棋");
			System.out.println("请输入行:");
			Scanner scanner = new Scanner(System.in);
			int row = scanner.nextInt();
			System.out.println("请输入列:");
			int col = scanner.nextInt();
			if (row < 0 || row >= game.length) {
				continue;
			}
			if (col < 0 || col >= game[row].length) {
				continue;
			}
			if (game[row][col] != 0) {
				continue;
			}
			game[row][col] = role;// 下棋
			// 判断获胜

			// 横向判断输赢
			int count = 0;
			int i = 0;
			while (col - i >= 0 && game[row][col - i] == role) {// 横着往左走
				count++;
				i++;
			}
			i = 0;
			while (col + i < game[row].length && game[row][col + i] == role) {// 横着往右走
				count++;
				i++;
			}
			if (count >= 6) {
				System.out.println("恭喜" + (role == 1 ? "黑棋获胜" : "白棋获胜"));
				break;
			}

			// 竖向判断输赢
			count = 0;
			i = 0;
			while (row - i >= 0 && game[row - i][col] == role) {// 竖着向上走
				count++;
				i++;
			}
			i = 0;
			while (row + i < game.length && game[row + i][col] == role) {// 竖着向下走
				count++;
				i++;
			}

			if (count >= 6) {
				System.out.println("恭喜" + (role == 1 ? "黑棋获胜" : "白棋获胜"));
				break;
			}

			// 判断 “/” 方向

			count = 0;
			i = 0;
			while (row - i >= 0 && col + i < game[row].length && game[row - i][col + i] == role) {// 往右上
				count++;
				i++;
			}
			i = 0;
			while (row + i < game.length && col - i >= 0 && game[row + i][col - i] == role) {// 往左下
				count++;
				i++;
			}
			if (count >= 6) {
				System.out.println("恭喜" + (role == 1 ? "黑棋获胜" : "白棋获胜"));
				break;
			}

			// 判断 “\” 方向

			count = 0;
			i = 0;
			while (row - i >= 0 && col - i >= 0 && game[row - i][col - i] == role) {// 向左上
				count++;
				i++;
			}
			i = 0;
			while (row + i < game.length && col + i < game[row].length && game[row + i][col + i] == role) {// 向右下
				count++;
				i++;
			}
			if (count >= 6) {
				System.out.println("恭喜" + (role == 1 ? "黑棋获胜" : "白棋获胜"));
				break;
			}

			role = 3 - role;// 换子
		}
	}

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值