1
1
import math
2
2
3
+
3
4
class MinMax :
4
5
"""
5
6
A class to represent a game using the Minimax algorithm.
@@ -28,7 +29,7 @@ class MinMax:
28
29
def __init__ (self , scores : list [int ]) -> None :
29
30
"""
30
31
Initialize the MinMax game with a list of scores.
31
-
32
+
32
33
Parameters:
33
34
----------
34
35
scores : list[int]
@@ -37,10 +38,12 @@ def __init__(self, scores: list[int]) -> None:
37
38
self .scores = scores
38
39
self .tree_depth = int (math .log2 (len (scores )))
39
40
40
- def minimax (self , current_depth : int = 0 , node_index : int = 0 , is_max_turn : bool = True ) -> int :
41
+ def minimax (
42
+ self , current_depth : int = 0 , node_index : int = 0 , is_max_turn : bool = True
43
+ ) -> int :
41
44
"""
42
45
Recursive implementation of the minimax algorithm.
43
-
46
+
44
47
Parameters:
45
48
----------
46
49
current_depth : int
@@ -64,22 +67,22 @@ def minimax(self, current_depth: int = 0, node_index: int = 0, is_max_turn: bool
64
67
65
68
if current_depth == self .tree_depth :
66
69
return self .scores [node_index ]
67
-
70
+
68
71
if is_max_turn :
69
72
return max (
70
73
self .minimax (current_depth + 1 , node_index * 2 , False ),
71
- self .minimax (current_depth + 1 , node_index * 2 + 1 , False )
74
+ self .minimax (current_depth + 1 , node_index * 2 + 1 , False ),
72
75
)
73
76
else :
74
77
return min (
75
78
self .minimax (current_depth + 1 , node_index * 2 , True ),
76
- self .minimax (current_depth + 1 , node_index * 2 + 1 , True )
79
+ self .minimax (current_depth + 1 , node_index * 2 + 1 , True ),
77
80
)
78
81
79
82
def find_optimal_value (self ) -> int :
80
83
"""
81
84
Find and return the optimal value for the maximizing player.
82
-
85
+
83
86
Returns:
84
87
-------
85
88
int
@@ -93,8 +96,10 @@ def find_optimal_value(self) -> int:
93
96
"""
94
97
return self .minimax ()
95
98
99
+
96
100
if __name__ == "__main__" :
97
101
import doctest
102
+
98
103
doctest .testmod ()
99
104
100
105
scores = [3 , 5 , 2 , 9 , 12 , 5 , 23 , 23 ]
0 commit comments