我有一个正在改变的数组,即使我没有特别改变它

时间:2016-07-13 21:54:17

标签: java arrays for-loop

我正在编写AI来玩Mancala,这是我的方法,通过检查所有6种可能的动作的结果来完成AI的计算。在每次检查移动结果后,我使用数组staticBoardState来恢复boardState(它将有关板上所有孔的信息存储)恢复到原始值,但是staticBoardState似乎正在以奇怪的方式改变,即使我相信我做了不改变它。我是一名初学者业余编码员,所以如果我的代码没有意义,请提问。这是我的代码:

public int getBotCalc(int boardState[]) {

    int[] staticBoardState = boardState;

    double[] movePoints = new double[6];
    int initialScore = boardState[6];
    int scorePoints;
    int freeTurnPoints;

    double bestMovePoints;
    int bestMove;

    for(int f = 0; f <= 5; f++) {

        boardState = staticBoardState;

        int botChoice = f;
        int botHole = boardState[botChoice];
        boardState[botChoice] = 0;

        for(int g = 0; g < botHole; g++) {

            botChoice++;
            if(botChoice>12) {
                botChoice = 0;
            }

            boardState[botChoice]++;
        }

        if(botChoice<=5&&boardState[botChoice]==1&&boardState[12-botChoice]>=1) {
            boardState[6] += boardState[12 - botChoice] + 1;

            boardState[botChoice] = 0;
            boardState[12 - botChoice] = 0;
        }

        scorePoints = boardState[6] - initialScore;
        if(botChoice==6) {
            freeTurnPoints = 1;
        } else {
            freeTurnPoints = 0;
        }

        movePoints[f] = scorePoints + (1.5 * freeTurnPoints);
    }

    bestMovePoints = movePoints[0];
    bestMove = 0;
    for(int f = 1; f <= 5; f++) {
        if(movePoints[f]>bestMovePoints) {
            bestMovePoints = movePoints[f];
            bestMove = f;
        }
    }

    boardState = staticBoardState;

    return bestMove;
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

看起来你将值类型赋值与引用赋值混淆了。当你写

  

staticBoardState = boardState

发生的事情是staticBoardState只是对boardState已经引用的内存中的数组的引用。不是它们都在内存中引用相同的数组,这就是为什么staticBoardState显然是通过使用boardState进行修改的原因。解决此问题需要做的是将staticBoardState分配为 new 数组并显式复制其内容,例如使用boardState.clone(),并在每次需要时执行类似的复制恢复boardState