コード例 #1
0
ファイル: HighScoreManager.py プロジェクト: omkarmoghe/Scurvy
    def draw(self, p1name, p2name, easy_selected, ship_location):
        running = True

        menu_background = pygame.image.load(menu_background_image)
        menu_background_rect = menu_background.get_rect()

        position_label = pygame.font.Font(menu_font,
                                          25).render('High Scores Table', True,
                                                     (255, 255, 255))
        position_label_rect = position_label.get_rect()
        position_label_rect.centerx = WIDTH / 2

        ratio = HEIGHT / 12
        position_label_rect.centery = int(ratio)
        score_labels = []
        for (i, score) in enumerate(self.high_scores):
            score_label = pygame.font.Font(menu_font, 20).render(
                '{0:12s} {1:12s} scored {2:10d} points.'.format(
                    score[0], score[1], score[2]), True, (255, 255, 255))
            score_label_rect = score_label.get_rect()
            score_label_rect.left = WIDTH / 2 * 0.3
            score_label_rect.centery = int(ratio * (2 + i))
            score_labels.append((score_label, score_label_rect))

        home_button = ControlBox(home_button_image, None,
                                 (WIDTH / 2 * 0.1, 50),
                                 (button_size, button_size))
        restart_button = ControlBox(restart_button_image, None,
                                    (WIDTH / 2 * 1.8, 50),
                                    (button_size, button_size))

        while running:
            screen.fill((0, 0, 0))
            screen.blit(menu_background, menu_background_rect)

            screen.blit(position_label, position_label_rect)

            screen.blit(home_button.image, home_button.rect)
            screen.blit(restart_button.image, restart_button.rect)

            for score_label_thingy in score_labels:
                screen.blit(score_label_thingy[0], score_label_thingy[1])

            for event in pygame.event.get():
                if event.type == QUIT or (event.type == KEYDOWN
                                          and event.key == K_ESCAPE):
                    running = False
                if event.type == MOUSEBUTTONUP and event.button == LEFT:
                    pos = pygame.mouse.get_pos()
                    if home_button.is_mouse_selection(pos):
                        running = False
                    if restart_button.is_mouse_selection(pos):
                        infile = open(settings_file, "r")
                        array = infile.readlines()
                        main.play_game(p1name, p2name, easy_selected, array[0],
                                       array[1], array[2], ship_location)
                        return
            pygame.display.update()
コード例 #2
0
def play_again():
    response = input("Would you like to play again? [y/n] ")
    if response[0].upper() == "Y":
        "Okay, good luck!"
        main.play_game()
    elif response[0].upper() == "N":
        print("Okay. So long for now.")
        exit(0)
    print("Don't understand. Please enter Y for yes or N for No")
    return play_again()
コード例 #3
0
ファイル: train.py プロジェクト: gotastycake/snakeai
def train_models(n,
                 opt=optimizer,
                 act=activation,
                 loss=loss_function,
                 load_models=False):
    global df_stats
    global n_existing_models
    if load_models:
        models = create_models(n_best, opt, act, loss)
        for i, model in enumerate(models):
            model.load_weights('models\\last_epoch\\model-{}'.format(i))
    else:
        models = create_models(n_models, opt, act, loss)
    for i in range(n):
        system('cls')
        print('opt={}, act={}, loss={}'.format(opt, act, loss))
        print('Epoch {}/{}'.format(i, n - 1))
        df_epoch = pd.DataFrame(columns=columns)
        for model in models:
            print('Running model №{}'.format(model.model_id), end='')
            lifetime, score = run(model)
            try:
                # rating = 10 ** score
                rating = 10**score + lifetime**score
                # rating = 10**score * (1 - 6 / lifetime)
            except ZeroDivisionError:
                rating = -lifetime
            df_model = pd.DataFrame(
                [[i, model.model_id, lifetime, score, rating, model]],
                columns=columns)
            df_epoch = df_epoch.append(df_model, sort=False)
        # take n_best values and models
        df_epoch.sort_values(by='rating', inplace=True, ascending=False)
        best_models = list(df_epoch['model'][:n_best].values)
        save_models(best_models, i)
        the_best_model = best_models[0]
        play_game(the_best_model, i)
        print(df_epoch.drop('model', axis=1))
        del models
        print('Started crossing over')
        # new_models = crossing_over(best_models, opt, act, loss)
        new_models = new_crossover(best_models, opt, act, loss)

        print('Ended crossing over')
        models = new_models
        df_stats = df_stats.append(df_epoch.drop('model', axis=1), sort=False)
    del df_epoch
    del models
    del best_models
    del new_models

    return df_stats
