diff --git a/games.py b/games.py index f5061f4c8..d98b7473c 100644 --- a/games.py +++ b/games.py @@ -136,6 +136,10 @@ def min_value(state, alpha, beta, depth): def query_player(game, state): """Make a move by querying standard input.""" + print("current state:") + game.display(state) + print("available moves: {}".format(game.actions(state))) + print("") move_string = input('Your move? ') try: move = eval(move_string) @@ -153,18 +157,6 @@ def alphabeta_player(game, state): return alphabeta_full_search(state, game) -def play_game(game, *players): - """Play an n-person, move-alternating game.""" - - state = game.initial - while True: - for player in players: - move = player(game, state) - state = game.result(state, move) - if game.terminal_test(state): - game.display(state) - return game.utility(state, game.to_move(game.initial)) - # ______________________________________________________________________________ # Some Sample Games @@ -204,6 +196,17 @@ def display(self, state): def __repr__(self): return '<{}>'.format(self.__class__.__name__) + + def play_game(self, *players): + """Play an n-person, move-alternating game.""" + state = self.initial + while True: + for player in players: + move = player(self, state) + state = self.result(state, move) + if self.terminal_test(state): + self.display(state) + return self.utility(state, self.to_move(self.initial)) class Fig52Game(Game): @@ -255,7 +258,9 @@ def actions(self, state): def result(self, state, move): if move not in state.moves: - return state # Illegal move has no effect + return GameState(to_move=('O' if state.to_move == 'X' else 'X'), + utility=self.compute_utility(state.board, move, state.to_move), + board=state.board, moves=state.moves) # Illegal move has no effect board = state.board.copy() board[move] = state.to_move moves = list(state.moves) diff --git a/tests/test_games.py b/tests/test_games.py index 28644fbc5..35df9c827 100644 --- a/tests/test_games.py +++ b/tests/test_games.py @@ -60,13 +60,13 @@ def test_alphabeta_full_search(): def test_random_tests(): - assert play_game(Fig52Game(), alphabeta_player, alphabeta_player) == 3 + assert Fig52Game().play_game(alphabeta_player, alphabeta_player) == 3 # The player 'X' (one who plays first) in TicTacToe never loses: - assert play_game(ttt, alphabeta_player, alphabeta_player) >= 0 + assert ttt.play_game(alphabeta_player, alphabeta_player) >= 0 # The player 'X' (one who plays first) in TicTacToe never loses: - assert play_game(ttt, alphabeta_player, random_player) >= 0 + assert ttt.play_game(alphabeta_player, random_player) >= 0 if __name__ == '__main__':