def test_worker_milestones(): replay = sc2reader.load_replay( 'replays/Nerchio vs Neeb ZvP Newkirk Precinct TE (Void) WCS Austin.SC2Replay', engine=sc2reader.engine.GameEngine(plugins=[ APMTracker(), SelectionTracker(), ContextLoader(), GameHeartNormalizer(), workers_analysis(), ]), load_map=False) if replay.players[0].name == "Neeb": neeb = replay.players[0] nerchio = replay.players[1] else: nerchio = replay.players[0] neeb = replay.players[1] assert neeb.worker_milestones[40] == 5493 assert nerchio.worker_milestones[40] == 5213 assert neeb.worker_milestones[50] == 7466 assert nerchio.worker_milestones[50] == 7247 assert neeb.worker_milestones[60] == 8668 assert nerchio.worker_milestones[60] == 11838 assert neeb.worker_milestones[70] == 14631 assert nerchio.worker_milestones[70] == 17087
def test_workers_at_frame(): replay = sc2reader.load_replay( 'replays/Nerchio vs Neeb ZvP Newkirk Precinct TE (Void) WCS Austin.SC2Replay', engine=sc2reader.engine.GameEngine(plugins=[ APMTracker(), SelectionTracker(), ContextLoader(), GameHeartNormalizer(), workers_analysis(), ]), load_map=False) if replay.players[0].name == "Neeb": neeb = replay.players[0] nerchio = replay.players[1] else: nerchio = replay.players[0] neeb = replay.players[1] assert workers_at_frame(neeb, time_to_frame('4:06')) == 40 assert workers_at_frame(nerchio, time_to_frame('4:31')) == 40 assert workers_at_frame(nerchio, time_to_frame('5:25')) == 50 assert workers_at_frame(neeb, time_to_frame('5:34')) == 50 assert workers_at_frame(neeb, time_to_frame('6:28')) == 60 assert workers_at_frame(neeb, time_to_frame('10:56')) == 70 assert workers_at_frame(nerchio, time_to_frame('12:22')) == 58 assert workers_at_frame(nerchio, time_to_frame('12:23')) == 61
def test_alive_at_this_time(): replay = sc2reader.load_replay( 'replays/Nerchio vs Neeb ZvP Newkirk Precinct TE (Void) WCS Austin.SC2Replay', engine=sc2reader.engine.GameEngine(plugins=[ APMTracker(), SelectionTracker(), ContextLoader(), GameHeartNormalizer(), workers_analysis(), ]), load_map=False) if replay.players[0].name == "Neeb": neeb = replay.players[0] nerchio = replay.players[1] else: nerchio = replay.players[0] neeb = replay.players[1] probe = neeb.units[54] assert alive_at_this_time(probe, 0, replay.frames) is False assert alive_at_this_time(probe, 28870, replay.frames) is False assert alive_at_this_time(probe, 26000, replay.frames) is False assert alive_at_this_time(probe, 4500, replay.frames) is True assert alive_at_this_time(probe, 2000, replay.frames) is False
def parse_input(replay_path, VERBOSE=False): try: replay_file = replay_path except NameError: print( '\n' 'SETUP ERROR: Please follow the directions to add a .SC2Replay file and use\n' ' "Insert to code" to set the streaming_body_1 variable to the resulting bytes.\n' ' You may need to rename the data_* variable.') raise replay = sc2reader.load_replay( replay_file, engine=sc2reader.engine.GameEngine( plugins=[ContextLoader( ), APMTracker(), SelectionTracker()])) participants = [] for plays in replay.players: participants.append(plays) participants.append(plays.result) if VERBOSE: print("Replay successfully loaded.") for players in replay.players: print(players.result, players) is_AI = False for players in replay.players: if isinstance(players, (sc2reader.objects.Computer)): is_AI = True if VERBOSE: print('found an A.I.\n') if (len(replay.players) != 2) or (is_AI == True): if VERBOSE: if (is_AI == True): print('this is an A.I. game') else: print('this is not a 1v1 game') return None else: replay_object = ReplayData.parse_replay(replay=replay) try: y_data = list(replay_object.as_dict().get('winners'))[0][0] except: y_data = 3 x_data, data_dict_full = get_stats(replay_object) data_dict_full['winner'] = y_data data_dict = {'seq': [x_data], 'label': [y_data]} return data_dict, participants, data_dict_full, replay_object.as_dict( ).get('stats')
def test_30_apms(self): from sc2reader.factories.plugins.replay import APMTracker, SelectionTracker, toJSON factory = sc2reader.factories.SC2Factory() factory.register_plugin("Replay", APMTracker()) replay = factory.load_replay("test_replays/3.0.0.38215/fourth.SC2Replay") for player in replay.players: if player.name == 'Owl': print(player.name, player.avg_apm) self.assertTrue(player.avg_apm > 110)
def getTrainHotVectorData(myReplay): sc2reader.engine.register_plugin(APMTracker()) replay = sc2reader.load_replay(myReplay, load_level=4) data = [[]] unitStatusComments = [[]] players = initiatePlayers(replay) # printPlayers(players) data, unitStatusComments = getTrackerEvents(data, unitStatusComments,players, replay.tracker_events,"train") data, unitStatusComments = getGameEvents(data, unitStatusComments, players, replay.events,"train") return data[1:]
def getPlayer(name,myReplay): sc2reader.engine.register_plugin(APMTracker()) replay = sc2reader.load_replay(myReplay, load_level=4) for player in replay.people: temp = str(player).split() playerName = temp[3] if name == playerName: return player return -1
def test_engine_plugins(self): from sc2reader.engine.plugins import ContextLoader, APMTracker, SelectionTracker replay = sc2reader.load_replay( "test_replays/2.0.5.25092/cn1.SC2Replay", engine=sc2reader.engine.GameEngine(plugins=[ ContextLoader(), APMTracker(), SelectionTracker(), ])) code, details = replay.plugins['ContextLoader'] self.assertEqual(code, 0) self.assertEqual(details, dict())
def parse_replay(cls, replay=None, replay_file=None, file_object=None): replay_data = ReplayData(replay_file) try: # This is the engine that holds some required plugins for parsing engine = sc2reader.engine.GameEngine( plugins=[ContextLoader(), APMTracker(), SelectionTracker()]) if replay: pass elif replay_file and not file_object: # Then we are not using ObjectStorage for accessing replay files replay = sc2reader.load_replay(replay_file, engine=engine) elif file_object: # We are using ObjectStorage to access replay files replay = sc2reader.load_replay(file_object, engine=engine) else: pass # Get the number of frames (one frame is 1/16 of a second) replay_data.frames = replay.frames # Gets the game mode (if available) replay_data.game_mode = replay.real_type # Gets the map hash (if we want to download the map, or do map-based analysis) replay_data.map_hash = replay.map_hash # Use the parsers to get data for event in replay.events: for parser in cls.__parsers__: parser(replay_data, event) # Check if there was a winner if replay.winner is not None: replay_data.winners = replay.winner.players replay_data.losers = [ p for p in replay.players if p not in replay.winner.players ] else: replay_data.winners = [] replay_data.losers = [] # Check to see if expansion data is available replay_data.expansion = replay.expansion return replay_data except: # print our error and return NoneType object print_exc() return None, None
def getTestHotVectorData(myReplay): # TODO: append team_id instead of Win/Loss sc2reader.engine.register_plugin(APMTracker()) replay = sc2reader.load_replay(myReplay, load_level=4) data = [[]] unitStatusComments = [[]] players = initiatePlayers(replay) # printPlayers(players) data, unitStatusComments = getTrackerEvents(data, unitStatusComments,players, replay.tracker_events, "test") data, unitStatusComments = getGameEvents(data, unitStatusComments, players, replay.events, "test") return data[1:]
def test_factory_plugins(self): from sc2reader.factories.plugins.replay import APMTracker, SelectionTracker, toJSON factory = sc2reader.factories.SC2Factory() factory.register_plugin("Replay", APMTracker()) factory.register_plugin("Replay", SelectionTracker()) factory.register_plugin("Replay", toJSON()) replay = factory.load_replay("test_replays/2.0.5.25092/cn1.SC2Replay") # Load and quickly check the JSON output consistency result = json.loads(replay) self.assertEqual(result["map_name"], "生化实验区") self.assertEqual(result["players"][2]["name"], "ImYoonA") self.assertEqual(result["players"][2]["avg_apm"], 84.52332657200812) self.assertEqual(result["release"], "2.0.5.25092") self.assertEqual(result["game_length"], 986) self.assertEqual(result["real_length"], 704) self.assertEqual(result["gateway"], "cn") self.assertEqual(result["game_fps"], 16.0) self.assertTrue(result["is_ladder"])
def getWinner(myReplay): sc2reader.engine.register_plugin(APMTracker()) replay = sc2reader.load_replay(myReplay, load_level=4) #Traverse over all players for player in replay.people: name = str(player).split() playerName = name[3] # Get teamid from the player's data teamid = player.team_id # If this particular player wins, return the teamid if player.result == "Win": return playerName # Returns -1 if none of the players won return -1
def load_replays(self, glob_path, limit=None, verbose=True): ''' Loads SC2 replays found in the provided path. If the argument 'amount' is passed, then only that amount will be loaded. Parameters ---------- glob_path : str Path to .SC2Replay files as a glob string limit : int, optional Number of replays to be loaded (default is All) verbose : bool, optional Show verbose information (default is True) Returns ------- None ''' paths = [path for path in glob(glob_path, recursive=True)] loader_amount = len( paths) if limit is None or limit > len(paths) else limit n_replays = len(paths) register_plugin(APMTracker()) register_plugin(SelectionTracker()) register_plugin(ContextLoader()) replays = load_replays(paths[:limit]) if verbose: print('Loaded {} replays out of {}.'.format( loader_amount, n_replays)) self.paths = paths[:limit] self.replays = replays self.n_replays = n_replays self.loader_amount = loader_amount
def TestSVM(filename): commentOnList = parser.getPrintData(filename) hotVectorData = parser.getTestHotVectorData(filename) yOut1, yOut2 = svmHandler.callTestSVM(hotVectorData) sc2reader.engine.register_plugin(APMTracker()) replay = sc2reader.load_replay(filename, load_level=4) players = parser.initiatePlayers(replay) team1 = [] team2 = [] for player in players: if player.teamid == 1: team1.append([player.playerName]) else: team2.append([player.playerName]) # print("Player 1 : ",yOut1, yOut1[len(yOut1)-1]) # print("Player 2 : ", yOut2, yOut2[len(yOut2)-1]) # print("According to reality " + parser.getWinner(filename)+ " actually won the game") if yOut1[len(yOut1) - 1] > yOut2[len(yOut2) - 1]: # print(team1) winner = 1 else: # print(team2) winner = 2 if winner == 1: if [parser.getWinner(filename)] in team1: return 1 elif winner == 2: if [parser.getWinner(filename)] in team2: return 1 else: return 0
import sc2reader import pandas as pd from sc2reader.engine.plugins import SelectionTracker, APMTracker sc2reader.engine.register_plugin(SelectionTracker()) sc2reader.engine.register_plugin(APMTracker()) import matplotlib.pyplot as plt import os from os import listdir from os.path import isfile, join #https://github.com/GraylinKim/sc2reader/blob/master/sc2reader/events/tracker.py#L79 #https://github.com/GraylinKim/sc2reader/blob/master/sc2reader/events/game.py # python-sc2 # vars(self.state.common) #https://github.com/Dentosal/python-sc2/issues/33 #### GOALS for the weekend #complete######### A: Load all replays into list #complete######### B: Run through each replay and ask if a player in this match is Terran. #complete######### C: Extract PlayerStatsEvent (carry out linear interpolation on each), ########## BasicCommandEvent, player.untis??, player._____??, AttackEvents, etc.etc. #complete######### D: Build sklearn sub-library for logistic, linear, ensamble, SVM techniques #complete######### E: Apply simple ensamble ML to output BasicCommandEvents given a subset of PlayerStatsEvent ########## F: Create mappings from ML output (BasicCommandEvent) to python-sc2 functions #### ML goals ########## B: Use assorted ensamble ML methods to carry our desicions ########## C: Use KNN, SVM, Logistic regression on scrapped data. ########## D: Think about how you might use the upcoming module in this project.
"losers": [(s.pid, s.name, s.detail_data['race']) for s in self.losers], "stats_names": [k for k in self.players[1].keys()], "stats": {player: data for player, data in self.players.items()} } def __init__(self, replay): self.players = defaultdict(lambda: defaultdict(list)) self.replay = replay self.winners = [] self.losers = [] self.expansion = None ## change your files to the PATH = 'C:\\Program Files (x86)\\StarCraft II\\Replays\\samples\\' filenames = os.listdir(PATH) replay = sc2reader.load_replay(PATH+filenames[0], engine=GameEngine(plugins=[ContextLoader(), APMTracker(), SelectionTracker()])) replay_object = ReplayData.parse_replay(replay=replay) replay_dict = replay_object.as_dict() print(filenames[0]) print("Date: %s" % replay.date) print("Map Name: " + replay.map_name) for player in replay.players: print("%s: %s" % (player.result, player)) pprint(replay_dict) print("--------------------------") """ If you want to add more replays to the dataset you can add them to a PATH folder then run the code below which tries to check if the replay file is parseable. ## path to replays in my machine, change to your own
races = [] for player in replay.players: races.append(player.play_race) matchup = "v".join(race[0] for race in sorted(races)) return matchup if __name__ == "__main__": data = [] replays = glob.glob("all_replays/**/*.SC2Replay", recursive=True) for filename in replays: replay = sc2reader.load_replay( filename, engine=sc2reader.engine.GameEngine(plugins=[ APMTracker(), SelectionTracker(), ContextLoader(), GameHeartNormalizer(), ])) #game['matchup'] = replay.matchup for human in replay.players: game = {} game['length'] = replay.frames / 22.4 game['map'] = replay.map_name game['matchup'] = classify_matchup(replay) game['name'] = human.name game['race'] = human.play_race game['players'] = str(replay.players) game['buildings'] = {} game['buildings']['stargates'] = []
def get_plugins(cls): return [ContextLoader(), APMTracker(), SelectionTracker()]
def getAllPlayers(myReplay): sc2reader.engine.register_plugin(APMTracker()) replay = sc2reader.load_replay(myReplay, load_level=4) return replay.people