gpt4 book ai didi

Java 类构造函数更改输入参数 - MiniMax

转载 作者:行者123 更新时间:2023-11-30 08:11:20 27 4
gpt4 key购买 nike

我正在为 Connect 4 编写 MiniMax 代码。基本上,我有一个 SimpleMiniMax 类,它有一个方法 minimax (接受 grid 的输入),该方法应该返回类 Move 的实例。 minimax 方法调用 maxMove 方法,该方法接受网格输入(与第一个方法调用相同)。这里 maxMove 方法为 AI 生成 Move,然后运行 ​​mimMove。问题是,当它为 AI 生成 Move 时,它​​会传递当前网格并获取 Move 返回。但在此过程中它也会更改当前网格。因此,当它经历了所有的可能性时,它会继续添加人工智能到同一个网格。所以在所有 7 种可能性之后(连接 4 网格是标准的 6 行 7 列)AI 填补了 7 个位置,显然获胜。

我尝试将输入参数复制到局部变量中并传递它,但值仍然流过。我知道传递给 Java 方法的参数是按值传递的(如果愿意,请只读)。我不确定我在这里做错了什么。

这是简短的代码。

public class SimpleMiniMax {

private static Boolean noMoreMoves = false;


public Move minimax(int[][] gridCopy_minimax){
Move nextMove = null;
noMoreMoves = false;
return maxMove(gridCopy_minimax, 1);

}

private Move maxMove(int[][] gridCopy_max, int depth){
int gameValue = 0;

Move maxMove = null,
tempMove = null,
thisMove = null;

if(depth==0 || noMoreMoves){
return null;
} else {
for (int i = 0; i < 7; i++) {
try {
thisMove = new Move(gridCopy_max, i, Grid.getAI());
// Issue here---
// After this call the value of gridCopy_max carries the Ai move so when its
// called for next loop run it builds from there on.
tempMove = minMove(thisMove.newGrid, depth-1 );
if(tempMove==null) tempMove = thisMove;

if (maxMove==null && tempMove != null) maxMove = tempMove;

if(tempMove != null && tempMove.moveValue >= maxMove.moveValue ){
maxMove = tempMove;
}
} catch (Exception e) {
// TODO: handle exception
if(i==6){
noMoreMoves = true;
break;
}


}


}
}

return maxMove;

}

Class Move
public class Move {
public int[][] newGrid = new int[6][7];
public int moveX = 9,
moveY,
moveValue;




public Move(int[][] CurrGrid, int y, int player_in) throws Exception{



newGrid = CurrGrid;
int i = 0;
for (i = 0; i < 6 ; i++) {
if(CurrGrid[i][y] != 0){
moveX = i-1;
break;
}
}

if(i<0){
throw new Exception("No More Moves");
}

if(moveX==9){
moveX = 5;
}

moveY = y;
newGrid[moveX][y] = player_in;

this.moveValue(player_in);

System.out.println("Generating Move" + player_in + "|" + moveX + "|" + moveY);
}

最佳答案

复制到局部变量的是指向数组的指针。对于引用参数,Java 按值传递引用本身,该引用可以为 null,也可以为指向对象的指针。

我建议在修改之前将参数引用的数组的内容复制到本地创建的数组中。

关于Java 类构造函数更改输入参数 - MiniMax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30352091/

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