Minimax algorithm for AI evaluation.
(board: Board, depth: int, is_max: bool)
| 38 | |
| 39 | |
| 40 | def minimax(board: Board, depth: int, is_max: bool) -> int: |
| 41 | """Minimax algorithm for AI evaluation.""" |
| 42 | if check_winner(board, "X"): |
| 43 | return -1 |
| 44 | if check_winner(board, "O"): |
| 45 | return 1 |
| 46 | if is_board_full(board): |
| 47 | return 0 |
| 48 | |
| 49 | if is_max: |
| 50 | val = float("-inf") |
| 51 | for i in range(3): |
| 52 | for j in range(3): |
| 53 | if board[i][j] == " ": |
| 54 | board[i][j] = "O" |
| 55 | val = max(val, minimax(board, depth + 1, False)) |
| 56 | board[i][j] = " " |
| 57 | return val |
| 58 | else: |
| 59 | val = float("inf") |
| 60 | for i in range(3): |
| 61 | for j in range(3): |
| 62 | if board[i][j] == " ": |
| 63 | board[i][j] = "X" |
| 64 | val = min(val, minimax(board, depth + 1, True)) |
| 65 | board[i][j] = " " |
| 66 | return val |
| 67 | |
| 68 | |
| 69 | def best_move(board: Board) -> Optional[Tuple[int, int]]: |
no test coverage detected