Skip to content

Enhance readability of Minimax #10838

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 23, 2023
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions backtracking/minimax.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,21 @@ def minimax(
depth: int, node_index: int, is_max: bool, scores: list[int], height: float
) -> int:
"""
This function implements the minimax algorithm,
which helps achieve the maximum score in a game
by checking all possible moves.

Parameters:
- depth: Current depth in the game tree.
- node_index: Index of the current node in the scores list.
- is_max: A boolean indicating whether the current move
is for the maximizer (True) or minimizer (False).
- scores: A list containing the scores of the leaves of the game tree.
- height: The maximum height of the game tree.

Returns:
- An integer representing the optimal score for the current player.

>>> import math
>>> scores = [90, 23, 6, 33, 21, 65, 123, 34423]
>>> height = math.log(len(scores), 2)
Expand All @@ -35,36 +50,45 @@ def minimax(
12
"""

# Check for invalid inputs
if depth < 0:
raise ValueError("Depth cannot be less than 0")

if len(scores) == 0:
raise ValueError("Scores cannot be empty")

# Base case: If the current depth equals the height of the tree,
# return the score of the current node.
if depth == height:
return scores[node_index]

# If it's the maximizer's turn, choose the maximum score
# between the two possible moves.
if is_max:
return max(
minimax(depth + 1, node_index * 2, False, scores, height),
minimax(depth + 1, node_index * 2 + 1, False, scores, height),
)

# If it's the minimizer's turn, choose the minimum score
# between the two possible moves.
return min(
minimax(depth + 1, node_index * 2, True, scores, height),
minimax(depth + 1, node_index * 2 + 1, True, scores, height),
)


def main() -> None:
# Sample scores and height calculation
scores = [90, 23, 6, 33, 21, 65, 123, 34423]
height = math.log(len(scores), 2)

# Calculate and print the optimal value using the minimax algorithm
print("Optimal value : ", end="")
print(minimax(0, 0, True, scores, height))


if __name__ == "__main__":
import doctest

doctest.testmod()
main()
doctest.testmod() # Run doctests to ensure the function behaves as expected
main() # Run the main function to demonstrate the minimax algorithm in action