1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
| /**
* Alpha-Beta剪枝优化的Minimax算法
*/
public class AlphaBetaPruning {
/**
* Alpha-Beta剪枝算法
* 显著减少搜索空间
*/
public static int alphaBeta(MinimaxAlgorithm.GameState state, int depth,
int alpha, int beta, boolean isMaxPlayer) {
if (depth == 0 || state.isGameOver()) {
return state.evaluate();
}
if (isMaxPlayer) {
int maxEval = Integer.MIN_VALUE;
for (MinimaxAlgorithm.GameState child : state.generateMoves()) {
int eval = alphaBeta(child, depth - 1, alpha, beta, false);
maxEval = Math.max(maxEval, eval);
alpha = Math.max(alpha, eval);
if (beta <= alpha) {
break; // Beta剪枝
}
}
return maxEval;
} else {
int minEval = Integer.MAX_VALUE;
for (MinimaxAlgorithm.GameState child : state.generateMoves()) {
int eval = alphaBeta(child, depth - 1, alpha, beta, true);
minEval = Math.min(minEval, eval);
beta = Math.min(beta, eval);
if (beta <= alpha) {
break; // Alpha剪枝
}
}
return minEval;
}
}
/**
* 使用Alpha-Beta剪枝查找最佳移动
*/
public static MinimaxAlgorithm.GameState findBestMoveAB(
MinimaxAlgorithm.GameState state, int depth) {
int bestValue = Integer.MIN_VALUE;
MinimaxAlgorithm.GameState bestMove = null;
int alpha = Integer.MIN_VALUE;
int beta = Integer.MAX_VALUE;
for (MinimaxAlgorithm.GameState child : state.generateMoves()) {
int moveValue = alphaBeta(child, depth - 1, alpha, beta, false);
if (moveValue > bestValue) {
bestValue = moveValue;
bestMove = child;
}
alpha = Math.max(alpha, moveValue);
}
return bestMove;
}
/**
* 性能对比测试
*/
public static void performanceComparison() {
int[][] board = new int[3][3];
MinimaxAlgorithm.GameState state =
new MinimaxAlgorithm.GameState(board, true, 0);
int depth = 6;
// 标准Minimax测试
long startTime = System.nanoTime();
MinimaxAlgorithm.GameState result1 =
MinimaxAlgorithm.findBestMove(state, depth);
long minimaxTime = System.nanoTime() - startTime;
// Alpha-Beta剪枝测试
startTime = System.nanoTime();
MinimaxAlgorithm.GameState result2 = findBestMoveAB(state, depth);
long alphaBetaTime = System.nanoTime() - startTime;
System.out.printf("标准Minimax耗时: %.2f ms%n",
minimaxTime / 1_000_000.0);
System.out.printf("Alpha-Beta剪枝耗时: %.2f ms%n",
alphaBetaTime / 1_000_000.0);
System.out.printf("性能提升: %.2fx%n",
(double)minimaxTime / alphaBetaTime);
}
}
|