コード例 #4
0
    def test_win_diagonal(self):
        self.winner = [(0, 0), (1, 1), (2, 2)]
        self.loser = [(0, 1), (0, 2), (1, 2)]
        a_1 = AgentTest(self.winner, 'O')
        a_2 = AgentTest(self.loser, 'X')

        environnement = Environnement()

        test = play_game(a_1, a_2, environnement)

        self.assertEqual(test, 'O')
コード例 #5
0
# Référence https://www.youtube.com/watch?v=731LoaZCUjo&feature=youtu.be
import sys

sys.path.insert(0, '../')  #tell the system to go 1 directory higher
import pygame
from player import HumanPlayer

from screen import Screen
from game import Game
from main import play_game

if __name__ == "__main__":
    pygame.init()
    screen = Screen()
    player = HumanPlayer(screen.width / 2, screen.height - 100)
    game = Game()

    play_game(screen, player, game)
コード例 #6
0
# basic = BasicModel()
# #training_loop(training_model, basic, verbose=True)
# training_loop(training_model, Me(), verbose=True)
# training_model.save("from_scratch_against_me_new_reward.model")

# training_model.save("from_scratch_against_basic.model")

# Train against itself
# training_model = Model("from_scratch_against_basic.model")
# opponent_model = Model("from_scratch_against_basic.model")
# training_loop(training_model, opponent_model, verbose=True)
# training_loop(training_model, basic, verbose=True)
# training_model.save("v_itself_w_basic_training.model")

# # Train against itself2
# training_model = Model("v_itself_w_basic_training.model")
# opponent_model = Model("v_itself_w_basic_training.model")
# training_loop(training_model, opponent_model, verbose=True)
# training_loop(training_model, basic, verbose=True)
# training_model.save("v_itself_w_basic_training2.model")

# performance_stats(Model("from_scratch_against_basic.model"), BasicModel(), N_RUNS=500)
# performance_stats(Model("v_itself_w_basic_training.model"), BasicModel(), N_RUNS=500)
# performance_stats(Model("v_itself_w_basic_training2.model"), BasicModel(), N_RUNS=500)

# run_game(training_model, basic_model, verbose=True)
play_game(m1)
play_game(m2)

