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.
@@ -9,26 +10,13 @@ class MinMax:
9
10
scores : list[int]
10
11
List of terminal node scores.
11
12
tree_depth : int
12
- Depth of the game tree.
13
-
14
- Methods:
15
- -------
16
- minimax(current_depth: int = 0, node_index: int = 0, is_max_turn: bool = True) -> int:
17
- Recursive implementation of the minimax algorithm.
18
- find_optimal_value() -> int:
19
- Find and return the optimal value for the maximizing player.
20
-
21
- Examples:
22
- ---------
23
- >>> game = MinMax([3, 5, 2, 9, 12, 5, 23, 23])
24
- >>> game.find_optimal_value()
25
- 12
13
+ Depth of the minimax tree.
26
14
"""
27
15
28
- def __init__ (self , scores : list [int ]) -> None :
16
+ def __init__ (self , scores : list [int ]):
29
17
"""
30
18
Initialize the MinMax game with a list of scores.
31
-
19
+
32
20
Parameters:
33
21
----------
34
22
scores : list[int]
@@ -37,10 +25,13 @@ def __init__(self, scores: list[int]) -> None:
37
25
self .scores = scores
38
26
self .tree_depth = int (math .log2 (len (scores )))
39
27
40
- def minimax (self , current_depth : int = 0 , node_index : int = 0 , is_max_turn : bool = True ) -> int :
28
+ def minimax (
29
+ self , current_depth : int = 0 ,
30
+ node_index : int = 0 , is_max_turn : bool = True
31
+ ) -> int :
41
32
"""
42
33
Recursive implementation of the minimax algorithm.
43
-
34
+
44
35
Parameters:
45
36
----------
46
37
current_depth : int
@@ -54,17 +45,12 @@ def minimax(self, current_depth: int = 0, node_index: int = 0, is_max_turn: bool
54
45
-------
55
46
int
56
47
The optimal value for the current player.
57
-
58
- Examples:
59
- ---------
60
- >>> game = MinMax([3, 5, 2, 9, 12, 5, 23, 23])
61
- >>> game.minimax(0, 0, True)
62
- 12
63
48
"""
64
-
49
+ # Base case: we've reached a terminal node
65
50
if current_depth == self .tree_depth :
66
51
return self .scores [node_index ]
67
-
52
+
53
+ # Recursive case
68
54
if is_max_turn :
69
55
return max (
70
56
self .minimax (current_depth + 1 , node_index * 2 , False ),
@@ -79,25 +65,11 @@ def minimax(self, current_depth: int = 0, node_index: int = 0, is_max_turn: bool
79
65
def find_optimal_value (self ) -> int :
80
66
"""
81
67
Find and return the optimal value for the maximizing player.
82
-
68
+
83
69
Returns:
84
70
-------
85
71
int
86
72
The optimal value.
87
-
88
- Examples:
89
- ---------
90
- >>> game = MinMax([3, 5, 2, 9, 12, 5, 23, 23])
91
- >>> game.find_optimal_value()
92
- 12
93
73
"""
94
74
return self .minimax ()
95
75
96
- if __name__ == "__main__" :
97
- import doctest
98
- doctest .testmod ()
99
-
100
- scores = [3 , 5 , 2 , 9 , 12 , 5 , 23 , 23 ]
101
- game = MinMax (scores )
102
- optimal_value = game .find_optimal_value ()
103
- print (f"The optimal value is: { optimal_value } " )
0 commit comments