Ejemplo n.º 1
0
def play_game():
    """
    Use this function if you want to test a single game instance and control lots of things. For experiments, we will directly
    call some of the functions in gameplay from test_harness.py.

    This is where everything begins. Assign decision agents to your players, set up the board and start simulating! You can
    control any number of players you like, and assign the rest to the simple agent. We plan to release a more sophisticated
    but still relatively simple agent soon.
    :return: String. the name of the player who won the game, if there was a winner, otherwise None.
    """

    try:
        os.makedirs('../single_tournament/')
        print('Creating folder and logging gameplay.')
    except:
        print('Logging gameplay.')

    logger = log_file_create('../single_tournament/seed_6.log')
    player_decision_agents = dict()
    # for p in ['player_1','player_3']:
    #     player_decision_agents[p] = simple_decision_agent_1.decision_agent_methods
    player_decision_agents['player_1'] = Agent(**background_agent_v1.decision_agent_methods)
    player_decision_agents['player_2'] = Agent(**background_agent_v1.decision_agent_methods)
    player_decision_agents['player_3'] = Agent(**background_agent_v1.decision_agent_methods)
    player_decision_agents['player_4'] = Agent(**background_agent_v1.decision_agent_methods)
    game_elements = set_up_board('../monopoly_game_schema_v1-2.json',
                                 player_decision_agents)
    inject_novelty(game_elements)

    winner = simulate_game_instance(game_elements)
    logger.debug("GAME OVER")

    handlers_copy = logger.handlers[:]
    for handler in handlers_copy:
            logger.removeHandler(handler)
            handler.close()
            handler.flush()
    return winner
Ejemplo n.º 2
0
def play_tournament_without_novelty(tournament_log_folder=None,
                                    meta_seed=5,
                                    num_games=100):
    """
    Tournament logging is not currently supported, but will be soon.
    :param tournament_log_folder: String. The path to a folder.
    :param meta_seed: This is the seed we will use to generate a sequence of seeds, that will (in turn) spawn the games in gameplay/simulate_game_instance
    :param num_games: The number of games to simulate in a tournament
    :return: None. Will print out the win-loss metrics, and will write out game logs
    """

    if not tournament_log_folder:
        print(
            "No logging folder specified, cannot log tournaments. Provide a logging folder path."
        )
        raise Exception

    np.random.seed(meta_seed)
    big_list = list(range(0, 1000000))
    np.random.shuffle(big_list)
    tournament_seeds = big_list[0:num_games]
    winners = list()
    count = 1

    folder_name = "../tournament_logs" + tournament_log_folder
    try:
        os.makedirs(folder_name)
        print('Logging gameplay')
    except:
        print(
            'Given logging folder already exists. Clearing folder before logging new files.'
        )
        shutil.rmtree(folder_name)
        os.makedirs(folder_name)

    metadata_dict = {
        "function": "play_tournament_without_novelty",
        "parameters": {
            "meta_seed": meta_seed,
            "num_game": num_games
        }
    }

    json_filename = folder_name + "tournament_meta_data.json"
    out_file = open(json_filename, "w")
    json.dump(metadata_dict, out_file, indent=4)
    out_file.close()
    for t in tournament_seeds:
        print('Logging gameplay for seed: ', str(t),
              ' ---> Game ' + str(count))
        filename = folder_name + "meta_seed_" + str(
            meta_seed) + '_num_games_' + str(count) + '.log'
        logger = log_file_create(filename)
        winners.append(gameplay_server.play_game_in_tournament(t))
        handlers_copy = logger.handlers[:]
        for handler in handlers_copy:
            logger.removeHandler(handler)
            handler.close()
            handler.flush()
        count += 1

    print(winners)
    wins = 0
    for i in winners:
        if i == 'player_1':
            wins += 1

    print(wins)
Ejemplo n.º 3
0
def play_game():
    """
    Use this function if you want to test a single game instance and control lots of things. For experiments, we will directly
    call some of the functions in gameplay from test_harness.py.

    This is where everything begins. Assign decision agents to your players, set up the board and start simulating! You can
    control any number of players you like, and assign the rest to the simple agent. We plan to release a more sophisticated
    but still relatively simple agent soon.
    :return: String. the name of the player who won the game, if there was a winner, otherwise None.
    """

    try:
        os.makedirs('../single_tournament/')
        print('Creating folder and logging gameplay.')
    except:
        print('Logging gameplay.')

    logger = log_file_create('../single_tournament/seed_6.log')
    player_decision_agents = dict()
    # for p in ['player_1','player_3']:
    #     player_decision_agents[p] = simple_decision_agent_1.decision_agent_methods

    player_decision_agents['player_1'] = Agent(
        **background_agent_v3_1.decision_agent_methods)
    player_decision_agents['player_2'] = Agent(
        **background_agent_v3_1.decision_agent_methods)
    player_decision_agents['player_3'] = Agent(
        **background_agent_v3_1.decision_agent_methods)
    player_decision_agents['player_4'] = Agent(
        **background_agent_v3_1.decision_agent_methods)

    game_elements = set_up_board('../monopoly_game_schema_v1-2.json',
                                 player_decision_agents)

    #Comment out the above line and uncomment the piece of code to read the gameboard state from an existing json file so that
    #the game starts from a particular game state instead of initializing the gameboard with default start values.
    #Note that the novelties introduced in that particular game which was saved to file will be loaded into this game board as well.
    '''
    logger.debug("Loading gameboard from an existing game state that was saved to file.")
    infile = '../current_gameboard_state.json'
    game_elements = read_write_current_state.read_in_current_state_from_file(infile, player_decision_agents)
    '''

    inject_novelty(game_elements)

    if player_decision_agents['player_1'].startup(game_elements) == flag_config_dict['failure_code'] or \
            player_decision_agents['player_2'].startup(game_elements) == flag_config_dict['failure_code'] or \
            player_decision_agents['player_3'].startup(game_elements) == flag_config_dict['failure_code'] or \
            player_decision_agents['player_4'].startup(game_elements) == flag_config_dict['failure_code']:
        logger.error("Error in initializing agents. Cannot play the game.")
        return None
    else:
        logger.debug("Sucessfully initialized all player agents.")
        winner = simulate_game_instance(game_elements)
        if player_decision_agents['player_1'].shutdown() == flag_config_dict['failure_code'] or \
            player_decision_agents['player_2'].shutdown() == flag_config_dict['failure_code'] or \
            player_decision_agents['player_3'].shutdown() == flag_config_dict['failure_code'] or \
            player_decision_agents['player_4'].shutdown() == flag_config_dict['failure_code']:
            logger.error("Error in agent shutdown.")
            handlers_copy = logger.handlers[:]
            for handler in handlers_copy:
                logger.removeHandler(handler)
                handler.close()
                handler.flush()
            return None
        else:
            logger.debug("All player agents have been shutdown. ")
            logger.debug("GAME OVER")
            handlers_copy = logger.handlers[:]
            for handler in handlers_copy:
                logger.removeHandler(handler)
                handler.close()
                handler.flush()
            return winner
