def test_multiple_errors(self):
     turns = ['1', '2', '4', '5', '4', '5', '4', '5', '5', '5', '7']
     msg = 'Congratulations to player number {}'
     tic_tac = TicTacToe()
     for turn in turns[:-1]:
         tic_tac.turn(turn)
     self.assertEqual(tic_tac.turn(turns[-1]), msg.format(1))
Ejemplo n.º 2
0
 def input_name():
     if name_2 == self.a_i:
         self.game = TicTacToe(name_1.get(), self.a_i)
         self.user_stroke()
     else:
         self.game = TicTacToe(name_1.get(), name_2.get())
         self.user_stroke()
Ejemplo n.º 3
0
def main():
    board_size = 3
    exploration = 0.5
    learning_rate = 5.0
    discount = 5.0
    training_episodes = 10000
    episodes = 10

    random_state = random.Random()

    player_x = TicTacToeAgent("X", RandomAction(random_state))

    q_learning = QLearning(learning_rate, discount)
    training_player_o = TicTacToeAgent(
        "O", EpsilonExploration(q_learning, exploration))
    training_environment = TicTacToe(training_player_o, player_x, board_size)

    run_training(training_environment, [training_player_o], training_episodes)

    policy = policy_from_q_values(q_learning.q_values)
    evaluation_player_o = TicTacToeAgent(
        "O", FollowPolicy(policy, RandomAction(random_state)))
    evaluation_environment = TicTacToe(evaluation_player_o, player_x,
                                       board_size)

    run_timed_episodes(evaluation_environment, episodes)
 def test_draw(self):
     turns = ['1', '2', '5', '9', '6', '4', '3', '7', '8']
     msg = 'Draw'
     tic_tac = TicTacToe()
     for turn in turns[:-1]:
         tic_tac.turn(turn)
     self.assertEqual(tic_tac.turn(turns[-1]), msg)
    def test_game_winner(self):
        """Test all winning configurations."""
        # arrange
        game_descriptions = [
            ([(0, 0), (0, 1), (1, 0), (1, 1), (2, 0)], 'A win in the 1st column.'),
            ([(0, 1), (0, 0), (1, 1), (1, 0), (2, 1)], 'A win in the 2nd column.'),
            ([(0, 2), (0, 1), (1, 2), (1, 1), (2, 2)], 'A win in the 3st column.'),

            ([(0, 0), (1, 1), (0, 1), (1, 2), (0, 2)], 'A win in the 1st row.'),
            ([(1, 0), (0, 0), (1, 1), (0, 1), (1, 2)], 'A win in the 2nd row.'),
            ([(2, 0), (0, 1), (2, 1), (1, 1), (2, 2)], 'A win in the 3st row.'),

            ([(0, 0), (1, 0), (1, 1), (0, 1), (2, 2)], 'A win in the main diagonal.'),
            ([(0, 2), (1, 0), (1, 1), (0, 1), (2, 0)], 'A win in the minor diagonal.'),
            ]

        for turn_sequence, win_description in game_descriptions:
            game = TicTacToe()
            expected_winner = game.next_mark

            # assert
            for turn_index, turn in enumerate(turn_sequence):
                self.assertEqual(
                    PlayerMark.EMPTY,
                    game.winner,
                    f'Winner before the turn #{turn_index} of the game "{win_description}"')

                game.mark_cell(*turn)

            self.assertEqual(
                expected_winner,
                game.winner,
                'Winner after the last turn of the game "{win_description}"')

            self.assertTrue(game.has_ended(), "Game has ended")
 def test_winner_2(self):
     msg = 'Congratulations to player number {}'
     turns = ['1', '2', '3', '5', '4', '8']
     tic_tac = TicTacToe()
     for turn in turns[:-1]:
         tic_tac.turn(turn)
     self.assertEqual(tic_tac.turn(turns[-1]), msg.format(-1))
Ejemplo n.º 7
0
    def test_terminates(self):
        game = TicTacToe()
        game.board[:] = 1
        game.board[0, 0] = 0

        ai = MinimaxAI(game)

        row, column = ai.decide_turn()
Ejemplo n.º 8
0
    def test_makes_valid_turns(self):
        game = TicTacToe()

        game.o_ai = RandomAI(game)

        row, column = game.o_ai.decide_turn()

        assert 0 <= row <= 2
        assert 0 <= column <= 2
Ejemplo n.º 9
0
    def play_exploratory_move(self, game: TicTacToe):
        legal_moves = self.get_legal_moves(game)
        idx = randint(0, len(legal_moves) - 1)
        random_move = legal_moves[idx]

        outcome = game.update_board(random_move[0], random_move[1], self.marker)
        self.prev_state = TicTacToe.get_serialized_board(game.get_board())

        return outcome
