def test_generate_state_key(self): """Test generate_state_key method of TicTacToeGame. """ game = TicTacToeGame() game.state[:] = [[1, 0, 0], [2, 0, 0], [0, 0, 1]] self.assertEqual(game.generate_state_key(game.state, 1), b'S--O----S') self.assertEqual(game.generate_state_key(game.state, 2), b'O--S----O')
def make_better_test_game(input_list): state = { 'letter': 'x', 'board': [ ['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_'], ], } game = TicTacToeGame() game.state = state game.ui = BetterTestUI() game.ui.index = 0 game.ui.input_list = input_list return game
def test_check_game_state(self): """Test methods for checking game state (they should be identical). """ game = TicTacToeGame() for i in range(5): if i == 0: state = np.zeros((3, 3), dtype=int) else: state = np.random.randint(0, 3, size=9).reshape((3, 3)) result1 = game.check_game_state(state) # Numpy indexing method result2 = game.check_game_state(state, calc=True) # Numpy.sum method self.assertEqual( result1, result2), "Error in TicTacToeGame.check_game_state"
def test_initialize_game(self): """Test use of moves argument when initializing a new game. """ moves = [(1, (0, 2)), (2, (0, 1)), (1, (1, 1)), (2, (2, 2))] game = TicTacToeGame(moves=moves) state = np.array([[0, 2, 1], [0, 1, 0], [0, 0, 2]]) self.assertTrue(np.array_equal(game.state, state))
def test_expert_player(self): results = [] game = TicTacToeGame() expert_player1 = TicTacToeExpert("EXP1", seed=1) expert_player2 = TicTacToeExpert("EXP2", seed=1) random_player = RandomPlayer(seed=1) players = [expert_player1, expert_player2, random_player] game_stats = train_computer_players(game, players, iterations=100, seed=1, show=False) self.assertTrue(game_stats[expert_player1]['lost'] == 0) self.assertTrue(game_stats[expert_player2]['lost'] == 0) self.assertTrue(game_stats[random_player]['won'] == 0) # Save results results.append( {player.name: stat for player, stat in game_stats.items()}) # Check repeatability with random seed set game.reset() expert_player1 = TicTacToeExpert("EXP1", seed=1) expert_player2 = TicTacToeExpert("EXP2", seed=1) random_player = RandomPlayer(seed=1) players = [expert_player1, expert_player2, random_player] game_stats = train_computer_players(game, players, iterations=100, seed=1, show=False) self.assertTrue(game_stats[expert_player1]['lost'] == 0) self.assertTrue(game_stats[expert_player2]['lost'] == 0) self.assertTrue(game_stats[random_player]['won'] == 0) # Save results results.append( {player.name: stat for player, stat in game_stats.items()}) self.assertTrue(results[0] == results[1])
def test_with_players(self): game = TicTacToeGame() players = [RandomPlayer(seed=1), RandomPlayer(seed=1)] ctrl = GameController(game, players) ctrl.play(show=False) final_state = np.array([[1, 2, 1], [2, 1, 1], [1, 2, 2]]) self.assertTrue(np.array_equal(ctrl.game.state, final_state)) self.assertEqual(game.game_over, 1) self.assertEqual(game.winner, 1)
from gamelearner import * from tictactoe import TicTacToeGame, TicTacToeExpert, test_player seed = 1 td1, td2 = TDLearner("TD1"), TDLearner("TD2", seed=seed), expert_player = TicTacToeExpert("Expert", seed=seed) random_player = RandomPlayer("Random", seed=seed) players = [td1, td2, random_player, expert_player] game = TicTacToeGame() train_computer_players(game, players, 1000, seed=seed) scores = {player.name: round(test_player(player), 2) for player in players} print("Scores:", scores) assert expert_player.games_lost == 0
def setUp(self): """ Set up a sample game for tests and intercept stdout. """ self.std_out = sys.stdout sys.stdout = StringIO() self.game = TicTacToeGame()
class TwoComputerPlayerTestCase(unittest.TestCase): """ Tests for the TicTacToeGame class. """ def setUp(self): """ Set up a sample game for tests and intercept stdout. """ self.std_out = sys.stdout sys.stdout = StringIO() self.game = TicTacToeGame() def tearDown(self): """ Set the world right. """ sys.stdout = self.std_out def test_player_setup(self): """ Make sure that the game instance knows how to set up computer players. """ self.assertTrue(isinstance(self.game.player1, ComputerPlayer)) self.assertTrue(isinstance(self.game.player2, ComputerPlayer)) def test_build_board(self): """ Make sure build_board() is behaving. Order of tests is important, this test assumes no plays have been made. """ expected = " | | \n-----\n | | \n-----\n | | \nPlays: 0\n" self.assertEqual(self.game.build_board(), expected) self.assertEqual(self.game.build_board(echo=True), None) self.assertEqual(sys.stdout.getvalue().rstrip(), expected.rstrip()) def test_debug(self): """ Make sure debug output is working correctly. Maybe this should live in it's own test case. """ TicTacToeGame(debug=True) self.assertEqual( sys.stdout.getvalue().strip(), "Computer Player 1 has joined the game!\nComputer Player 2 has joined the game!" ) def test_game_is_over(self): """ Make sure that we can recognize when a game is over. """ # test non-wins self.game.board = [[' ',' ',' '], [' ', ' ', ' '], [' ', ' ', ' ']] self.assertFalse(self.game.game_is_over()) self.game.board = [['x','o','x'], [' ', ' ', ' '], [' ', ' ', ' ']] self.assertFalse(self.game.game_is_over()) self.game.board = [['x',' ','x'], [' ', 'o', ' '], [' ', ' ', ' ']] self.assertFalse(self.game.game_is_over()) # test row wins self.game.board = [['x','x','x'], [' ', ' ', ' '], [' ', ' ', ' ']] self.assertTrue(self.game.game_is_over()) self.game.board = [[' ', ' ', ' '], ['x','x','x'], [' ', ' ', ' ']] self.assertTrue(self.game.game_is_over()) self.game.board = [[' ', ' ', ' '], [' ', ' ', ' '], ['x','x','x']] self.assertTrue(self.game.game_is_over()) # test col wins self.game.board = [['x',' ',' '], ['x', ' ', ' '], ['x', ' ', ' ']] self.assertTrue(self.game.game_is_over()) self.game.board = [[' ', 'x', ' '], [' ','x',' '], [' ', 'x', ' ']] self.assertTrue(self.game.game_is_over()) self.game.board = [[' ', ' ', 'x'], [' ', ' ', 'x'], [' ',' ','x']] self.assertTrue(self.game.game_is_over()) # test diagonal wins self.game.board = [['x', ' ', ' '], [' ','x',' '], [' ', ' ', 'x']] self.assertTrue(self.game.game_is_over()) self.game.board = [[' ', ' ', 'x'], [' ', 'x', ' '], ['x',' ',' ']] self.assertTrue(self.game.game_is_over())
def setUpClass(self): self.game = TicTacToeGame() self.game.start()
class TicTacToe_Tests(unittest.TestCase): @classmethod def setUpClass(self): self.game = TicTacToeGame() self.game.start() def test_board_creation(self): self.assertEqual(self.game.instance, [['.', '.', '.'], ['.', '.', '.'], ['.', '.', '.']]) def test_current_player(self): self.assertEqual(self.game.current_player, '') def test_check_win(self): self.assertFalse(self.game.check_win()) def test_receive_input(self): self.game.receive_input([0, 0], 'x') self.assertEqual(self.game.instance, [['x', '.', '.'], ['.', '.', '.'], ['.', '.', '.']]) def test_rotate_player(self): self.game.current_player = 'x' self.game.rotate_player() self.assertEqual(self.game.current_player, 'o') def test_overwrite_impossible(self): self.game.current_player = 'x' self.game.receive_input([0, 0], 'x') self.game.rotate_player() self.game.receive_input([0, 0], 'o') self.assertEqual(self.game.instance, [['x', '.', '.'], ['.', '.', '.'], ['.', '.', '.']])
def test_validate_turn(self): game = TicTacToeGame() assert game.validate_turn("1") assert not game.validate_turn("M")
def test_game_execution(self): """Steps through one game of Tic-Tac-Toe checking various attributes and methods. """ game = TicTacToeGame() self.assertEqual(game.roles, [1, 2]) self.assertEqual(game.size, 3) self.assertEqual(game.possible_n_players, [2]) self.assertEqual(game.marks, ['X', 'O']) self.assertIsInstance(game.input_example, tuple) self.assertEqual(len(game.input_example), 2) self.assertFalse(game.game_over) self.assertEqual(game.winner, None) self.assertTrue( np.array_equal(game.state, np.zeros((game.size, game.size)))) # Make some moves game.make_move((1, (0, 2))) # Check rewards self.assertEqual(game.get_rewards(), {2: 0.0}) game.make_move((2, (0, 1))) self.assertEqual(game.get_rewards(), {1: 0.0}) game.make_move((1, (1, 1))) game.make_move((2, (2, 2))) state = np.array([[0, 2, 1], [0, 1, 0], [0, 0, 2]]) self.assertTrue(np.array_equal(game.state, state)) self.assertFalse(game.game_over) self.assertEqual(game.moves, [(1, (0, 2)), (2, (0, 1)), (1, (1, 1)), (2, (2, 2))]) self.assertEqual(game.turn, 1) self.assertEqual(game.available_moves(), [(0, 0), (1, 0), (1, 2), (2, 0), (2, 1)]) game.make_move((1, (2, 0))) self.assertTrue(game.game_over) self.assertEqual(game.winner, 1) # Check terminal rewards rewards = game.get_terminal_rewards() self.assertEqual(rewards, { 1: game.terminal_rewards['win'], 2: game.terminal_rewards['lose'] }) game.reverse_move() self.assertTrue(np.array_equal(game.state, state)) self.assertTrue(game.winner is None) with self.assertRaises(Exception) as context: game.make_move((2, (1, 2))) self.assertTrue("It is not player 2's turn." in str(context.exception)) # Make some more moves... game.make_move((1, (1, 2))) game.make_move((2, (2, 0))) game.make_move((1, (0, 0))) game.make_move((2, (1, 0))) self.assertEqual(game.state[2, 1], 0) game.make_move((1, (2, 1))) self.assertTrue(game.game_over) self.assertEqual(game.winner, None) rewards = game.get_terminal_rewards() self.assertEqual(rewards, { 1: game.terminal_rewards['draw'], 2: game.terminal_rewards['draw'] })