我正在编写一个AI来玩Mancala,这是我的方法,其中AI的计算是通过检查所有6种可能动作的结果来完成的。每次检查移动结果后,我都使用数组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;
}
任何帮助是极大的赞赏。
最佳答案
您似乎将值类型分配与引用分配混淆了。当你写
staticBoardState = boardState
发生的是staticBoardState
只是在内存中保留了对boardState
也已经在引用的数组的引用。并非两者都指向内存中的同一数组,这就是为什么staticBoardState
显然是通过使用boardState
进行修改的原因。要解决此问题,您需要将staticBoardState
分配为新数组,并显式复制其内容(例如使用boardState.clone()
),并在每次要恢复boardState
时执行类似的复制。