将字符映射转换为数组

Converting character map to array

我正在尝试学习 java 使用基本的 tictactoe 示例,但为了好玩我想稍后设计一个 ai。

我在将 char[] 扁平化为数组时遇到问题。我很困惑有没有更好的方法来做到这一点? 我是否需要创建另一种方法来将此 char[] 特定转换为数组?

错误:

The method mapToCharater(Charater.class::cast) is undefined for the type Stream<Object>

控制台输出

编辑:

Exception in thread "main" java.lang.ClassCastException: Cannot cast [C to java.lang.Character
    at java.base/java.lang.Class.cast(Class.java:3610)
    at java.base/java.util.stream.ReferencePipeline.accept(ReferencePipeline.java:195)
    at java.base/java.util.stream.Streams$StreamBuilderImpl.forEachRemaining(Streams.java:411)
    at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
    at java.base/java.util.stream.ReferencePipeline.accept(ReferencePipeline.java:274)
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:550)
    at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
    at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:517)
    at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:523)
    at aiPackage.game.Board.<init>(Board.java:17)
    at aiPackage.game.Tester.main(Tester.java:15)

    package aiPackage.game;

    import java.util.*;
    import java.util.stream.*;

    public class Board {
        //declaration of private members
        private int score;
        private Board previousB = null;
        private char[][] thisBoard;

        // ------------------------------------------------------;

        public Board (char [][] inBoard) {
            //what
            //char[] flats = flatten(inBoard).map
            Object[] flats = flatten(inBoard).map(Character.class::cast).toArray(); //mapToCharater(Charater.class::cast).toArray();

            int[] flat = flatten(inBoard).mapToInt(Integer.class::cast).toArray();
            int flatSize = flat.length;


            // ------------------------------------------------------;

            //check if square
            if (Math.sqrt(flatSize)==3) {
                if(inBoard.length == 3) {
                    thisBoard = inBoard;
                }
                else {
                    System.out.println("The array isnt a square.");
                }
            }
            else {
                System.out.println("It doesnt match the dimensions of a tictactoe board.");
            }

            //we'll assume its not gonna break from the input atm
            setThisBoard(inBoard);
        }

        //
        private static Stream<Object> flatten(Object[] array) {
            return Arrays.stream(array)
                    .flatMap(o -> o instanceof Object[]? flatten((Object[])o): Stream.of(o));
        }

        public Board getPreviousB() {
            return previousB;
        }

        public void setPreviousB(Board previousB) {
            this.previousB = previousB;
        }

        public int getScore() {
            return score;
        }

        public void setScore(int score) {
            this.score = score;
        }

        public char[][] getThisBoard() {
            return thisBoard;
        }

        public void setThisBoard(char[][] thisBoard) {
            this.thisBoard = thisBoard;
        }

        //if there are even elements on the board, its x's turn
        public ArrayList<Board> getChildren(){

            return null;
        }

        public void checkIfEnded() {
            for (int i = 0; i < 3; i++) {
                //check row wins
                if (thisBoard[i][0] != '-' &&
                        thisBoard[i][0] == thisBoard[i][1] &&
                        thisBoard[i][1] == thisBoard[i][2]) {

                    //updates score based on winner
                    if (thisBoard[0][2] == 'x') {
                        updateScore(1);
                    }
                    else {
                        updateScore(-1);
                    }

                    return;
                }

                //check column wins
                if (thisBoard[i][0] != '-' &&
                        thisBoard[0][i] == thisBoard[1][i] &&
                        thisBoard[1][i] == thisBoard[2][i]) {

                    //updates score based on winner
                    if (thisBoard[0][2] == 'x') {
                        updateScore(1);
                    }
                    else {
                        updateScore(-1);
                    }

                    return;
                }


            }

            //check diagnals
            if (thisBoard[0][0] != '-' &&
                    thisBoard[0][0] == thisBoard[1][1] &&
                    thisBoard[1][1] == thisBoard[2][2]) {

                //updates score based on winner
                if (thisBoard[0][2] == 'x') {
                    updateScore(1);
                }
                else {
                    updateScore(-1);
                }

                return;
            }
            if (thisBoard[0][2] != '-' &&
                    thisBoard[0][2] == thisBoard[1][1] &&
                    thisBoard[1][1] == thisBoard[2][0]) {

                //updates score based on winner
                if (thisBoard[0][2] == 'x') {
                    updateScore(1);
                }
                else {
                    updateScore(-1);
                }

                return;
            }
        }

        //outputs the board's contents as a string
        public String toString() {
            String result = "";

            //gets the previous board's info to output first
            result = "" + previousB;

            //gets this boards info to output
            for(int i = 0; i < 3; i++) {
                for(int j = 0; j < 3; j++) {
                    result += thisBoard[i][j] + " ";
                }

                //adds newline char at end of row
                result += "\n";
            }
            //adds an extra newline char at end of board
            result += "\n";

            return result;
        }

        private void updateScore(int win) {
            if (win > 0) {
                score = 1;
            } else if(win == 0){
                score = 0;
            }else {
                score = -1;
            }
        }
    }
package aiPackage.game;

import java.util.*;

public class Tester {
    private static Board start;
    private static Board finish;

    public static void main(String[] args) {
        char temp [][] = {
            {'o','-','x'},
            {'-','-','-'},
            {'-','-','-'}};

        start = new Board(temp);
        finish = minMax(start.getChildren());
        System.out.println();

    }

    public static Board minMax(ArrayList<Board> resultList) {


        return null;
    }



}

您的问题在这里:

private static Stream<Object> flatten(Object[] array) {
    return Arrays.stream(array)
            .flatMap(o -> o instanceof Object[]? flatten((Object[])o): Stream.of(o));
}

你是用Object[]的比较来分解数组,但实际上是一个char[]。

这使得您的结果不是 Stream 对象而是 Stream char[]。

要点是您不能使用 Stream 来处理原语。 Stream 仅适用于 Objects 而 char 是原始类型。

您可以使用经典循环手动压平 char[][]。

它失败的原因是因为Arrays.stream()不接受char[]以下应该有效。

Arrays.stream(inBoard)
      .flatMap(x -> (Stream<Character>)new String(x).chars().mapToObj(i->(char)i))
      .collect(Collectors.toList())

退房 Want to create a stream of characters from char array in java 为 和 Why is String.chars() a stream of ints in Java 8? 为了更好地理解。

扁平化char[][]或者不可能的不算

char[] array = Stream.of( inBoard ).flatMap( arr -> Stream.of( String.valueOf( arr ) ) )
    .collect( Collectors.joining() ).toCharArray();  // [o, -, x, -, -, -, -, -, -]