Esempio n. 1
0
def main():
    print("Choosing player X...")
    player_x = _pick_agent(Player.X)

    print("Choosing player O...")
    player_o = _pick_agent(Player.O)
    play = "y"

    while play == "y":
        game = Game(player_x, player_o)
        game.play()
        print("check", Game.end_value)
        play = input("Play again? y/[n]: ")

    print("Averge move time for x: ", x_average_move_time())
    print("Averge move time for o: ", o_average_move_time())
Esempio n. 2
0
def main():

    size = int(input("Board size: "))
    num_to_win = int(input("Number to win: "))

    stats = {'turn':[], 'runtime':[], 'states_visited':[]}

    print("Choosing player X...")
    player_x = _pick_agent(Player.X, size, stats=stats)

    print("Choosing player O...")
    player_o = _pick_agent(Player.O, size, stats=stats)
    play = "y"

    wins = [0] * 3
    
    while play == "y":
        game = Game(player_x, player_o, size, num_to_win)
        wins[game.play()] += 1
        print("x: {} | o: {} | {} draws".format(wins[Player.X],wins[Player.O],wins[2]))
        play = input("Play again? y/[n]: ")

    if input("Save data? y/[n]: ") == "y":
        folder = "plots/" + input("folder: plots/")
        os.mkdir(folder)

        ax = sns.violinplot(x="turn", y="runtime", data=stats)
        ax.set(xlabel='turn', ylabel='runtime (seconds)')
        plt.tight_layout()
        plt.savefig(folder + "/runtime")

        plt.cla()
        ax = sns.violinplot(x="turn", y="states_visited", data=stats)
        ax.set(xlabel='turn', ylabel='states visited')
        plt.savefig(folder + "/states_visited")

        stats_file = open(folder + '/stats', 'w')
        df = DataFrame(stats)
        means = df.groupby(['turn']).mean()
        stats_file.write("Average runtime per turn:\n")
        for i in range(len(means)):
            stats_file.write("(%d,%f)\n"%(i+1, means['runtime'].loc[i+1].item()))
        stats_file.write("\n")
        stats_file.write("Average number of states visited per turn (if applicable)\n")
        for i in range(len(means)):
            try:
                stats_file.write("(%d,%d)\n"%(i+1, means['states_visited'].loc[i+1].item()))
            except:
                pass
        stats_file.write("\n")
        stats_file.write("Frequency of turns:\n")
        for i in range(max(stats['turn'])):
            stats_file.write("(%d,%d)\n"%(i+1,stats['turn'].count(i+1)))
        stats_file.write("\n")
        stats_file.write("x wins: %d\n" % wins[Player.X])
        stats_file.write("o wins: %d\n" % wins[Player.O])
        stats_file.write("draws: %d\n" % wins[2])
        stats_file.close()
Esempio n. 3
0
def main():
    print("Choosing player X...")
    player_x = _pick_agent(Player.X)

    print("Choosing player O...")
    player_o = _pick_agent(Player.O)

    size = int(input("Select size of the board >= 3: "))

    print("Select number in a row to win, <=",size,": ", end = '')
    to_win = int(input(""))

    random_board = input("Random board state? y/[n]:")

    play = "y"
    games = 0

    while play == "y":
        if(random_board == "y"):
            game_board = Board(size, to_win)
            game_board.randomize()
            winner = game_board.winner
            while(winner is not None):
                game_board = Board(size, to_win)
                game_board.randomize()
                winner = game_board.winner
        else:
            game_board = None

        game = Game(player_x, player_o, size, to_win, game_board)
        res = game.play()
        games += 1
        
        RESULTS[res + 1][1] += 1

        for line in RESULTS:
            print(*line)

        print("")

        print("X average runtime: ",player_x.average_runtime)
        print("O average runtime: ",player_o.average_runtime)
        print("States visited X", player_x.states_visited)
        print("States visited O", player_o.states_visited)

        play = input("Play again? y/[n]: ")
