@@ -16,6 +16,22 @@ def minimax(
16
16
depth : int , node_index : int , is_max : bool , scores : list [int ], height : float
17
17
) -> int :
18
18
"""
19
+ This function implements the minimax algorithm, which helps achieve the optimal
20
+ score for a player in a two-player game by checking all possible moves.
21
+ If the player is the maximizer, then the score is maximized.
22
+ If the player is the minimizer, then the score is minimized.
23
+
24
+ Parameters:
25
+ - depth: Current depth in the game tree.
26
+ - node_index: Index of the current node in the scores list.
27
+ - is_max: A boolean indicating whether the current move
28
+ is for the maximizer (True) or minimizer (False).
29
+ - scores: A list containing the scores of the leaves of the game tree.
30
+ - height: The maximum height of the game tree.
31
+
32
+ Returns:
33
+ - An integer representing the optimal score for the current player.
34
+
19
35
>>> import math
20
36
>>> scores = [90, 23, 6, 33, 21, 65, 123, 34423]
21
37
>>> height = math.log(len(scores), 2)
@@ -37,28 +53,36 @@ def minimax(
37
53
38
54
if depth < 0 :
39
55
raise ValueError ("Depth cannot be less than 0" )
40
-
41
56
if len (scores ) == 0 :
42
57
raise ValueError ("Scores cannot be empty" )
43
58
59
+ # Base case: If the current depth equals the height of the tree,
60
+ # return the score of the current node.
44
61
if depth == height :
45
62
return scores [node_index ]
46
63
64
+ # If it's the maximizer's turn, choose the maximum score
65
+ # between the two possible moves.
47
66
if is_max :
48
67
return max (
49
68
minimax (depth + 1 , node_index * 2 , False , scores , height ),
50
69
minimax (depth + 1 , node_index * 2 + 1 , False , scores , height ),
51
70
)
52
71
72
+ # If it's the minimizer's turn, choose the minimum score
73
+ # between the two possible moves.
53
74
return min (
54
75
minimax (depth + 1 , node_index * 2 , True , scores , height ),
55
76
minimax (depth + 1 , node_index * 2 + 1 , True , scores , height ),
56
77
)
57
78
58
79
59
80
def main () -> None :
81
+ # Sample scores and height calculation
60
82
scores = [90 , 23 , 6 , 33 , 21 , 65 , 123 , 34423 ]
61
83
height = math .log (len (scores ), 2 )
84
+
85
+ # Calculate and print the optimal value using the minimax algorithm
62
86
print ("Optimal value : " , end = "" )
63
87
print (minimax (0 , 0 , True , scores , height ))
64
88
0 commit comments