在构造函数中创建相同类的对象会更改原始对象

时间:2015-11-27 22:00:40

标签: java constructor

所以我的任务是机器学习tic tac toe游戏。我通过让机器计算每个可能的板状态,然后找到每个移动产量的预期值来解决它。我这样做的方法是使用一个类,Board,它包含一个显示当前板的数组,以及另一个包含所有可能的数组随后的“董事会”。 问题是在创建新的后续Board对象时,父对象中的当前板在保持不变时会发生更改。

Board的构造函数如下

public Board(int[][] board, int[] newSpot, int turn) {
    this.current = board; //current is the current board state
    if (newSpot != null) {
        this.current[newSpot[0]][newSpot[1]] = turn*-1; //adds the latest move
    }
    this.newSpot = newSpot;
    this.TURN = turn;
    WON = getWinner();
    if (WON != 0) {
        VALUE = WON;
    }
    else {
        options = getOptions();
    }
}

我已将问题追溯到getOptions()方法,如下所示

private ArrayList<Board> getOptions() {
    ArrayList<Board> workingOptions = new ArrayList<Board>();
    int workingValue = 0;
    for (int r=0; r<this.current.length; r++) {
        for (int c=0; c<this.current[r].length; c++) {
            if (this.current[r][c] == 0) {
                Board workingBoard = new Board(Arrays.copyOf(this.current, this.current.length), new int[] {r, c}, TURN*-1);
                workingValue += workingBoard.VALUE;
                workingOptions.add(workingBoard);
            }
        }
    }
    VALUE = workingValue / openSpaces;
    return workingOptions;
}

感谢您的帮助

0 个答案:

没有答案
相关问题