1
1
import math
2
2
3
- def minimax_with_pruning (depth , node_index , is_maximizing_player , scores , height , alpha , beta ):
3
+
4
+ def minimax_with_pruning (
5
+ depth , node_index , is_maximizing_player , scores , height , alpha , beta
6
+ ):
4
7
"""
5
8
Minimax algorithm with alpha-beta pruning to determine the optimal move with improved efficiency.
6
-
9
+
7
10
Parameters:
8
11
- depth (int): Current depth in the game tree, used to track recursion level.
9
12
- node_index (int): Index of the current node in the scores array, representing leaf nodes.
@@ -24,7 +27,9 @@ def minimax_with_pruning(depth, node_index, is_maximizing_player, scores, height
24
27
if is_maximizing_player :
25
28
best_score = - math .inf # Start with the worst possible score for maximizer
26
29
for i in range (2 ): # Two branches at each level in binary tree
27
- val = minimax_with_pruning (depth + 1 , node_index * 2 + i , False , scores , height , alpha , beta )
30
+ val = minimax_with_pruning (
31
+ depth + 1 , node_index * 2 + i , False , scores , height , alpha , beta
32
+ )
28
33
best_score = max (best_score , val ) # Maximizer selects the maximum value
29
34
alpha = max (alpha , best_score ) # Update alpha (best option for maximizer)
30
35
if beta <= alpha :
@@ -35,21 +40,28 @@ def minimax_with_pruning(depth, node_index, is_maximizing_player, scores, height
35
40
else :
36
41
best_score = math .inf # Start with the worst possible score for minimizer
37
42
for i in range (2 ):
38
- val = minimax_with_pruning (depth + 1 , node_index * 2 + i , True , scores , height , alpha , beta )
43
+ val = minimax_with_pruning (
44
+ depth + 1 , node_index * 2 + i , True , scores , height , alpha , beta
45
+ )
39
46
best_score = min (best_score , val ) # Minimizer selects the minimum value
40
47
beta = min (beta , best_score ) # Update beta (best option for minimizer)
41
48
if beta <= alpha :
42
49
break # Alpha cut-off
43
50
return best_score
44
51
52
+
45
53
def main ():
46
54
# Scores array representing the leaf nodes of a binary tree (depth = 3)
47
55
scores = [3 , 5 , 2 , 9 , 12 , 5 , 23 , 23 ]
48
56
# Calculate the height of the binary tree based on the number of leaf nodes
49
57
height = math .ceil (math .log2 (len (scores )))
50
58
51
59
# Print the optimal outcome for the maximizing player with alpha-beta pruning
52
- print ("Optimal value for the maximizing player with pruning:" , minimax_with_pruning (0 , 0 , True , scores , height , - math .inf , math .inf ))
60
+ print (
61
+ "Optimal value for the maximizing player with pruning:" ,
62
+ minimax_with_pruning (0 , 0 , True , scores , height , - math .inf , math .inf ),
63
+ )
64
+
53
65
54
66
if __name__ == "__main__" :
55
67
main ()
0 commit comments