# training_model = Model(load_model_name="a.model")
コード例 #7
0
def play_match(player_1,
               rnd_1,
               player_2,
               rnd_2,
               board_name,
               n_rounds,
               tourn_output_path,
               tourn_name=""):
    """
    Play a match according to arguments passed.

    Arguments:
        player_1 (str): Name of the first player, e.g. "crowny-iv".
        rnd_1 (float):  Random factor applied to player 1.
                        None = 0.0
        player_2 (str): Name of the second player, e.g. "crowny-iii".
        rnd_2 (float):  Random factor applied to player 2.
                        None = 0.0
        board_name (str):
                        Initial position of the game to play.
                        None = "initial_position.cor"
        n_rounds (int): Number of rounds these players must play;
                        (if both are deterministic, n_rounds is made 1).
                        Each round = 2 games, alternating sides;
                        (if it's the same player and it's deterministic,
                        only 1 game is played).
        tourn_output_path (str):   
                        Full route to text file to update match results.
        tourn_name (str):
                        Name of the tournament (e.g. "I_Crown_Tournament")

    Returns:
        float:          Score obtained by player_1
        float:          Score obtained by player_2

    """
    # Retrieve players' data from their .yaml files.
    player_1_dict = main.read_player_data(player_1)
    player_2_dict = main.read_player_data(player_2)

    # Update players' parameters as needed, overriding original values.
    if rnd_1 is not None:
        player_1_dict["randomness"] = rnd_1
    if rnd_2 is not None:
        player_2_dict["randomness"] = rnd_2
    # Determine the games to actually play.
    is_deterministic = \
        player_1_dict["randomness"] == 0 and \
        player_2_dict["randomness"] == 0

    # Identify board position.
    dir_path = os.path.dirname(os.path.realpath(__file__))
    if board_name is None:
        board_file_name = None
    else:
        board_file_name = f"{dir_path}{GAMES_PATH}{board_name}"

    # Number of rounds:
    if is_deterministic:
        # Force one round if players have no randomness.
        n_rounds = 1
    # No need to change sides if 100% symmetric.
    n_turns = 1 if is_deterministic and player_1 == player_2 \
        else 2

    # Initialize players' list and scores (a dict. by name).
    player_set = [player_1_dict, player_2_dict]
    player_scores = [0.0, 0.0]

    # Play now all required rounds.
    game_type = "Match"
    for round in range(n_rounds):
        # Each round normally two turns (except full simmetry).
        for turn in range(n_turns):  # 1 or 2.
            # Play a game of the round between the two players.
            board = bd.Board(board_file_name)
            if not gp.is_legal_loaded_board(board):
                print(
                    f"Error: {board_file_name} is not a legal board for The Crown."
                )
                sys.exit(1)
            game_result, end_status, rec_file_path, metrics_file_path = \
                main.play_game(
                    board, board_file_name, player_set,
                    game_type=game_type, round=round + 1, tourn_name=tourn_name
                )
            # Check results and update scorings.
            assert(end_status != gp.ON_GOING), \
                "Error: game between {} and {} ended as 'ON_GOING'.".format(
                    player_1_dict["name"], player_2_dict["name"]
                )
            if game_result == gp.TXT_WHITE_WINS:
                score_w = 1
                score_b = 0
                player_scores[0] += 1
            elif game_result == gp.TXT_BLACK_WINS:
                score_w = 0
                score_b = 1
                player_scores[1] += 1
            else:
                score_w = 0.5
                score_b = 0.5
                player_scores[0] += 0.5
                player_scores[1] += 0.5

            # Update Tournament's tracking file
            with open(tourn_output_path, mode="a") as tourn_out_file:
                game_writer = csv.writer(tourn_out_file,
                                         delimiter=',',
                                         quotechar='"',
                                         quoting=csv.QUOTE_MINIMAL)
                game_writer.writerow([
                    player_set[0]["file_name"], player_set[0]["randomness"],
                    player_set[1]["file_name"], player_set[1]["randomness"],
                    board_name, n_rounds, score_w, score_b
                ])

            # Move game record file the tournament's directory .
            # rec_file_path is now '.../thecrown/output/<game-data>.txt
            rec_file_name = rec_file_path.split("/")[-1]  # <game-data>.txt
            new_file_path = "{}{}{}".format(dir_path, GAMES_RECORD_PATH,
                                            rec_file_name)
            shutil.move(rec_file_path, new_file_path)

            # Change turns if needed.
            if n_turns > 1:
                aux1, aux2 = player_set
                player_set = [aux2, aux1]
                aux1, aux2 = player_scores
                player_scores = [aux2, aux1]

    # Match ended.
    return player_scores[0], player_scores[1]
コード例 #8
0
pop_size = 30
n_enemies = 5
n_games = 5
mutation_chance = 0.05
generations = 100
population = [It() for i in range(pop_size)]