Ejemplo n.º 10
0
def run_trials():
    for i in range(n_games):
        ttt = TicTacToe()
        x_ai = MinimaxAI(ttt)
        o_ai = RandomAI(ttt)
        ttt.o_ai = o_ai
        ttt.x_ai = x_ai

        result = ttt.loop()
        counters[result] += 1
Ejemplo n.º 11
0
    def test_chooses_blocking_move(self):
        game = TicTacToe()
        game.x_next = False
        game.board = np.array([[-1, 1, 0], [1, 1, -1], [-1, 0, 1]])

        ai = MinimaxAI(game)

        row, column = ai.decide_turn()

        assert (row, column) == (2, 1)
Ejemplo n.º 12
0
def tictactoe():
    global game, bot, moving
    # reset moving
    moving = False
    game = TicTacToe()
    # randomize the first player
    game.active_player = random.choice([0, 1])
    # use the bot that has memorized all the best moves
    bot = tic_tac_toe_bot
    return render_template("tictactoe.html", player=game.active_player)
Ejemplo n.º 13
0
    def test_set_params(self):
        moves = [[0, 0, 'o'], [0, 2, 'x'], [1, 1, 'o'], [0, 1, 'x'],
                 [2, 2, 'o'], [1, 0, 'x'], [2, 1, 'o']]
        t = TicTacToe()
        result = 0
        for move in moves:
            result = t.place_marker(move[2], move[0], move[1])
            self.assertIsNotNone(result)

        self.assertIs(result, t.STATES.NAUGHT_WON.value)
Ejemplo n.º 14
0
 def get_possible_next_states(self, game: TicTacToe, legal_moves: list):
     planning_board = deepcopy(game.get_board())
     possible_states = []
     for move in legal_moves:
         planning_board[move[0]][move[1]] = self.marker
         state = TicTacToe.get_serialized_board(planning_board)
         possible_states.append(state)
         # reset planning board
         planning_board[move[0]][move[1]] = ""
     return possible_states
Ejemplo n.º 15
0
    def test_who_wins(self):
        t = TicTacToe()
        testcase1 = [1, 0]
        testcase2 = [3, 0]

        result = t.who_wins(testcase1)
        self.assertIs(result, t.STATES.DRAW.value)

        result = t.who_wins(testcase2)
        self.assertIs(result, t.STATES.CROSS_WON.value)
Ejemplo n.º 16
0
    def test_setting_mark_in_an_out_of_range_cell(self):
        """Test game's reaction to setting mark into a non-existing cell."""
        #arrange
        game = TicTacToe()

        #act
        try:
            game.mark_cell(game.grid_size + 1, game.grid_size + 1)
        #assert
        except IndexError as error:
            self.fail(f"Exception raised unexpectedly: {error}.")
Ejemplo n.º 17
0
    def __init__(self, game_presenter: GamePresenterBase,
                 player1: GamePlayerBase, player2: GamePlayerBase):
        self.game_presenter = game_presenter
        self._current_player = player1
        self._next_player = player2
        self.game = TicTacToe()

        self._current_player.set_mark(self.game.next_mark)
        self._next_player.set_mark(self.game._previous_mark)

        self.on_mark_selected = None
Ejemplo n.º 18
0
    def _restart_game(self) -> None:
        """
        Restarts the game, and all variables associated with it
        """

        self._game = TicTacToe(self._board_size)
        self._has_game_started = False
        self._update_player_prompt()

        for cell in self._board_cells:
            cell.setText(TicTacToe.NEUTRAL_PLAYER)
Ejemplo n.º 19
0
    def test_set_coord(self):
        ''' Тесты функции set_coord()'''
        game = TicTacToe()
        for i in range(9):
            game.set_coord(i)
        with self.assertRaises(AlreadyExistsError):
            game.set_coord(3)

        game = TicTacToe()
        for i in range(1, 10):
            game.set_coord(i)
        self.assertListEqual(game._table,
                             ['X', 'O', 'X', 'O', 'X', 'O', 'X', 'O', 'X'])
Ejemplo n.º 20
0
    def test_getting_mark_from_a_cell(self):
        """Test requesting a mark from a game cell."""
        #arrange
        game = TicTacToe()
        expected_mark = game.next_mark
        tested_cell = (0, 0)
        game.mark_cell(*tested_cell)

        #assert
        self.assertEqual(
            expected_mark,
            game.get_cell_mark(*tested_cell),
            "Cell's mark")
