MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / minimax

Function minimax

backtracking/minimax.py:16–78  ·  view source on GitHub ↗

This function implements the minimax algorithm, which helps achieve the optimal score for a player in a two-player game by checking all possible moves. If the player is the maximizer, then the score is maximized. If the player is the minimizer, then the score is minimized. Para

(
    depth: int, node_index: int, is_max: bool, scores: list[int], height: float
)

Source from the content-addressed store, hash-verified

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

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected