Java---二维数组

一.数组的维数

假象:一维数组

二维数组:数组中的元素是一维数组

二.五子棋游戏

import javax.swing.*;

public class Array06 {

    static String[][] matrix = new String[15][15];
    static String black = "⚫";
    static String white = "⚪";
    static boolean blackOrWhite = true;   //默认为黑棋

    public static void main(String[] args) {
        init();
        draw();
        play();
    }

    public static void init(){
        for (int i = 0;i < 15;i++){
            for (int j = 0;j < 15;j++){
                matrix[i][j] = "+";
            }
        }
    }

    //画出一个棋盘,并将+号存入二维数组
    public static void draw(){

        for (int i = 0;i < 15;i++){
            System.out.print("\t" + i);
        }
        System.out.println();

        for (int i = 0;i < 15;i++){
            System.out.print(i);
            for (int j = 0;j < 15;j++){
                System.out.print("\t" + matrix[i][j]);
            }
            System.out.println();
        }
    }

    public static void play(){
        while (true) {
            String player = blackOrWhite ? "黑棋" : "白棋";
            String input = JOptionPane.showInputDialog("请" + player + "请输入落子方位(例如[2,3])");
            // System.out.println(input);

            String[] split = input.split(",");
            int x = Integer.parseInt(split[0]);
            int y = Integer.parseInt(split[1]);
            if (x > 15||y > 15||x < 0||y < 0){
                JOptionPane.showMessageDialog(null,"落子方位超出范围");
            }
            System.out.println("坐标(" + x + "," + y + ")");

            matrix[x][y] = blackOrWhite ? black : white;
            draw();
            System.out.println(horizontalWin(matrix[x][y],x,y));
            blackOrWhite = !blackOrWhite;
        }
    }

    public static boolean horizontalWin(String color,int x,int y){
        int result = 1;
        int left = y;
        int right = x;

        while (left > 0){
            if (result >= 3) return true;

            if (matrix[x][--left].equals(color)){
                result++;
            }
        }

        while (right < 14){
            if (result >= 3) return true;
            if (matrix[x][++right].equals(color)){
                result++;
            }
        }
        return false;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值