Created
August 9, 2018 18:12
-
-
Save llSourcell/76e0e465a5ba7189decfaaa832cec75a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from games.tictactoe import TicTacToeGame | |
| #Returns -1 for loss, +1 for win, 0 for draw | |
| def value(game): | |
| if game.over(): | |
| return -game.score() | |
| state_values = [] | |
| for move in game.valid_moves(): | |
| game.make_move(move) | |
| # guaranteed win for P2 is loss for P1, so we flip values | |
| state_values.append(-value(game)) | |
| game.undo_move() | |
| # The player always chooses the optimal game state | |
| # +1 (win) if possible, otherwise draw, then loss | |
| return max(state_values) | |
| #Chooses optimal move to play | |
| def ai_best_move(game): | |
| action_dict = {} | |
| for move in game.valid_moves(): | |
| game.make_move(move) | |
| action_dict[move] = value(game) | |
| game.undo_move() | |
| return min(action_dict, key=action_dict.get) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment