def test_canExtractPlayers(self):
     sc2reader.configure(debug=True)
     print os.getcwd()
     replay = sc2reader.load_replay('data/Akilon Wastes (2).SC2Replay', load_level=4)
     for player in replay.players:
         #if player.is_human:
         print "Player: %s (%s) - %s" % (player.name, player.play_race, player.result)
Exemple #2
0
    def __init__(self, *args, **kwargs):
        super(Command, self).__init__(*args, **kwargs)

        self.import_count = {
            'Map': 0,
            'Player': 0,
            'Game': 0,
            'GameTeam': 0,
            'GamePlayer': 0,
        }

        sc2reader.configure(directory='', exclude=['Customs',], followLinks=False, depth=10)
Exemple #3
0
def main():
    paths = sys.argv[1:]

    #You can create a factory with a custom configuration
    sc2 = SC2Factory(
            directory=replaypath,
            exclude=['Customs','Pros'],
            followlinks=True
        )
    sc2.configure(depth=1)
        
    #Or configure the default factory: 
    sc2reader.configure(
        directory=mainpath,
        exclude=['Customs','Pros'],
        depth=1, #Max recursion depth
        followlinks=True #Recurse on subdirectories
    )

    replay = sc2reader.load_replay('derp.SC2Replay')
    #replays = sc2reader.load_replays()
    #replays = sc2reader.load_replays(replaypath)
    
    #Print out all event types and and example of their attributes
    #print json.dumps(getEventTypes(replay, "game"), indent = 2)

    #Print out the attributes contained in the sc2reader class
    #printFormattedList(getAttributesWithValues(replay, True))

    #Print out the abilities used in the replay
    #print json.dumps(getAbilityIDs(replay), indent = 2)

    #Print out command events in the replay in chronological order
    #print printFormattedList(getCommandEvents(replay))
    
    #Add new ability IDs to the json archive
    archiveAbilityIDs('abilities.txt')
 def test_canOpenReplay(self):
     sc2reader.configure(debug=True)
     print os.getcwd()
     replay = sc2reader.load_replay('data/Akilon Wastes (2).SC2Replay')
     print replay
    def ExtractGameInformation(cls, file_name, match_id=None):
        """
        Creates a Game object from a replay file.
        If match_id is not specified a new match will be created based on data from provided replay.
        """
        sc2reader.configure(debug=True)
        replay = sc2reader.load_replay(file_name, load_level=4)

        # TODO: delete this logging
        logging.info('Game Type: ' + replay.game_type)
        logging.info('Category: ' + replay.category)
        for rplayer in replay.players:
            logging.info('Archon Leader Id: ' + str(rplayer.archon_leader_id))

        season_id = lookup_current_season().season_id

        #Gather the player performance stats
        all_player_stats = []
        winning_player_ranks = []
        losing_player_ranks = []
        is_archon_mode = False

        # compile list of players while filtering out ai/observers/referees
        replay_players = [replay_player for replay_player in replay.players
                          if replay_player.is_human and not replay_player.is_observer and not replay_player.is_referee]

        for replay_player in replay_players:
            player_stats = PlayerStatsModel()
            player_stats.battle_net_name = replay_player.name
            player_stats.was_random = replay_player.pick_race.lower() == Keys.RANDOM
            player_stats.race = replay_player.play_race
            if not replay_player.result:
                raise ValueError('Replay must be uploaded by winning player(s).')
            player_stats.won = replay_player.result.lower() == Keys.WIN
            player_stats.handicap = replay_player.handicap
            player_stats.season_id = season_id
            all_player_stats.append(player_stats)

            # create player and rank for this season if one does not exist
            PlayerModel.get_or_create(battle_net_name=replay_player.name)
            player_rank = PlayerRankModel.get_or_create(player_stats.battle_net_name, season_id)
            player_rank.last_game_played = replay.start_time

            if replay.game_type == '2v2':
                player_rank.last_2v2_game_played = replay.start_time

            if player_stats.won:
                winning_player_ranks.append(player_rank)
            else:
                losing_player_ranks.append(player_rank)
            logging.debug("Player: %s (%s) - %s" % (replay_player.name, replay_player.play_race, replay_player.result))

            if replay_player.archon_leader_id:
                # if one of the players is an archon leader than game was played in archon mode
                is_archon_mode = True

            player_rank.put()

        # if no match was provided then create a new one from replay information
        if match_id:
            match = get_match(match_id, season_id)
        else:
            match = create_match([rank.battle_net_name for rank in winning_player_ranks],
                                 [rank.battle_net_name for rank in losing_player_ranks])

        player_names = [player.name for player in replay.players]
        game_key = GameModel.generate_key(replay.start_time, player_names, match.match_id, season_id)
        existing_game = game_key.get()
        if existing_game:
            raise ValueError('This replay has already been uploaded.')

        #Gather the game stats
        game = GameModel(key=game_key)
        game.game_length_seconds = replay.real_length.seconds
        game.game_time = replay.start_time
        game.release = replay.release_string
        game.map_name = replay.map_name
        game.speed = replay.speed
        game.players = all_player_stats
        game.type = replay.real_type
        game.is_archon_mode = is_archon_mode
        game.put()

        replay_entity = ReplayModel()
        file_name.seek(0)
        replay_entity.replay_file = file_name.read()
        replay_entity.key = ReplayModel.build_key(game.game_id)
        replay_entity.put()

        # update_player_ranks(winning_player_ranks, losing_player_ranks)

        match.games_played += 1
        winning_battle_net_names = [player.battle_net_name for player in game.players if player.won]
        if any([bnet_name for bnet_name in match.team1_battle_net_names if bnet_name in winning_battle_net_names]):
            match.team1_wins += 1
        elif any([bnet_name for bnet_name in match.team2_battle_net_names if bnet_name in winning_battle_net_names]):
            match.team2_wins += 1
        match.put()

        #Return the game model
        return game
Exemple #6
0
def main(argv):
    test_flag = False
    help_message = """
    Available options are:
        -h help: Help (display this message)
        -t test: Run a test on a single replay"
        """

    sc2reader.configure(depth=1)

    replays = sc2reader.load_replays('/home/steve/starcraft_replays',
                                     load_level=2)

    history = {
        "steve": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "ryan_s": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "kevin": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "stephen": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "laura": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "j": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "colin": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "bo": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "george": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "ryan_k": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "ai_very_easy": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "ai_easy": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "ai_medium": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "ai_hard": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "ai_harder": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "ai_very_hard": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "ai_elite": {
            "protoss": [],
            "terran": [],
            "zerg": []
        },
        "ai_insane": {
            "protoss": [],
            "terran": [],
            "zerg": []
        }
    }

    valid_replay_length = 0

    sorted_replays = sorted(replays, key=attrgetter('unix_timestamp'))

    for replay in sorted_replays:
        pprint(
            f"Date: {datetime.utcfromtimestamp(replay.unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')}"
        )
        pprint(f"Teams: {replay.teams}")
        if replay.winner is None:
            pprint("No winner found?")
            continue
        pprint(f"Winner: {replay.winner.players}")
        rating_groups = []
        if not check_if_valid_teams(replay):
            continue
        for team in replay.teams:
            ratings_group = {}
            for p in team.players:
                if p.is_human and p.name in players:
                    ratings_group[p] = getattr(
                        players[p.name], p.play_race.lower()).current_trueskill
                elif not p.is_human:
                    ratings_group[p] = getattr(
                        players[f"A.I. ({p.difficulty})"],
                        p.play_race.lower()).current_trueskill
                else:
                    break
            if team.result == 'Win':
                rating_groups.insert(0, ratings_group)
            else:
                rating_groups.append(ratings_group)
        if len(ratings_group) > 1:
            rated_rating_groups = rate(rating_groups)
        else:
            continue
        valid_replay_length += 1
        for i, team in enumerate(rated_rating_groups):
            for player, rating in team.items():
                if player.is_human:
                    player_race = getattr(players[player.name],
                                          player.play_race.lower())
                else:
                    player_race = getattr(
                        players[f"A.I. ({player.difficulty})"],
                        player.play_race.lower())
                player_race.current_trueskill = rating

        history["steve"]["protoss"].append(steve.protoss.current_trueskill.mu)
        history["steve"]["terran"].append(steve.terran.current_trueskill.mu)
        history["steve"]["zerg"].append(steve.zerg.current_trueskill.mu)
        history["ryan_s"]["protoss"].append(
            ryan_s.protoss.current_trueskill.mu)
        history["ryan_s"]["terran"].append(ryan_s.terran.current_trueskill.mu)
        history["ryan_s"]["zerg"].append(ryan_s.zerg.current_trueskill.mu)
        history["kevin"]["protoss"].append(kevin.protoss.current_trueskill.mu)
        history["kevin"]["terran"].append(kevin.terran.current_trueskill.mu)
        history["kevin"]["zerg"].append(kevin.zerg.current_trueskill.mu)
        history["stephen"]["protoss"].append(
            stephen.protoss.current_trueskill.mu)
        history["stephen"]["terran"].append(
            stephen.terran.current_trueskill.mu)
        history["stephen"]["zerg"].append(stephen.zerg.current_trueskill.mu)
        history["laura"]["protoss"].append(laura.protoss.current_trueskill.mu)
        history["laura"]["terran"].append(laura.terran.current_trueskill.mu)
        history["laura"]["zerg"].append(laura.zerg.current_trueskill.mu)
        history["j"]["protoss"].append(j.protoss.current_trueskill.mu)
        history["j"]["terran"].append(j.terran.current_trueskill.mu)
        history["j"]["zerg"].append(j.zerg.current_trueskill.mu)
        history["colin"]["protoss"].append(colin.protoss.current_trueskill.mu)
        history["colin"]["terran"].append(colin.terran.current_trueskill.mu)
        history["colin"]["zerg"].append(colin.zerg.current_trueskill.mu)
        history["bo"]["protoss"].append(bo.protoss.current_trueskill.mu)
        history["bo"]["terran"].append(bo.terran.current_trueskill.mu)
        history["bo"]["zerg"].append(bo.zerg.current_trueskill.mu)
        history["george"]["protoss"].append(
            george.protoss.current_trueskill.mu)
        history["george"]["terran"].append(george.terran.current_trueskill.mu)
        history["george"]["zerg"].append(george.zerg.current_trueskill.mu)
        history["ryan_k"]["protoss"].append(
            ryan_k.protoss.current_trueskill.mu)
        history["ryan_k"]["terran"].append(ryan_k.terran.current_trueskill.mu)
        history["ryan_k"]["zerg"].append(ryan_k.zerg.current_trueskill.mu)
        history["ai_very_easy"]["protoss"].append(
            ai_very_easy.protoss.current_trueskill.mu)
        history["ai_very_easy"]["terran"].append(
            ai_very_easy.terran.current_trueskill.mu)
        history["ai_very_easy"]["zerg"].append(
            ai_very_easy.zerg.current_trueskill.mu)
        history["ai_easy"]["protoss"].append(
            ai_easy.protoss.current_trueskill.mu)
        history["ai_easy"]["terran"].append(
            ai_easy.terran.current_trueskill.mu)
        history["ai_easy"]["zerg"].append(ai_easy.zerg.current_trueskill.mu)
        history["ai_medium"]["protoss"].append(
            ai_medium.protoss.current_trueskill.mu)
        history["ai_medium"]["terran"].append(
            ai_medium.terran.current_trueskill.mu)
        history["ai_medium"]["zerg"].append(
            ai_medium.zerg.current_trueskill.mu)
        history["ai_hard"]["protoss"].append(
            ai_hard.protoss.current_trueskill.mu)
        history["ai_hard"]["terran"].append(
            ai_hard.terran.current_trueskill.mu)
        history["ai_hard"]["zerg"].append(ai_hard.zerg.current_trueskill.mu)
        history["ai_harder"]["protoss"].append(
            ai_harder.protoss.current_trueskill.mu)
        history["ai_harder"]["terran"].append(
            ai_harder.terran.current_trueskill.mu)
        history["ai_harder"]["zerg"].append(
            ai_harder.zerg.current_trueskill.mu)
        history["ai_very_hard"]["protoss"].append(
            ai_very_hard.protoss.current_trueskill.mu)
        history["ai_very_hard"]["terran"].append(
            ai_very_hard.terran.current_trueskill.mu)
        history["ai_very_hard"]["zerg"].append(
            ai_very_hard.zerg.current_trueskill.mu)
        history["ai_elite"]["protoss"].append(
            ai_elite.protoss.current_trueskill.mu)
        history["ai_elite"]["terran"].append(
            ai_elite.terran.current_trueskill.mu)
        history["ai_elite"]["zerg"].append(ai_elite.zerg.current_trueskill.mu)
        history["ai_insane"]["protoss"].append(
            ai_insane.protoss.current_trueskill.mu)
        history["ai_insane"]["terran"].append(
            ai_insane.terran.current_trueskill.mu)
        history["ai_insane"]["zerg"].append(
            ai_insane.zerg.current_trueskill.mu)

    for player in history:
        ax_num = 0
        fig = plt.figure(figsize=(12, 12))
        for race in ["protoss", "terran", "zerg"]:
            ax_num += 1
            ax = fig.add_subplot(3, 1, ax_num)
            ax.set(xlim=(1, valid_replay_length + 1), ylim=(0, 50))
            ax.set_ylabel('TrueSkill')
            ax.plot(range(0, valid_replay_length),
                    list(
                        map(lambda x: x.current_trueskill,
                            history[player][race])),
                    label=f"{player} as {race}")
            ax.set_title(f"{player} as {race}")
            pprint(
                f"{player} as {race} TrueSkill mu: {round(history[player][race][-1].current_trueskill.mu, 2)}, sigma: {round(history[player][race][-1].current_trueskill.sigma, 2)}"
            )
        image_file = Path(f"plots/{player.replace(' ', '_')}")
        fig.savefig(image_file)

    try:
        opts, args = getopt.getopt(argv, "", [
            "help", "test", "steve=", "ryan_s=", "ryan_k=", "colin=", "bo=",
            "j=", "laura=", "kevin=", "stephen=", "george="
        ])
    except getopt.GetoptError:
        print(help_message)
        sys.exit(2)

    players_array = []

    for opt, arg in opts:
        if opt in ("--steve"):
            player_name = "steve"
        elif opt in ("--ryan_s"):
            player_name = "ryan_s"
        elif opt in ("--ryan_k"):
            player_name = "ryan_k"
        elif opt in ("--colin"):
            player_name = "colin"
        elif opt in ("--bo"):
            player_name = "bo"
        elif opt in ("--j"):
            player_name = "j"
        elif opt in ("--laura"):
            player_name = "laura"
        elif opt in ("--kevin"):
            player_name = "kevin"
        elif opt in ("--stephen"):
            player_name = "stephen"
        elif opt in ("--george"):
            player_name = "george"
        if arg == "protoss":
            player_race = "protoss"
        elif arg == "terran":
            player_race = "terran"
        elif arg == "zerg":
            player_race = "zerg"
        players_array.append({
            "name":
            player_name,
            "race":
            player_race,
            "rating":
            getattr(globals()[player_name], player_race).current_trueskill
        })

    total_sum = sum(map(lambda x: x['rating'].mu, players_array))
    teams = []
    for i in range(1, len(players_array)):
        combinations = itertools.combinations(players_array, i)
        for combo in combinations:
            for player in combo:
                print(f"{player['name']} {player['race']}", end=", ")
            team_1_sum = sum(map(lambda x: x['rating'].mu, combo))
            print(team_1_sum)
            team_2_sum = total_sum - team_1_sum
            difference = team_1_sum - team_2_sum
            print(f"Difference: {difference}")
            teams.append({
                'team': (list(map(lambda x: x['name'],
                                  combo)), list(map(lambda x: x['race'],
                                                    combo))),
                'difference':
                abs(difference)
            })
    sorted_teams = sorted(teams, key=lambda x: x['difference'])
    for i, team in enumerate(sorted_teams):
        if i % 2 == 0:
            print(
                f"Team {int((i / 2) + 1)}: {sorted_teams[i]['team']}, difference: {sorted_teams[i]['difference']}"
            )