Ejemplo n.º 4
0
def play_tournament_with_novelty_1(tournament_log_folder=None,
                                   meta_seed=5,
                                   num_games=100,
                                   novelty_index=23):
    """

    :param tournament_log_folder:
    :param meta_seed:
    :param num_games:
    :param novelty_index: an integer between 1 and num_games-1. We will play this many games BEFORE introducing novelty.
    :return:
    """

    if not tournament_log_folder:
        print(
            "No logging folder specified, cannot log tournaments. Provide a logging folder path."
        )
        raise Exception

    np.random.seed(meta_seed)
    big_list = list(range(0, 1000000))
    np.random.shuffle(big_list)
    tournament_seeds = big_list[0:num_games]
    winners = list()
    count = 1

    folder_name = "../tournament_logs" + tournament_log_folder
    try:
        os.makedirs(folder_name)
        print('Logging gameplay')
    except:
        print(
            'Given logging folder already exists. Clearing folder before logging new files.'
        )
        shutil.rmtree(folder_name)
        os.makedirs(folder_name)

    metadata_dict = {
        "function": "play_tournament_with_novelty_1",
        "parameters": {
            "meta_seed": meta_seed,
            "novelty_index": novelty_index,
            "num_game": num_games
        }
    }

    json_filename = folder_name + "tournament_meta_data.json"
    out_file = open(json_filename, "w")
    json.dump(metadata_dict, out_file, indent=4)
    out_file.close()

    for t in range(0, novelty_index):
        print('Logging gameplay without novelty for seed: ', str(t),
              ' ---> Game ' + str(count))
        filename = folder_name + "meta_seed_" + str(
            meta_seed) + '_without_novelty' + '_num_games_' + str(
                count) + '.log'
        logger = log_file_create(filename)
        winners.append(
            gameplay_server.play_game_in_tournament(tournament_seeds[t]))
        handlers_copy = logger.handlers[:]
        for handler in handlers_copy:
            logger.removeHandler(handler)
            handler.close()
            handler.flush()
        count += 1

    new_winners = list()
    for t in range(novelty_index, len(tournament_seeds)):
        print('Logging gameplay with novelty for seed: ', str(t),
              ' ---> Game ' + str(count))
        filename = folder_name + "meta_seed_" + str(
            meta_seed) + '_with_novelty' + '_num_games_' + str(count) + '.log'
        logger = log_file_create(filename)
        new_winners.append(
            gameplay_server.play_game_in_tournament(tournament_seeds[t],
                                                    class_novelty_1))
        handlers_copy = logger.handlers[:]
        for handler in handlers_copy:
            logger.removeHandler(handler)
            handler.close()
            handler.flush()
        count += 1

    print('pre_novelty winners', winners)
    print('post_novelty_winners', new_winners)
Ejemplo n.º 5
0
    
    granularityNovelty = novelty_generator.GranularityRepresentationNovelty()
    granularityNovelty.granularity_novelty(current_gameboard, current_gameboard['location_objects']['Baltic Avenue'], 6)
    granularityNovelty.granularity_novelty(current_gameboard, current_gameboard['location_objects']['States Avenue'], 20)
    granularityNovelty.granularity_novelty(current_gameboard, current_gameboard['location_objects']['Tennessee Avenue'], 27)

    spatialNovelty = novelty_generator.SpatialRepresentationNovelty()
    spatialNovelty.color_reordering(current_gameboard, ['Boardwalk', 'Park Place'], 'Blue')

    granularityNovelty.granularity_novelty(current_gameboard, current_gameboard['location_objects']['Park Place'], 52)
    '''

try:
    os.makedirs('../single_tournament/')
    print('Creating folder and logging gameplay.')
except:
    print('Logging gameplay.')

##Logs game play in the single_tournament folder
logger = log_file_create('../single_tournament/seed_6.log')
player_decision_agents = dict()
player_decision_agents['player_1'] = Agent(**background_agent_v1.decision_agent_methods)
player_decision_agents['player_2'] = Agent(**background_agent_v2.decision_agent_methods)
player_decision_agents['player_3'] = Agent(**background_agent_v3.decision_agent_methods)
player_decision_agents['player_4'] = Agent(**background_agent_v1.decision_agent_methods)
game_elements = set_up_board('../monopoly_game_schema_v1-2.json',
                             player_decision_agents)
inject_class_novelty_1(game_elements)
MyMainApp(game_elements).run()