Ejemplo n.º 21
0
def randomTTT(numGames):
    t = TicTacToe()
    winnerStats = [0] * 3
    gameLength = [0] * 10
    for _ in range(numGames):
        winner, length = t.simulate()
        winnerStats[winner] += 1
        gameLength[length] += 1
    print(winnerStats[BLACK], " wins for X, ", winnerStats[WHITE],
          " wins for O, ", winnerStats[EMPTY], " draws")
    print("Game length:")
    for length in range(5, 10):
        if gameLength[length] > 0:
            print("Length ", length, ": ", gameLength[length])
Ejemplo n.º 22
0
    def test_change_cell(self):
        """Trying to break changing precautions"""
        self.assertFalse(self.change_cell(0, 0, 'X'))
        self.assertFalse(self.change_cell(-1, -2, 'X'))
        self.assertFalse(self.change_cell(110, 10, 'X'))
        self.assertFalse(self.change_cell(0, 0, '0'))
        self.assertFalse(self.change_cell(0, 5, 'O'))
        self.assertFalse(self.change_cell(5, 0, 'O'))
        self.assertFalse(self.change_cell(0, 5, 6))
        self.assertFalse(self.change_cell(0, 5, 'das'))

        instance = TicTacToe()
        instance.change_cell(1, 1, 'X')
        self.assertFalse(instance.change_cell(1, 1, 'X'))
Ejemplo n.º 23
0
def main():
    tic_tac_toe = TicTacToe()
    tic_tac_toe.print_field()

    while True:
        input_ = input('Enter the coordinates: ').split()
        if tic_tac_toe.check_input(input_):
            if tic_tac_toe.move():
                tic_tac_toe.print_field()
                if tic_tac_toe.check_win():
                    break
Ejemplo n.º 24
0
def main():
    game = TicTacToe()
    gui = TicTacToeGui(0, 0, 500, 500, game)
    win = Window(title="Ultimate Tic Tac Toe",
                 flags=["SCALED"],
                 gui_objects=[gui])
    win.start()
Ejemplo n.º 25
0
    def get_state(self, game: TicTacToe):
        state = [
            game.get_cell_mark(x, y).value for x in range(game.grid_size)
            for y in range(game.grid_size)
        ]

        return np.asarray(state)
Ejemplo n.º 26
0
 def test_ttt_clear(self):
     ttt = TicTacToe()
     self.assertEqual(ttt.board, [[0, 0, 0], [0, 0, 0], [0, 0, 0]])
     ttt.put('b2')
     self.assertEqual(ttt.board, [[0, 0, 0], [0, 'x', 0], [0, 0, 0]])
     ttt.put('a1')
     self.assertEqual(ttt.board, [['o', 0, 0], [0, 'x', 0], [0, 0, 0]])
     ttt.clear()
     self.assertEqual(ttt.board, [[0, 0, 0], [0, 0, 0], [0, 0, 0]])
Ejemplo n.º 27
0
    def play_greedy_move(self, game: TicTacToe):
        legal_moves = self.get_legal_moves(game)
        possible_states = self.get_possible_next_states(game, legal_moves)

        best_state_index, best_state = self.choose_best_state_index(possible_states)
        # best_state_index is also best_move_index
        best_move = legal_moves[best_state_index]

        current_state = TicTacToe.get_serialized_board(game.get_board())
        outcome = game.update_board(best_move[0], best_move[1], self.marker)

        # Finished game outcomes are handled differently
        if outcome == TicTacToe.END_MOVE:
            self.update_value(best_state)

        self.prev_state = best_state
        return outcome
Ejemplo n.º 28
0
    def test_game_with_no_winner(self):
        """Test the draw game ending."""
        # arrange
        game = TicTacToe()

        draw_complete_turn_sequence = [
            (0, 0), (1, 1), (2, 2), (0, 1), (2, 1), (2, 0), (0, 2), (1, 2), (1, 0)
            ]

        # assert
        for turn_index, turn in enumerate(draw_complete_turn_sequence):
            self.assertEqual(PlayerMark.EMPTY, game.winner, f'Winner before the turn #{turn_index}')
            game.mark_cell(*turn)

        self.assertEqual(PlayerMark.EMPTY, game.winner, 'Winner after the last turn')

        self.assertTrue(game.has_ended(), "Game has ended")
Ejemplo n.º 29
0
 def get_legal_moves(self, game: TicTacToe):
     legal_moves = []
     board = game.get_board()
     for row in range(3):
         for col in range(3):
             if board[row][col] == "":
                 legal_moves.append((row, col))
     return legal_moves
