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()
def test_winner_check(self): """Testing win check by implementing possible cases""" instance = TicTacToe() instance.change_cell(1, 1, 'X') instance.change_cell(1, 2, 'X') instance.change_cell(1, 3, 'X') self.assertTrue(instance.check_if_there_is_a_winner()) instance = TicTacToe() instance.change_cell(1, 1, 'X') instance.change_cell(2, 2, 'X') instance.change_cell(3, 3, 'X') self.assertTrue(instance.check_if_there_is_a_winner()) instance = TicTacToe() instance.change_cell(1, 1, 'X') instance.change_cell(2, 1, 'X') instance.change_cell(3, 1, 'X') self.assertTrue(instance.check_if_there_is_a_winner()) instance = TicTacToe() instance.change_cell(1, 1, 'X') instance.change_cell(2, 2, 'O') instance.change_cell(3, 3, 'X') self.assertFalse(instance.check_if_there_is_a_winner()) instance = TicTacToe() instance.change_cell(1, 1, 'X') instance.change_cell(3, 3, 'X') self.assertFalse(instance.check_if_there_is_a_winner())
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 main_pg(): pygame.init() pygame.display.set_caption("Tic Tac Toe") # Hack: Loads before game window as it can take a very long time on my MacOs Catalina 10.15.4 pygame.freetype.SysFont(None, 30) # default background screen_w = 300 screen_h = 300 screen = pygame.display.set_mode((screen_w, screen_h)) # screen.fill((0, 0, 0)) ttt = TicTacToe() blocks = get_blocks(93, 93, 5) while True: is_finished = ttt.is_game_finished() if is_finished is not None: draw_end_screen(screen, 150, 100, is_finished) # game variables are reset screen.fill((0, 0, 0)) ttt = TicTacToe() draw_board(screen, ttt, blocks) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.MOUSEBUTTONUP: pos = pygame.mouse.get_pos() rect_index = get_rect_index(blocks, pos) if ttt.play(rect_index) is False: # Blink rect to indicate invalid move for x in range(7): # blink will either blink the square or choose a number # outside of the range of blocks to blink; negating its role. blink = 10 if x % 2 == 0 else 0 draw_board(screen, ttt, blocks, rect_index + blink) pygame.display.flip() pygame.event.pump() pygame.time.wait(65) else: # play as AI ttt.play(-1) draw_board(screen, ttt, blocks) pygame.display.flip()
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'])
def test_is_winner(self): ''' Тесты двух случаев игры с победителем и без''' game = TicTacToe() game.set_coord(1) game.set_coord(2) game.set_coord(5) game.set_coord(3) game.set_coord(9) self.assertTrue(game.is_winner()) game = TicTacToe() game.set_coord(1) game.set_coord(2) self.assertFalse(game.is_winner())
def test_ttt_put(self): ttt = TicTacToe() self.assertEqual(ttt.board, [[0, 0, 0], [0, 0, 0], [0, 0, 0]]) self.assertEqual(ttt.now_move(), 'x') self.assertTrue(ttt.put('b2')) self.assertEqual(ttt.now_move(), 'o') self.assertEqual(ttt.board, [[0, 0, 0], [0, 'x', 0], [0, 0, 0]]) self.assertTrue(ttt.put('a1')) self.assertEqual(ttt.now_move(), 'x') self.assertEqual(ttt.board, [['o', 0, 0], [0, 'x', 0], [0, 0, 0]]) self.assertTrue(ttt.put('c3')) self.assertEqual(ttt.now_move(), 'o') self.assertEqual(ttt.board, [['o', 0, 0], [0, 'x', 0], [0, 0, 'x']]) self.assertTrue(ttt.put('a3')) self.assertEqual(ttt.now_move(), 'x') self.assertEqual(ttt.board, [['o', 0, 0], [0, 'x', 0], ['o', 0, 'x']]) self.assertFalse(ttt.put('d1')) self.assertEqual(ttt.now_move(), 'x') self.assertEqual(ttt.board, [['o', 0, 0], [0, 'x', 0], ['o', 0, 'x']]) self.assertFalse(ttt.put('a1')) self.assertEqual(ttt.now_move(), 'x') self.assertEqual(ttt.board, [['o', 0, 0], [0, 'x', 0], ['o', 0, 'x']]) self.assertFalse(ttt.put('a1')) self.assertEqual(ttt.now_move(), 'x') self.assertEqual(ttt.board, [['o', 0, 0], [0, 'x', 0], ['o', 0, 'x']]) self.assertFalse(ttt.put('b2')) self.assertEqual(ttt.now_move(), 'x') self.assertEqual(ttt.board, [['o', 0, 0], [0, 'x', 0], ['o', 0, 'x']]) self.assertFalse(ttt.put('a0')) self.assertEqual(ttt.now_move(), 'x') self.assertEqual(ttt.board, [['o', 0, 0], [0, 'x', 0], ['o', 0, 'x']]) self.assertFalse(ttt.put('3')) self.assertEqual(ttt.now_move(), 'x') self.assertEqual(ttt.board, [['o', 0, 0], [0, 'x', 0], ['o', 0, 'x']])
def main(): try: game = TicTacToe() while True: game.printBoard() # Prompt Player One to play the move. print('Player One') pos = game.choosePosition() game.playMove(pos, PLAYER_ONE_SYMBOL) game.printBoard() if game.isWon(PLAYER_ONE_SYMBOL): print('Player One - Won the game') break elif game.isFinished(): print("It's a draw") break # Prompt Player Two to play the move print('Player Two') pos = game.choosePosition() game.playMove(pos, PLAYER_TWO_SYMBOL) game.printBoard() if game.isWon(PLAYER_TWO_SYMBOL): print('Player Two - Won the game') break elif game.isFinished(): print("It's a draw") break except Exception as e: print(e)
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()
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))
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))
def test_terminates(self): game = TicTacToe() game.board[:] = 1 game.board[0, 0] = 0 ai = MinimaxAI(game) row, column = ai.decide_turn()
def test_makes_valid_turns(self): game = TicTacToe() ai = MinimaxAI(game) row, column = ai.decide_turn() assert 0 <= row <= 2 assert 0 <= column <= 2
def test_next_side(self): test_board = TicTacToe() self.assertEqual(test_board.next_side('x'), 'o') self.assertEqual(test_board.next_side('o'), 'x') with self.assertRaises(TypeError): test_board.next_side(1223) with self.assertRaises(ValueError): test_board.next_side('xo')
def test_read_coord(self): ''' Тесты функции read_coord()''' game = TicTacToe() with self.assertRaises(ValueError): game.read_coord('string') with self.assertRaises(IndexError): game.read_coord('0') self.assertEqual(game.read_coord('1'), 1)
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]])
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
def test_victory_condition_rows(): game = TicTacToe() assert game.evaluate(game.board) is None game.board[0] = 1 assert game.evaluate(game.board) == 1 game.board[0] = -1 assert game.evaluate(game.board) == -1
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)
def test_player_a_win(self): game = TicTacToe() game.record_player_a_move((0, 0)) game.record_player_b_move((0, 1)) game.record_player_a_move((1, 0)) game.record_player_b_move((1, 1)) self.assertFalse(game.has_ended()) game.record_player_a_move((2, 0)) self.assertTrue(game.has_ended()) self.assertEqual(game.game_result, "A")
def test_victory_condition_columns(self): game = TicTacToe() assert game.evaluate(game.board) is None game.board[:, 0] = 1 assert game.evaluate(game.board) == 1 game.board[:, 0] = -1 assert game.evaluate(game.board) == -1
def run_script(game_mode, arg_1=0, arg_2=0): # Run game: if game_mode == 1: ttt = TicTacToe(1) ttt.run_game() elif game_mode == 2: ttt = TicTacToe(2) ttt.run_game() elif game_mode == 3: # The number of test and training data to collect data_gathering(game_mode, arg_1, arg_2) elif game_mode == 4: # The number of test and training data to collect data_gathering(game_mode, arg_1, arg_2) elif game_mode == 5: # The number of test and training data to collect data_gathering(game_mode, arg_1, arg_2) else: print("Error. Please use -h for help.")
def gather_data(game_mode, game_total_count, data_type_name): data = [] for x in range(1, game_total_count, 1): data.append(TicTacToe(game_mode, data_type_name).run_game()) if x % 10 == 0: print("Iteration: {}".format(x)) return data
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)
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)
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)
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
def main(): board_size = 4 episodes = 10 player_o = TicTacToeAgent("O", Minimax(2)) player_x = TicTacToeAgent("X", AlphaBetaPruning(3)) environment = TicTacToe(player_o, player_x, board_size) run_timed_episodes(environment, episodes)