Skip to content

Instantly share code, notes, and snippets.

@llSourcell
Created August 9, 2018 18:12
Show Gist options
  • Select an option

  • Save llSourcell/76e0e465a5ba7189decfaaa832cec75a to your computer and use it in GitHub Desktop.

Select an option

Save llSourcell/76e0e465a5ba7189decfaaa832cec75a to your computer and use it in GitHub Desktop.
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