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