Return the computer's best move.
(board: List[str], computer_letter: str)
| 134 | |
| 135 | |
| 136 | def get_computer_move(board: List[str], computer_letter: str) -> int: |
| 137 | """Return the computer's best move.""" |
| 138 | player_letter = "O" if computer_letter == "X" else "X" |
| 139 | |
| 140 | # Try to win |
| 141 | for i in range(1, 10): |
| 142 | copy = get_board_copy(board) |
| 143 | if is_space_free(copy, i): |
| 144 | make_move(copy, computer_letter, i) |
| 145 | if is_winner(copy, computer_letter): |
| 146 | return i |
| 147 | |
| 148 | # Block player's winning move |
| 149 | for i in range(1, 10): |
| 150 | copy = get_board_copy(board) |
| 151 | if is_space_free(copy, i): |
| 152 | make_move(copy, player_letter, i) |
| 153 | if is_winner(copy, player_letter): |
| 154 | return i |
| 155 | |
| 156 | # Try corners |
| 157 | move = choose_random_move_from_list(board, [1, 3, 7, 9]) |
| 158 | if move is not None: |
| 159 | return move |
| 160 | |
| 161 | # Take center |
| 162 | if is_space_free(board, 5): |
| 163 | return 5 |
| 164 | |
| 165 | # Try sides |
| 166 | return choose_random_move_from_list(board, [2, 4, 6, 8]) # type: ignore |
| 167 | |
| 168 | |
| 169 | def is_board_full(board: List[str]) -> bool: |
no test coverage detected