MCPcopy Create free account
hub / github.com/geekcomputers/Python / get_computer_move

Function get_computer_move

Tic-Tac-Toe Games/tic-tac-toe5.py:136–166  ·  view source on GitHub ↗

Return the computer's best move.

(board: List[str], computer_letter: str)

Source from the content-addressed store, hash-verified

134
135
136def 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
169def is_board_full(board: List[str]) -> bool:

Callers 1

mainFunction · 0.85

Calls 5

get_board_copyFunction · 0.85
is_space_freeFunction · 0.85
is_winnerFunction · 0.85
make_moveFunction · 0.70

Tested by

no test coverage detected