所以我为奥赛罗的比赛买了一个小桌面游戏。在这个游戏中,AI应该决定使用Alpha Beta Prune搜索算法进行移动。我使用了以下伪代码格式geeksforgeeks:
function minimax(node, depth, isMaximizingPlayer, alpha, beta):
if node is a leaf node :
return value of the node
if isMaximizingPlayer :
bestVal = -INFINITY
for each child node :
value = minimax(node, depth+1, false, alpha, beta)
bestVal = max( bestVal, value)
alpha = max( alpha, bestVal)
if beta <= alpha:
break
return bestVal
else :
bestVal = +INFINITY
for each child node :
value = minimax(node, depth+1, true, alpha, beta)
bestVal = min( bestVal, value)
beta = min( beta, bestVal)
if beta <= alpha:
break
return bestVal
这是我实施它的方式:
//Called when it's the AI's turn to make a move.
public Board makeMove(Board board) {
setRoot(board);
int alpha = Integer.MIN_VALUE;
int beta = Integer.MAX_VALUE;
int val = alphaBetaSearch(tree.getRoot(), 0, true, alpha, beta);
Board resultBoard = //Should be AI Board/move
setRoot(resultBoard);
return resultBoard;
}
private int alphaBetaSearch(Node node, int depth, boolean maximizing, int alpha, int beta) {
currentDepth = depth;
if (node.isLeaf()) {
return evaluateUtility(node.getBoard());
}
if (maximizing) {
int bestValue = Integer.MIN_VALUE;
for (Node child : node.getChildren()) {
int value = alphaBetaSearch(child, depth + 1, false, alpha, beta);
bestValue = Integer.max(bestValue, value);
alpha = Integer.max(alpha, bestValue);
if (beta <= alpha) {
break;
}
return alpha;
}
} else {
int bestValue = Integer.MAX_VALUE;
for (Node child : node.getChildren()) {
int value = alphaBetaSearch(child, depth + 1, true, alpha, beta);
bestValue = Integer.min(bestValue, value);
beta = Integer.min(beta, bestValue);
if (beta <= alpha) {
break;
}
return beta;
}
}
return 0; //Not sure what should be returned here
}
private int evaluateUtility(Board board) {
int whitePieces = board.getNumberOfWhiteCells();
int blackPieces = board.getNumberOfBlackCells();
int sum = (blackPieces - whitePieces);
return sum;
}
由于我的棋盘非常小(4x4),我能够在游戏开始前大约20秒内计算完整的搜索树。这应该可以改善我的搜索,因为我在玩游戏时没有构建任何内容。我树中的每个节点都包含一个Board,它本身有一个2D单元格。根节点/板看起来像这样:
EMPTY EMPTY EMPTY EMPTY
EMPTY WHITE BLACK EMPTY
EMPTY BLACK WHITE EMPTY
EMPTY EMPTY EMPTY EMPTY
现在,当我开始游戏时,这是首发板,我打电话给AI进行移动。当minimax调用执行时,它返回深度为12的值2.深度12是树中的叶节点/板。在使用调试器运行它之后,似乎我的实现没有遍历树。它所做的只是向下到最左边的树并返回它的评估。