From 2a493562c23a6535c2bed4c22be35da876849d79 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 25 May 2022 18:26:00 +0200 Subject: [PATCH 1/2] Drop support for legacy Python --- .circleci/config.yml | 6 -- docs/source/conf.py | 1 - examples/sc2autosave.py | 41 ++++++----- examples/sc2store.py | 3 +- generate_build_data.py | 22 +++--- new_units.py | 8 +-- sc2reader/__init__.py | 2 - sc2reader/constants.py | 3 - sc2reader/data/__init__.py | 19 +++--- sc2reader/data/create_lookup.py | 4 +- sc2reader/decoders.py | 21 +++--- sc2reader/engine/__init__.py | 3 - sc2reader/engine/engine.py | 7 +- sc2reader/engine/events.py | 10 +-- sc2reader/engine/plugins/__init__.py | 3 - sc2reader/engine/plugins/apm.py | 5 +- sc2reader/engine/plugins/context.py | 34 +++++---- sc2reader/engine/plugins/creeptracker.py | 15 ++-- sc2reader/engine/plugins/gameheart.py | 5 +- sc2reader/engine/plugins/selection.py | 6 +- sc2reader/engine/plugins/supply.py | 15 ++-- sc2reader/engine/utils.py | 7 +- sc2reader/events/__init__.py | 3 - sc2reader/events/base.py | 6 +- sc2reader/events/game.py | 55 +++++++-------- sc2reader/events/message.py | 11 ++- sc2reader/events/tracker.py | 41 ++++++----- sc2reader/exceptions.py | 8 +-- sc2reader/factories/__init__.py | 2 - sc2reader/factories/plugins/replay.py | 13 ++-- sc2reader/factories/plugins/utils.py | 13 ++-- sc2reader/factories/sc2factory.py | 17 ++--- sc2reader/log_utils.py | 5 +- sc2reader/objects.py | 55 +++++++-------- sc2reader/readers.py | 37 +++++----- sc2reader/resources.py | 87 ++++++++++++------------ sc2reader/scripts/__init__.py | 3 - sc2reader/scripts/sc2attributes.py | 14 ++-- sc2reader/scripts/sc2json.py | 2 - sc2reader/scripts/sc2parse.py | 44 ++++++------ sc2reader/scripts/sc2printer.py | 48 +++++++------ sc2reader/scripts/sc2replayer.py | 10 ++- sc2reader/scripts/utils.py | 3 - sc2reader/utils.py | 15 ++-- test_replays/test_replays.py | 69 ++++++++----------- test_s2gs/test_all.py | 2 - 46 files changed, 334 insertions(+), 469 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 0799ef91..9c0a5914 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -25,11 +25,6 @@ jobs: - run: black . --check - Python2: - docker: - - image: circleci/python:2.7.18 - steps: *build_and_test_steps - Python3: docker: - image: circleci/python:3.10 @@ -41,5 +36,4 @@ workflows: build: jobs: - StyleCheck - - Python2 - Python3 diff --git a/docs/source/conf.py b/docs/source/conf.py index 17164624..ead7fdd3 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # sc2reader documentation build configuration file, created by # sphinx-quickstart on Sun May 01 12:39:48 2011. diff --git a/examples/sc2autosave.py b/examples/sc2autosave.py index f7091ba4..b7f1ffbd 100755 --- a/examples/sc2autosave.py +++ b/examples/sc2autosave.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- """sc2autosave is a utility for reorganizing and renaming Starcraft II files. Overview @@ -78,16 +77,16 @@ keeps the script from looking into the 'Saved' subdirectory. sc2autosave \ - --source ~/My\ Documents/Starcraft\ II/Accounts/.../Mutliplayer \ - --dest ~/My\ Documents/Starcraft\ II/Accounts/.../Multiplater/Saved \ + --source ~/My\\ Documents/Starcraft\\ II/Accounts/.../Mutliplayer \ + --dest ~/My\\ Documents/Starcraft\\ II/Accounts/.../Multiplater/Saved \ --period 10 \ --depth 0 This next configuration runs in batch mode using the default renaming format. sc2autosave \ - --source ~/My\ Documents/Starcraft\ II/Accounts/.../Mutliplayer \ - --dest ~/My\ Documents/Starcraft\ II/Accounts/.../Multiplater/Saved \ + --source ~/My\\ Documents/Starcraft\\ II/Accounts/.../Mutliplayer \ + --dest ~/My\\ Documents/Starcraft\\ II/Accounts/.../Multiplater/Saved \ --rename (ZvP) Lost Temple: ShadesofGray(Z) vs Trisfall(P).SC2Replay @@ -97,8 +96,8 @@ by replay format and favors ShadesofGray in the player and team orderings. sc2autosave \ - --source ~/My\ Documents/Starcraft\ II/Accounts/.../Mutliplayer \ - --dest ~/My\ Documents/Starcraft\ II/Accounts/.../Multiplater/Saved \ + --source ~/My\\ Documents/Starcraft\\ II/Accounts/.../Mutliplayer \ + --dest ~/My\\ Documents/Starcraft\\ II/Accounts/.../Multiplater/Saved \ --rename "{:format}/{:matchup} on {:map}: {:teams}" \ --player-format "{:name}({:play_race})" \ --team-order-by number \ @@ -113,8 +112,8 @@ length to show both minutes and seconds. sc2autosave \ - --source ~/My\ Documents/Starcraft\ II/Accounts/.../Mutliplayer \ - --dest ~/My\ Documents/Starcraft\ II/Accounts/.../Multiplater/Saved \ + --source ~/My\\ Documents/Starcraft\\ II/Accounts/.../Mutliplayer \ + --dest ~/My\\ Documents/Starcraft\\ II/Accounts/.../Multiplater/Saved \ --rename "{:matchup}/({:length}) {:map}: {:teams}" \ --player-format "{:name}({:play_race})" \ --team-order-by number \ @@ -200,7 +199,7 @@ def run(args): directory = make_directory(args, ("parse_error",)) new_path = os.path.join(directory, file_name) source_path = path[len(args.source) :] - args.log.write("Error parsing replay: {0}".format(source_path)) + args.log.write(f"Error parsing replay: {source_path}") if not args.dryrun: args.action.run(path, new_path) @@ -250,7 +249,7 @@ def run(args): def filter_out_replay(args, replay): - player_names = set([player.name for player in replay.players]) + player_names = {player.name for player in replay.players} filter_out_player = not set(args.filter_player) & player_names if args.filter_rule == "ALLOW": @@ -262,7 +261,7 @@ def filter_out_replay(args, replay): # We need to create these compare functions at runtime because the ordering # hinges on the --favored PLAYER options passed in from the command line. def create_compare_funcs(args): - favored_set = set(name.lower() for name in args.favored) + favored_set = {name.lower() for name in args.favored} def player_compare(player1, player2): # Normalize the player names and generate our key metrics @@ -290,8 +289,8 @@ def player_compare(player1, player2): def team_compare(team1, team2): # Normalize the team name lists and generate our key metrics - team1_names = set(p.name.lower() for p in team1.players) - team2_names = set(p.name.lower() for p in team2.players) + team1_names = {p.name.lower() for p in team1.players} + team2_names = {p.name.lower() for p in team2.players} team1_favored = team1_names & favored_set team2_favored = team2_names & favored_set @@ -341,7 +340,7 @@ def make_directory(args, path_parts): for part in path_parts: directory = os.path.join(directory, part) if not os.path.exists(directory): - args.log.write("Creating subfolder: {0}\n".format(directory)) + args.log.write(f"Creating subfolder: {directory}\n") if not args.dryrun: os.mkdir(directory) elif not os.path.isdir(directory): @@ -351,7 +350,7 @@ def make_directory(args, path_parts): def scan(args, state): - args.log.write("SCANNING: {0}\n".format(args.source)) + args.log.write(f"SCANNING: {args.source}\n") files = sc2reader.utils.get_files( path=args.source, regex=args.exclude_files, @@ -374,13 +373,13 @@ def reset(args): exit("Cannot reset, destination must be directory: {0}", args.dest) print( - "About to reset directory: {0}\nAll files and subdirectories will be removed.".format( + "About to reset directory: {}\nAll files and subdirectories will be removed.".format( args.dest ) ) choice = raw_input("Proceed anyway? (y/n) ") if choice.lower() == "y": - args.log.write("Removing old directory: {0}\n".format(args.dest)) + args.log.write(f"Removing old directory: {args.dest}\n") if not args.dryrun: print(args.dest) shutil.rmtree(args.dest) @@ -404,13 +403,13 @@ def setup(args): if not args.dryrun: os.mkdir(args.dest) else: - args.log.write("Creating destination: {0}\n".format(args.dest)) + args.log.write(f"Creating destination: {args.dest}\n") elif not os.path.isdir(args.dest): sys.exit("Destination must be a directory.\n\nScript Aborted") data_file = os.path.join(args.dest, "sc2autosave.dat") - args.log.write("Loading state from file: {0}\n".format(data_file)) + args.log.write(f"Loading state from file: {data_file}\n") if os.path.isfile(data_file) and not args.reset: with open(data_file) as file: return cPickle.load(file) @@ -425,7 +424,7 @@ def save_state(state, args): with open(data_file, "w") as file: cPickle.dump(state, file) else: - args.log.write("Writing state to file: {0}\n".format(data_file)) + args.log.write(f"Writing state to file: {data_file}\n") def main(): diff --git a/examples/sc2store.py b/examples/sc2store.py index 0a072f43..6aff2a98 100755 --- a/examples/sc2store.py +++ b/examples/sc2store.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- import cPickle import os @@ -196,7 +195,7 @@ def main(): for path in args.paths: for file_name in sc2reader.utils.get_files(path, depth=0): - print("CREATING: {0}".format(file_name)) + print(f"CREATING: {file_name}") db.add(Game(sc2reader.read_file(file_name), db)) db.commit() diff --git a/generate_build_data.py b/generate_build_data.py index 32bdbbd2..a13f9807 100644 --- a/generate_build_data.py +++ b/generate_build_data.py @@ -58,7 +58,7 @@ def generate_build_data(balance_data_path): elif unit_id == "Drone": build_ability_name = "ZergBuild" else: - build_ability_name = "{}Build".format(unit_id) + build_ability_name = f"{unit_id}Build" if build_ability_index: abilities[build_ability_index] = build_ability_name @@ -77,7 +77,7 @@ def generate_build_data(balance_data_path): while len(ability_lookup[build_ability_name]) <= command_index: ability_lookup[build_ability_name].append("") - build_command_name = "Build{}".format(built_unit_id) + build_command_name = f"Build{built_unit_id}" ability_lookup[build_ability_name][ command_index ] = build_command_name @@ -87,7 +87,7 @@ def generate_build_data(balance_data_path): train_ability_index = train_unit_elements[0].get("ability") if train_ability_index: - train_ability_name = "{}Train".format(unit_id) + train_ability_name = f"{unit_id}Train" abilities[train_ability_index] = train_ability_name if train_ability_name not in ability_lookup: @@ -137,7 +137,7 @@ def generate_build_data(balance_data_path): ): ability_lookup[train_ability_name].append("") - train_command_name = "Train{}".format(trained_unit_name) + train_command_name = f"Train{trained_unit_name}" ability_lookup[train_ability_name][ command_index ] = train_command_name @@ -145,7 +145,7 @@ def generate_build_data(balance_data_path): research_upgrade_elements = root.findall("./researches/upgrade") if research_upgrade_elements: research_ability_index = research_upgrade_elements[0].get("ability") - research_ability_name = "{}Research".format(unit_id) + research_ability_name = f"{unit_id}Research" abilities[research_ability_index] = research_ability_name @@ -163,7 +163,7 @@ def generate_build_data(balance_data_path): while len(ability_lookup[research_ability_name]) <= command_index: ability_lookup[research_ability_name].append("") - research_command_name = "Research{}".format(researched_upgrade_id) + research_command_name = f"Research{researched_upgrade_id}" ability_lookup[research_ability_name][ command_index ] = research_command_name @@ -175,7 +175,7 @@ def generate_build_data(balance_data_path): sorted(abilities.items(), key=lambda x: int(x[0])) ) - unit_lookup = dict((unit_name, unit_name) for _, unit_name in sorted_units.items()) + unit_lookup = {unit_name: unit_name for _, unit_name in sorted_units.items()} return sorted_units, sorted_abilities, unit_lookup, ability_lookup @@ -258,7 +258,7 @@ def main(): unit_lookup_path = os.path.join( args.project_path, "sc2reader", "data", "unit_lookup.csv" ) - with open(unit_lookup_path, "r") as file: + with open(unit_lookup_path) as file: csv_reader = csv.reader(file, delimiter=",", lineterminator=os.linesep) old_unit_lookup = collections.OrderedDict( [(row[0], row[1]) for row in csv_reader if len(row) > 1] @@ -267,7 +267,7 @@ def main(): ability_lookup_path = os.path.join( args.project_path, "sc2reader", "data", "ability_lookup.csv" ) - with open(ability_lookup_path, "r") as file: + with open(ability_lookup_path) as file: csv_reader = csv.reader(file, delimiter=",", lineterminator=os.linesep) old_ability_lookup = collections.OrderedDict( [(row[0], row[1:]) for row in csv_reader if len(row) > 0] @@ -290,7 +290,7 @@ def main(): "sc2reader", "data", args.expansion, - "{}_units.csv".format(args.build_version), + f"{args.build_version}_units.csv", ) with open(units_file_path, "w") as file: csv_writer = csv.writer(file, delimiter=",", lineterminator=os.linesep) @@ -302,7 +302,7 @@ def main(): "sc2reader", "data", args.expansion, - "{}_abilities.csv".format(args.build_version), + f"{args.build_version}_abilities.csv", ) with open(abilities_file_path, "w") as file: csv_writer = csv.writer(file, delimiter=",", lineterminator=os.linesep) diff --git a/new_units.py b/new_units.py index dcc609a0..86d82ee5 100644 --- a/new_units.py +++ b/new_units.py @@ -15,11 +15,11 @@ str_id, title = entry.strip().split(",") UNIT_LOOKUP[str_id] = title -with open(sys.argv[1], "r") as new_units: +with open(sys.argv[1]) as new_units: for line in new_units: new_unit_name = line.strip().split(",")[1] if new_unit_name not in UNIT_LOOKUP: - print("{0},{1}".format(new_unit_name, new_unit_name)) + print(f"{new_unit_name},{new_unit_name}") print("") print("") @@ -31,8 +31,8 @@ str_id, abilities = entry.split(",", 1) ABIL_LOOKUP[str_id] = abilities.split(",") -with open(sys.argv[2], "r") as new_abilities: +with open(sys.argv[2]) as new_abilities: for line in new_abilities: new_ability_name = line.strip().split(",")[1] if new_ability_name not in ABIL_LOOKUP: - print("{0},{1}".format(new_ability_name, new_ability_name)) + print(f"{new_ability_name},{new_ability_name}") diff --git a/sc2reader/__init__.py b/sc2reader/__init__.py index 419f47b5..415b270d 100644 --- a/sc2reader/__init__.py +++ b/sc2reader/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ sc2reader ~~~~~~~~~~~ @@ -18,7 +17,6 @@ :copyright: (c) 2011 by Graylin Kim. :license: MIT, see LICENSE for more details. """ -from __future__ import absolute_import, print_function, unicode_literals, division __version__ = "1.8.0" diff --git a/sc2reader/constants.py b/sc2reader/constants.py index 1edfa70e..db34afa7 100644 --- a/sc2reader/constants.py +++ b/sc2reader/constants.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - # These are found in Repack-MPQ/fileset.{locale}#Mods#Core.SC2Mod#{locale}.SC2Data/LocalizedData/Editor/EditorCategoryStrings.txt # EDSTR_CATEGORY_Race # EDSTR_PLAYERPROPS_RACE diff --git a/sc2reader/data/__init__.py b/sc2reader/data/__init__.py index 6cbb9425..cb333d47 100755 --- a/sc2reader/data/__init__.py +++ b/sc2reader/data/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import json import pkgutil @@ -41,7 +38,7 @@ train_commands = json.loads(command_data) -class Unit(object): +class Unit: """Represents an in-game unit.""" def __init__(self, unit_id): @@ -190,7 +187,7 @@ def is_army(self): return self._type_class.is_army if self._type_class else False def __str__(self): - return "{0} [{1:X}]".format(self.name, self.id) + return f"{self.name} [{self.id:X}]" def __cmp__(self, other): return cmp(self.id, other.id) @@ -220,7 +217,7 @@ def __repr__(self): return str(self) -class UnitType(object): +class UnitType: """Represents an in game unit type""" def __init__( @@ -271,7 +268,7 @@ def __init__( self.is_army = is_army -class Ability(object): +class Ability: """Represents an in-game ability""" def __init__( @@ -297,7 +294,7 @@ def __init__( @loggable -class Build(object): +class Build: """ :param build_id: The build number identifying this dataset. @@ -342,7 +339,7 @@ def change_type(self, unit, new_type, frame): unit.set_type(unit_type, frame) else: self.logger.error( - "Unable to change type of {0} to {1} [frame {2}]; unit type not found in build {3}".format( + "Unable to change type of {} to {} [frame {}]; unit type not found in build {}".format( unit, new_type, frame, self.id ) ) @@ -402,7 +399,7 @@ def add_unit_type( def load_build(expansion, version): build = Build(version) - unit_file = "{0}/{1}_units.csv".format(expansion, version) + unit_file = f"{expansion}/{version}_units.csv" for entry in ( pkgutil.get_data("sc2reader.data", unit_file).decode("utf8").split("\n") ): @@ -421,7 +418,7 @@ def load_build(expansion, version): build.add_unit_type(**values) - abil_file = "{0}/{1}_abilities.csv".format(expansion, version) + abil_file = f"{expansion}/{version}_abilities.csv" build.add_ability(ability_id=0, name="RightClick", title="Right Click") for entry in ( pkgutil.get_data("sc2reader.data", abil_file).decode("utf8").split("\n") diff --git a/sc2reader/data/create_lookup.py b/sc2reader/data/create_lookup.py index 2ffa2560..427d1e27 100755 --- a/sc2reader/data/create_lookup.py +++ b/sc2reader/data/create_lookup.py @@ -1,10 +1,10 @@ abilities = dict() -with open("hots_abilities.csv", "r") as f: +with open("hots_abilities.csv") as f: for line in f: num, ability = line.strip("\r\n ").split(",") abilities[ability] = [""] * 32 -with open("command_lookup.csv", "r") as f: +with open("command_lookup.csv") as f: for line in f: ability, commands = line.strip("\r\n ").split("|", 1) abilities[ability] = commands.split("|") diff --git a/sc2reader/decoders.py b/sc2reader/decoders.py index 56674a1c..9085ab7d 100644 --- a/sc2reader/decoders.py +++ b/sc2reader/decoders.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - from io import BytesIO import struct @@ -12,7 +9,7 @@ from ordereddict import OrderedDict -class ByteDecoder(object): +class ByteDecoder: """ :param contents: The string or file-like object to decode :param endian: Either > or <. Indicates the endian the bytes are stored in. @@ -144,7 +141,7 @@ def read_cstring(self, encoding="utf8"): cstring.write(c) -class BitPackedDecoder(object): +class BitPackedDecoder: """ :param contents: The string of file-like object to decode @@ -306,9 +303,9 @@ def read_bytes(self, count): temp_buffer = BytesIO() prev_byte = self._next_byte lo_mask, hi_mask = self._bit_masks[self._bit_shift] - for next_byte in struct.unpack(str("B") * count, data): + for next_byte in struct.unpack("B" * count, data): temp_buffer.write( - struct.pack(str("B"), prev_byte & hi_mask | next_byte & lo_mask) + struct.pack("B", prev_byte & hi_mask | next_byte & lo_mask) ) prev_byte = next_byte @@ -357,7 +354,7 @@ def read_bits(self, count): result |= self._buffer.read_uint32() << bits else: - for byte in struct.unpack(str("B") * bytes, self._read(bytes)): + for byte in struct.unpack("B" * bytes, self._read(bytes)): bits -= 8 result |= byte << bits @@ -413,9 +410,9 @@ def read_struct(self, datatype=None): elif datatype == 0x05: # Struct entries = self.read_vint() - data = dict( - [(self.read_vint(), self.read_struct()) for i in range(entries)] - ) + data = { + self.read_vint(): self.read_struct() for i in range(entries) + } elif datatype == 0x06: # u8 data = ord(self._buffer.read(1)) @@ -430,6 +427,6 @@ def read_struct(self, datatype=None): data = self.read_vint() else: - raise TypeError("Unknown Data Structure: '{0}'".format(datatype)) + raise TypeError(f"Unknown Data Structure: '{datatype}'") return data diff --git a/sc2reader/engine/__init__.py b/sc2reader/engine/__init__.py index b3b8ad87..e76bf41b 100644 --- a/sc2reader/engine/__init__.py +++ b/sc2reader/engine/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import sys from sc2reader.engine.engine import GameEngine from sc2reader.engine.events import PluginExit diff --git a/sc2reader/engine/engine.py b/sc2reader/engine/engine.py index 15c0af66..9c7ee68f 100644 --- a/sc2reader/engine/engine.py +++ b/sc2reader/engine/engine.py @@ -1,12 +1,9 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import collections from sc2reader.events import * from sc2reader.engine.events import InitGameEvent, EndGameEvent, PluginExit -class GameEngine(object): +class GameEngine: """ GameEngine Specification -------------------------- @@ -200,7 +197,7 @@ def run(self, replay): def _get_event_handlers(self, event, plugins): return sum( - [self._get_plugin_event_handlers(plugin, event) for plugin in plugins], [] + (self._get_plugin_event_handlers(plugin, event) for plugin in plugins), [] ) def _get_plugin_event_handlers(self, plugin, event): diff --git a/sc2reader/engine/events.py b/sc2reader/engine/events.py index 8857a4b1..fc6d4728 100644 --- a/sc2reader/engine/events.py +++ b/sc2reader/engine/events.py @@ -1,16 +1,12 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - - -class InitGameEvent(object): +class InitGameEvent: name = "InitGame" -class EndGameEvent(object): +class EndGameEvent: name = "EndGame" -class PluginExit(object): +class PluginExit: name = "PluginExit" def __init__(self, plugin, code=0, details=None): diff --git a/sc2reader/engine/plugins/__init__.py b/sc2reader/engine/plugins/__init__.py index 7ddff085..ca62c70c 100644 --- a/sc2reader/engine/plugins/__init__.py +++ b/sc2reader/engine/plugins/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - from sc2reader.engine.plugins.apm import APMTracker from sc2reader.engine.plugins.selection import SelectionTracker from sc2reader.engine.plugins.context import ContextLoader diff --git a/sc2reader/engine/plugins/apm.py b/sc2reader/engine/plugins/apm.py index ec6fee7c..d1b7ad38 100644 --- a/sc2reader/engine/plugins/apm.py +++ b/sc2reader/engine/plugins/apm.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - from collections import defaultdict -class APMTracker(object): +class APMTracker: """ Builds ``player.aps`` and ``player.apm`` dictionaries where an action is any Selection, ControlGroup, or Command event. diff --git a/sc2reader/engine/plugins/context.py b/sc2reader/engine/plugins/context.py index 5a8fb34a..1a07ca6c 100644 --- a/sc2reader/engine/plugins/context.py +++ b/sc2reader/engine/plugins/context.py @@ -1,13 +1,11 @@ -# -*- coding: utf-8 -*- # TODO: Dry this up a bit! -from __future__ import absolute_import, print_function, unicode_literals, division from sc2reader.log_utils import loggable from sc2reader.utils import Length @loggable -class ContextLoader(object): +class ContextLoader: name = "ContextLoader" def handleInitGame(self, event, replay): @@ -45,7 +43,7 @@ def handleCommandEvent(self, event, replay): event.logger.error("\t" + player.__str__()) self.logger.error( - "{0}\t{1}\tMissing ability {2:X} from {3}".format( + "{}\t{}\tMissing ability {:X} from {}".format( event.frame, event.player.name, event.ability_id, @@ -60,7 +58,7 @@ def handleCommandEvent(self, event, replay): if event.other_unit_id in replay.objects: event.other_unit = replay.objects[event.other_unit_id] elif event.other_unit_id is not None: - self.logger.error("Other unit {0} not found".format(event.other_unit_id)) + self.logger.error(f"Other unit {event.other_unit_id} not found") def handleTargetUnitCommandEvent(self, event, replay): self.last_target_ability_event[event.player.pid] = event @@ -199,13 +197,13 @@ def handleUnitDiedEvent(self, event, replay): del replay.active_units[event.unit_id_index] else: self.logger.error( - "Unable to delete unit index {0} at {1} [{2}], index not active.".format( + "Unable to delete unit index {} at {} [{}], index not active.".format( event.killer_pid, Length(seconds=event.second), event.frame ) ) else: self.logger.error( - "Unit {0} died at {1} [{2}] before it was born!".format( + "Unit {} died at {} [{}] before it was born!".format( event.unit_id, Length(seconds=event.second), event.frame ) ) @@ -217,7 +215,7 @@ def handleUnitDiedEvent(self, event, replay): event.killing_player.killed_units.append(event.unit) elif event.killing_player_id: self.logger.error( - "Unknown killing player id {0} at {1} [{2}]".format( + "Unknown killing player id {} at {} [{}]".format( event.killing_player_id, Length(seconds=event.second), event.frame ) ) @@ -229,7 +227,7 @@ def handleUnitDiedEvent(self, event, replay): event.killing_unit.killed_units.append(event.unit) elif event.killing_unit_id: self.logger.error( - "Unknown killing unit id {0} at {1} [{2}]".format( + "Unknown killing unit id {} at {} [{}]".format( event.killing_unit_id, Length(seconds=event.second), event.frame ) ) @@ -245,7 +243,7 @@ def handleUnitOwnerChangeEvent(self, event, replay): event.unit = replay.objects[event.unit_id] else: self.logger.error( - "Unit {0} owner changed at {1} [{2}] before it was born!".format( + "Unit {} owner changed at {} [{}] before it was born!".format( event.unit_id, Length(seconds=event.second), event.frame ) ) @@ -265,7 +263,7 @@ def handleUnitTypeChangeEvent(self, event, replay): replay.datapack.change_type(event.unit, event.unit_type_name, event.frame) else: self.logger.error( - "Unit {0} type changed at {1} [{2}] before it was born!".format( + "Unit {} type changed at {} [{}] before it was born!".format( event.unit_id, Length(seconds=event.second) ) ) @@ -308,7 +306,7 @@ def handleUnitDoneEvent(self, event, replay): event.unit.finished_at = event.frame else: self.logger.error( - "Unit {0} done at {1} [{2}] before it was started!".format( + "Unit {} done at {} [{}] before it was started!".format( event.killer_pid, Length(seconds=event.second), event.frame ) ) @@ -324,7 +322,7 @@ def handleUnitPositionsEvent(self, event, replay): event.units[unit] = unit.location else: self.logger.error( - "Unit at active_unit index {0} moved at {1} [{2}] but it doesn't exist!".format( + "Unit at active_unit index {} moved at {} [{}] but it doesn't exist!".format( event.killer_pid, Length(seconds=event.second), event.frame ) ) @@ -338,7 +336,7 @@ def load_message_game_player(self, event, replay): event.player.events.append(event) elif event.pid != 16: self.logger.error( - "Bad pid ({0}) for event {1} at {2} [{3}].".format( + "Bad pid ({}) for event {} at {} [{}].".format( event.pid, event.__class__, Length(seconds=event.second), @@ -354,7 +352,7 @@ def load_message_game_player(self, event, replay): event.player.events.append(event) elif event.pid != 16: self.logger.error( - "Bad pid ({0}) for event {1} at {2} [{3}].".format( + "Bad pid ({}) for event {} at {} [{}].".format( event.pid, event.__class__, Length(seconds=event.second), @@ -369,7 +367,7 @@ def load_tracker_player(self, event, replay): event.player = replay.entity[event.pid] else: self.logger.error( - "Bad pid ({0}) for event {1} at {2} [{3}].".format( + "Bad pid ({}) for event {} at {} [{}].".format( event.pid, event.__class__, Length(seconds=event.second), @@ -382,7 +380,7 @@ def load_tracker_upkeeper(self, event, replay): event.unit_upkeeper = replay.entity[event.upkeep_pid] elif event.upkeep_pid != 0: self.logger.error( - "Bad upkeep_pid ({0}) for event {1} at {2} [{3}].".format( + "Bad upkeep_pid ({}) for event {} at {} [{}].".format( event.upkeep_pid, event.__class__, Length(seconds=event.second), @@ -395,7 +393,7 @@ def load_tracker_controller(self, event, replay): event.unit_controller = replay.entity[event.control_pid] elif event.control_pid != 0: self.logger.error( - "Bad control_pid ({0}) for event {1} at {2} [{3}].".format( + "Bad control_pid ({}) for event {} at {} [{}].".format( event.control_pid, event.__class__, Length(seconds=event.second), diff --git a/sc2reader/engine/plugins/creeptracker.py b/sc2reader/engine/plugins/creeptracker.py index 5a56b4f2..90f01e0c 100644 --- a/sc2reader/engine/plugins/creeptracker.py +++ b/sc2reader/engine/plugins/creeptracker.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - from io import BytesIO try: @@ -21,7 +18,7 @@ from itertools import tee # The creep tracker plugin -class CreepTracker(object): +class CreepTracker: """ The Creep tracker populates player.max_creep_spread and player.creep_spread by minute @@ -41,14 +38,14 @@ def handleInitGame(self, event, replay): if player.play_race[0] == "Z": self.creepTracker.init_cgu_lists(player.pid) except Exception as e: - print("Whoa! {}".format(e)) + print(f"Whoa! {e}") pass def handleUnitDiedEvent(self, event, replay): try: self.creepTracker.remove_from_list(event.unit_id, event.second) except Exception as e: - print("Whoa! {}".format(e)) + print(f"Whoa! {e}") pass def handleUnitInitEvent(self, event, replay): @@ -62,7 +59,7 @@ def handleUnitInitEvent(self, event, replay): event.second, ) except Exception as e: - print("Whoa! {}".format(e)) + print(f"Whoa! {e}") pass def handleUnitBornEvent(self, event, replay): @@ -76,7 +73,7 @@ def handleUnitBornEvent(self, event, replay): event.second, ) except Exception as e: - print("Whoa! {}".format(e)) + print(f"Whoa! {e}") pass def handleEndGame(self, event, replay): @@ -98,7 +95,7 @@ def handleEndGame(self, event, replay): ## Else statement is for players with no creep spread(ie: not Zerg) player.max_creep_spread = 0 except Exception as e: - print("Whoa! {}".format(e)) + print(f"Whoa! {e}") pass diff --git a/sc2reader/engine/plugins/gameheart.py b/sc2reader/engine/plugins/gameheart.py index d3905624..f2af2e82 100644 --- a/sc2reader/engine/plugins/gameheart.py +++ b/sc2reader/engine/plugins/gameheart.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - from datetime import datetime from sc2reader.utils import Length, get_real_type from sc2reader.objects import Observer, Team @@ -8,7 +5,7 @@ from sc2reader.constants import GAME_SPEED_FACTOR -class GameHeartNormalizer(object): +class GameHeartNormalizer: """ normalize a GameHeart replay to: 1) reset frames to the game start diff --git a/sc2reader/engine/plugins/selection.py b/sc2reader/engine/plugins/selection.py index 52f50c65..006ac78e 100644 --- a/sc2reader/engine/plugins/selection.py +++ b/sc2reader/engine/plugins/selection.py @@ -1,8 +1,4 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - - -class SelectionTracker(object): +class SelectionTracker: """ Tracks a player's active selection as an input into other plugins. diff --git a/sc2reader/engine/plugins/supply.py b/sc2reader/engine/plugins/supply.py index 8305e50b..6935b847 100644 --- a/sc2reader/engine/plugins/supply.py +++ b/sc2reader/engine/plugins/supply.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - from collections import defaultdict -class SupplyTracker(object): +class SupplyTracker: def add_to_units_alive(self, event, replay): unit_name = event.unit_type_name if unit_name in self.unit_name_to_supply: @@ -14,7 +11,7 @@ def add_to_units_alive(self, event, replay): time_built = 0 if time_built < 0 else time_built new_unit = (supplyCount, event.unit_id) self.units_alive[event.control_pid].append(new_unit) - total_supply = sum([x[0] for x in self.units_alive[event.control_pid]]) + total_supply = sum(x[0] for x in self.units_alive[event.control_pid]) replay.players[event.control_pid - 1].current_food_used[ time_built ] = total_supply @@ -33,7 +30,7 @@ def add_to_units_alive(self, event, replay): time_complete = event.second + build_time supply_gen_unit = (supply_gen_count, event.unit_id) self.supply_gen[event.control_pid].append(supply_gen_unit) - total_supply_gen = sum([x[0] for x in self.supply_gen[event.control_pid]]) + total_supply_gen = sum(x[0] for x in self.supply_gen[event.control_pid]) replay.players[event.control_pid - 1].current_food_made[ time_complete ] = total_supply_gen @@ -45,7 +42,7 @@ def add_to_units_alive(self, event, replay): replay.players[event.control_pid - 1].current_food_made[time_complete], ) else: - print("Unit name {0} does not exist".format(event.unit_type_name)) + print(f"Unit name {event.unit_type_name} does not exist") return def remove_from_units_alive(self, event, replay): @@ -54,7 +51,7 @@ def remove_from_units_alive(self, event, replay): dead_unit = filter(lambda x: x[1] == died_unit_id, self.units_alive[player]) if dead_unit: self.units_alive[player].remove(dead_unit[0]) - total_supply = sum([x[0] for x in self.units_alive[player]]) + total_supply = sum(x[0] for x in self.units_alive[player]) replay.players[player - 1].current_food_used[ event.second @@ -73,7 +70,7 @@ def remove_from_units_alive(self, event, replay): ) if dead_supply_gen: self.supply_gen[player].remove(dead_supply_gen[0]) - total_supply_gen = sum([x[0] for x in self.supply_gen[player]]) + total_supply_gen = sum(x[0] for x in self.supply_gen[player]) replay.players[player - 1].current_food_made[ event.second ] = total_supply_gen diff --git a/sc2reader/engine/utils.py b/sc2reader/engine/utils.py index c8ca4af5..4c62597e 100644 --- a/sc2reader/engine/utils.py +++ b/sc2reader/engine/utils.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - from bisect import bisect_left @@ -13,7 +10,7 @@ def __init__(self, initial_state): def __getitem__(self, frame): if frame in self: - return super(GameState, self).__getitem__(frame) + return super().__getitem__(frame) # Get the previous frame from our sorted frame list # bisect_left returns the left most key where an item is @@ -42,4 +39,4 @@ def __setitem__(self, frame, value): self._frames.insert(bisect_left(self._frames, frame), frame) self._frameset.add(frame) - super(GameState, self).__setitem__(frame, value) + super().__setitem__(frame, value) diff --git a/sc2reader/events/__init__.py b/sc2reader/events/__init__.py index 6ceaa632..126f482a 100644 --- a/sc2reader/events/__init__.py +++ b/sc2reader/events/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - # Export all events of all types to the package interface from sc2reader.events import base, game, message, tracker from sc2reader.events.base import * diff --git a/sc2reader/events/base.py b/sc2reader/events/base.py index 89f16c5e..7245c4e2 100644 --- a/sc2reader/events/base.py +++ b/sc2reader/events/base.py @@ -1,6 +1,2 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - - -class Event(object): +class Event: name = "Event" diff --git a/sc2reader/events/game.py b/sc2reader/events/game.py index 82232011..2d04c4c2 100644 --- a/sc2reader/events/game.py +++ b/sc2reader/events/game.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - from sc2reader.utils import Length from sc2reader.events.base import Event from sc2reader.log_utils import loggable @@ -41,14 +38,14 @@ def _str_prefix(self): if getattr(self, "pid", 16) == 16: player_name = "Global" elif self.player and not self.player.name: - player_name = "Player {0} - ({1})".format( + player_name = "Player {} - ({})".format( self.player.pid, self.player.play_race ) elif self.player: player_name = self.player.name else: player_name = "no name" - return "{0}\t{1:<15} ".format(Length(seconds=int(self.frame / 16)), player_name) + return f"{Length(seconds=int(self.frame / 16))}\t{player_name:<15} " def __str__(self): return self._str_prefix() + self.name @@ -61,7 +58,7 @@ class GameStartEvent(GameEvent): """ def __init__(self, frame, pid, data): - super(GameStartEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: ??? self.data = data @@ -73,7 +70,7 @@ class PlayerLeaveEvent(GameEvent): """ def __init__(self, frame, pid, data): - super(PlayerLeaveEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: ??? self.data = data @@ -86,7 +83,7 @@ class UserOptionsEvent(GameEvent): """ def __init__(self, frame, pid, data): - super(UserOptionsEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: self.game_fully_downloaded = data["game_fully_downloaded"] @@ -145,7 +142,7 @@ class CommandEvent(GameEvent): """ def __init__(self, frame, pid, data): - super(CommandEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: Flags on the command??? self.flags = data["flags"] @@ -240,19 +237,19 @@ def __init__(self, frame, pid, data): def __str__(self): string = self._str_prefix() if self.has_ability: - string += "Ability ({0:X})".format(self.ability_id) + string += f"Ability ({self.ability_id:X})" if self.ability: - string += " - {0}".format(self.ability.name) + string += f" - {self.ability.name}" else: string += "Right Click" if self.ability_type == "TargetUnit": - string += "; Target: {0} [{1:0>8X}]".format( + string += "; Target: {} [{:0>8X}]".format( self.target.name, self.target_unit_id ) if self.ability_type in ("TargetPoint", "TargetUnit"): - string += "; Location: {0}".format(str(self.location)) + string += f"; Location: {str(self.location)}" return string @@ -268,7 +265,7 @@ class BasicCommandEvent(CommandEvent): """ def __init__(self, frame, pid, data): - super(BasicCommandEvent, self).__init__(frame, pid, data) + super().__init__(frame, pid, data) class TargetPointCommandEvent(CommandEvent): @@ -284,7 +281,7 @@ class TargetPointCommandEvent(CommandEvent): """ def __init__(self, frame, pid, data): - super(TargetPointCommandEvent, self).__init__(frame, pid, data) + super().__init__(frame, pid, data) #: The x coordinate of the target. Available for TargetPoint and TargetUnit type events. self.x = self.ability_type_data["point"].get("x", 0) / 4096.0 @@ -312,7 +309,7 @@ class TargetUnitCommandEvent(CommandEvent): """ def __init__(self, frame, pid, data): - super(TargetUnitCommandEvent, self).__init__(frame, pid, data) + super().__init__(frame, pid, data) #: Flags set on the target unit. Available for TargetUnit type events self.target_flags = self.ability_type_data.get("flags", None) @@ -393,7 +390,7 @@ class DataCommandEvent(CommandEvent): """ def __init__(self, frame, pid, data): - super(DataCommandEvent, self).__init__(frame, pid, data) + super().__init__(frame, pid, data) #: Other target data. Available for Data type events. self.target_data = self.ability_type_data.get("data", None) @@ -410,7 +407,7 @@ class CommandManagerStateEvent(GameEvent): """ def __init__(self, frame, pid, data): - super(CommandManagerStateEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: Always 1? self.state = data["state"] @@ -433,7 +430,7 @@ class SelectionEvent(GameEvent): """ def __init__(self, frame, pid, data): - super(SelectionEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: The control group being modified. 10 for active selection self.control_group = data["control_group_index"] @@ -554,7 +551,7 @@ class ControlGroupEvent(GameEvent): """ def __init__(self, frame, pid, data): - super(ControlGroupEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: Index to the control group being modified self.control_group = data["control_group_index"] @@ -612,7 +609,7 @@ class CameraEvent(GameEvent): """ def __init__(self, frame, pid, data): - super(CameraEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: The x coordinate of the center of the camera self.x = (data["target"]["x"] if data["target"] is not None else 0) / 256.0 @@ -633,7 +630,7 @@ def __init__(self, frame, pid, data): self.yaw = data["yaw"] def __str__(self): - return self._str_prefix() + "{0} at ({1}, {2})".format( + return self._str_prefix() + "{} at ({}, {})".format( self.name, self.x, self.y ) @@ -646,7 +643,7 @@ class ResourceTradeEvent(GameEvent): """ def __init__(self, frame, pid, data): - super(ResourceTradeEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: The id of the player sending the resources self.sender_id = pid @@ -676,7 +673,7 @@ def __init__(self, frame, pid, data): self.custom_resource = self.resources[3] if len(self.resources) >= 4 else None def __str__(self): - return self._str_prefix() + " transfer {0} minerals, {1} gas, {2} terrazine, and {3} custom to {4}".format( + return self._str_prefix() + " transfer {} minerals, {} gas, {} terrazine, and {} custom to {}".format( self.minerals, self.vespene, self.terrazine, @@ -691,7 +688,7 @@ class ResourceRequestEvent(GameEvent): """ def __init__(self, frame, pid, data): - super(ResourceRequestEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: An array of resources sent self.resources = data["resources"] @@ -711,7 +708,7 @@ def __init__(self, frame, pid, data): def __str__(self): return ( self._str_prefix() - + " requests {0} minerals, {1} gas, {2} terrazine, and {3} custom".format( + + " requests {} minerals, {} gas, {} terrazine, and {} custom".format( self.minerals, self.vespene, self.terrazine, self.custom_resource ) ) @@ -723,7 +720,7 @@ class ResourceRequestFulfillEvent(GameEvent): """ def __init__(self, frame, pid, data): - super(ResourceRequestFulfillEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: The id of the request being fulfilled self.request_id = data["request_id"] @@ -735,7 +732,7 @@ class ResourceRequestCancelEvent(GameEvent): """ def __init__(self, frame, pid, data): - super(ResourceRequestCancelEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: The id of the request being cancelled self.request_id = data["request_id"] @@ -747,7 +744,7 @@ class HijackReplayGameEvent(GameEvent): """ def __init__(self, frame, pid, data): - super(HijackReplayGameEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: The method used. Not sure what 0/1 represent self.method = data["method"] diff --git a/sc2reader/events/message.py b/sc2reader/events/message.py index 57da5dce..c1848f64 100644 --- a/sc2reader/events/message.py +++ b/sc2reader/events/message.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - from sc2reader.events.base import Event from sc2reader.utils import Length from sc2reader.log_utils import loggable @@ -27,7 +24,7 @@ def __init__(self, frame, pid): def _str_prefix(self): player_name = self.player.name if getattr(self, "pid", 16) != 16 else "Global" - return "{0}\t{1:<15} ".format(Length(seconds=int(self.frame / 16)), player_name) + return f"{Length(seconds=int(self.frame / 16))}\t{player_name:<15} " def __str__(self): return self._str_prefix() + self.name @@ -40,7 +37,7 @@ class ChatEvent(MessageEvent): """ def __init__(self, frame, pid, target, text): - super(ChatEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: The numerical target type. 0 = to all; 2 = to allies; 4 = to observers. self.target = target @@ -64,7 +61,7 @@ class ProgressEvent(MessageEvent): """ def __init__(self, frame, pid, progress): - super(ProgressEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: Marks the load progress for the player. Scaled 0-100. self.progress = progress @@ -77,7 +74,7 @@ class PingEvent(MessageEvent): """ def __init__(self, frame, pid, target, x, y): - super(PingEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: The numerical target type. 0 = to all; 2 = to allies; 4 = to observers. self.target = target diff --git a/sc2reader/events/tracker.py b/sc2reader/events/tracker.py index 6220d5fe..7355ef35 100644 --- a/sc2reader/events/tracker.py +++ b/sc2reader/events/tracker.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import functools from sc2reader.events.base import Event @@ -29,7 +26,7 @@ def load_context(self, replay): pass def _str_prefix(self): - return "{0}\t ".format(Length(seconds=int(self.frame / 16))) + return f"{Length(seconds=int(self.frame / 16))}\t " def __str__(self): return self._str_prefix() + self.name @@ -39,7 +36,7 @@ class PlayerSetupEvent(TrackerEvent): """Sent during game setup to help us organize players better""" def __init__(self, frames, data, build): - super(PlayerSetupEvent, self).__init__(frames) + super().__init__(frames) #: The player id of the player we are setting up self.pid = data[0] @@ -68,7 +65,7 @@ class PlayerStatsEvent(TrackerEvent): """ def __init__(self, frames, data, build): - super(PlayerStatsEvent, self).__init__(frames) + super().__init__(frames) #: Id of the player the stats are for self.pid = data[0] @@ -275,7 +272,7 @@ def __init__(self, frames, data, build): ) def __str__(self): - return self._str_prefix() + "{0: >15} - Stats Update".format(str(self.player)) + return self._str_prefix() + f"{str(self.player): >15} - Stats Update" class UnitBornEvent(TrackerEvent): @@ -291,7 +288,7 @@ class UnitBornEvent(TrackerEvent): """ def __init__(self, frames, data, build): - super(UnitBornEvent, self).__init__(frames) + super().__init__(frames) #: The index portion of the unit id self.unit_id_index = data[0] @@ -337,7 +334,7 @@ def __init__(self, frames, data, build): self.location = (self.x, self.y) def __str__(self): - return self._str_prefix() + "{0: >15} - Unit born {1}".format( + return self._str_prefix() + "{: >15} - Unit born {}".format( str(self.unit_upkeeper), self.unit ) @@ -349,7 +346,7 @@ class UnitDiedEvent(TrackerEvent): """ def __init__(self, frames, data, build): - super(UnitDiedEvent, self).__init__(frames) + super().__init__(frames) #: The index portion of the unit id self.unit_id_index = data[0] @@ -412,7 +409,7 @@ def __init__(self, frames, data, build): ) def __str__(self): - return self._str_prefix() + "{0: >15} - Unit died {1}.".format( + return self._str_prefix() + "{: >15} - Unit died {}.".format( str(self.unit.owner), self.unit ) @@ -424,7 +421,7 @@ class UnitOwnerChangeEvent(TrackerEvent): """ def __init__(self, frames, data, build): - super(UnitOwnerChangeEvent, self).__init__(frames) + super().__init__(frames) #: The index portion of the unit id self.unit_id_index = data[0] @@ -451,7 +448,7 @@ def __init__(self, frames, data, build): self.unit_controller = None def __str__(self): - return self._str_prefix() + "{0: >15} took {1}".format( + return self._str_prefix() + "{: >15} took {}".format( str(self.unit_upkeeper), self.unit ) @@ -464,7 +461,7 @@ class UnitTypeChangeEvent(TrackerEvent): """ def __init__(self, frames, data, build): - super(UnitTypeChangeEvent, self).__init__(frames) + super().__init__(frames) #: The index portion of the unit id self.unit_id_index = data[0] @@ -482,7 +479,7 @@ def __init__(self, frames, data, build): self.unit_type_name = data[2].decode("utf8") def __str__(self): - return self._str_prefix() + "{0: >15} - Unit {1} type changed to {2}".format( + return self._str_prefix() + "{: >15} - Unit {} type changed to {}".format( str(self.unit.owner), self.unit, self.unit_type_name ) @@ -493,7 +490,7 @@ class UpgradeCompleteEvent(TrackerEvent): """ def __init__(self, frames, data, build): - super(UpgradeCompleteEvent, self).__init__(frames) + super().__init__(frames) #: The player that completed the upgrade self.pid = data[0] @@ -508,7 +505,7 @@ def __init__(self, frames, data, build): self.count = data[2] def __str__(self): - return self._str_prefix() + "{0: >15} - {1} upgrade completed".format( + return self._str_prefix() + "{: >15} - {} upgrade completed".format( str(self.player), self.upgrade_type_name ) @@ -521,7 +518,7 @@ class UnitInitEvent(TrackerEvent): """ def __init__(self, frames, data, build): - super(UnitInitEvent, self).__init__(frames) + super().__init__(frames) #: The index portion of the unit id self.unit_id_index = data[0] @@ -567,7 +564,7 @@ def __init__(self, frames, data, build): self.location = (self.x, self.y) def __str__(self): - return self._str_prefix() + "{0: >15} - Unit initiated {1}".format( + return self._str_prefix() + "{: >15} - Unit initiated {}".format( str(self.unit_upkeeper), self.unit ) @@ -579,7 +576,7 @@ class UnitDoneEvent(TrackerEvent): """ def __init__(self, frames, data, build): - super(UnitDoneEvent, self).__init__(frames) + super().__init__(frames) #: The index portion of the unit id self.unit_id_index = data[0] @@ -594,7 +591,7 @@ def __init__(self, frames, data, build): self.unit = None def __str__(self): - return self._str_prefix() + "{0: >15} - Unit {1} done".format( + return self._str_prefix() + "{: >15} - Unit {} done".format( str(self.unit.owner), self.unit ) @@ -607,7 +604,7 @@ class UnitPositionsEvent(TrackerEvent): """ def __init__(self, frames, data, build): - super(UnitPositionsEvent, self).__init__(frames) + super().__init__(frames) #: The starting unit index point. self.first_unit_index = data[0] diff --git a/sc2reader/exceptions.py b/sc2reader/exceptions.py index dff2d31b..5dc20e81 100644 --- a/sc2reader/exceptions.py +++ b/sc2reader/exceptions.py @@ -1,7 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - - class SC2ReaderError(Exception): pass @@ -29,10 +25,10 @@ class MultipleMatchingFilesError(SC2ReaderError): class ReadError(SC2ReaderError): def __init__(self, msg, type, location, replay=None, game_events=[], buffer=None): self.__dict__.update(locals()) - super(ReadError, self).__init__(msg) + super().__init__(msg) def __str__(self): - return "{0}, Type: {1}".format(self.msg, self.type) + return f"{self.msg}, Type: {self.type}" class ParseError(SC2ReaderError): diff --git a/sc2reader/factories/__init__.py b/sc2reader/factories/__init__.py index c6c469f6..744e1aae 100644 --- a/sc2reader/factories/__init__.py +++ b/sc2reader/factories/__init__.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, print_function, unicode_literals, division - from sc2reader.factories.sc2factory import SC2Factory from sc2reader.factories.sc2factory import FileCachedSC2Factory from sc2reader.factories.sc2factory import DictCachedSC2Factory diff --git a/sc2reader/factories/plugins/replay.py b/sc2reader/factories/plugins/replay.py index f7669ef7..b3ba681b 100644 --- a/sc2reader/factories/plugins/replay.py +++ b/sc2reader/factories/plugins/replay.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import json from collections import defaultdict @@ -159,7 +156,7 @@ def SelectionTracker(replay): selections[event.control_group] = control_group if debug: logger.info( - "[{0}] {1} selected {2} units: {3}".format( + "[{}] {} selected {} units: {}".format( Length(seconds=event.second), person.name, len(selections[0x0A].objects), @@ -172,7 +169,7 @@ def SelectionTracker(replay): selections[event.control_group] = selections[0x0A].copy() if debug: logger.info( - "[{0}] {1} set hotkey {2} to current selection".format( + "[{}] {} set hotkey {} to current selection".format( Length(seconds=event.second), person.name, event.hotkey ) ) @@ -185,7 +182,7 @@ def SelectionTracker(replay): selections[event.control_group] = control_group if debug: logger.info( - "[{0}] {1} added current selection to hotkey {2}".format( + "[{}] {} added current selection to hotkey {}".format( Length(seconds=event.second), person.name, event.hotkey ) ) @@ -197,7 +194,7 @@ def SelectionTracker(replay): selections[0xA] = control_group if debug: logger.info( - "[{0}] {1} retrieved hotkey {2}, {3} units: {4}".format( + "[{}] {} retrieved hotkey {}, {} units: {}".format( Length(seconds=event.second), person.name, event.control_group, @@ -216,7 +213,7 @@ def SelectionTracker(replay): person.selection_errors += 1 if debug: logger.warn( - "Error detected in deselection mode {0}.".format( + "Error detected in deselection mode {}.".format( event.mask_type ) ) diff --git a/sc2reader/factories/plugins/utils.py b/sc2reader/factories/plugins/utils.py index 7eef123a..f747c36f 100644 --- a/sc2reader/factories/plugins/utils.py +++ b/sc2reader/factories/plugins/utils.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - from bisect import bisect_left from collections import defaultdict from datetime import datetime @@ -40,7 +37,7 @@ def __init__(self, initial_state): def __getitem__(self, frame): if frame in self: - return super(GameState, self).__getitem__(frame) + return super().__getitem__(frame) # Get the previous frame from our sorted frame list # bisect_left returns the left most key where an item is @@ -69,11 +66,11 @@ def __setitem__(self, frame, value): self._frames.insert(bisect_left(self._frames, frame), frame) self._frameset.add(frame) - super(GameState, self).__setitem__(frame, value) + super().__setitem__(frame, value) @loggable -class UnitSelection(object): +class UnitSelection: def __init__(self, objects=None): self.objects = objects or list() @@ -95,7 +92,7 @@ def deselect(self, mode, data): # pad to the right mask = mask + [False] * (len(self.objects) - len(mask)) - self.logger.debug("Deselection Mask: {0}".format(mask)) + self.logger.debug(f"Deselection Mask: {mask}") self.objects = [ obj for (slct, obj) in filter( @@ -130,7 +127,7 @@ def copy(self): class PlayerSelection(defaultdict): def __init__(self): - super(PlayerSelection, self).__init__(UnitSelection) + super().__init__(UnitSelection) def copy(self): new = PlayerSelection() diff --git a/sc2reader/factories/sc2factory.py b/sc2reader/factories/sc2factory.py index 1bde3ac1..e4b38c6f 100644 --- a/sc2reader/factories/sc2factory.py +++ b/sc2reader/factories/sc2factory.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - from collections import defaultdict from io import BytesIO import os @@ -27,7 +24,7 @@ @log_utils.loggable -class SC2Factory(object): +class SC2Factory: """ The SC2Factory class acts as a generic loader interface for all available to sc2reader resources. At current time this includes @@ -262,7 +259,7 @@ def get_remote_cache_key(self, remote_resource): def load_remote_resource_contents(self, remote_resource, **options): cache_key = self.get_remote_cache_key(remote_resource) if not self.cache_has(cache_key): - resource = super(CachedSC2Factory, self).load_remote_resource_contents( + resource = super().load_remote_resource_contents( remote_resource, **options ) self.cache_set(cache_key, resource) @@ -290,15 +287,15 @@ class FileCachedSC2Factory(CachedSC2Factory): """ def __init__(self, cache_dir, **options): - super(FileCachedSC2Factory, self).__init__(**options) + super().__init__(**options) self.cache_dir = os.path.abspath(cache_dir) if not os.path.isdir(self.cache_dir): raise ValueError( - "cache_dir ({0}) must be an existing directory.".format(self.cache_dir) + f"cache_dir ({self.cache_dir}) must be an existing directory." ) elif not os.access(self.cache_dir, os.F_OK | os.W_OK | os.R_OK): raise ValueError( - "Must have read/write access to {0} for local file caching.".format( + "Must have read/write access to {} for local file caching.".format( self.cache_dir ) ) @@ -333,7 +330,7 @@ class DictCachedSC2Factory(CachedSC2Factory): """ def __init__(self, cache_max_size=0, **options): - super(DictCachedSC2Factory, self).__init__(**options) + super().__init__(**options) self.cache_dict = dict() self.cache_used = dict() self.cache_max_size = cache_max_size @@ -366,7 +363,7 @@ class DoubleCachedSC2Factory(DictCachedSC2Factory, FileCachedSC2Factory): """ def __init__(self, cache_dir, cache_max_size=0, **options): - super(DoubleCachedSC2Factory, self).__init__( + super().__init__( cache_max_size, cache_dir=cache_dir, **options ) diff --git a/sc2reader/log_utils.py b/sc2reader/log_utils.py index c4288820..3337e348 100644 --- a/sc2reader/log_utils.py +++ b/sc2reader/log_utils.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import logging try: @@ -78,7 +75,7 @@ def get_logger(entity): return logging.getLogger(entity.__module__ + "." + entity.__name__) except AttributeError: - raise TypeError("Cannot retrieve logger for {0}.".format(entity)) + raise TypeError(f"Cannot retrieve logger for {entity}.") def loggable(cls): diff --git a/sc2reader/objects.py b/sc2reader/objects.py index 11ef8eb7..2949b516 100644 --- a/sc2reader/objects.py +++ b/sc2reader/objects.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import hashlib import math from collections import namedtuple @@ -12,7 +9,7 @@ Location = namedtuple("Location", ["x", "y"]) -class Team(object): +class Team: """ The team object primarily a container object for organizing :class:`Player` objects with some metadata. As such, it implements iterable and can be @@ -22,7 +19,7 @@ class Team(object): """ #: A unique hash identifying the team of players - hash = str() + hash = '' #: The team number as recorded in the replay number = int() @@ -32,7 +29,7 @@ class Team(object): #: The result of the game for this team. #: One of "Win", "Loss", or "Unknown" - result = str() + result = '' def __init__(self, number): self.number = number @@ -56,7 +53,7 @@ def hash(self): return hashlib.sha256(raw_hash).hexdigest() def __str__(self): - return "Team {0}: {1}".format( + return "Team {}: {}".format( self.number, ", ".join([str(p) for p in self.players]) ) @@ -65,14 +62,14 @@ def __repr__(self): @log_utils.loggable -class Attribute(object): +class Attribute: def __init__(self, header, attr_id, player, value): self.header = header self.id = attr_id self.player = player if self.id not in LOBBY_PROPERTIES: - self.logger.info("Unknown attribute id: {0}".format(self.id)) + self.logger.info(f"Unknown attribute id: {self.id}") self.name = "Unknown" self.value = None else: @@ -80,17 +77,17 @@ def __init__(self, header, attr_id, player, value): try: self.value = lookup[value.strip("\x00 ")[::-1]] except KeyError: - self.logger.info("Missing attribute value: {0}".format(value)) + self.logger.info(f"Missing attribute value: {value}") self.value = None def __repr__(self): return str(self) def __str__(self): - return "[{0}] {1}: {2}".format(self.player, self.name, self.value) + return f"[{self.player}] {self.name}: {self.value}" -class Entity(object): +class Entity: """ :param integer sid: The entity's unique slot id. :param dict slot_data: The slot data associated with this entity @@ -164,7 +161,7 @@ def format(self, format_string): return format_string.format(**self.__dict__) -class Player(object): +class Player: """ :param integer pid: The player's unique player id. :param dict detail_data: The detail data associated with this player @@ -253,7 +250,7 @@ def __init__(self, pid, slot_data, detail_data, attribute_data): self.toon_id = detail_data["bnet"]["uid"] -class User(object): +class User: """ :param integer uid: The user's unique user id :param dict init_data: The init data associated with this user @@ -317,7 +314,7 @@ def __init__(self, sid, slot_data, uid, init_data, pid): self.pid = pid def __str__(self): - return "Observer {0} - {1}".format(self.uid, self.name) + return f"Observer {self.uid} - {self.name}" def __repr__(self): return str(self) @@ -342,7 +339,7 @@ def __init__(self, sid, slot_data, pid, detail_data, attribute_data): self.name = detail_data["name"] def __str__(self): - return "Player {0} - {1} ({2})".format(self.pid, self.name, self.play_race) + return f"Player {self.pid} - {self.name} ({self.play_race})" def __repr__(self): return str(self) @@ -369,7 +366,7 @@ def __init__( Player.__init__(self, pid, slot_data, detail_data, attribute_data) def __str__(self): - return "Player {0} - {1} ({2})".format(self.pid, self.name, self.play_race) + return f"Player {self.pid} - {self.name} ({self.play_race})" def __repr__(self): return str(self) @@ -388,10 +385,10 @@ class PlayerSummary: teamid = int() #: The race the player played in the game. - play_race = str() + play_race = '' #: The race the player picked in the lobby. - pick_race = str() + pick_race = '' #: If the player is a computer is_ai = False @@ -406,7 +403,7 @@ class PlayerSummary: subregion = int() #: The player's region, such as us, eu, sea - region = str() + region = '' #: unknown1 unknown1 = int() @@ -429,11 +426,11 @@ def __init__(self, pid): def __str__(self): if not self.is_ai: - return "User {0}-S2-{1}-{2}".format( + return "User {}-S2-{}-{}".format( self.region.upper(), self.subregion, self.bnetid ) else: - return "AI ({0})".format(self.play_race) + return f"AI ({self.play_race})" def __repr__(self): return str(self) @@ -441,7 +438,7 @@ def __repr__(self): def get_stats(self): s = "" for k in self.stats: - s += "{0}: {1}\n".format(self.stats_pretty_names[k], self.stats[k]) + s += f"{self.stats_pretty_names[k]}: {self.stats[k]}\n" return s.strip() @@ -480,10 +477,10 @@ def as_points(self): return list(zip(self.times, self.values)) def __str__(self): - return "Graph with {0} values".format(len(self.times)) + return f"Graph with {len(self.times)} values" -class MapInfoPlayer(object): +class MapInfoPlayer: """ Describes the player data as found in the MapInfo document of SC2Map archives. """ @@ -542,7 +539,7 @@ def __init__(self, pid, control, color, race, unknown, start_point, ai, decal): @log_utils.loggable -class MapInfo(object): +class MapInfo: """ Represents the data encoded into the MapInfo file inside every SC2Map archive """ @@ -553,7 +550,7 @@ def __init__(self, contents): data = ByteDecoder(contents, endian="LITTLE") magic = data.read_string(4) if magic != "MapI": - self.logger.warn("Invalid MapInfo file: {0}".format(magic)) + self.logger.warn(f"Invalid MapInfo file: {magic}") return #: The map info file format version @@ -572,7 +569,7 @@ def __init__(self, contents): self.small_preview_type = data.read_uint32() #: (Optional) Small map preview path; relative to root of map archive - self.small_preview_path = str() + self.small_preview_path = '' if self.small_preview_type == 2: self.small_preview_path = data.read_cstring() @@ -580,7 +577,7 @@ def __init__(self, contents): self.large_preview_type = data.read_uint32() #: (Optional) Large map preview path; relative to root of map archive - self.large_preview_path = str() + self.large_preview_path = '' if self.large_preview_type == 2: self.large_preview_path = data.read_cstring() diff --git a/sc2reader/readers.py b/sc2reader/readers.py index 89ba67fc..92aeefb9 100644 --- a/sc2reader/readers.py +++ b/sc2reader/readers.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import struct from sc2reader.exceptions import ParseError, ReadError @@ -12,7 +9,7 @@ from sc2reader.decoders import BitPackedDecoder, ByteDecoder -class InitDataReader(object): +class InitDataReader: def __call__(self, data, replay): data = BitPackedDecoder(data) result = dict( @@ -292,11 +289,11 @@ def __call__(self, data, replay): ), ) if not data.done(): - raise ValueError("{0} bytes left!".format(data.length - data.tell())) + raise ValueError(f"{data.length - data.tell()} bytes left!") return result -class AttributesEventsReader(object): +class AttributesEventsReader: def __call__(self, data, replay): data = ByteDecoder(data, endian="LITTLE") data.read_bytes(5 if replay.base_build >= 17326 else 4) @@ -314,7 +311,7 @@ def __call__(self, data, replay): return result -class DetailsReader(object): +class DetailsReader: def __call__(self, data, replay): details = BitPackedDecoder(data).read_struct() return dict( @@ -363,7 +360,7 @@ def __call__(self, data, replay): ) -class MessageEventsReader(object): +class MessageEventsReader: def __call__(self, data, replay): data = BitPackedDecoder(data) pings = list() @@ -402,7 +399,7 @@ def __call__(self, data, replay): return dict(pings=pings, messages=messages, packets=packets) -class GameEventsReader_Base(object): +class GameEventsReader_Base: def __init__(self): self.EVENT_DISPATCH = { 0: (None, self.unknown_event), @@ -523,7 +520,7 @@ def __call__(self, data, replay): # Otherwise throw a read error else: raise ReadError( - "Event type {0} unknown at position {1}.".format( + "Event type {} unknown at position {}.".format( hex(event_type), hex(event_start) ), event_type, @@ -539,7 +536,7 @@ def __call__(self, data, replay): return game_events except ParseError as e: raise ReadError( - "Parse error '{0}' unknown at position {1}.".format( + "Parse error '{}' unknown at position {}.".format( e.msg, hex(event_start) ), event_type, @@ -550,7 +547,7 @@ def __call__(self, data, replay): ) except EOFError as e: raise ReadError( - "EOFError error '{0}' unknown at position {1}.".format( + "EOFError error '{}' unknown at position {}.".format( e.msg, hex(event_start) ), event_type, @@ -585,7 +582,7 @@ def read_selection_bitmask(self, data, mask_length): bits_left -= 8 # Compile the finished mask into a large integer for bit checks - bit_mask = sum([c << (i * 8) for i, c in enumerate(mask)]) + bit_mask = sum(c << (i * 8) for i, c in enumerate(mask)) # Change mask representation from an int to a bit array with # True => Deselect, False => Keep @@ -1097,7 +1094,7 @@ class GameEventsReader_16939(GameEventsReader_16755): class GameEventsReader_17326(GameEventsReader_16939): def __init__(self): - super(GameEventsReader_17326, self).__init__() + super().__init__() self.EVENT_DISPATCH.update({59: (None, self.trigger_mouse_moved_event)}) @@ -1257,7 +1254,7 @@ class GameEventsReader_21029(GameEventsReader_19595): class GameEventsReader_22612(GameEventsReader_21029): def __init__(self): - super(GameEventsReader_22612, self).__init__() + super().__init__() self.EVENT_DISPATCH.update( { @@ -1551,7 +1548,7 @@ def trigger_dialog_control_event(self, data): class GameEventsReader_24247(GameEventsReader_HotSBeta): def __init__(self): - super(GameEventsReader_24247, self).__init__() + super().__init__() self.EVENT_DISPATCH.update( { @@ -1736,7 +1733,7 @@ def game_user_join_event(self, data): class GameEventsReader_34784(GameEventsReader_27950): def __init__(self): - super(GameEventsReader_34784, self).__init__() + super().__init__() self.EVENT_DISPATCH.update( { @@ -1987,7 +1984,7 @@ def control_group_update_event(self, data): class GameEventsReader_38215(GameEventsReader_36442): def __init__(self): - super(GameEventsReader_38215, self).__init__() + super().__init__() self.EVENT_DISPATCH.update( { @@ -2188,7 +2185,7 @@ class GameEventsReader_65895(GameEventsReader_64469): """ def __init__(self): - super(GameEventsReader_65895, self).__init__() + super().__init__() self.EVENT_DISPATCH.update( {116: (None, self.set_sync_loading), 117: (None, self.set_sync_playing)} @@ -2260,7 +2257,7 @@ def command_event(self, data): ) -class TrackerEventsReader(object): +class TrackerEventsReader: def __init__(self): self.EVENT_DISPATCH = { 0: PlayerStatsEvent, diff --git a/sc2reader/resources.py b/sc2reader/resources.py index 428e9cc9..564801d3 100644 --- a/sc2reader/resources.py +++ b/sc2reader/resources.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - from collections import defaultdict, namedtuple from datetime import datetime import hashlib @@ -29,7 +26,7 @@ from sc2reader.constants import GAME_SPEED_FACTOR, LOBBY_PROPERTIES -class Resource(object): +class Resource: def __init__(self, file_object, filename=None, factory=None, **options): self.factory = factory self.opt = options @@ -50,7 +47,7 @@ class Replay(Resource): attributes = defaultdict(dict) #: Fully qualified filename of the replay file represented. - filename = str() + filename = '' #: Total number of frames in this game at 16 frames per second. frames = int() @@ -62,27 +59,27 @@ class Replay(Resource): base_build = int() #: The full version release string as seen on Battle.net - release_string = str() + release_string = '' #: A tuple of the individual pieces of the release string versions = tuple() #: The game speed: Slower, Slow, Normal, Fast, Faster - speed = str() + speed = '' #: Deprecated, use :attr:`game_type` or :attr:`real_type` instead - type = str() + type = '' #: The game type chosen at game creation: 1v1, 2v2, 3v3, 4v4, FFA - game_type = str() + game_type = '' #: The real type of the replay as observed by counting players on teams. #: For outmatched games, the smaller team numbers come first. #: Example Values: 1v1, 2v2, 3v3, FFA, 2v4, etc. - real_type = str() + real_type = '' #: The category of the game, Ladder and Private - category = str() + category = '' #: A flag for public ladder games is_ladder = bool() @@ -91,10 +88,10 @@ class Replay(Resource): is_private = bool() #: The raw hash name of the s2ma resource as hosted on bnet depots - map_hash = str() + map_hash = '' #: The name of the map the game was played on - map_name = str() + map_name = '' #: A reference to the loaded :class:`Map` resource. map = None @@ -130,7 +127,7 @@ class Replay(Resource): real_length = None #: The region the game was played on: us, eu, sea, etc - region = str() + region = '' #: An integrated list of all the game events events = list() @@ -187,10 +184,10 @@ class Replay(Resource): #: A sha256 hash uniquely representing the combination of people in the game. #: Can be used in conjunction with date times to match different replays #: of the game game. - people_hash = str() + people_hash = '' #: SC2 Expansion. One of 'WoL', 'HotS' - expansion = str() + expansion = '' #: True of the game was resumed from a replay resume_from_replay = False @@ -210,7 +207,7 @@ def __init__( do_tracker_events=True, **options ): - super(Replay, self).__init__(replay_file, filename, **options) + super().__init__(replay_file, filename, **options) self.datapack = None self.raw_data = dict() @@ -277,7 +274,7 @@ def __init__( self.frames = header_data[3] self.build = self.versions[4] self.base_build = self.versions[5] - self.release_string = "{0}.{1}.{2}.{3}".format(*self.versions[1:5]) + self.release_string = "{}.{}.{}.{}".format(*self.versions[1:5]) fps = self.game_fps if 34784 <= self.build: # lotv replay, adjust time fps = self.game_fps * 1.4 @@ -396,17 +393,17 @@ def load_details(self): dependency_hashes = [d.hash for d in details["cache_handles"]] if ( - hashlib.sha256("Standard Data: Void.SC2Mod".encode("utf8")).hexdigest() + hashlib.sha256(b"Standard Data: Void.SC2Mod").hexdigest() in dependency_hashes ): self.expansion = "LotV" elif ( - hashlib.sha256("Standard Data: Swarm.SC2Mod".encode("utf8")).hexdigest() + hashlib.sha256(b"Standard Data: Swarm.SC2Mod").hexdigest() in dependency_hashes ): self.expansion = "HotS" elif ( - hashlib.sha256("Standard Data: Liberty.SC2Mod".encode("utf8")).hexdigest() + hashlib.sha256(b"Standard Data: Liberty.SC2Mod").hexdigest() in dependency_hashes ): self.expansion = "WoL" @@ -550,14 +547,14 @@ def get_team(team_id): # Pull results up for teams for team in self.teams: - results = set([p.result for p in team.players]) + results = {p.result for p in team.players} if len(results) == 1: team.result = list(results)[0] if team.result == "Win": self.winner = team else: self.logger.warn( - "Conflicting results for Team {0}: {1}".format(team.number, results) + f"Conflicting results for Team {team.number}: {results}" ) team.result = "Unknown" @@ -884,7 +881,7 @@ def _get_reader(self, data_file): return reader else: raise ValueError( - "Valid {0} reader could not found for build {1}".format( + "Valid {} reader could not found for build {}".format( data_file, self.build ) ) @@ -904,7 +901,7 @@ def _read_data(self, data_file, reader): "replay.message.events", "replay.tracker.events", ]: - raise ValueError("{0} not found in archive".format(data_file)) + raise ValueError(f"{data_file} not found in archive") def __getstate__(self): state = self.__dict__.copy() @@ -915,19 +912,19 @@ def __getstate__(self): class Map(Resource): def __init__(self, map_file, filename=None, region=None, map_hash=None, **options): - super(Map, self).__init__(map_file, filename, **options) + super().__init__(map_file, filename, **options) #: The localized (only enUS supported right now) map name. - self.name = str() + self.name = '' #: The localized (only enUS supported right now) map author. - self.author = str() + self.author = '' #: The localized (only enUS supported right now) map description. - self.description = str() + self.description = '' #: The localized (only enUS supported right now) map website. - self.website = str() + self.website = '' #: The unique hash used to identify this map on bnet's depots. self.hash = map_hash @@ -949,7 +946,7 @@ def __init__(self, map_file, filename=None, region=None, map_hash=None, **option # just because US English wasn't a concern of the map author. # TODO: Make this work regardless of the localizations available. game_strings_file = self.archive.read_file( - "enUS.SC2Data\LocalizedData\GameStrings.txt" + r"enUS.SC2Data\LocalizedData\GameStrings.txt" ) if game_strings_file: for line in game_strings_file.decode("utf8").split("\r\n"): @@ -1018,7 +1015,7 @@ class GameSummary(Resource): """ #: Game speed - game_speed = str() + game_speed = '' #: Game length (real-time) real_length = int() @@ -1045,7 +1042,7 @@ class GameSummary(Resource): localization_urls = dict() def __init__(self, summary_file, filename=None, lang="enUS", **options): - super(GameSummary, self).__init__(summary_file, filename, lang=lang, **options) + super().__init__(summary_file, filename, lang=lang, **options) #: A dict of team# -> teams self.team = dict() @@ -1072,8 +1069,8 @@ def __init__(self, summary_file, filename=None, lang="enUS", **options): self.localization_urls = dict() self.lobby_properties = dict() self.lobby_player_properties = dict() - self.game_type = str() - self.real_type = str() + self.game_type = '' + self.real_type = '' # The first 16 bytes appear to be some sort of compression header buffer = BitPackedDecoder(zlib.decompress(summary_file.read()[16:])) @@ -1256,7 +1253,7 @@ def use_property(prop, player=None): # Because of the above complication we resort to a set intersection of # the applicable values and the set of required values. - if not set(requirement.values[val][0] for val in values) & set(req[1]): + if not {requirement.values[val][0] for val in values} & set(req[1]): break else: @@ -1283,7 +1280,7 @@ def use_property(prop, player=None): def load_player_stats(self): translation = self.translations[self.opt["lang"]] - stat_items = sum([p[0] for p in self.parts[3:]], []) + stat_items = sum((p[0] for p in self.parts[3:]), []) for item in stat_items: # Each stat item is laid out as follows @@ -1336,7 +1333,7 @@ def load_player_stats(self): ) ) elif stat_id != 83886080: # We know this one is always bad. - self.logger.warn("Untranslatable key = {0}".format(stat_id)) + self.logger.warn(f"Untranslatable key = {stat_id}") # Once we've compiled all the build commands we need to make # sure they are properly sorted for presentation. @@ -1432,7 +1429,7 @@ def load_players(self): self.player[player.pid] = player def __str__(self): - return "{0} - {1} {2}".format( + return "{} - {} {}".format( self.start_time, self.game_length, "v".join( @@ -1445,19 +1442,19 @@ class MapHeader(Resource): """**Experimental**""" #: The name of the map - name = str() + name = '' #: Hash of map file - map_hash = str() + map_hash = '' #: Link to the map file - map_url = str() + map_url = '' #: Hash of the map image - image_hash = str() + image_hash = '' #: Link to the image of the map (.s2mv) - image_url = str() + image_url = '' #: Localization dictionary, {language, url} localization_urls = dict() @@ -1466,7 +1463,7 @@ class MapHeader(Resource): blizzard = False def __init__(self, header_file, filename=None, **options): - super(MapHeader, self).__init__(header_file, filename, **options) + super().__init__(header_file, filename, **options) self.data = BitPackedDecoder(header_file).read_struct() # Name diff --git a/sc2reader/scripts/__init__.py b/sc2reader/scripts/__init__.py index e826f791..551b70ab 100755 --- a/sc2reader/scripts/__init__.py +++ b/sc2reader/scripts/__init__.py @@ -1,5 +1,2 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - # import submodules from sc2reader.scripts import utils diff --git a/sc2reader/scripts/sc2attributes.py b/sc2reader/scripts/sc2attributes.py index a794e235..7eba02ca 100644 --- a/sc2reader/scripts/sc2attributes.py +++ b/sc2reader/scripts/sc2attributes.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Recursively searches for s2gs files in specified paths. Adds # new attributes and values and allows the user to choose when @@ -28,7 +27,6 @@ # those decisions. The decisions are pickled instead of in json # because the data structure is too complex for the json format. # -from __future__ import absolute_import, print_function, unicode_literals, division import argparse import json @@ -64,7 +62,7 @@ def main(): attributes = dict() if os.path.exists(data_path): - with open(data_path, "r") as data_file: + with open(data_path) as data_file: data = json.load(data_file) attributes = data.get("attributes", attributes) decisions = pickle.loads(data.get("decisions", "(dp0\n.")) @@ -100,7 +98,7 @@ def main(): attribute_values[str(value_key)] = value_name - attributes["{0:0>4}".format(group_key)] = ( + attributes[f"{group_key:0>4}"] = ( group_name, attribute_values, ) @@ -122,15 +120,15 @@ def get_choice(s2gs_key, old_value, new_value): key = frozenset([s2gs_key, old_value, new_value]) if key not in decisions: print( - "Naming conflict on {0}: {1} != {2}".format(s2gs_key, old_value, new_value) + f"Naming conflict on {s2gs_key}: {old_value} != {new_value}" ) print("Which do you want to use?") - print(" (o) Old value '{0}'".format(old_value)) - print(" (n) New value '{0}'".format(new_value)) + print(f" (o) Old value '{old_value}'") + print(f" (n) New value '{new_value}'") while True: answer = raw_input("Choose 'o' or 'n' then press enter: ").lower() if answer not in ("o", "n"): - print("Invalid choice `{0}`".format(answer)) + print(f"Invalid choice `{answer}`") else: break decisions[key] = {"o": old_value, "n": new_value}[answer] diff --git a/sc2reader/scripts/sc2json.py b/sc2reader/scripts/sc2json.py index c7e842e8..d2fdb8ef 100755 --- a/sc2reader/scripts/sc2json.py +++ b/sc2reader/scripts/sc2json.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division import sc2reader from sc2reader.factories.plugins.replay import toJSON diff --git a/sc2reader/scripts/sc2parse.py b/sc2reader/scripts/sc2parse.py index 868f897a..3f0aab6f 100755 --- a/sc2reader/scripts/sc2parse.py +++ b/sc2reader/scripts/sc2parse.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- """ This script is intended for use debugging parse issues on replays. @@ -16,7 +15,6 @@ If there are parse exceptions, this script should be run to generate an info for the ticket filed. """ -from __future__ import absolute_import, print_function, unicode_literals, division import argparse import sc2reader @@ -46,7 +44,7 @@ def main(): releases_parsed = set() for folder in args.folders: - print("dealing with {0}".format(folder)) + print(f"dealing with {folder}") for path in sc2reader.utils.get_files(folder, extension="SC2Replay"): try: rs = sc2reader.load_replay(path, load_level=0).release_string @@ -57,24 +55,20 @@ def main(): if not args.one_each or replay.is_ladder: replay = sc2reader.load_replay(path, debug=True) - human_pids = set([human.pid for human in replay.humans]) - event_pids = set( - [ + human_pids = {human.pid for human in replay.humans} + event_pids = { event.player.pid for event in replay.events if getattr(event, "player", None) - ] - ) - player_pids = set( - [player.pid for player in replay.players if player.is_human] - ) - ability_pids = set( - [ + } + player_pids = { + player.pid for player in replay.players if player.is_human + } + ability_pids = { event.player.pid for event in replay.events if "CommandEvent" in event.name - ] - ) + } if human_pids != event_pids: print( "Event Pid problem! pids={pids} but event pids={event_pids}".format( @@ -105,9 +99,9 @@ def main(): ) print( "Units were: {units}".format( - units=set( - [obj.name for obj in replay.objects.values()] - ) + units={ + obj.name for obj in replay.objects.values() + } ) ) @@ -124,7 +118,7 @@ def main(): ) print("[ERROR] {}", e) for event in e.game_events[-5:]: - print("{0}".format(event)) + print(f"{event}") print(e.buffer.read_range(e.location, e.location + 50).encode("hex")) print except Exception as e: @@ -137,13 +131,13 @@ def main(): **replay.__dict__ ) ) - print("[ERROR] {0}".format(e)) + print(f"[ERROR] {e}") for pid, attributes in replay.attributes.items(): - print("{0} {1}".format(pid, attributes)) + print(f"{pid} {attributes}") for pid, info in enumerate(replay.players): - print("{0} {1}".format(pid, info)) + print(f"{pid} {info}") for message in replay.messages: - print("{0} {1}".format(message.pid, message.text)) + print(f"{message.pid} {message.text}") traceback.print_exc() print("") except Exception as e2: @@ -153,8 +147,8 @@ def main(): **replay.__dict__ ) ) - print("[ERROR] {0}".format(e)) - print("[ERROR] {0}".format(e2)) + print(f"[ERROR] {e}") + print(f"[ERROR] {e2}") traceback.print_exc() print diff --git a/sc2reader/scripts/sc2printer.py b/sc2reader/scripts/sc2printer.py index f27fda49..25b58189 100755 --- a/sc2reader/scripts/sc2printer.py +++ b/sc2reader/scripts/sc2printer.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division import os import argparse @@ -16,37 +14,37 @@ def printReplay(filepath, arguments): replay = sc2reader.load_replay(filepath, debug=True) if arguments.map: - print(" Map: {0}".format(replay.map_name)) + print(f" Map: {replay.map_name}") if arguments.length: - print(" Length: {0} minutes".format(replay.game_length)) + print(f" Length: {replay.game_length} minutes") if arguments.date: - print(" Date: {0}".format(replay.start_time)) + print(f" Date: {replay.start_time}") if arguments.teams: lineups = [team.lineup for team in replay.teams] - print(" Teams: {0}".format("v".join(lineups))) + print(" Teams: {}".format("v".join(lineups))) for team in replay.teams: print( - " Team {0}\t{1} ({2})".format( + " Team {}\t{} ({})".format( team.number, team.players[0].name, team.players[0].pick_race[0] ) ) for player in team.players[1:]: print( - " \t{0} ({1})".format( + " \t{} ({})".format( player.name, player.pick_race[0] ) ) if arguments.observers: print(" Observers:") for observer in replay.observers: - print(" {0}".format(observer.name)) + print(f" {observer.name}") if arguments.messages: print(" Messages:") for message in replay.messages: - print(" {0}".format(message)) + print(f" {message}") if arguments.version: - print(" Version: {0}".format(replay.release_string)) + print(f" Version: {replay.release_string}") print except ReadError as e: @@ -54,19 +52,19 @@ def printReplay(filepath, arguments): return prev = e.game_events[-1] print( - "\nVersion {0} replay:\n\t{1}".format( + "\nVersion {} replay:\n\t{}".format( e.replay.release_string, e.replay.filepath ) ) - print("\t{0}, Type={1:X}".format(e.msg, e.type)) - print("\tPrevious Event: {0}".format(prev.name)) + print(f"\t{e.msg}, Type={e.type:X}") + print(f"\tPrevious Event: {prev.name}") print("\t\t" + prev.bytes.encode("hex")) print("\tFollowing Bytes:") print("\t\t" + e.buffer.read_range(e.location, e.location + 30).encode("hex")) - print("Error with '{0}': ".format(filepath)) + print(f"Error with '{filepath}': ") print(e) except Exception as e: - print("Error with '{0}': ".format(filepath)) + print(f"Error with '{filepath}': ") print(e) raise @@ -75,21 +73,21 @@ def printGameSummary(filepath, arguments): summary = sc2reader.load_game_summary(filepath) if arguments.map: - print(" Map: {0}".format(summary.map_name)) + print(f" Map: {summary.map_name}") if arguments.length: - print(" Length: {0} minutes".format(summary.game_length)) + print(f" Length: {summary.game_length} minutes") if arguments.date: - print(" Date: {0}".format(summary.start_time)) + print(f" Date: {summary.start_time}") if arguments.teams: lineups = [team.lineup for team in summary.teams] - print(" Teams: {0}".format("v".join(lineups))) + print(" Teams: {}".format("v".join(lineups))) for team in summary.teams: - print(" Team {0}\t{1}".format(team.number, team.players[0])) + print(f" Team {team.number}\t{team.players[0]}") for player in team.players[1:]: - print(" \t{0}".format(player)) + print(f" \t{player}") if arguments.builds: for player in summary.players: - print("\n== {0} ==\n".format(player)) + print(f"\n== {player} ==\n") for order in summary.build_orders[player.pid]: msg = " {0:0>2}:{1:0>2} {2:<35} {3:0>2}/{4}" print( @@ -177,12 +175,12 @@ def main(): name, ext = os.path.splitext(filepath) if ext.lower() == ".sc2replay": print( - "\n--------------------------------------\n{0}\n".format(filepath) + f"\n--------------------------------------\n{filepath}\n" ) printReplay(filepath, arguments) elif ext.lower() == ".s2gs": print( - "\n--------------------------------------\n{0}\n".format(filepath) + f"\n--------------------------------------\n{filepath}\n" ) printGameSummary(filepath, arguments) diff --git a/sc2reader/scripts/sc2replayer.py b/sc2reader/scripts/sc2replayer.py index 3d8212ca..c3e61b5e 100755 --- a/sc2reader/scripts/sc2replayer.py +++ b/sc2reader/scripts/sc2replayer.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division try: # Assume that we are on *nix or Mac @@ -22,7 +20,7 @@ def getch(): try: sys.stdin.read(1) break - except IOError: + except OSError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) @@ -78,15 +76,15 @@ def main(): for filename in sc2reader.utils.get_files(args.FILE): replay = sc2reader.load_replay(filename, debug=True) - print("Release {0}".format(replay.release_string)) + print(f"Release {replay.release_string}") print( - "{0} on {1} at {2}".format(replay.type, replay.map_name, replay.start_time) + f"{replay.type} on {replay.map_name} at {replay.start_time}" ) print("") for team in replay.teams: print(team) for player in team.players: - print(" {0}".format(player)) + print(f" {player}") print("\n--------------------------\n\n") # Allow picking of the player to 'watch' diff --git a/sc2reader/scripts/utils.py b/sc2reader/scripts/utils.py index cf998e5d..cab32a13 100644 --- a/sc2reader/scripts/utils.py +++ b/sc2reader/scripts/utils.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import argparse import re import textwrap diff --git a/sc2reader/utils.py b/sc2reader/utils.py index 93787212..514ca807 100644 --- a/sc2reader/utils.py +++ b/sc2reader/utils.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import binascii import os import json @@ -11,7 +8,7 @@ from sc2reader.constants import COLOR_CODES, COLOR_CODES_INV -class DepotFile(object): +class DepotFile: """ :param bytes: The raw bytes representing the depot file @@ -49,7 +46,7 @@ def windows_to_unix(windows_time): @loggable -class Color(object): +class Color: """ Stores a color name and rgba representation of a color. Individual color components can be retrieved with the dot operator:: @@ -145,7 +142,7 @@ def recovery_attempt(): # Python2 and Python3 handle wrapped exceptions with old tracebacks in incompatible ways # Python3 handles it by default and Python2's method won't compile in python3 # Since the underlying traceback isn't important to most people, don't expose it anymore - raise MPQError("Unable to extract file: {0}".format(data_file), e) + raise MPQError(f"Unable to extract file: {data_file}", e) def get_files( @@ -162,7 +159,7 @@ def get_files( """ # os.walk and os.path.isfile fail silently. We want to be loud! if not os.path.exists(path): - raise ValueError("Location `{0}` does not exist".format(path)) + raise ValueError(f"Location `{path}` does not exist") # If an extension is supplied, use it to do a type check if extension: @@ -235,9 +232,9 @@ def secs(self): def __str__(self): if self.hours: - return "{0:0>2}.{1:0>2}.{2:0>2}".format(self.hours, self.mins, self.secs) + return f"{self.hours:0>2}.{self.mins:0>2}.{self.secs:0>2}" else: - return "{0:0>2}.{1:0>2}".format(self.mins, self.secs) + return f"{self.mins:0>2}.{self.secs:0>2}" class JSONDateEncoder(json.JSONEncoder): diff --git a/test_replays/test_replays.py b/test_replays/test_replays.py index 2b1d1492..a7f7ac37 100644 --- a/test_replays/test_replays.py +++ b/test_replays/test_replays.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals - import datetime import json from xml.dom import minidom @@ -214,16 +211,14 @@ def test_hots_pids(self): replay = sc2reader.load_replay(replayfilename) self.assertEqual(replay.expansion, "HotS") - player_pids = set( - [player.pid for player in replay.players if player.is_human] - ) - ability_pids = set( - [ + player_pids = { + player.pid for player in replay.players if player.is_human + } + ability_pids = { event.player.pid for event in replay.events if "CommandEvent" in event.name - ] - ) + } self.assertEqual(ability_pids, player_pids) def test_wol_pids(self): @@ -231,27 +226,23 @@ def test_wol_pids(self): "test_replays/1.5.4.24540/ggtracker_1471849.SC2Replay" ) self.assertEqual(replay.expansion, "WoL") - ability_pids = set( - [ + ability_pids = { event.player.pid for event in replay.events if "CommandEvent" in event.name - ] - ) - player_pids = set([player.pid for player in replay.players]) + } + player_pids = {player.pid for player in replay.players} self.assertEqual(ability_pids, player_pids) def test_hots_hatchfun(self): replay = sc2reader.load_replay("test_replays/2.0.0.24247/molten.SC2Replay") - player_pids = set([player.pid for player in replay.players]) - spawner_pids = set( - [ + player_pids = {player.pid for player in replay.players} + spawner_pids = { event.player.pid for event in replay.events if "TargetUnitCommandEvent" in event.name and event.ability.name == "SpawnLarva" - ] - ) + } self.assertTrue(spawner_pids.issubset(player_pids)) def test_hots_vs_ai(self): @@ -407,15 +398,13 @@ def test_gameheartnormalizer_plugin(self): # Not a GameHeart game! replay = sc2reader.load_replay("test_replays/2.0.0.24247/molten.SC2Replay") - player_pids = set([player.pid for player in replay.players]) - spawner_pids = set( - [ + player_pids = {player.pid for player in replay.players} + spawner_pids = { event.player.pid for event in replay.events if "TargetUnitCommandEvent" in event.name and event.ability.name == "SpawnLarva" - ] - ) + } self.assertTrue(spawner_pids.issubset(player_pids)) replay = sc2reader.load_replay("test_replays/gameheart/gameheart.SC2Replay") @@ -541,8 +530,8 @@ def test_30(self): def test_31(self): for i in range(1, 5): - print("DOING {}".format(i)) - replay = sc2reader.load_replay("test_replays/3.1.0/{}.SC2Replay".format(i)) + print(f"DOING {i}") + replay = sc2reader.load_replay(f"test_replays/3.1.0/{i}.SC2Replay") def test_30_map(self): for replayfilename in ["test_replays/3.0.0.38215/third.SC2Replay"]: @@ -587,13 +576,11 @@ def test_funny_minerals(self): if "MineralField" in ou.attributes["UnitType"].value ] mineralFieldNames = list( - set( - [ + { ou.attributes["UnitType"].value for ou in itemlist if "MineralField" in ou.attributes["UnitType"].value - ] - ) + } ) # print(mineralFieldNames) self.assertTrue(len(mineralPosStrs) > 0) @@ -609,7 +596,7 @@ def test_32(self): def test_33(self): for replaynum in range(1, 4): replay = sc2reader.load_replay( - "test_replays/3.3.0/{}.SC2Replay".format(replaynum) + f"test_replays/3.3.0/{replaynum}.SC2Replay" ) self.assertTrue(replay is not None) @@ -727,7 +714,7 @@ def test_game_event_string(self): player.play_race = "TestRace" event = GameEvent(16, 16) event.player = player - self.assertEqual("{0}\t{1:<15} ".format(time, "Global"), event._str_prefix()) + self.assertEqual("{}\t{:<15} ".format(time, "Global"), event._str_prefix()) # Player with name player = MockPlayer() @@ -735,12 +722,12 @@ def test_game_event_string(self): player.play_race = "TestRace" event = GameEvent(16, 1) event.player = player - self.assertEqual("{0}\t{1:<15} ".format(time, player.name), event._str_prefix()) + self.assertEqual(f"{time}\t{player.name:<15} ", event._str_prefix()) # No Player player = MockPlayer() event = GameEvent(16, 1) - self.assertEqual("{0}\t{1:<15} ".format(time, "no name"), event._str_prefix()) + self.assertEqual("{}\t{:<15} ".format(time, "no name"), event._str_prefix()) # Player without name player = MockPlayer() @@ -749,13 +736,13 @@ def test_game_event_string(self): event = GameEvent(16, 1) event.player = player self.assertEqual( - "{0}\tPlayer {1} - ({2}) ".format(time, player.pid, player.play_race), + f"{time}\tPlayer {player.pid} - ({player.play_race}) ", event._str_prefix(), ) class TestGameEngine(unittest.TestCase): - class TestEvent(object): + class TestEvent: name = "TestEvent" def __init__(self, value): @@ -764,7 +751,7 @@ def __init__(self, value): def __str__(self): return self.value - class TestPlugin1(object): + class TestPlugin1: name = "TestPlugin1" def handleInitGame(self, event, replay): @@ -782,7 +769,7 @@ def handleTestEvent(self, event, replay): def handleEndGame(self, event, replay): yield TestGameEngine.TestEvent("g") - class TestPlugin2(object): + class TestPlugin2: name = "TestPlugin2" def handleInitGame(self, event, replay): @@ -797,7 +784,7 @@ def handlePluginExit(self, event, replay): def handleEndGame(self, event, replay): yield TestGameEngine.TestEvent("f") - class MockReplay(object): + class MockReplay: def __init__(self, events): self.events = events @@ -813,7 +800,7 @@ def test_plugin1(self): self.assertEqual(replay.plugin_result["TestPlugin2"], (0, dict())) -class MockPlayer(object): +class MockPlayer: def __init__(self): self.name = None self.play_race = None diff --git a/test_s2gs/test_all.py b/test_s2gs/test_all.py index be867add..75a1daa9 100644 --- a/test_s2gs/test_all.py +++ b/test_s2gs/test_all.py @@ -1,5 +1,3 @@ -# -*- coding: UTF-8 -*- - # Newer unittest features aren't built in for python 2.6 import sys From 1f18ff757e91801190ddffb95da2f12da2c52adf Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 25 May 2022 18:40:18 +0200 Subject: [PATCH 2/2] Update README.rst and setup.py --- README.rst | 16 ++++----- sc2reader/decoders.py | 4 +-- sc2reader/events/game.py | 19 +++++----- sc2reader/factories/plugins/replay.py | 4 +-- sc2reader/factories/sc2factory.py | 8 ++--- sc2reader/objects.py | 14 ++++---- sc2reader/resources.py | 50 +++++++++++++-------------- sc2reader/scripts/sc2attributes.py | 4 +-- sc2reader/scripts/sc2parse.py | 16 ++++----- sc2reader/scripts/sc2printer.py | 8 ++--- sc2reader/scripts/sc2replayer.py | 4 +-- setup.py | 10 ++---- test_replays/test_replays.py | 40 +++++++++------------ 13 files changed, 82 insertions(+), 115 deletions(-) diff --git a/README.rst b/README.rst index dcbcb938..63d74a99 100644 --- a/README.rst +++ b/README.rst @@ -4,7 +4,7 @@ What is sc2reader? ==================== -sc2reader is a python library for extracting information from various different Starcraft II resources. These resources currently include Replays, Maps, and Game Summaries; we have plans to add support for Battle.net profiles and would gladly accept adapters to the more entrenched SCII sites such as sc2ranks. +sc2reader is a Python 3 library for extracting information from various different Starcraft II resources. These resources currently include Replays, Maps, and Game Summaries; we have plans to add support for Battle.net profiles and would gladly accept adapters to the more entrenched SCII sites such as sc2ranks. There is a pressing need in the SC2 community for better statistics, better analytics, better tools for organizing and searching replays. Better websites for sharing replays and hosting tournaments. These tools can't be created without first being able to open up Starcraft II game files and analyze the data within. Our goal is to give anyone and everyone the power to construct their own tools, do their own analysis, and hack on their own Starcraft II projects under the open MIT license. @@ -195,7 +195,7 @@ The new GameHeartNormalizerplugin is registered by default. Installation ================ -sc2reader runs on any system with Python 2.6+, 3.2+, or PyPy installed. +sc2reader runs on any system with Python 3.7+, or PyPy3 installed. From PyPI (stable) @@ -203,18 +203,14 @@ From PyPI (stable) Install from the latest release on PyPI with pip:: - pip install sc2reader - -or easy_install:: - - easy_install sc2reader + python3 -m pip install sc2reader or with setuptools (specify a valid x.x.x):: wget http://pypi.python.org/packages/source/s/sc2reader/sc2reader-x.x.x.tar.gz tar -xzf sc2reader-x.x.x.tar.gz cd sc2reader-x.x.x - python setup.py install + python3 setup.py install Releases to PyPi can be very delayed (sorry!), for the latest and greatest you are encouraged to install from Github upstream. @@ -235,7 +231,7 @@ or with setuptools:: wget -O sc2reader-upstream.tar.gz https://github.com/ggtracker/sc2reader/tarball/upstream tar -xzf sc2reader-upstream.tar.gz cd sc2reader-upstream - python setup.py install + python3 setup.py install .. _circle-ci: https://circleci.com/ .. _coveralls.io: https://coveralls.io @@ -250,7 +246,7 @@ Contributors should install from an active git repository using setuptools in `d git clone https://github.com/ggtracker/sc2reader.git cd sc2reader - python setup.py develop + python3 setup.py develop Please review the `CONTRIBUTING.md`_ file and get in touch with us before doing too much work. It'll make everyone happier in the long run. diff --git a/sc2reader/decoders.py b/sc2reader/decoders.py index 9085ab7d..ed726356 100644 --- a/sc2reader/decoders.py +++ b/sc2reader/decoders.py @@ -410,9 +410,7 @@ def read_struct(self, datatype=None): elif datatype == 0x05: # Struct entries = self.read_vint() - data = { - self.read_vint(): self.read_struct() for i in range(entries) - } + data = {self.read_vint(): self.read_struct() for i in range(entries)} elif datatype == 0x06: # u8 data = ord(self._buffer.read(1)) diff --git a/sc2reader/events/game.py b/sc2reader/events/game.py index 2d04c4c2..50a9f8f0 100644 --- a/sc2reader/events/game.py +++ b/sc2reader/events/game.py @@ -630,9 +630,7 @@ def __init__(self, frame, pid, data): self.yaw = data["yaw"] def __str__(self): - return self._str_prefix() + "{} at ({}, {})".format( - self.name, self.x, self.y - ) + return self._str_prefix() + "{} at ({}, {})".format(self.name, self.x, self.y) @loggable @@ -673,12 +671,15 @@ def __init__(self, frame, pid, data): self.custom_resource = self.resources[3] if len(self.resources) >= 4 else None def __str__(self): - return self._str_prefix() + " transfer {} minerals, {} gas, {} terrazine, and {} custom to {}".format( - self.minerals, - self.vespene, - self.terrazine, - self.custom_resource, - self.recipient, + return ( + self._str_prefix() + + " transfer {} minerals, {} gas, {} terrazine, and {} custom to {}".format( + self.minerals, + self.vespene, + self.terrazine, + self.custom_resource, + self.recipient, + ) ) diff --git a/sc2reader/factories/plugins/replay.py b/sc2reader/factories/plugins/replay.py index b3ba681b..7f645eb3 100644 --- a/sc2reader/factories/plugins/replay.py +++ b/sc2reader/factories/plugins/replay.py @@ -213,9 +213,7 @@ def SelectionTracker(replay): person.selection_errors += 1 if debug: logger.warn( - "Error detected in deselection mode {}.".format( - event.mask_type - ) + "Error detected in deselection mode {}.".format(event.mask_type) ) person.selection = player_selections diff --git a/sc2reader/factories/sc2factory.py b/sc2reader/factories/sc2factory.py index e4b38c6f..c020459f 100644 --- a/sc2reader/factories/sc2factory.py +++ b/sc2reader/factories/sc2factory.py @@ -259,9 +259,7 @@ def get_remote_cache_key(self, remote_resource): def load_remote_resource_contents(self, remote_resource, **options): cache_key = self.get_remote_cache_key(remote_resource) if not self.cache_has(cache_key): - resource = super().load_remote_resource_contents( - remote_resource, **options - ) + resource = super().load_remote_resource_contents(remote_resource, **options) self.cache_set(cache_key, resource) else: resource = self.cache_get(cache_key) @@ -363,9 +361,7 @@ class DoubleCachedSC2Factory(DictCachedSC2Factory, FileCachedSC2Factory): """ def __init__(self, cache_dir, cache_max_size=0, **options): - super().__init__( - cache_max_size, cache_dir=cache_dir, **options - ) + super().__init__(cache_max_size, cache_dir=cache_dir, **options) def load_remote_resource_contents(self, remote_resource, **options): cache_key = self.get_remote_cache_key(remote_resource) diff --git a/sc2reader/objects.py b/sc2reader/objects.py index 2949b516..d6c9491d 100644 --- a/sc2reader/objects.py +++ b/sc2reader/objects.py @@ -19,7 +19,7 @@ class Team: """ #: A unique hash identifying the team of players - hash = '' + hash = "" #: The team number as recorded in the replay number = int() @@ -29,7 +29,7 @@ class Team: #: The result of the game for this team. #: One of "Win", "Loss", or "Unknown" - result = '' + result = "" def __init__(self, number): self.number = number @@ -385,10 +385,10 @@ class PlayerSummary: teamid = int() #: The race the player played in the game. - play_race = '' + play_race = "" #: The race the player picked in the lobby. - pick_race = '' + pick_race = "" #: If the player is a computer is_ai = False @@ -403,7 +403,7 @@ class PlayerSummary: subregion = int() #: The player's region, such as us, eu, sea - region = '' + region = "" #: unknown1 unknown1 = int() @@ -569,7 +569,7 @@ def __init__(self, contents): self.small_preview_type = data.read_uint32() #: (Optional) Small map preview path; relative to root of map archive - self.small_preview_path = '' + self.small_preview_path = "" if self.small_preview_type == 2: self.small_preview_path = data.read_cstring() @@ -577,7 +577,7 @@ def __init__(self, contents): self.large_preview_type = data.read_uint32() #: (Optional) Large map preview path; relative to root of map archive - self.large_preview_path = '' + self.large_preview_path = "" if self.large_preview_type == 2: self.large_preview_path = data.read_cstring() diff --git a/sc2reader/resources.py b/sc2reader/resources.py index 564801d3..2f8085d6 100644 --- a/sc2reader/resources.py +++ b/sc2reader/resources.py @@ -47,7 +47,7 @@ class Replay(Resource): attributes = defaultdict(dict) #: Fully qualified filename of the replay file represented. - filename = '' + filename = "" #: Total number of frames in this game at 16 frames per second. frames = int() @@ -59,27 +59,27 @@ class Replay(Resource): base_build = int() #: The full version release string as seen on Battle.net - release_string = '' + release_string = "" #: A tuple of the individual pieces of the release string versions = tuple() #: The game speed: Slower, Slow, Normal, Fast, Faster - speed = '' + speed = "" #: Deprecated, use :attr:`game_type` or :attr:`real_type` instead - type = '' + type = "" #: The game type chosen at game creation: 1v1, 2v2, 3v3, 4v4, FFA - game_type = '' + game_type = "" #: The real type of the replay as observed by counting players on teams. #: For outmatched games, the smaller team numbers come first. #: Example Values: 1v1, 2v2, 3v3, FFA, 2v4, etc. - real_type = '' + real_type = "" #: The category of the game, Ladder and Private - category = '' + category = "" #: A flag for public ladder games is_ladder = bool() @@ -88,10 +88,10 @@ class Replay(Resource): is_private = bool() #: The raw hash name of the s2ma resource as hosted on bnet depots - map_hash = '' + map_hash = "" #: The name of the map the game was played on - map_name = '' + map_name = "" #: A reference to the loaded :class:`Map` resource. map = None @@ -127,7 +127,7 @@ class Replay(Resource): real_length = None #: The region the game was played on: us, eu, sea, etc - region = '' + region = "" #: An integrated list of all the game events events = list() @@ -184,10 +184,10 @@ class Replay(Resource): #: A sha256 hash uniquely representing the combination of people in the game. #: Can be used in conjunction with date times to match different replays #: of the game game. - people_hash = '' + people_hash = "" #: SC2 Expansion. One of 'WoL', 'HotS' - expansion = '' + expansion = "" #: True of the game was resumed from a replay resume_from_replay = False @@ -205,7 +205,7 @@ def __init__( load_level=4, engine=sc2reader.engine, do_tracker_events=True, - **options + **options, ): super().__init__(replay_file, filename, **options) self.datapack = None @@ -915,16 +915,16 @@ def __init__(self, map_file, filename=None, region=None, map_hash=None, **option super().__init__(map_file, filename, **options) #: The localized (only enUS supported right now) map name. - self.name = '' + self.name = "" #: The localized (only enUS supported right now) map author. - self.author = '' + self.author = "" #: The localized (only enUS supported right now) map description. - self.description = '' + self.description = "" #: The localized (only enUS supported right now) map website. - self.website = '' + self.website = "" #: The unique hash used to identify this map on bnet's depots. self.hash = map_hash @@ -1015,7 +1015,7 @@ class GameSummary(Resource): """ #: Game speed - game_speed = '' + game_speed = "" #: Game length (real-time) real_length = int() @@ -1069,8 +1069,8 @@ def __init__(self, summary_file, filename=None, lang="enUS", **options): self.localization_urls = dict() self.lobby_properties = dict() self.lobby_player_properties = dict() - self.game_type = '' - self.real_type = '' + self.game_type = "" + self.real_type = "" # The first 16 bytes appear to be some sort of compression header buffer = BitPackedDecoder(zlib.decompress(summary_file.read()[16:])) @@ -1442,19 +1442,19 @@ class MapHeader(Resource): """**Experimental**""" #: The name of the map - name = '' + name = "" #: Hash of map file - map_hash = '' + map_hash = "" #: Link to the map file - map_url = '' + map_url = "" #: Hash of the map image - image_hash = '' + image_hash = "" #: Link to the image of the map (.s2mv) - image_url = '' + image_url = "" #: Localization dictionary, {language, url} localization_urls = dict() diff --git a/sc2reader/scripts/sc2attributes.py b/sc2reader/scripts/sc2attributes.py index 7eba02ca..6e2ca4d1 100644 --- a/sc2reader/scripts/sc2attributes.py +++ b/sc2reader/scripts/sc2attributes.py @@ -119,9 +119,7 @@ def get_choice(s2gs_key, old_value, new_value): # This way old/new values can be swapped and decision is remembered key = frozenset([s2gs_key, old_value, new_value]) if key not in decisions: - print( - f"Naming conflict on {s2gs_key}: {old_value} != {new_value}" - ) + print(f"Naming conflict on {s2gs_key}: {old_value} != {new_value}") print("Which do you want to use?") print(f" (o) Old value '{old_value}'") print(f" (n) New value '{new_value}'") diff --git a/sc2reader/scripts/sc2parse.py b/sc2reader/scripts/sc2parse.py index 3f0aab6f..22f792a4 100755 --- a/sc2reader/scripts/sc2parse.py +++ b/sc2reader/scripts/sc2parse.py @@ -57,17 +57,17 @@ def main(): human_pids = {human.pid for human in replay.humans} event_pids = { - event.player.pid - for event in replay.events - if getattr(event, "player", None) + event.player.pid + for event in replay.events + if getattr(event, "player", None) } player_pids = { player.pid for player in replay.players if player.is_human } ability_pids = { - event.player.pid - for event in replay.events - if "CommandEvent" in event.name + event.player.pid + for event in replay.events + if "CommandEvent" in event.name } if human_pids != event_pids: print( @@ -99,9 +99,7 @@ def main(): ) print( "Units were: {units}".format( - units={ - obj.name for obj in replay.objects.values() - } + units={obj.name for obj in replay.objects.values()} ) ) diff --git a/sc2reader/scripts/sc2printer.py b/sc2reader/scripts/sc2printer.py index 25b58189..634aff53 100755 --- a/sc2reader/scripts/sc2printer.py +++ b/sc2reader/scripts/sc2printer.py @@ -174,14 +174,10 @@ def main(): for filepath in utils.get_files(path, depth=depth): name, ext = os.path.splitext(filepath) if ext.lower() == ".sc2replay": - print( - f"\n--------------------------------------\n{filepath}\n" - ) + print(f"\n--------------------------------------\n{filepath}\n") printReplay(filepath, arguments) elif ext.lower() == ".s2gs": - print( - f"\n--------------------------------------\n{filepath}\n" - ) + print(f"\n--------------------------------------\n{filepath}\n") printGameSummary(filepath, arguments) diff --git a/sc2reader/scripts/sc2replayer.py b/sc2reader/scripts/sc2replayer.py index c3e61b5e..c6c16c93 100755 --- a/sc2reader/scripts/sc2replayer.py +++ b/sc2reader/scripts/sc2replayer.py @@ -77,9 +77,7 @@ def main(): for filename in sc2reader.utils.get_files(args.FILE): replay = sc2reader.load_replay(filename, debug=True) print(f"Release {replay.release_string}") - print( - f"{replay.type} on {replay.map_name} at {replay.start_time}" - ) + print(f"{replay.type} on {replay.map_name} at {replay.start_time}") print("") for team in replay.teams: print(team) diff --git a/setup.py b/setup.py index f0f57022..95bf19fd 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,3 @@ -import sys import setuptools setuptools.setup( @@ -20,13 +19,10 @@ "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", - "Programming Language :: Python :: 2.7", - "Programming Language :: Python :: 3.4", - "Programming Language :: Python :: 3.5", - "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", "Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python :: Implementation :: CPython", "Topic :: Games/Entertainment", @@ -44,9 +40,7 @@ "sc2json = sc2reader.scripts.sc2json:main", ] }, - install_requires=["mpyq>=0.2.3", "argparse", "ordereddict", "unittest2", "pil"] - if float(sys.version[:3]) < 2.7 - else ["mpyq>=0.2.4"], + install_requires=["mpyq", "pillow"], tests_require=["pytest"], packages=setuptools.find_packages(), include_package_data=True, diff --git a/test_replays/test_replays.py b/test_replays/test_replays.py index a7f7ac37..022be926 100644 --- a/test_replays/test_replays.py +++ b/test_replays/test_replays.py @@ -211,13 +211,11 @@ def test_hots_pids(self): replay = sc2reader.load_replay(replayfilename) self.assertEqual(replay.expansion, "HotS") - player_pids = { - player.pid for player in replay.players if player.is_human - } + player_pids = {player.pid for player in replay.players if player.is_human} ability_pids = { - event.player.pid - for event in replay.events - if "CommandEvent" in event.name + event.player.pid + for event in replay.events + if "CommandEvent" in event.name } self.assertEqual(ability_pids, player_pids) @@ -227,9 +225,7 @@ def test_wol_pids(self): ) self.assertEqual(replay.expansion, "WoL") ability_pids = { - event.player.pid - for event in replay.events - if "CommandEvent" in event.name + event.player.pid for event in replay.events if "CommandEvent" in event.name } player_pids = {player.pid for player in replay.players} self.assertEqual(ability_pids, player_pids) @@ -238,10 +234,10 @@ def test_hots_hatchfun(self): replay = sc2reader.load_replay("test_replays/2.0.0.24247/molten.SC2Replay") player_pids = {player.pid for player in replay.players} spawner_pids = { - event.player.pid - for event in replay.events - if "TargetUnitCommandEvent" in event.name - and event.ability.name == "SpawnLarva" + event.player.pid + for event in replay.events + if "TargetUnitCommandEvent" in event.name + and event.ability.name == "SpawnLarva" } self.assertTrue(spawner_pids.issubset(player_pids)) @@ -400,10 +396,10 @@ def test_gameheartnormalizer_plugin(self): replay = sc2reader.load_replay("test_replays/2.0.0.24247/molten.SC2Replay") player_pids = {player.pid for player in replay.players} spawner_pids = { - event.player.pid - for event in replay.events - if "TargetUnitCommandEvent" in event.name - and event.ability.name == "SpawnLarva" + event.player.pid + for event in replay.events + if "TargetUnitCommandEvent" in event.name + and event.ability.name == "SpawnLarva" } self.assertTrue(spawner_pids.issubset(player_pids)) @@ -577,9 +573,9 @@ def test_funny_minerals(self): ] mineralFieldNames = list( { - ou.attributes["UnitType"].value - for ou in itemlist - if "MineralField" in ou.attributes["UnitType"].value + ou.attributes["UnitType"].value + for ou in itemlist + if "MineralField" in ou.attributes["UnitType"].value } ) # print(mineralFieldNames) @@ -595,9 +591,7 @@ def test_32(self): def test_33(self): for replaynum in range(1, 4): - replay = sc2reader.load_replay( - f"test_replays/3.3.0/{replaynum}.SC2Replay" - ) + replay = sc2reader.load_replay(f"test_replays/3.3.0/{replaynum}.SC2Replay") self.assertTrue(replay is not None) def test_33_shift_click_calldown_mule(self):