|
1 |
| -import math |
| 1 | +import math |
2 | 2 |
|
3 |
| -''' Minimax helps to achieve maximum score in a game by checking all possible moves |
| 3 | +""" Minimax helps to achieve maximum score in a game by checking all possible moves |
4 | 4 | depth is current depth in game tree.
|
5 | 5 | nodeIndex is index of current node in scores[].
|
6 | 6 | if move is of maximizer return true else false
|
7 | 7 | leaves of game tree is stored in scores[]
|
8 | 8 | height is maximum height of Game tree
|
9 |
| -''' |
| 9 | +""" |
10 | 10 |
|
11 |
| -def minimax (Depth, nodeIndex, isMax, scores, height): |
12 | 11 |
|
13 |
| - if Depth == height: |
14 |
| - return scores[nodeIndex] |
| 12 | +def minimax(Depth, nodeIndex, isMax, scores, height): |
15 | 13 |
|
16 |
| - if isMax: |
17 |
| - return (max(minimax(Depth + 1, nodeIndex * 2, False, scores, height), |
18 |
| - minimax(Depth + 1, nodeIndex * 2 + 1, False, scores, height))) |
19 |
| - return (min(minimax(Depth + 1, nodeIndex * 2, True, scores, height), |
20 |
| - minimax(Depth + 1, nodeIndex * 2 + 1, True, scores, height))) |
| 14 | + if Depth == height: |
| 15 | + return scores[nodeIndex] |
21 | 16 |
|
22 |
| -if __name__ == "__main__": |
23 |
| - |
24 |
| - scores = [90, 23, 6, 33, 21, 65, 123, 34423] |
25 |
| - height = math.log(len(scores), 2) |
| 17 | + if isMax: |
| 18 | + return max( |
| 19 | + minimax(Depth + 1, nodeIndex * 2, False, scores, height), |
| 20 | + minimax(Depth + 1, nodeIndex * 2 + 1, False, scores, height), |
| 21 | + ) |
| 22 | + return min( |
| 23 | + minimax(Depth + 1, nodeIndex * 2, True, scores, height), |
| 24 | + minimax(Depth + 1, nodeIndex * 2 + 1, True, scores, height), |
| 25 | + ) |
26 | 26 |
|
27 |
| - print("Optimal value : ", end = "") |
28 |
| - print(minimax(0, 0, True, scores, height)) |
| 27 | + |
| 28 | +if __name__ == "__main__": |
| 29 | + |
| 30 | + scores = [90, 23, 6, 33, 21, 65, 123, 34423] |
| 31 | + height = math.log(len(scores), 2) |
| 32 | + |
| 33 | + print("Optimal value : ", end="") |
| 34 | + print(minimax(0, 0, True, scores, height)) |
0 commit comments