Esempio n. 4
0
def main():
    clock = pygame.time.Clock()
    game = Game(WIN)

    while game.is_active:
        clock.tick(FPS)

        if game.turn == RED:
            _, new_board = minimax(game.get_board(), 3, False)
            game.ai_move(new_board)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game.is_active = False

            elif event.type == pygame.MOUSEBUTTONDOWN:
                x, y = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(x, y)
                game.is_active = game.play(row, col)

        game.update()

    pygame.quit()
Esempio n. 5
0
player_o = _pick_agent(Player.O)
play = "y"
num_simulations = 1
num_times = int(input("How many simulations?: "))
performance = Performance()

num_x_wins = 0
num_o_wins = 0
num_draws = 0
player_x_total_time = 0
player_o_total_time = 0

while play == "y":
    for i in range(num_times):
        game = Game(player_x, player_o)
        performance = game.play(board_size, k, random_state)

        num_x_wins += performance.num_x_wins
        num_o_wins += performance.num_o_wins
        num_draws += performance.num_draws
        player_x_total_time += performance.player_x_total_time
        player_o_total_time += performance.player_o_total_time

    if num_times > 1:
        #stats for carrying out multiple simulations
        player_x_average_runtime = player_x_total_time / num_times
        player_o_average_runtime = player_o_total_time / num_times
        print("Player X's average runtime over " + str(num_simulations) +
              " simulations was " + str(player_x_average_runtime) + " seconds")
        print("Player O's average runtime over " + str(num_simulations) +
              " simulations was " + str(player_o_average_runtime) + " seconds")
