gpt4 book ai didi

java - 我有一个正在更改的数组,即使我没有专门更改它

转载 作者:行者123 更新时间:2023-12-01 21:24:42 25 4
gpt4 key购买 nike

我正在编写一个 AI 来玩 Mancala,这是我的方法,其中 AI 的计算是通过检查所有 6 个可能的 Action 的结果来完成的。每次检查移动结果后,我使用数组 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 时执行类似的复制。

关于java - 我有一个正在更改的数组,即使我没有专门更改它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38362344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com