for generation in range(0, generations):
    print("Simulation generation " + str(generation) + "...")

    for one in population:
        enemies = random.sample(population, n_enemies)

        for enemy in enemies:
            one_s, enemy_s = play_game(one.play, enemy.play, N=n_games)
            one.score += one_s
            enemy.score += enemy_s

    population.sort(key=lambda x: x.score, reverse=True)
    strongest = population[0:5]

    new_population = []
    for i in range(pop_size):
        father = random.choice(strongest)
        mother = random.choice(strongest)

        crossover_point = random.randint(0, genome_size - 1)

        child = It()
        child.genome = father.genome[0:crossover_point] + mother.genome[
コード例 #9
0
def show_customization():

    pygame.display.set_caption('Customization Menu')

    quit_status = 0
    easy_selected = 1
    ship_location = classic_ship_location

    textbox_selected = 0

    player1name = 'PLAYER 1'
    player2name = 'PLAYER 2'

    menu_background = pygame.image.load(menu_background_image)
    menu_background_rect = menu_background.get_rect()

    title_label = pygame.font.Font(menu_font, 70).render('{0}'.format('Customization'), True, WHITE)
    title_rect = title_label.get_rect()
    title_rect.centerx = WIDTH * 1 / 2
    title_rect.centery = HEIGHT * 1 / 6

    # creates the difficulty label
    difficulty_label = pygame.font.Font(menu_font, 40).render('{0}'.format('Difficulty'), True, WHITE)
    difficulty_rect = difficulty_label.get_rect()
    difficulty_rect.centerx = WIDTH * 1 / 6
    difficulty_rect.centery = HEIGHT * 1 / 3

    # creates the sound on label
    easy_label = pygame.font.Font(menu_font, 30).render('{0}'.format('Easy'), True, WHITE)
    easy_rect = easy_label.get_rect()
    easy_rect.centerx = WIDTH * 1 / 10
    easy_rect.centery = HEIGHT * 5 / 9

    # creates the sound off label
    hard_label = pygame.font.Font(menu_font, 30).render('{0}'.format('Hard'), True, WHITE)
    hard_rect = hard_label.get_rect()
    hard_rect.centerx = WIDTH * 1 / 10
    hard_rect.centery = HEIGHT * 5 / 7
    
    # creates the ship label
    ship_label = pygame.font.Font(menu_font, 40).render('{0}'.format('Ship'), True, WHITE)
    ship_rect = ship_label.get_rect()
    ship_rect.centerx = WIDTH * 1 / 2
    ship_rect.centery = HEIGHT * 1 / 3

    angle_for_ship = "/PlayerShip0.0.png"

    classic_boat_image = classic_ship_location + angle_for_ship
    classic_boat = pygame.image.load(classic_boat_image)
    classic_boat = pygame.transform.scale(classic_boat, (menu_ship_scale, menu_ship_scale))
    classic_boat_rect = classic_boat.get_rect()
    classic_boat_rect.centerx = WIDTH * 1/2
    classic_boat_rect.centery = HEIGHT * 4 / 9 + 10
    
    michigan_boat_image = maize_and_blue_ship_location + angle_for_ship
    michigan_boat = pygame.image.load(michigan_boat_image)
    michigan_boat = pygame.transform.scale(michigan_boat, (menu_ship_scale, menu_ship_scale))
    michigan_boat_rect = michigan_boat.get_rect()
    michigan_boat_rect.centerx = WIDTH * 1 / 2
    michigan_boat_rect.centery = HEIGHT * 5 / 9 + 10
    
    neon_boat_image = neon_ship_location + angle_for_ship
    neon_boat = pygame.image.load(neon_boat_image)
    neon_boat = pygame.transform.scale(neon_boat, (menu_ship_scale, menu_ship_scale))
    neon_boat_rect = neon_boat.get_rect()
    neon_boat_rect.centerx = WIDTH * 1 / 2
    neon_boat_rect.centery = HEIGHT * 2 / 3 + 10
    
    ship_checkbox1 = ControlBox(checkbox_image, checkbox_selected_image, (WIDTH * 13 / 20, HEIGHT * 4 / 9 + 10),
                                (checkbox_size, checkbox_size), True)
    ship_checkbox2 = ControlBox(checkbox_image, checkbox_selected_image, (WIDTH * 13 / 20, HEIGHT * 5 / 9 + 10),
                                (checkbox_size, checkbox_size))
    ship_checkbox3 = ControlBox(checkbox_image, checkbox_selected_image, (WIDTH * 13 / 20, HEIGHT * 6 / 9 + 10),
                                (checkbox_size, checkbox_size))

    # creates the names label
    names_label = pygame.font.Font(menu_font, 40).render('{0}'.format('Names'), True, WHITE)
    names_rect = names_label.get_rect()
    names_rect.centerx = WIDTH * 6 / 7
    names_rect.centery = HEIGHT * 1 / 3

    # creates the player 1 label
    player1_label = pygame.font.Font(menu_font, 20).render('{0}'.format('Player 1'), True, WHITE)
    player1_rect = player1_label.get_rect()
    player1_rect.centerx = WIDTH * 12 / 14
    player1_rect.centery = HEIGHT * 1 / 2

    # creates the player 2 label
    player2_label = pygame.font.Font(menu_font, 20).render('{0}'.format('Player 2'), True, WHITE)
    player2_rect = player2_label.get_rect()
    player2_rect.centerx = WIDTH * 12 / 14
    player2_rect.centery = HEIGHT * 9 / 14 + 10

    checkbox = ControlBox(checkbox_image, checkbox_selected_image, (WIDTH / 4, HEIGHT * 5 / 9),
                          (checkbox_size, checkbox_size), True)
    checkbox2 = ControlBox(checkbox_image, checkbox_selected_image, (WIDTH / 4, HEIGHT * 5 / 7),
                           (checkbox_size, checkbox_size))

    # creates the player 1 box
    textbox = ControlBox(textbox_image, textbox_highlighted_image, (WIDTH * 12 / 14, HEIGHT * 5 / 9),
                         (textbox_width, textbox_height))
    textbox2 = ControlBox(textbox_image, textbox_highlighted_image, (WIDTH * 12 / 14, HEIGHT * 5 / 7),
                          (textbox_width, textbox_height))

    # creates the play label
    play_label = pygame.font.Font(menu_font, 50).render('{0}'.format('Play!'), True, WHITE)
    play_rect = play_label.get_rect()
    play_rect.centerx = WIDTH * 1 / 2
    play_rect.centery = HEIGHT * 5 / 6

    play_button = ControlBox(play_button_image, None, (WIDTH / 2, HEIGHT * 14 / 15), (button_size, button_size))
    back_button = ControlBox(back_button_image, None, (50, 50), (button_size, button_size))

    while quit_status != 1:
        screen.blit(menu_background, menu_background_rect)

        m_pos = pygame.mouse.get_pos()
        # checks to see if the user quits
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                return
            if event.type == KEYDOWN and (event.key == K_TAB):
                if textbox_selected == 1:
                    if player1name == "":
                        player1name = "PLAYER 1"
                    textbox_selected = 2
                    textbox.selected = False
                    textbox2.selected = True
                    if player2name == "PLAYER 2":
                        player2name = ""
                elif textbox_selected == 2:
                    if player1name == "PLAYER 1":
                        player1name = ""
                    textbox_selected = 1
                    textbox.selected = True
                    textbox2.selected = False
                    if player2name == "":
                        player2name = "PLAYER 2"

            if event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
                if back_button.is_mouse_selection(m_pos):
                    return
                if textbox.is_mouse_selection(m_pos):
                    textbox_selected = 1
                    textbox2.selected = False
                    if player2name == "":
                        player2name = "PLAYER 2"
                    if player1name == "PLAYER 1":
                        player1name = ""

                elif textbox2.is_mouse_selection(m_pos):
                    textbox.selected = False
                    if player1name == "":
                        player1name = "PLAYER 1"
                    if player2name == "PLAYER 2":
                        player2name = ""
                    textbox_selected = 2

                if play_button.is_mouse_selection(m_pos):
                    infile = open(settings_file, "r")
                    array = infile.readlines()
                    if player1name == "":
                        player1name = "PLAYER 1"
                    if player2name == "":
                        player2name = "PLAYER 2"
                    main.play_game(player1name, player2name, easy_selected, array[0], array[1], array[2], ship_location)
                    return
                elif easy_selected == 1 and checkbox2.is_mouse_selection(m_pos):
                    easy_selected = 0
                    checkbox.selected = False
                elif easy_selected == 0 and checkbox.is_mouse_selection(m_pos):
                    easy_selected = 1
                    checkbox2.selected = False
                elif ship_checkbox1.is_mouse_selection(m_pos):
                    ship_checkbox1.selected = True
                    ship_checkbox2.selected = False
                    ship_checkbox3.selected = False
                    ship_location = classic_ship_location
                elif ship_checkbox2.is_mouse_selection(m_pos):
                    ship_checkbox2.selected = True
                    ship_checkbox1.selected = False
                    ship_checkbox3.selected = False
                    ship_location = maize_and_blue_ship_location
                elif ship_checkbox3.is_mouse_selection(m_pos):
                    ship_checkbox3.selected = True
                    ship_checkbox2.selected = False
                    ship_checkbox1.selected = False
                    ship_location = neon_ship_location
            if event.type == KEYDOWN:
                if textbox_selected == 1:
                    player1name = check_keys(player1name, event.key)
                elif textbox_selected == 2:
                    player2name = check_keys(player2name, event.key)

        screen.blit(title_label, title_rect)
        screen.blit(difficulty_label, difficulty_rect)
        screen.blit(easy_label, easy_rect)
        screen.blit(hard_label, hard_rect)
        
        screen.blit(ship_label, ship_rect)
        screen.blit(classic_boat, classic_boat_rect)
        screen.blit(michigan_boat, michigan_boat_rect)
        screen.blit(neon_boat, neon_boat_rect)
        screen.blit(ship_checkbox1.get_image(), ship_checkbox1.rect)
        screen.blit(ship_checkbox2.get_image(), ship_checkbox2.rect)
        screen.blit(ship_checkbox3.get_image(), ship_checkbox3.rect)

        screen.blit(names_label, names_rect)
        screen.blit(player1_label, player1_rect)
        screen.blit(player2_label, player2_rect)

        screen.blit(play_label, play_rect)
        screen.blit(play_button.image, play_button.rect)
        screen.blit(back_button.image, back_button.rect)

        screen.blit(checkbox.get_image(), checkbox.rect)
        screen.blit(checkbox2.get_image(), checkbox2.rect)
        screen.blit(textbox.get_image(), textbox.rect)
        screen.blit(textbox2.get_image(), textbox2.rect)

        # creates the player 1 name label
        player1name_label = pygame.font.Font(menu_font, 18).render('{0}'.format(player1name), True, BLACK)
        player1name_rect = player1name_label.get_rect()
        player1name_rect.left = WIDTH * 10/13 + 5
        player1name_rect.centery = HEIGHT * 5 / 9

        # creates the player 2 name label
        player2name_label = pygame.font.Font(menu_font, 18).render('{0}'.format(player2name), True, BLACK)
        player2name_rect = player2name_label.get_rect()
        player2name_rect.left = WIDTH * 10/13 + 5
        player2name_rect.centery = HEIGHT * 5 / 7

        screen.blit(player1name_label, player1name_rect)
        screen.blit(player2name_label, player2name_rect)
        pygame.display.flip()
コード例 #10
0
class HiddenPrints:
    def __enter__(self):
        self._original_stdout = sys.stdout
        sys.stdout = open(os.devnull, "w")

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.close()
        sys.stdout = self._original_stdout


print(f"We are going to play {NUMBER_OF_GAMES} games. Please stand by.", end="\n\n")
outcomes = []
with HiddenPrints():
    for _ in range(NUMBER_OF_GAMES):
        outcomes.append(play_game())

outcomes.sort()
print(f"The best game had {str(min(outcomes))} remaining.")
print(f"The worst game had {str(max(outcomes))} remaining.")
print(f"The average game had {str(mean(outcomes))} cards remaining.")
print(f"The median game had {str(median(outcomes))} cards remaining.")
try:
    print(f"The mode was {str(mode(outcomes))} cards remaining.")
except:
    print("There was more than one most common value, so there is no mode.")

wins = outcomes.count(0)
counts = Counter(outcomes)
excellents = 0
for x in range(0, 11):