Esempio n. 6
0
class GameTest(unittest.TestCase):
    def setUp(self):
        self.player_x = DummyAgent()
        self.player_o = DummyAgent()
        self.game = Game(self.player_x, self.player_o, verbose=False)

    def test_board(self):
        start_board = [['EMPTY', 'EMPTY',
                        'EMPTY'], ['EMPTY', 'EMPTY', 'EMPTY'],
                       ['EMPTY', 'EMPTY', 'EMPTY']]
        self.assertListEqual(start_board, self.game.board, "no board set up")

    def test_player_sides(self):
        self.assertEqual(VALUES.X, self.player_x.side,
                         'player x side is incorrect')
        self.assertEqual(VALUES.O, self.player_o.side,
                         'player o side is incorrect')

    def test_next_player(self):
        self.game.step = 2
        self.assertEqual(self.player_x, self.game.next_player())
        self.game.step = 5
        self.assertEqual(self.player_o, self.game.next_player())

    def test_winner_x(self):
        self.assertEqual(VALUES.X, self.game.play())

    def test_game_test_not_finished1(self):
        state = [['EMPTY', 'EMPTY', 'EMPTY'], ['EMPTY', 'EMPTY', 'EMPTY'],
                 ['EMPTY', 'EMPTY', 'EMPTY']]
        self.assertEqual(VALUES.NOT_FINISHED, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_not_finished2(self):
        state = [['EMPTY', 'X', 'EMPTY'], ['EMPTY', 'O', 'EMPTY'],
                 ['X', 'EMPTY', 'EMPTY']]
        self.assertEqual(VALUES.NOT_FINISHED, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_xr1(self):
        state = [['X', 'X', 'X'], ['X', 'O', 'O'], ['O', 'EMPTY', 'EMPTY']]
        self.assertEqual(VALUES.X, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_xr2(self):
        state = [['X', 'O', 'O'], ['X', 'X', 'X'], ['EMPTY', 'EMPTY', 'O']]
        self.assertEqual(VALUES.X, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_xr3(self):
        state = [['X', 'O', 'O'], ['EMPTY', 'EMPTY', 'O'], ['X', 'X', 'X']]
        self.assertEqual(VALUES.X, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_xd1(self):
        state = [['X', 'O', 'EMPTY'], ['O', 'X', 'X'], ['EMPTY', 'O', 'X']]
        self.assertEqual(VALUES.X, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_xd2(self):
        state = [['O', 'O', 'X'], ['EMPTY', 'X', 'EMPTY'], ['X', 'X', 'O']]
        self.assertEqual(VALUES.X, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_xc1(self):
        state = [['X', 'O', 'O'], ['X', 'X', 'O'], ['X', 'EMPTY', 'EMPTY']]
        self.assertEqual(VALUES.X, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_xc2(self):
        state = [['O', 'X', 'X'], ['O', 'X', 'O'], ['EMPTY', 'X', 'EMPTY']]
        self.assertEqual(VALUES.X, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_xc3(self):
        state = [['O', 'O', 'X'], ['EMPTY', 'EMPTY', 'X'],
                 ['EMPTY', 'EMPTY', 'X']]
        self.assertEqual(VALUES.X, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_or1(self):
        state = [['O', 'O', 'O'], ['X', 'X', 'EMPTY'], ['X', 'EMPTY', 'EMPTY']]
        self.assertEqual(VALUES.O, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_or2(self):
        state = [['X', 'X', 'EMPTY'], ['O', 'O', 'O'], ['X', 'EMPTY', 'EMPTY']]
        self.assertEqual(VALUES.O, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_or3(self):
        state = [['X', 'X', 'EMPTY'], ['X', 'EMPTY', 'EMPTY'], ['O', 'O', 'O']]
        self.assertEqual(VALUES.O, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_od1(self):
        state = [['O', 'X', 'X'], ['X', 'O', 'EMPTY'], ['EMPTY', 'EMPTY', 'O']]
        self.assertEqual(VALUES.O, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_od2(self):
        state = [['X', 'X', 'O'], ['X', 'O', 'EMPTY'], ['O', 'EMPTY', 'EMPTY']]
        self.assertEqual(VALUES.O, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_oc1(self):
        state = [['O', 'X', 'X'], ['O', 'X', 'EMPTY'], ['O', 'EMPTY', 'EMPTY']]
        self.assertEqual(VALUES.O, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_oc2(self):
        state = [['X', 'O', 'EMPTY'], ['X', 'O', 'X'], ['EMPTY', 'O', 'EMPTY']]
        self.assertEqual(VALUES.O, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_winner_oc3(self):
        state = [['X', 'X', 'O'], ['X', 'EMPTY', 'O'], ['EMPTY', 'EMPTY', 'O']]
        self.assertEqual(VALUES.O, self.game.game_state(state),
                         'game state incorrect')

    def test_game_test_draw(self):
        state = [['X', 'O', 'X'], ['X', 'O', 'X'], ['O', 'X', 'O']]
        self.assertEqual(VALUES.DRAW, self.game.game_state(state),
                         'game state incorrect')

    def test_is_allowed_true(self):
        move = (1, 2)
        self.assertTrue(self.game.is_allowed(move), 'move should be allowed')

    def test_is_allowed_false_index(self):
        move = (-1, 2)
        self.assertFalse(self.game.is_allowed(move),
                         'move should not be allowed')

    def test_is_allowed_false_state(self):
        board = deepcopy(self.game.board)
        self.game.board = [['X', 'X', 'O'], ['X', 'EMPTY', 'O'],
                           ['EMPTY', 'EMPTY', 'O']]
        move = (0, 2)
        self.assertFalse(self.game.is_allowed(move),
                         'move should not be allowed')
        self.game.board = board

    def test_is_allowed_none(self):
        move = None
        self.assertFalse(self.game.is_allowed(move),
                         'move should not be allowed')

    def test_is_allowed_no_tuple(self):
        move = {}
        self.assertFalse(self.game.is_allowed(move),
                         'move should not be allowed')

    def test_is_allowed_tuple_size(self):
        move = 1, 2, 3
        self.assertFalse(self.game.is_allowed(move),
                         'move should not be allowed')