我正在制作四子棋AI,但游戏会一直进行直到所有42个格子都被填满。
每连成4个棋子得1分来计分。
public int[] Max_Value(GameBoard playBoard, int depth){ GameBoard temp = new GameBoard(playBoard.playBoard); int h = 0, tempH = 999, tempCol=0; int myDepth = depth - 1; int[] tempH2 = new int[2]; boolean noChildren = true; if(myDepth != -1){ for(int i = 0; i < 7; i++){ if(temp.isValidPlay(i)){ count++; temp.playPiece(i); noChildren = false; tempH2 = Min_Value(temp, myDepth); if(tempH2[1] < tempH){ tempH=tempH2[1]; tempCol = i; } temp.removePiece(i); } } } int[] x = new int[2]; if(noChildren){ h = temp.getHeuristic(); } else{ h = tempH; x[0]=tempCol; } x[1]=h; return x; }public int[] Min_Value(GameBoard playBoard, int depth){ GameBoard temp = new GameBoard(playBoard.playBoard); int h = 0, tempH = -999, tempCol=0; int myDepth = depth - 1; int[] tempH2 = new int[2]; boolean noChildren = true; if(myDepth != -1){ for(int i = 0; i < 7; i++){ if(temp.isValidPlay(i)){ count++; temp.playPiece(i); noChildren = false; tempH2 = Max_Value(temp, myDepth); if(tempH2[1] > tempH){ tempH=tempH2[1]; tempCol = i; } temp.removePiece(i); } } } int[] x = new int[2]; if(noChildren){ h = temp.getHeuristic(); } else{ h = tempH; x[0]=tempCol; } x[1]=h; return x; }
我感觉自己只是在摸索,代码看起来很糟糕。然而,我之前从未尝试过这种事情,任何建议我都会很感激。我不知道哪里出了问题。我的评估函数只是为每个状态找到的每4个连在一起的棋子给1分。主函数调用Min_Value函数以10的深度开始运行。
我试图返回列以及启发式函数的值。我希望我提供了足够的信息。感谢任何见解。
回答:
好的,在实现了未显示的方法(如评估、移动、移除等)后,我能够调试这个问题。假设这些函数在你的版本中以某种正确的方式实现了,错误在于当深度为-1时,你从未实际调用评估函数:
你有这样的代码:
[...]if(myDepth != -1){/*restofthecode*/}[...]
但你需要的是这样的代码:
[...]if(myDepth == -1){return temp.getHeuristic();}/*restofthecode*/[...]
这样一来,每当你达到深度-1(Minimax树中的叶子节点)时,棋盘将被评估并返回值(这正是Minimax算法所需的)。
在最小化和最大化部分都进行此修改,一切应该没问题。如果还有其他问题,请随时提问。