【问题标题】:Add elements of ArrayList into a 2d Array将 ArrayList 的元素添加到二维数组中
【发布时间】:2020-01-28 19:23:28
【问题描述】:

我正在读取一个文本文件并将其内容保存到一个 ArrayList 中,我知道我想用 Arraylist 的内容填充一个 8x8 数组。我的目标是读取包含棋子、颜色和位置的文件,然后检查有效的移动。但是,我是 java 新手,不确定如何检查 arrayList 的这些属性,即它是白色还是黑色。

感谢任何帮助。


public static void MoveCheck(String answer,ArrayList<String> board){
        String move; 
        if(answer.equalsIgnoreCase("pawn")){
            System.out.println("What position do you want to move to?");
            Scanner scanner = new Scanner(System.in);
            move = scanner.nextLine();
            if(board.contains("white")){ 
                if(move.equalsIgnoreCase("B3")||(move.equalsIgnoreCase("B4"))){
                    System.out.println("Valid move");
                }
                else{
                    System.out.println("Invalid move/Not on the board");
                }
            }
        }

public static void main(String args[]){

        String answer;
        ArrayList<String> result = new ArrayList<>();
        int [][] board = new int[7][7];
        try (BufferedReader br = new BufferedReader(new FileReader("chess.txt"))){
            while(br.ready()){
                result.add(br.readLine());
            }
        }   catch (Exception e){
            System.out.print("Error occurred while reading.");
        }

       for (String line : result){
            System.out.println(line);
       }

        System.out.println("Select a piece to move");
        Scanner scanner = new Scanner(System.in);
        answer = scanner.nextLine();

        MoveCheck(answer,result);

    }

【问题讨论】:

    标签: arrays chess


    【解决方案1】:

    你应该阅读FEN Notation

    您可以使用 pgn 表示法导入位置

    它看起来像这样

    rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
    

    然后您可以一次从左到右读取这个字符串一个字符,以便能够填充您的板。

    小写字母 = 黑块

    大写字母 = 白块

    / 表示下一行

    number = 从 A 列到下一块的空方格数

    w 表示移动是白色的

    KQkq 表示双方都可以攻守王翼和王翼

    0 1 表示当前是白方先手

    【讨论】:

      猜你喜欢
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多