Ejemplo n.º 30
0
    def test_makes_valid_turns(self):
        game = TicTacToe()
        ai = MinimaxAI(game)

        row, column = ai.decide_turn()

        assert 0 <= row <= 2
        assert 0 <= column <= 2
Ejemplo n.º 31
0
class TestTicTacToe(unittest.TestCase):
    def setUp(self):
        self.game = TicTacToe()

    def test_choose(self):
        self.game.choose(1, 1)
        expected = [' ', ' ', ' ', ' ', 'X', ' ', ' ', ' ', ' ']
        actual = self.game.get_board().get_data()
        self.assertEqual(actual, expected)

    def test_finished(self):
        self.game.choose(0, 0)
        self.game.choose(1, 0)
        self.game.choose(1, 1)
        self.game.choose(2, 2)
        self.game.choose(0, 1)
        self.game.choose(2, 1)
        self.game.choose(0, 2)
        actual = self.game.finished()
        expected = True
        self.assertEqual(actual, expected)
Ejemplo n.º 32
0
 def setUp(self):
     self.game = TicTacToe()
Ejemplo n.º 33
0
 def test_o_rows_board(self):
     game = TicTacToe()
     winner = game.winner(3, [], [(0,0), (0,1), (0,2)])
     self.assertEquals(winner, "o")
Ejemplo n.º 34
0
 def setUp(self):
     self.tic = TicTacToe()
Ejemplo n.º 35
0
class TicTacToeTests(unittest.TestCase):
    def setUp(self):
        self.tic = TicTacToe()

    def test_is_winner(self):
        self.tic.board[6] = 'X'
        self.tic.board[7] = 'X'
        self.tic.board[8] = 'X'
        self.assertTrue(self.tic.is_winner('X'))

    def test_is_winning(self):
        self.tic.board[3] = 'O'
        self.tic.board[4] = 'X'
        self.tic.board[5] = 'X'
        self.assertFalse(self.tic.is_winner('O'))

    def test_try_to_win_successfully(self):
        self.tic.computer_symbol = "O"
        self.tic.player_symbol = "X"
        self.tic.board[0] = 'X'
        self.tic.board[1] = ' '
        self.tic.board[2] = 'O'
        self.tic.board[3] = ' '
        self.tic.board[4] = 'X'
        self.tic.board[5] = 'X'
        self.tic.board[6] = 'O'
        self.tic.board[7] = ' '
        self.tic.board[8] = 'O'
        self.tic.free_positions = [1, 3, 7]
        self.assertEqual(self.tic.computer_choose_position(3), 7)

    def test_config(self):
        self.tic.computer_symbol = "O"
        self.tic.player_symbol = "X"
        self.tic.board[0] = 'X'
        self.tic.board[1] = ' '
        self.tic.board[2] = 'O'
        self.tic.board[3] = 'O'
        self.tic.board[4] = 'X'
        self.tic.board[5] = 'X'
        self.tic.board[6] = ' '
        self.tic.board[7] = ' '
        self.tic.board[8] = 'O'
        self.tic.free_positions = [1, 6, 7]
        self.tic.make_move(7, 'X')
        self.assertEqual(self.tic.computer_choose_position(3), 6)

    def test_computer_block_player(self):
        self.tic.computer_symbol = "O"
        self.tic.player_symbol = "X"
        self.tic.board[0] = 'X'
        self.tic.board[1] = ' '
        self.tic.board[2] = ' '
        self.tic.board[3] = 'O'
        self.tic.board[4] = 'X'
        self.tic.free_positions = [1, 5, 6, 7, 8]
        self.assertEqual(self.tic.computer_choose_position(1), 8)

    def test_computer_chooses_corner(self):
        self.tic.computer_symbol = "O"
        self.tic.player_symbol = "X"
        self.tic.board[4] = 'X'
        move = self.tic.computer_choose_position(1)
        self.tic.free_positions = [0, 1, 2, 3, 5, 6, 7, 8]
        corners = [0, 2, 6, 8]
        self.assertIn(move, corners)
Ejemplo n.º 36
0
 def test_x_second_line(self):
     game = TicTacToe()
     winner = game.winner(3, [], [(1,0), (1,1), (1,2)])
     self.assertEquals(winner, "o")
Ejemplo n.º 37
0
 def test_x_wins(self):
     game = TicTacToe()
     winner = game.winner(1, [(0,0)], [])
     self.assertEquals(winner, "x")
Ejemplo n.º 38
0
 def test_nobody_wins(self):
     game = TicTacToe()
     winner = game.winner(3, [], [])
     self.assertEquals(winner, "nobody")