@@ -16,6 +16,22 @@ def minimax(
1616 depth : int , node_index : int , is_max : bool , scores : list [int ], height : float
1717) -> int :
1818 """
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+
1935 >>> import math
2036 >>> scores = [90, 23, 6, 33, 21, 65, 123, 34423]
2137 >>> height = math.log(len(scores), 2)
@@ -37,28 +53,36 @@ def minimax(
3753
3854 if depth < 0 :
3955 raise ValueError ("Depth cannot be less than 0" )
40-
4156 if len (scores ) == 0 :
4257 raise ValueError ("Scores cannot be empty" )
4358
59+ # Base case: If the current depth equals the height of the tree,
60+ # return the score of the current node.
4461 if depth == height :
4562 return scores [node_index ]
4663
64+ # If it's the maximizer's turn, choose the maximum score
65+ # between the two possible moves.
4766 if is_max :
4867 return max (
4968 minimax (depth + 1 , node_index * 2 , False , scores , height ),
5069 minimax (depth + 1 , node_index * 2 + 1 , False , scores , height ),
5170 )
5271
72+ # If it's the minimizer's turn, choose the minimum score
73+ # between the two possible moves.
5374 return min (
5475 minimax (depth + 1 , node_index * 2 , True , scores , height ),
5576 minimax (depth + 1 , node_index * 2 + 1 , True , scores , height ),
5677 )
5778
5879
5980def main () -> None :
81+ # Sample scores and height calculation
6082 scores = [90 , 23 , 6 , 33 , 21 , 65 , 123 , 34423 ]
6183 height = math .log (len (scores ), 2 )
84+
85+ # Calculate and print the optimal value using the minimax algorithm
6286 print ("Optimal value : " , end = "" )
6387 print (minimax (0 , 0 , True , scores , height ))
6488
0 commit comments