def get_match_info(data): try: # some files seems broken for this library when using the `Summary`. m = parse_match(data) players = [dict(name=p.name, user_id=p.profile_id, number=p.number, civilization=p.civilization) for p in m.players] return dict( map_name=m.map.name, game_version=f"{m.version.name} {m.version.value}", game_map_type=m.type, players=players, teams=m.teams, completed=False, start_time_seconds=str(m.actions[0].timestamp.seconds), duration_seconds=m.duration.seconds, ) except RuntimeError: # the `parse_match` method doesn't work for restored recordings, thus, let's try with the `Summary`. s = Summary(data) return dict( map_name=s.get_map()['name'], game_version=" ".join(str(x) for x in s.get_version()), game_map_type=s.get_settings()['type'][1], players=s.get_players(), teams=s.get_teams(), completed=s.get_completed(), start_time_seconds=int(s.get_start_time()/1000), duration_seconds=int(s.get_duration()/1000), )
def print_info(path): """Print basic info.""" with open(path, 'rb') as handle: header = mgz.header.parse_stream(handle) handle.seek(0) summary = Summary(handle) dataset = summary.get_dataset() print('-------------') print( tabulate( [ ['Path', path], [ 'Duration', mgz.util.convert_to_timestamp( summary.get_duration() / 1000) ], ['Completed', summary.get_completed()], ['Restored', header.initial.restore_time > 0], ['Postgame', bool(summary.get_postgame())], [ 'Version', '{} ({}, {})'.format( header.version.name, header.game_version, round(header.save_version, 2)) ], [ 'Dataset', '{} {}'.format(dataset['name'], dataset['version']) ], ['Hash', summary.get_hash().hexdigest()], ['Encoding', summary.get_encoding()], ['Language', summary.get_language()], ['Map', summary.get_map()['name']] # pylint: disable=unsubscriptable-object ], tablefmt='plain'))
async def play_rec(playback, path): """Play a recorded game.""" with open(path, 'rb') as handle: summary = Summary(handle) client = await Client.create(playback, path, summary.get_start_time(), summary.get_duration()) async for _, _, _ in progress_bar(client.sync(), client.duration): pass
def print_chat(path): """Extract chat.""" with open(path, 'rb') as handle: summary = Summary(handle) encoding = summary.get_encoding() handle.seek(summary.body_pos) while handle.tell() < summary.size: operation = mgz.body.operation.parse_stream(handle) if operation.type == 'message' and operation.subtype == 'chat': print(operation.data.text.decode(encoding))
async def play_rec(playback, path): """Play a recorded game.""" if not playback: raise RuntimeError('playback not supported') from mgz.playback import Client, progress_bar with open(path, 'rb') as handle: summary = Summary(handle) client = await Client.create(playback, path, summary.get_start_time(), summary.get_duration()) async for _, _, _ in progress_bar(client.sync(), client.duration): pass
async def extract_rec(playback, path, select=None): """Extract data from a recorded game.""" with open(path, 'rb') as handle: summary = Summary(handle, playback=playback) data = await summary.async_extract() for key, records in data.items(): if select and key != select: continue print(key) print('-------------') for record in records: print(json.dumps(record))
def _load_game(f): with open(f, 'rb') as data: try: summary = Summary(data) error = None except Exception as e: summary = None error = str(e) if error: print(error, '| path:', f) return summary, error
async def extract_rec(playback, path, select=None): """Extract data from a recorded game.""" with open(path, 'rb') as handle: summary = Summary(handle, playback=playback) data = await summary.async_extract(30000) print('version: {}, runtime: {}'.format(data['version'], data['runtime'])) for key, records in data.items(): if select and key != select: continue print(key) print('-------------') for record in records: print(record)
def print_chat(path): """Extract chat.""" with open(path, 'rb') as handle: summary = Summary(handle) for c in summary.get_chat(): print(c)
def get_info(input_file: str) -> dict(): '''Obtiene la información más relevante de la partida''' info = dict() with open(f'{input_file}', 'rb') as data: sumario = Summary(data) info['nombre_archivo'] = input_file info['duracion_partida'] = mgz.util.convert_to_timestamp( sumario.get_duration() / 1000) info['punto_de_vista'] = sumario.get_players()[sumario.get_owner() - 1]['name'] info['mapa_revelado'] = en_es['reveal_map'][ sumario.get_settings()['map_reveal_choice'][1].capitalize()] info['velocidad'] = en_es['game_speeds'][sumario.get_settings()['speed'] [1].capitalize()] info['poblacion'] = sumario.get_settings()['population_limit'] info['diplomacia'] = sumario.get_diplomacy()['type'] try: info['nombre_mapa'] = en_es['map_names'][sumario.get_map()['name']] except KeyError: info['nombre_mapa'] = sumario.get_map()['name'] info['tamano_mapa'] = sumario.get_map()['size'].capitalize() info['bloqueo_diplomacia_equipos'] = 1 if sumario.get_settings( )['lock_teams'] else 0 info['dificultad'] = en_es['difficulties'][sumario.get_settings() ['difficulty'][1].capitalize()] for map_size in en_es['map_sizes'].keys(): if info['tamano_mapa'] in map_size: info['tamano_mapa'] = en_es['map_sizes'][map_size] info['teams'] = '' if info['diplomacia'] == 'TG': info['teams'] = sumario.get_diplomacy()['team_size'] info['diplomacia'] = 'Batalla de equipos' equipos = dict() for index, team in enumerate(sumario.get_teams()): index += 1 equipos[index] = dict() for jugador in team: equipos[index][jugador] = dict() equipos[index][jugador]['nickname'] = sumario.get_players()[ jugador - 1]['name'] civ_cod = str(sumario.get_players()[jugador - 1]['civilization']) civ = sumario.reference['civilizations'][civ_cod]['name'] equipos[index][jugador]['civ_cod'] = civ_cod equipos[index][jugador]['civ'] = en_es['civilizations'][civ] if sumario.get_players()[jugador - 1]['winner']: equipos[index][jugador]['victoria'] = 0 # False else: equipos[index][jugador]['victoria'] = 1 # True id_color = str(sumario.get_players()[jugador - 1]['color_id']) equipos[index][jugador]['color_cod'] = id_color equipos[index][jugador]['color'] = mgz.reference.get_consts( )['player_colors'][id_color] info['equipos'] = equipos return info
def get_data_from(input_file: str): '''Gets a summary''' with open(f'{input_file}', 'rb') as data: return Summary(data)
def print_info(path): """Print basic info.""" with open(path, 'rb') as handle: summary = Summary(handle) dataset = summary.get_dataset() header = summary.get_header() print('-------------') print( tabulate( [ ['Path', path], [ 'Duration', mgz.util.convert_to_timestamp( summary.get_duration() / 1000) ], ['Completed', summary.get_completed()], ['Restored', header.initial.restore_time > 0], ['Postgame', bool(summary.get_postgame())], ['Objects', bool(summary.get_objects()['objects'])], [ 'Version', '{} ({}, {}, {})'.format( header.version.name, header.game_version, header.save_version, header.log_version) ], [ 'Dataset', '{} {}'.format(dataset['name'], dataset['version']) ], ['File Hash', summary.get_file_hash()], [ 'Match Hash', summary.get_hash().hexdigest() if summary.get_hash() else None ], ['Encoding', summary.get_encoding()], ['Language', summary.get_language()], [ 'Map', '{} ({})'.format(summary.get_map()['name'], summary.get_map()['seed']) ] # pylint: disable=unsubscriptable-object ], tablefmt='plain'))
import os from mgz.summary import Summary ##fyi - there is a change in python 3.9.2+ that breaks this module ###### muckaround ###### fp_to_test_replay = "MP Replay v101.101.46295.0 @2021.04.04 134216 (6).aoe2record" #https://github.com/happyleavesaoc/aoc-mgz with open(fp_to_test_replay, 'rb') as data: s = Summary(data) # eof = os.fstat(data.fileno()).st_size # header.parse_stream(data) # body.meta.parse_stream(data) # while data.tell() < eof: # body.operation.parse_stream(data) print("")