|
| 1 | +""" |
| 2 | +Minimax helps to achieve maximum score in a game by checking all possible moves. |
| 3 | +
|
| 4 | +""" |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import math |
| 8 | + |
| 9 | + |
| 10 | +def minimax( |
| 11 | + depth: int, node_index: int, is_max: bool, scores: list[int], height: float |
| 12 | +) -> int: |
| 13 | + """ |
| 14 | + depth is current depth in game tree. |
| 15 | + node_index is index of current node in scores[]. |
| 16 | + scores[] contains the leaves of game tree. |
| 17 | + height is maximum height of game tree. |
| 18 | +
|
| 19 | + >>> scores = [90, 23, 6, 33, 21, 65, 123, 34423] |
| 20 | + >>> height = math.log(len(scores), 2) |
| 21 | + >>> minimax(0, 0, True, scores, height) |
| 22 | + 65 |
| 23 | + >>> minimax(-1, 0, True, scores, height) |
| 24 | + Traceback (most recent call last): |
| 25 | + ... |
| 26 | + ValueError: Depth cannot be less than 0 |
| 27 | + >>> minimax(0, 0, True, [], 2) |
| 28 | + Traceback (most recent call last): |
| 29 | + ... |
| 30 | + ValueError: Scores cannot be empty |
| 31 | + >>> scores = [3, 5, 2, 9, 12, 5, 23, 23] |
| 32 | + >>> height = math.log(len(scores), 2) |
| 33 | + >>> minimax(0, 0, True, scores, height) |
| 34 | + 12 |
| 35 | + """ |
| 36 | + |
| 37 | + if depth < 0: |
| 38 | + raise ValueError("Depth cannot be less than 0") |
| 39 | + |
| 40 | + if not scores: |
| 41 | + raise ValueError("Scores cannot be empty") |
| 42 | + |
| 43 | + if depth == height: |
| 44 | + return scores[node_index] |
| 45 | + |
| 46 | + return ( |
| 47 | + max( |
| 48 | + minimax(depth + 1, node_index * 2, False, scores, height), |
| 49 | + minimax(depth + 1, node_index * 2 + 1, False, scores, height), |
| 50 | + ) |
| 51 | + if is_max |
| 52 | + else min( |
| 53 | + minimax(depth + 1, node_index * 2, True, scores, height), |
| 54 | + minimax(depth + 1, node_index * 2 + 1, True, scores, height), |
| 55 | + ) |
| 56 | + ) |
| 57 | + |
| 58 | + |
| 59 | +def main() -> None: |
| 60 | + scores = [90, 23, 6, 33, 21, 65, 123, 34423] |
| 61 | + height = math.log(len(scores), 2) |
| 62 | + print(f"Optimal value : {minimax(0, 0, True, scores, height)}") |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + import doctest |
| 67 | + |
| 68 | + doctest.testmod() |
| 69 | + main() |
0 commit comments