diff --git a/.circleci/config.yml b/.circleci/config.yml index 1370bc61..85dfc97c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,32 +1,37 @@ version: 2.0 -my-steps: &steps +build_and_test: &build_and_test_steps - checkout - - run: sudo pip install -r requirements.txt - - run: sudo pip install flake8 pytest - - run: python --version ; pip --version ; pwd ; ls -l - # stop the build if there are Python syntax errors or undefined names - - run: flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics - # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide - - run: flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics - #- run: pytest # test_s2gs test_replays - - run: python -m unittest discover test_s2gs - - run: python -m unittest discover test_replays + # Do not use `sudo pip` + # pipx is already installed but `pipx list` is empty + - run: python --version ; pip --version ; pipx --version ; pwd ; ls -l + - run: pip install pytest -r requirements.txt + - run: pip install --editable . + - run: pytest + jobs: - Python2: + StyleCheck: docker: - - image: circleci/python:2.7.15 - steps: *steps + - image: cimg/python:3.11 + steps: + - checkout + - run: python --version ; pip --version ; pwd ; ls -l + - run: pip install black codespell ruff + - run: codespell -L queenland,uint,assertin + - run: ruff check + - run: black . --check + Python3: docker: - - image: circleci/python:3.7 - steps: *steps + - image: cimg/python:3.11 + steps: *build_and_test_steps + workflows: version: 2 build: jobs: - - Python2 + - StyleCheck - Python3 diff --git a/.gitignore b/.gitignore index 6643915a..22d56881 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ *~ *.pyc +*.ipynb +*-checkpoint* dist build sc2reader.egg-info diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 1fc93c94..00000000 --- a/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: python -python: - - 2.6 - - 2.7 - - 3.4 - - 3.6 - - pypy -install: - - python setup.py develop - - pip install coveralls hacking - - mkdir local_cache -before_script: - # stop the build if there are Python syntax errors or undefined names - - time flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics - # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide - - time flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics -script: - - SC2READER_CACHE_DIR=local_cache coverage run --source=sc2reader test_replays/test_all.py - - SC2READER_CACHE_DIR=local_cache coverage run --source=sc2reader --append test_s2gs/test_all.py -after_success: - - coveralls -branches: - only: - - master -notifications: - irc: "chat.freenode.net#sc2reader" diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 52337169..ba71454a 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,49 @@ CHANGELOG ============ +1.8.0 - May 4, 2022 +------------------- +* Fix various typos in docs #146 +* Fix various URLs for blizzard resources #151 #154 #156 +* Fix Ravager data #161 +* Add CommandManagerStateEvent #162 +* Fix participant state from gameheart #171 + + +1.7.0 - May 17, 2021 +-------------------- +* Add DOI to the README #128 +* Add various missing attributes for co-op replays #129 +* Add support for python 3.8, 3.9 #132 #136 +* Fix owner on an event with no unit #133 +* Add support for ResourceTradeEvent #135 +* Fix depot URL template #139 + +1.6.0 - July 30, 2020 +--------------------- +* Add support for protocol 80949 (StarCraft 5.0) #122 +* Fix toJson script #118 + +1.5.0 - January 18, 2020 +------------------------ +* Add support for protocol 77379 #106 #107 +* Workaround for missing data #102 #104 + +1.4.0 - August 19, 2019 +----------------------- +* Add support for protocol 75689 #95 + +1.3.2 - August 9, 2019 +---------------------- +* Allow pytest #84 +* Format code with black #87 +* Fix UnitTypeChangeEvent.__str__ #92 +* Add Stetmann #93 + +1.3.1 - November 29, 2018 +------------------------- +* Parse backup if data is missing #69 + 1.3.0 - November 16, 2018 ------------------------- * Added support for protocol 70154 (StarCraft 4.7.0) @@ -139,7 +182,7 @@ Changed Stuff (non-backwards compatible!): -------------------- * Fixes several game event parsing issues for older replays. -* Propperly maps ability ids for armory vehicle & ship armor upgrades. +* Properly maps ability ids for armory vehicle & ship armor upgrades. * Uses the US depot for SEA battle.net depot dependencies. * ``PlayerStatEvent.food_used`` and ``food_made`` are now properly divided by 4096 * ``AbilityEvent.flags`` are now processed into a dictionary mapping flag name to True/False (``AbilityEvent.flag``) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ce923408..6858ab95 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,7 +1,7 @@ Support ========= -For real-time support, please visit #sc2reader on the FreeNode.net IRC. For all other support please use the sc2reader@googlegroups.com mailing list or open an issue in the github tracker. +As of Sept 2023, the best way to get support on sc2reader is on the GitHub project page. Preferably, it would be a new discussion https://github.com/ggtracker/sc2reader/discussions but can also be submitted as n issue Issues ========= @@ -14,7 +14,22 @@ If you can't share your code/replays publicly try to replicate with a smaller sc Patches ========= -Please submit patches by pull request where possible. Patches should add a test to confirm their fix and should not break previously working tests. Circle CI automatically runs tests on each pull request so please check https://circleci.com/gh/ggtracker/sc2reader to see the results of those tests. +Please submit patches by pull request where possible. Patches should add a test to confirm their fix and should not break previously working tests. Circle CI automatically runs tests on each pull request so please check https://circleci.com/gh/ggtracker/sc2reader to see the results of those tests. If you are having trouble running/add/fixing tests for your patch let me know and I'll see if I can help. + +Coding Style +============== + +We would like our code to follow [Ruff](https://docs.astral.sh/ruff/) coding style in this project. +We use [python/black](https://github.com/python/black) in order to make our lives easier. +We propose you do the same within this project, otherwise you might be asked to +reformat your pull requests. + +It's really simple just: + + pip install black + black . + +And [there are plugins for many editors](https://black.readthedocs.io/en/stable/editor_integration.html). diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt index aea5dd40..76299e88 100644 --- a/CONTRIBUTORS.txt +++ b/CONTRIBUTORS.txt @@ -13,5 +13,6 @@ Contributors: Kevin Leung - @StoicLoofah on github Daniele Zannotti (Durrza) Mike Anderson + Christian Clauss - @cclauss on github Special thanks to ggtracker, inc (ggtracker.com) for sponsoring sc2reader's continued development. diff --git a/README.rst b/README.rst index ca2dfb3e..63d74a99 100644 --- a/README.rst +++ b/README.rst @@ -1,8 +1,10 @@ +.. image:: https://zenodo.org/badge/DOI/10.5281/zenodo.4007376.svg + :target: https://doi.org/10.5281/zenodo.4007376 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. @@ -16,7 +18,7 @@ sc2reader is currently powering: * Tools: `The Core`_ * Experiments: `Midi Conversion`_ -If you use sc2reader and you would like your tool, site, project, or implementation listed above, drop us a line on our `mailing list`_ or stop by our #sc2reader IRC channel and say hi! +If you use sc2reader and you would like your tool, site, project, or implementation listed above, drop us a line on our `mailing list`_. .. _gggreplays.com: http://gggreplays.com @@ -193,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) @@ -201,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. @@ -233,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 @@ -248,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. @@ -259,21 +257,36 @@ Please review the `CONTRIBUTING.md`_ file and get in touch with us before doing Testing ------------------- -We use the built in ``unittest`` module for testing. If you are still on Python 2.6 you will need to install ``unittest2`` because our test suite requires newer features than are included in the main distribution. +We use ``pytest`` for testing. If you don't have it just ``pip install pytest``. + +To run the tests, just do:: + + pytest + -To run the tests just use:: +When repeatedly running tests it can be very helpful to make sure you've set a local cache directory to prevent long fetch times from battle.net. +So make some local cache folder:: - python test_replays/test_all.py - python test_s2gs/test_all.py + mkdir cache -When repeatedly running tests it can be very helpful to make sure you've set a local cache directory to prevent long fetch times from battle.net:: +And then run the tests like this:: - SC2READER_CACHE_DIR=local_cache PYTHONPATH=. python -m unittest test_replays.test_all + SC2READER_CACHE_DIR=./cache pytest To run just one test: - SC2READER_CACHE_DIR=local_cache PYTHONPATH=. python -m unittest test_replays.test_all.TestReplays.test_38749 + SC2READER_CACHE_DIR=./cache pytest test_replays/test_replays.py::TestReplays::test_38749 + +If you'd like to see which are the 10 slowest tests (to find performance issues maybe):: + + pytest --durations=10 + +If you want ``pytest`` to stop after the first failing test:: + + pytest -x + +Have a look at the very fine ``pytest`` docs for more information. Good luck, have fun! diff --git a/STYLE_GUIDE.rst b/STYLE_GUIDE.rst index 26b0bb8f..a25c04ff 100644 --- a/STYLE_GUIDE.rst +++ b/STYLE_GUIDE.rst @@ -1,11 +1,14 @@ STYLE GUIDE ============== -As a rough style guide, please lint your code with pep8:: +As a rough style guide, please lint your code with black, codespell, and ruff:: - pip install pep8 - pep8 --ignore E501,E226,E241 sc2reader + pip install black codespell ruff + codespell -L queenland,uint + ruff . + black . --check +More up-to-date checks may be detailed in `.circleci/config.yml`. All files should start with the following:: @@ -17,11 +20,4 @@ All files should start with the following:: All imports should be absolute. - -All string formatting sound be done in the following style:: - - "my {0} formatted {1} string {2}".format("super", "python", "example") - "the {x} style of {y} is also {z}".format(x="dict", y="arguments", z="acceptable") - -The format argument index numbers are important for 2.6 support. ``%`` formatting is not allowed for 3.x support - +All string formatting should be done with f-strings. See https://docs.python.org/3/reference/lexical_analysis.html#f-strings diff --git a/docs/source/articles/conceptsinsc2reader.rst b/docs/source/articles/conceptsinsc2reader.rst index d4467029..8a83704a 100644 --- a/docs/source/articles/conceptsinsc2reader.rst +++ b/docs/source/articles/conceptsinsc2reader.rst @@ -55,7 +55,7 @@ Many attributes in sc2reader are prefixed with ``game_`` and ``real_``. Game ref GameEngine ---------------- -The game engine is used to process replay events and augument the replay with new statistics and game state. It implements a plugin system that allows developers +The game engine is used to process replay events and augment the replay with new statistics and game state. It implements a plugin system that allows developers to inject their own logic into the game loop. It also allows plugins to ``yield`` new events to the event stream. This allows for basic message passing between plugins. diff --git a/docs/source/articles/creatingagameengineplugin.rst b/docs/source/articles/creatingagameengineplugin.rst index 1d371aeb..c37ad079 100644 --- a/docs/source/articles/creatingagameengineplugin.rst +++ b/docs/source/articles/creatingagameengineplugin.rst @@ -52,7 +52,7 @@ Plugins may also handle special ``InitGame`` and ``EndGame`` events. These handl replay state necessary. * handleEndGame - is called after all events have been processed and - can be used to perform post processing on aggrated data or clean up + can be used to perform post processing on aggregated data or clean up intermediate data caches. Message Passing diff --git a/docs/source/articles/whatsinareplay.rst b/docs/source/articles/whatsinareplay.rst index 5acf6ea4..466f3bf0 100644 --- a/docs/source/articles/whatsinareplay.rst +++ b/docs/source/articles/whatsinareplay.rst @@ -35,7 +35,7 @@ The last file provides a record of important events from the game. * replay.tracker.events - Records important game events and game state updates. -This file was introduced in 2.0.4 and is unncessary for the Starcraft II to reproduce the game. Instead, it records interesting game events and game state for community developers to use when analyzing replays. +This file was introduced in 2.0.4 and is unnecessary for the Starcraft II to reproduce the game. Instead, it records interesting game events and game state for community developers to use when analyzing replays. What isn't in a replay? diff --git a/docs/source/conf.py b/docs/source/conf.py index 91b8a826..4fc4f46e 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. @@ -11,7 +10,9 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys, os +import os +import sys + import sc2reader autodoc_member_order = "bysource" @@ -19,32 +20,32 @@ # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) +# sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' +# needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode'] +extensions = ["sphinx.ext.autodoc", "sphinx.ext.imgmath", "sphinx.ext.viewcode"] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix of source filenames. -source_suffix = '.rst' +source_suffix = ".rst" # The encoding of source files. -#source_encoding = 'utf-8-sig' +# source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'sc2reader' -copyright = u'2011-2013' +project = "sc2reader" +copyright = "2011-2013" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -58,163 +59,159 @@ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -#language = None +# language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: -#today = '' +# today = '' # Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' +# today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None +# default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +# add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). -#add_module_names = True +# add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. -#show_authors = False +# show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] +# modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'nature' +html_theme = "nature" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -#html_theme_options = {} +# html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] +# html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". -#html_title = None +# html_title = None # A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None +# html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. -#html_logo = None +# html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -#html_favicon = None +# html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +# html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. -#html_use_smartypants = True +# html_use_smartypants = True # Custom sidebar templates, maps document names to template names. -#html_sidebars = {} +# html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. -#html_additional_pages = {} +# html_additional_pages = {} # If false, no module index is generated. -#html_domain_indices = True +# html_domain_indices = True # If false, no index is generated. -#html_use_index = True +# html_use_index = True # If true, the index is split into individual pages for each letter. -#html_split_index = False +# html_split_index = False # If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True +# html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True +# html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True +# html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. -#html_use_opensearch = '' +# html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None +# html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'sc2readerdoc' +htmlhelp_basename = "sc2readerdoc" # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). -#latex_paper_size = 'letter' +# latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). -#latex_font_size = '10pt' +# latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ - ('index', 'sc2reader.tex', u'sc2reader Documentation', - u'Graylin Kim', 'manual'), + ("index", "sc2reader.tex", "sc2reader Documentation", "Graylin Kim", "manual") ] # The name of an image file (relative to this directory) to place at the top of # the title page. -#latex_logo = None +# latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. -#latex_use_parts = False +# latex_use_parts = False # If true, show page references after internal links. -#latex_show_pagerefs = False +# latex_show_pagerefs = False # If true, show URL addresses after external links. -#latex_show_urls = False +# latex_show_urls = False # Additional stuff for the LaTeX preamble. -#latex_preamble = '' +# latex_preamble = '' # Documents to append as an appendix to all manuals. -#latex_appendices = [] +# latex_appendices = [] # If false, no module index is generated. -#latex_domain_indices = True +# latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'sc2reader', u'sc2reader Documentation', - [u'Graylin Kim'], 1) -] +man_pages = [("index", "sc2reader", "sc2reader Documentation", ["Graylin Kim"], 1)] diff --git a/docs/source/tutorials/prettyprinter.rst b/docs/source/tutorials/prettyprinter.rst index a8584620..f72005a0 100644 --- a/docs/source/tutorials/prettyprinter.rst +++ b/docs/source/tutorials/prettyprinter.rst @@ -89,11 +89,11 @@ Many of the replay attributes are nested data structures which are generally all >>> replay.teams[0].players[0].color.hex 'B4141E' >>> replay.player.name('Remedy').url - 'http://us.battle.net/sc2/en/profile/2198663/1/Remedy/' + 'https://starcraft2.com/en-us/profile/1/1/2198663' Each of these nested structures can be found either on its own reference page or lumped together with the other minor structures on the Misc Structures page. -So now all we need to do is build the ouput using the available replay attributes. Lets start with the header portion. We'll use a block string formatting method that makes this clean and easy: +So now all we need to do is build the output using the available replay attributes. Lets start with the header portion. We'll use a block string formatting method that makes this clean and easy: :: @@ -182,7 +182,7 @@ So lets put it all together into the final script, ``prettyPrinter.py``: Making Improvements --------------------------- -So our script works fine for single files, but what if you want to handle multiple files or directories? sc2reader provides two functions for loading replays: :meth:`~sc2reader.factories.SC2Factory.load_replay` and :meth:`~sc2reader.factories.SC2Factory.load_replays` which return a single replay and a list respectively. :meth:`~sc2reader.factories.SC2Factory.load_replay` was used above for convenience but :meth:`~sc2reader.factories.SC2Factory.load_replays` is much more versitile. Here's the difference: +So our script works fine for single files, but what if you want to handle multiple files or directories? sc2reader provides two functions for loading replays: :meth:`~sc2reader.factories.SC2Factory.load_replay` and :meth:`~sc2reader.factories.SC2Factory.load_replays` which return a single replay and a list respectively. :meth:`~sc2reader.factories.SC2Factory.load_replay` was used above for convenience but :meth:`~sc2reader.factories.SC2Factory.load_replays` is much more versatile. Here's the difference: * :meth:`~sc2reader.factories.SC2Factory.load_replay`: accepts a file path or an opened file object. * :meth:`~sc2reader.factories.SC2Factory.load_replays`: accepts a collection of opened file objects or file paths. Can also accept a single path to a directory; files will be pulled from the directory using :func:`~sc2reader.utils.get_files` and the given options. @@ -199,7 +199,7 @@ With this in mind, lets make a slight change to our main function to support any Any time that you start dealing with directories or collections of files you run into dangers with recursion and annoyances of tedium. sc2reader provides options to mitigate these concerns. * directory: Default ''. The directory string when supplied, becomes the base of all the file paths sent into sc2reader and can save you the hassle of fully qualifying your file paths each time. -* depth: Default -1. When handling directory inputs, sc2reader searches the directory recursively until all .SC2Replay files have been loaded. By setting the maxium depth value this behavior can be mitigated. +* depth: Default -1. When handling directory inputs, sc2reader searches the directory recursively until all .SC2Replay files have been loaded. By setting the maximum depth value this behavior can be mitigated. * exclude: Default []. When recursing directories you can choose to exclude directories from the file search by directory name (not full path). * followlinks: Default false. When recursing directories, enables or disables the follow symlinks behavior. diff --git a/docs/source/utilities.rst b/docs/source/utilities.rst index e06078ac..340d87d3 100644 --- a/docs/source/utilities.rst +++ b/docs/source/utilities.rst @@ -26,19 +26,6 @@ Length :members: -PersonDict ---------------- - -.. autoclass:: PersonDict - :members: - - -AttributeDict ------------------- - -.. autoclass:: AttributeDict - :members: - get_files --------------- diff --git a/examples/sc2autosave.py b/examples/sc2autosave.py index eb6b48e4..af272530 100755 --- a/examples/sc2autosave.py +++ b/examples/sc2autosave.py @@ -1,6 +1,5 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -'''sc2autosave is a utility for reorganizing and renaming Starcraft II files. +"""sc2autosave is a utility for reorganizing and renaming Starcraft II files. Overview ============== @@ -37,7 +36,7 @@ -------------------- The --rename option allows you to specify a renaming format string. The string -is constructed the pythonic (3.0) way with {:field} indicating the substition +is constructed the pythonic (3.0) way with {:field} indicating the substitution of a field. The forward slash (/) is a special character here which terminates a folder name and allows for organization into subdirectories. All other string characters form the template into which the fields are inserted. @@ -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/.../Multiplayer \ + --dest ~/My\\ Documents/Starcraft\\ II/Accounts/.../Multiplayer/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/.../Multiplayer \ + --dest ~/My\\ Documents/Starcraft\\ II/Accounts/.../Multiplayer/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/.../Multiplayer \ + --dest ~/My\\ Documents/Starcraft\\ II/Accounts/.../Multiplayer/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/.../Multiplayer \ + --dest ~/My\\ Documents/Starcraft\\ II/Accounts/.../Multiplayer/Saved \ --rename "{:matchup}/({:length}) {:map}: {:teams}" \ --player-format "{:name}({:play_race})" \ --team-order-by number \ @@ -138,7 +137,7 @@ files every SECONDS seconds. --rename FORMAT :map - Inserts the map name. - :date - Inserts a string formated datetime object using --date-format. + :date - Inserts a string formatted datetime object using --date-format. :length - Inserts a string formatted time object using --length-format. :teams - Inserts a comma separated player list. Teams are separated with a ' vs ' string. Format the player with --player-format. @@ -158,102 +157,157 @@ POST-Parse filtering vs preparse filtering? POST-Parse, how to do it?!?!?!?! -''' +""" import argparse -import cPickle import os +import pickle +import re import shutil import sys +import textwrap import time +from functools import cmp_to_key import sc2reader -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 + +class Formatter(argparse.RawTextHelpFormatter): + """FlexiFormatter which respects new line formatting and wraps the rest + + Example: + >>> parser = argparse.ArgumentParser(formatter_class=FlexiFormatter) + >>> parser.add_argument('a',help='''\ + ... This argument's help text will have this first long line\ + ... wrapped to fit the target window size so that your text\ + ... remains flexible. + ... + ... 1. This option list + ... 2. is still persisted + ... 3. and the option strings get wrapped like this\ + ... with an indent for readability. + ... + ... You must use backslashes at the end of lines to indicate that\ + ... you want the text to wrap instead of preserving the newline. + ... ''') + + Only the name of this class is considered a public API. All the methods + provided by the class are considered an implementation detail. + """ + + @classmethod + def new(cls, **options): + return lambda prog: Formatter(prog, **options) + + def _split_lines(self, text, width): + lines = list() + main_indent = len(re.match(r"( *)", text).group(1)) + # Wrap each line individually to allow for partial formatting + for line in text.splitlines(): + # Get this line's indent and figure out what indent to use + # if the line wraps. Account for lists of small variety. + indent = len(re.match(r"( *)", line).group(1)) + list_match = re.match(r"( *)(([*-+>]+|\w+\)|\w+\.) +)", line) + if list_match: + sub_indent = indent + len(list_match.group(2)) + else: + sub_indent = indent + + # Textwrap will do all the hard work for us + line = self._whitespace_matcher.sub(" ", line).strip() + new_lines = textwrap.wrap( + text=line, + width=width, + initial_indent=" " * (indent - main_indent), + subsequent_indent=" " * (sub_indent - main_indent), + ) + + # Blank lines get eaten by textwrap, put it back with [' '] + lines.extend(new_lines or [" "]) + + return lines def run(args): - #Reset wipes the destination clean so we can start over. + # Reset wipes the destination clean so we can start over. if args.reset: reset(args) - #Set up validates the destination and source directories. - #It also loads the previous state or creates one as necessary. + # Set up validates the destination and source directories. + # It also loads the previous state or creates one as necessary. state = setup(args) - #We break out of this loop in batch mode and on KeyboardInterrupt + # We break out of this loop in batch mode and on KeyboardInterrupt while True: - - #The file scan uses the arguments and the state to filter down to - #only new (since the last sync time) files. + # The file scan uses the arguments and the state to filter down to + # only new (since the last sync time) files. for path in scan(args, state): try: - #Read the file and expose useful aspects for renaming/filtering + # Read the file and expose useful aspects for renaming/filtering replay = sc2reader.load_replay(path, load_level=2) except KeyboardInterrupt: raise - except: - #Failure to parse + except Exception as e: + # Failure to parse + args.log.write(f"{e!r}") file_name = os.path.basename(path) - directory = make_directory(args, ('parse_error',)) + 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)) + source_path = path[len(args.source) :] + args.log.write(f"Error parsing replay: {source_path}") if not args.dryrun: args.action.run(path, new_path) - #Skip to the next replay + # Skip to the next replay continue aspects = generate_aspects(args, replay) - #Use the filter args to select files based on replay attributes + # Use the filter args to select files based on replay attributes if filter_out_replay(args, replay): continue - #Apply the aspects to the rename formatting. + # Apply the aspects to the rename formatting. #'/' is a special character for creation of subdirectories. - #TODO: Handle duplicate replay names, its possible.. - path_parts = args.rename.format(**aspects).split('/') - filename = path_parts.pop()+'.SC2Replay' + # TODO: Handle duplicate replay names, its possible.. - #Construct the directory and file paths; create needed directories + path_parts = args.rename.format(**aspects).split("/") + filename = path_parts.pop() + ".SC2Replay" + + # Construct the directory and file paths; create needed directories directory = make_directory(args, path_parts) new_path = os.path.join(directory, filename) - #Find the source relative to the source directory for reporting - dest_path = new_path[len(args.dest):] - source_path = path[len(args.source):] + # Find the source relative to the source directory for reporting + dest_path = new_path[len(args.dest) :] + source_path = path[len(args.source) :] - #Log the action and run it if we are live + # Log the action and run it if we are live msg = "{0}:\n\tSource: {1}\n\tDest: {2}\n" - args.log.write(msg.format(args.action.type, source_path, dest_path)) + args.log.write(msg.format(args.action["type"], source_path, dest_path)) if not args.dryrun: - args.action.run(path, new_path) + args.action["run"](path, new_path) - #After every batch completes, save the state and flush the log - #TODO: modify the state to include a list of remaining files + # After every batch completes, save the state and flush the log + # TODO: modify the state to include a list of remaining files args.log.flush() save_state(state, args) - #We only run once in batch mode! - if args.mode == 'BATCH': + # We only run once in batch mode! + if args.mode == "BATCH": break - #Since new replays come in fairly infrequently, reduce system load - #by sleeping for an acceptable response time before the next scan. + # Since new replays come in fairly infrequently, reduce system load + # by sleeping for an acceptable response time before the next scan. time.sleep(args.period) - args.log.write('Batch Completed') + args.log.write("Batch Completed") 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': + if args.filter_rule == "ALLOW": return filter_out_player else: return not filter_out_player @@ -262,14 +316,14 @@ 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 player1_name = player1.name.lower() player2_name = player2.name.lower() - player1_favored = (player1_name in favored_set) - player2_favored = (player2_name in favored_set) + player1_favored = player1_name in favored_set + player2_favored = player2_name in favored_set # The favored player always comes first in the ordering if player1_favored and not player2_favored: @@ -286,12 +340,12 @@ def player_compare(player1, player2): # If neither is favored, we'll order by number for now # TODO: Allow command line specification of other orderings (maybe?) else: - return player1.pid-player2.pid + return player1.pid - player2.pid 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 @@ -310,29 +364,29 @@ def team_compare(team1, team2): # If neither is favored, we'll order by number for now # TODO: Allow command line specification of other orderings (maybe?) else: - return team1.number-team2.number + return team1.number - team2.number return team_compare, player_compare def generate_aspects(args, replay): - teams = sorted(replay.teams, args.team_compare) + teams = sorted(replay.teams, key=cmp_to_key(args.team_compare)) matchups, team_strings = list(), list() for team in teams: - team.players = sorted(team.players, args.player_compare) + team.players = sorted(team.players, key=cmp_to_key(args.player_compare)) composition = sorted(p.play_race[0].upper() for p in team.players) - matchups.append(''.join(composition)) - string = ', '.join(p.format(args.player_format) for p in team.players) + matchups.append("".join(composition)) + string = ", ".join(p.format(args.player_format) for p in team.players) team_strings.append(string) - return sc2reader.utils.AttributeDict( + return dict( result=teams[0].result, length=replay.length, - map=replay.map, + map=replay.map_name.replace(":", ""), type=replay.type, date=replay.date.strftime(args.date_format), - matchup='v'.join(matchups), - teams=' vs '.join(team_strings) + matchup="v".join(matchups), + teams=" vs ".join(team_strings), ) @@ -341,29 +395,30 @@ 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): - exit('Cannot create subfolder. Path is occupied: {0}', directory) + exit("Cannot create subfolder. Path is occupied: {0}", directory) return directory 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, allow=False, exclude=args.exclude_dirs, depth=args.depth, - followlinks=args.follow_links) - return filter(lambda f: os.path.getctime(f) > state.last_sync, files) + followlinks=args.follow_links, + ) + return filter(lambda f: os.path.getctime(f) > state["last_sync"], files) def exit(msg, *args, **kwargs): - sys.exit(msg.format(*args, **kwargs)+"\n\nScript Aborted.") + sys.exit(msg.format(*args, **kwargs) + "\n\nScript Aborted.") def reset(args): @@ -372,10 +427,11 @@ def reset(args): elif not os.path.isdir(args.dest): exit("Cannot reset, destination must be directory: {0}", args.dest) - print('About to reset directory: {0}\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)) + print( + f"About to reset directory: {args.dest}\nAll files and subdirectories will be removed." + ) + if input("Proceed anyway? (y/n) ").strip().lower() == "y": + args.log.write(f"Removing old directory: {args.dest}\n") if not args.dryrun: print(args.dest) shutil.rmtree(args.dest) @@ -385,95 +441,145 @@ def reset(args): def setup(args): args.team_compare, args.player_compare = create_compare_funcs(args) - args.action = sc2reader.utils.AttributeDict(type=args.action, run=shutil.copy if args.action == 'COPY' else shutil.move) + args.action = dict( + type=args.action, run=shutil.copy if args.action == "COPY" else shutil.move + ) if not os.path.exists(args.source): - msg = 'Source does not exist: {0}.\n\nScript Aborted.' + msg = "Source does not exist: {0}.\n\nScript Aborted." sys.exit(msg.format(args.source)) elif not os.path.isdir(args.source): - msg = 'Source is not a directory: {0}.\n\nScript Aborted.' + msg = "Source is not a directory: {0}.\n\nScript Aborted." sys.exit(msg.format(args.source)) if not os.path.exists(args.dest): 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') + sys.exit("Destination must be a directory.\n\nScript Aborted") - data_file = os.path.join(args.dest, 'sc2autosave.dat') + 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) + with open(data_file, "rb") as file: + return pickle.load(file) else: - return sc2reader.utils.AttributeDict(last_sync=0) + return dict(last_sync=0) def save_state(state, args): - state.last_sync = time.time() - data_file = os.path.join(args.dest, 'sc2autosave.dat') + state["last_sync"] = time.time() + data_file = os.path.join(args.dest, "sc2autosave.dat") if not args.dryrun: - with open(data_file, 'w') as file: - cPickle.dump(state, file) + with open(data_file, "wb") as file: + pickle.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(): parser = argparse.ArgumentParser( - description='Automatically copy new replays to directory', - fromfile_prefix_chars='@', - formatter_class=sc2reader.scripts.utils.Formatter.new(max_help_position=35), - epilog="And that's all folks") - - required = parser.add_argument_group('Required Arguments') - required.add_argument('source', type=str, - help='The source directory to poll') - required.add_argument('dest', type=str, - help='The destination directory to copy to') - - general = parser.add_argument_group('General Options') - general.add_argument('--mode', dest='mode', - type=str, choices=['BATCH', 'CYCLE'], default='BATCH', - help='The operating mode for the organizer') - - general.add_argument('--action', dest='action', - choices=['COPY', 'MOVE'], default="COPY", type=str, - help='Have the organizer move your files instead of copying') - general.add_argument('--period', - dest='period', type=int, default=0, - help='The period of time to wait between scans.') - general.add_argument('--log', dest='log', metavar='LOGFILE', - type=argparse.FileType('w'), default=sys.stdout, - help='Destination file for log information') - general.add_argument('--dryrun', - dest='dryrun', action="store_true", - help="Don't do anything. Only simulate the output") - general.add_argument('--reset', - dest='reset', action='store_true', default=False, - help='Wipe the destination directory clean and start over.') - - fileargs = parser.add_argument_group('File Options') - fileargs.add_argument('--depth', - dest='depth', type=int, default=-1, - help='Maximum recussion depth. -1 (default) is unlimited.') - fileargs.add_argument('--exclude-dirs', dest='exclude_dirs', - type=str, metavar='NAME', nargs='+', default=[], - help='A list of directory names to exclude during recursion') - fileargs.add_argument('--exclude-files', dest='exclude_files', - type=str, metavar='REGEX', default="", - help='An expression to match excluded files') - fileargs.add_argument('--follow-links', - dest='follow_links', action="store_true", default=False, - help="Enable following of symbolic links while scanning") - - renaming = parser.add_argument_group('Renaming Options') - renaming.add_argument('--rename', - dest='rename', type=str, metavar='FORMAT', nargs='?', + description="Automatically copy new replays to directory", + fromfile_prefix_chars="@", + formatter_class=Formatter.new(max_help_position=35), + epilog="And that's all folks", + ) + + required = parser.add_argument_group("Required Arguments") + required.add_argument("source", type=str, help="The source directory to poll") + required.add_argument("dest", type=str, help="The destination directory to copy to") + + general = parser.add_argument_group("General Options") + general.add_argument( + "--mode", + dest="mode", + type=str, + choices=["BATCH", "CYCLE"], + default="BATCH", + help="The operating mode for the organizer", + ) + + general.add_argument( + "--action", + dest="action", + choices=["COPY", "MOVE"], + default="COPY", + type=str, + help="Have the organizer move your files instead of copying", + ) + general.add_argument( + "--period", + dest="period", + type=int, + default=0, + help="The period of time to wait between scans.", + ) + general.add_argument( + "--log", + dest="log", + metavar="LOGFILE", + type=argparse.FileType("w"), + default=sys.stdout, + help="Destination file for log information", + ) + general.add_argument( + "--dryrun", + dest="dryrun", + action="store_true", + help="Don't do anything. Only simulate the output", + ) + general.add_argument( + "--reset", + dest="reset", + action="store_true", + default=False, + help="Wipe the destination directory clean and start over.", + ) + + fileargs = parser.add_argument_group("File Options") + fileargs.add_argument( + "--depth", + dest="depth", + type=int, + default=-1, + help="Maximum recussion depth. -1 (default) is unlimited.", + ) + fileargs.add_argument( + "--exclude-dirs", + dest="exclude_dirs", + type=str, + metavar="NAME", + nargs="+", + default=[], + help="A list of directory names to exclude during recursion", + ) + fileargs.add_argument( + "--exclude-files", + dest="exclude_files", + type=str, + metavar="REGEX", + default="", + help="An expression to match excluded files", + ) + fileargs.add_argument( + "--follow-links", + dest="follow_links", + action="store_true", + default=False, + help="Enable following of symbolic links while scanning", + ) + + renaming = parser.add_argument_group("Renaming Options") + renaming.add_argument( + "--rename", + dest="rename", + type=str, + metavar="FORMAT", + nargs="?", default="{length} {type} on {map}", - help='''\ + help="""\ The renaming format string. can have the following values: * {length} - The length of the replay ([H:]MM:SS) @@ -482,41 +588,73 @@ def main(): * {match} - Race matchup in team order, alphabetically by race. * {date} - The date the replay was played on * {teams} - The player line up - ''') - - renaming.add_argument('--length-format', - dest='length_format', type=str, metavar='FORMAT', default='%M.%S', - help='The length format string. See the python time module for details') - renaming.add_argument('--player-format', - dest='player_format', type=str, metavar='FORMAT', default='{name} ({play_race})', - help='The player format string used to render the :teams content item.') - renaming.add_argument('--date-format', - dest='date_format', type=str, metavar='FORMAT', default='%m-%d-%Y', - help='The date format string used to render the :date content item.') - ''' + """, + ) + + renaming.add_argument( + "--length-format", + dest="length_format", + type=str, + metavar="FORMAT", + default="%M.%S", + help="The length format string. See the python time module for details", + ) + renaming.add_argument( + "--player-format", + dest="player_format", + type=str, + metavar="FORMAT", + default="{name} ({play_race})", + help="The player format string used to render the :teams content item.", + ) + renaming.add_argument( + "--date-format", + dest="date_format", + type=str, + metavar="FORMAT", + default="%m-%d-%Y", + help="The date format string used to render the :date content item.", + ) + """ renaming.add_argument('--team-order-by', dest='team_order', type=str, metavar='FIELD', default='NUMBER', help='The field by which teams are ordered.') renaming.add_argument('--player-order-by', dest='player_order', type=str, metavar='FIELD', default='NAME', help='The field by which players are ordered on teams.') - ''' - renaming.add_argument('--favored', dest='favored', - type=str, default=[], metavar='NAME', nargs='+', - help='A list of the players to favor in ordering teams and players') - - filterargs = parser.add_argument_group('Filtering Options') - filterargs.add_argument('--filter-rule', dest='filter_rule', - choices=["ALLOW","DENY"], - help="The filters can either be used as a white list or a black list") - filterargs.add_argument('--filter-player', metavar='NAME', - dest='filter_player', nargs='+', type=str, default=[], - help="A list of players to filter on") + """ + renaming.add_argument( + "--favored", + dest="favored", + type=str, + default=[], + metavar="NAME", + nargs="+", + help="A list of the players to favor in ordering teams and players", + ) + + filterargs = parser.add_argument_group("Filtering Options") + filterargs.add_argument( + "--filter-rule", + dest="filter_rule", + choices=["ALLOW", "DENY"], + help="The filters can either be used as a white list or a black list", + ) + filterargs.add_argument( + "--filter-player", + metavar="NAME", + dest="filter_player", + nargs="+", + type=str, + default=[], + help="A list of players to filter on", + ) try: run(parser.parse_args()) except KeyboardInterrupt: - print("\n\nScript Interupted. Process Aborting") + print("\n\nScript Interrupted. Process Aborting") + -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/examples/sc2store.py b/examples/sc2store.py index 55ff22b0..7f54a3fb 100755 --- a/examples/sc2store.py +++ b/examples/sc2store.py @@ -1,17 +1,15 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -import cPickle import os +import pickle import shutil -import sys import sqlite3 +import sys import time import sc2reader from pprint import PrettyPrinter -pprint = PrettyPrinter(indent=2).pprint from sqlalchemy import create_engine from sqlalchemy import Column, ForeignKey, distinct, Table @@ -22,50 +20,56 @@ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.associationproxy import association_proxy + +pprint = PrettyPrinter(indent=2).pprint + Base = declarative_base() -party_member = Table('party_member', Base.metadata, - Column('person_id', Integer, ForeignKey('person.id')), - Column('party_id', Integer, ForeignKey('party.id')), +party_member = Table( + "party_member", + Base.metadata, + Column("person_id", Integer, ForeignKey("person.id")), + Column("party_id", Integer, ForeignKey("party.id")), ) + class Person(Base): - __tablename__ = 'person' - id = Column(Integer, Sequence('person_id_seq'), primary_key=True) + __tablename__ = "person" + id = Column(Integer, Sequence("person_id_seq"), primary_key=True) name = Column(String(50)) url = Column(String(50)) - parties = relationship('Party', secondary=party_member) - players = relationship('Player') + parties = relationship("Party", secondary=party_member) + players = relationship("Player") class Party(Base): - __tablename__ = 'party' - id = Column(Integer, Sequence('party_id_seq'), primary_key=True) + __tablename__ = "party" + id = Column(Integer, Sequence("party_id_seq"), primary_key=True) player_names = Column(String(255)) - members = relationship('Person', secondary=party_member) - teams = relationship('Team') + members = relationship("Person", secondary=party_member) + teams = relationship("Team") def __init__(self, *players): - self.player_names = '' + self.player_names = "" self.members = list() self.add_players(*players) def add_players(self, *players): for player in players: - self.player_names += '['+player.name+']' + self.player_names += "[" + player.name + "]" self.members.append(player.person) @classmethod def make_player_names(self, players): - return ''.join(sorted('['+player.name+']' for player in players)) + return "".join(sorted("[" + player.name + "]" for player in players)) class Game(Base): - __tablename__ = 'game' - id = Column(Integer, Sequence('game_id_seq'), primary_key=True) + __tablename__ = "game" + id = Column(Integer, Sequence("game_id_seq"), primary_key=True) map = Column(String(255)) file_name = Column(String(255)) @@ -77,8 +81,8 @@ class Game(Base): build = Column(String(25)) release_string = Column(String(50)) - teams = relationship('Team') - players = relationship('Player') + teams = relationship("Team") + players = relationship("Player") def __init__(self, replay, db): self.map = replay.map @@ -90,54 +94,58 @@ def __init__(self, replay, db): self.winner_known = replay.winner_known self.build = replay.build self.release_string = replay.release_string - self.teams = [Team(team,db) for team in replay.teams] - self.matchup = 'v'.join(sorted(team.lineup for team in self.teams)) + self.teams = [Team(team, db) for team in replay.teams] + self.matchup = "v".join(sorted(team.lineup for team in self.teams)) self.players = sum((team.players for team in self.teams), []) class Team(Base): - __tablename__ = 'team' - id = Column(Integer, Sequence('team_id_seq'), primary_key=True) - game_id = Column(Integer, ForeignKey('game.id')) - party_id = Column(Integer, ForeignKey('party.id')) + __tablename__ = "team" + id = Column(Integer, Sequence("team_id_seq"), primary_key=True) + game_id = Column(Integer, ForeignKey("game.id")) + party_id = Column(Integer, ForeignKey("party.id")) result = Column(String(50)) number = Column(Integer) lineup = Column(String(10)) - players = relationship('Player') - party = relationship('Party') - game = relationship('Game') + players = relationship("Player") + party = relationship("Party") + game = relationship("Game") def __init__(self, team, db): self.number = team.number self.result = team.result - self.players = [Player(player,db) for player in team.players] - self.lineup = ''.join(sorted(player.play_race[0].upper() for player in self.players)) + self.players = [Player(player, db) for player in team.players] + self.lineup = "".join( + sorted(player.play_race[0].upper() for player in self.players) + ) try: player_names = Party.make_player_names(self.players) - self.party = db.query(Party).filter(Party.player_names == player_names).one() + self.party = ( + db.query(Party).filter(Party.player_names == player_names).one() + ) except NoResultFound as e: self.party = Party(*self.players) class Player(Base): - __tablename__ = 'player' - id = Column(Integer, Sequence('player_id_seq'), primary_key=True) - game_id = Column(Integer, ForeignKey('game.id')) - team_id = Column(Integer, ForeignKey('team.id')) - person_id = Column(Integer, ForeignKey('person.id')) + __tablename__ = "player" + id = Column(Integer, Sequence("player_id_seq"), primary_key=True) + game_id = Column(Integer, ForeignKey("game.id")) + team_id = Column(Integer, ForeignKey("team.id")) + person_id = Column(Integer, ForeignKey("person.id")) play_race = Column(String(20)) pick_race = Column(String(20)) color_str = Column(String(20)) color_hex = Column(String(20)) - name = association_proxy('person','name') - person = relationship('Person') - team = relationship('Team') - game = relationship('Game') + name = association_proxy("person", "name") + person = relationship("Person") + team = relationship("Team") + game = relationship("Game") def __init__(self, player, db): try: @@ -154,32 +162,47 @@ def __init__(self, player, db): class Message(Base): - __tablename__ = 'message' - id = Column(Integer, Sequence('message_id_seq'), primary_key=True) - player_id = Column(Integer, ForeignKey('player.id')) + __tablename__ = "message" + id = Column(Integer, Sequence("message_id_seq"), primary_key=True) + player_id = Column(Integer, ForeignKey("player.id")) def parse_args(): import argparse - parser = argparse.ArgumentParser(description='Stores replay meta data into an SQL database') - parser.add_argument('--storage', default='sqlite:///:memory:', type=str, help='Path to the sql storage file of choice') - parser.add_argument('paths', metavar='PATH', type=str, nargs='+', help='Path to a replay file or a folder of replays') + + parser = argparse.ArgumentParser( + description="Stores replay meta data into an SQL database" + ) + parser.add_argument( + "--storage", + default="sqlite:///:memory:", + type=str, + help="Path to the sql storage file of choice", + ) + parser.add_argument( + "paths", + metavar="PATH", + type=str, + nargs="+", + help="Path to a replay file or a folder of replays", + ) return parser.parse_args() + def main(): args = parse_args() db = load_session(args) 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() print(list(db.query(distinct(Person.name)).all())) - #for row in db.query(distinct(Person.name)).all(): + # for row in db.query(distinct(Person.name)).all(): # print(row) @@ -190,5 +213,5 @@ def load_session(args): return Session() -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/generate_build_data.py b/generate_build_data.py index b56a72eb..7419e547 100644 --- a/generate_build_data.py +++ b/generate_build_data.py @@ -35,7 +35,9 @@ def generate_build_data(balance_data_path): while len(ability_lookup[ability_name]) <= command_index: ability_lookup[ability_name].append("") - command_name = command_id if command_id != "Execute" else ability_name + command_name = ( + command_id if command_id != "Execute" else ability_name + ) ability_lookup[ability_name][command_index] = command_name unit_id = root.get("id") @@ -56,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 @@ -75,63 +77,73 @@ 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) - ability_lookup[build_ability_name][command_index] = build_command_name + build_command_name = f"Build{built_unit_id}" + ability_lookup[build_ability_name][ + command_index + ] = build_command_name train_unit_elements = root.findall("./trains/unit") if train_unit_elements: 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: ability_lookup[train_ability_name] = [] for element in train_unit_elements: - element_ability_index = element.get("ability") - trained_unit_name = element.get("id") + element_ability_index = element.get("ability") + trained_unit_name = element.get("id") - if trained_unit_name: - # Handle cases where a unit can train other units using multiple ability indices. - # The Nexus is currently the only known example. - if element_ability_index != train_ability_index: - train_ability_index = element_ability_index + if trained_unit_name: + # Handle cases where a unit can train other units using multiple ability indices. + # The Nexus is currently the only known example. + if element_ability_index != train_ability_index: + train_ability_index = element_ability_index - train_ability_name = "{}Train{}".format(unit_id, trained_unit_name) - abilities[train_ability_index] = train_ability_name + train_ability_name = f"{unit_id}Train{trained_unit_name}" + abilities[train_ability_index] = train_ability_name - if train_ability_name not in ability_lookup: - ability_lookup[train_ability_name] = [] + if train_ability_name not in ability_lookup: + ability_lookup[train_ability_name] = [] - command_index_str = element.get("index") + command_index_str = element.get("index") - if command_index_str: - command_index = int(command_index_str) + if command_index_str: + command_index = int(command_index_str) - # Pad potential gaps in command indices with empty strings - while len(ability_lookup[train_ability_name]) <= command_index: - ability_lookup[train_ability_name].append("") + # Pad potential gaps in command indices with empty strings + while ( + len(ability_lookup[train_ability_name]) <= command_index + ): + ability_lookup[train_ability_name].append("") - ability_lookup[train_ability_name][command_index] = train_ability_name - else: - command_index_str = element.get("index") + ability_lookup[train_ability_name][ + command_index + ] = train_ability_name + else: + command_index_str = element.get("index") - if command_index_str: - command_index = int(command_index_str) + if command_index_str: + command_index = int(command_index_str) - # Pad potential gaps in command indices with empty strings - while len(ability_lookup[train_ability_name]) <= command_index: - ability_lookup[train_ability_name].append("") + # Pad potential gaps in command indices with empty strings + while ( + len(ability_lookup[train_ability_name]) <= command_index + ): + ability_lookup[train_ability_name].append("") - train_command_name = "Train{}".format(trained_unit_name) - ability_lookup[train_ability_name][command_index] = train_command_name + train_command_name = f"Train{trained_unit_name}" + ability_lookup[train_ability_name][ + command_index + ] = train_command_name 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 @@ -149,18 +161,26 @@ 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) - ability_lookup[research_ability_name][command_index] = research_command_name + research_command_name = f"Research{researched_upgrade_id}" + ability_lookup[research_ability_name][ + command_index + ] = research_command_name - sorted_units = collections.OrderedDict(sorted(units.items(), key=lambda x: int(x[0]))) - sorted_abilities = collections.OrderedDict(sorted(abilities.items(), key=lambda x: int(x[0]))) + sorted_units = collections.OrderedDict( + sorted(units.items(), key=lambda x: int(x[0])) + ) + sorted_abilities = collections.OrderedDict( + 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 -def combine_lookups(old_unit_lookup, old_ability_lookup, new_unit_lookup, new_ability_lookup): +def combine_lookups( + old_unit_lookup, old_ability_lookup, new_unit_lookup, new_ability_lookup +): unit_lookup = collections.OrderedDict(old_unit_lookup) ability_lookup = collections.OrderedDict(old_ability_lookup) @@ -190,21 +210,42 @@ def combine_lookups(old_unit_lookup, old_ability_lookup, new_unit_lookup, new_ab def main(): - parser = argparse.ArgumentParser(description='Generate and install new [BUILD_VERSION]_abilities.csv, ' - '[BUILD_VERSION]_units.csv, and update ability_lookup.csv and ' - 'unit_lookup.csv files with any new units and ability commands.') - parser.add_argument('expansion', metavar='EXPANSION', type=str, choices=['WoL', 'HotS', 'LotV'], - help='the expansion level of the balance data export, one of \'WoL\', \'HotS\', or \'LotV\'') - parser.add_argument('build_version', metavar='BUILD_VERSION', type=int, - help='the build version of the balance data export') - parser.add_argument('balance_data_path', metavar='BALANCE_DATA_PATH', type=str, - help='the path to the balance data export') - parser.add_argument('project_path', metavar='SC2READER_PROJECT_PATH', type=str, - help='the path to the root of the sc2reader project directory') + parser = argparse.ArgumentParser( + description="Generate and install new [BUILD_VERSION]_abilities.csv, " + "[BUILD_VERSION]_units.csv, and update ability_lookup.csv and " + "unit_lookup.csv files with any new units and ability commands." + ) + parser.add_argument( + "expansion", + metavar="EXPANSION", + type=str, + choices=["WoL", "HotS", "LotV"], + help="the expansion level of the balance data export, one of 'WoL', 'HotS', or 'LotV'", + ) + parser.add_argument( + "build_version", + metavar="BUILD_VERSION", + type=int, + help="the build version of the balance data export", + ) + parser.add_argument( + "balance_data_path", + metavar="BALANCE_DATA_PATH", + type=str, + help="the path to the balance data export", + ) + parser.add_argument( + "project_path", + metavar="SC2READER_PROJECT_PATH", + type=str, + help="the path to the root of the sc2reader project directory", + ) args = parser.parse_args() - units, abilities, new_unit_lookup, new_ability_lookup = generate_build_data(args.balance_data_path) + units, abilities, new_unit_lookup, new_ability_lookup = generate_build_data( + args.balance_data_path + ) if not units or not abilities: parser.print_help() @@ -212,46 +253,67 @@ def main(): raise ValueError("No balance data found at provided balance data path.") - unit_lookup_path = os.path.join(args.project_path, 'sc2reader', 'data', 'unit_lookup.csv') - with open(unit_lookup_path, 'r') 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]) - - ability_lookup_path = os.path.join(args.project_path, 'sc2reader', 'data', 'ability_lookup.csv') - with open(ability_lookup_path, 'r') 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]) + unit_lookup_path = os.path.join( + args.project_path, "sc2reader", "data", "unit_lookup.csv" + ) + 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] + ) + + ability_lookup_path = os.path.join( + args.project_path, "sc2reader", "data", "ability_lookup.csv" + ) + 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] + ) if not old_unit_lookup or not old_ability_lookup: parser.print_help() print("\n") - raise ValueError("Could not find existing unit or ability lookups. Is the sc2reader project path correct?") + raise ValueError( + "Could not find existing unit or ability lookups. Is the sc2reader project path correct?" + ) unit_lookup, ability_lookup = combine_lookups( - old_unit_lookup, old_ability_lookup, new_unit_lookup, new_ability_lookup) + old_unit_lookup, old_ability_lookup, new_unit_lookup, new_ability_lookup + ) units_file_path = os.path.join( - args.project_path, 'sc2reader', 'data', args.expansion, '{}_units.csv'.format(args.build_version)) - with open(units_file_path, 'w') as file: - csv_writer = csv.writer(file, delimiter=',', lineterminator=os.linesep) + args.project_path, + "sc2reader", + "data", + args.expansion, + f"{args.build_version}_units.csv", + ) + with open(units_file_path, "w") as file: + csv_writer = csv.writer(file, delimiter=",", lineterminator=os.linesep) for unit_index, unit_name in units.items(): csv_writer.writerow([unit_index, unit_name]) abilities_file_path = os.path.join( - args.project_path, 'sc2reader', 'data', args.expansion, '{}_abilities.csv'.format(args.build_version)) - with open(abilities_file_path, 'w') as file: - csv_writer = csv.writer(file, delimiter=',', lineterminator=os.linesep) + args.project_path, + "sc2reader", + "data", + args.expansion, + f"{args.build_version}_abilities.csv", + ) + with open(abilities_file_path, "w") as file: + csv_writer = csv.writer(file, delimiter=",", lineterminator=os.linesep) for ability_index, ability_name in abilities.items(): csv_writer.writerow([ability_index, ability_name]) - with open(unit_lookup_path, 'w') as file: - csv_writer = csv.writer(file, delimiter=',', lineterminator=os.linesep) + with open(unit_lookup_path, "w") as file: + csv_writer = csv.writer(file, delimiter=",", lineterminator=os.linesep) for entry in unit_lookup.items(): csv_writer.writerow(list(entry)) - with open(ability_lookup_path, 'w') as file: - csv_writer = csv.writer(file, delimiter=',', lineterminator=os.linesep) + with open(ability_lookup_path, "w") as file: + csv_writer = csv.writer(file, delimiter=",", lineterminator=os.linesep) for ability_name, commands in ability_lookup.items(): csv_writer.writerow([ability_name] + commands) diff --git a/new_units.py b/new_units.py index e0d80118..26ffa133 100644 --- a/new_units.py +++ b/new_units.py @@ -9,28 +9,30 @@ import sys UNIT_LOOKUP = dict() -for entry in pkgutil.get_data('sc2reader.data', 'unit_lookup.csv').split('\n'): - if not entry: continue - str_id, title = entry.strip().split(',') +for entry in pkgutil.get_data("sc2reader.data", "unit_lookup.csv").splitlines(): + if not entry: + continue + str_id, title = entry.strip().split(",") UNIT_LOOKUP[str_id] = title -with open(sys.argv[1],'r') 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)) +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(f"{new_unit_name},{new_unit_name}") -print('') -print('') +print("") +print("") ABIL_LOOKUP = dict() -for entry in pkgutil.get_data('sc2reader.data', 'ability_lookup.csv').split('\n'): - if not entry: continue - str_id, abilities = entry.split(',',1) - ABIL_LOOKUP[str_id] = abilities.split(',') +for entry in pkgutil.get_data("sc2reader.data", "ability_lookup.csv").splitlines(): + if not entry: + continue + str_id, abilities = entry.split(",", 1) + ABIL_LOOKUP[str_id] = abilities.split(",") -with open(sys.argv[2], 'r') 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)) +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(f"{new_ability_name},{new_ability_name}") diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..e33c1d05 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,80 @@ +[build-system] +build-backend = "setuptools.build_meta" +requires = [ + "setuptools>=61.2", +] + +[project] +name = "sc2reader" +description = "Utility for parsing Starcraft II replay files" +keywords = [ + "parser", + "replay", + "sc2", + "starcraft 2", +] +license = { text = "MIT" } +authors = [ { name = "Kevin Leung", email = "kkleung89@gmail.com" } ] +requires-python = ">=3.9" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Environment :: Console", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Natural Language :: English", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Games/Entertainment", + "Topic :: Games/Entertainment :: Real Time Strategy", + "Topic :: Software Development", + "Topic :: Software Development :: Libraries", + "Topic :: Utilities", +] +dynamic = [ + "readme", + "version", +] +dependencies = [ + "mpyq", + "pillow", +] +optional-dependencies.testing = [ + "pytest", +] +urls.Homepage = "https://github.com/ggtracker/sc2reader" +scripts.sc2attributes = "sc2reader.scripts.sc2attributes:main" +scripts.sc2json = "sc2reader.scripts.sc2json:main" +scripts.sc2parse = "sc2reader.scripts.sc2parse:main" +scripts.sc2printer = "sc2reader.scripts.sc2printer:main" +scripts.sc2replayer = "sc2reader.scripts.sc2replayer:main" + +[tool.setuptools] +include-package-data = true +zip-safe = true +platforms = [ "any" ] + +[tool.setuptools.dynamic] +readme = { file = [ "README.rst", "CHANGELOG.rst" ] } +version = { attr = "sc2reader.__version__" } + +[tool.setuptools.packages] +find = { namespaces = false } + +[tool.ruff] +line-length = 129 + +lint.ignore = [ + "F401", # module imported but unused; consider using `importlib.util.find_spec` to test for availability + "F403", # Run `removestar` on this codebase + "F405", # Run `removestar` on this codebase + "F841", # Run `ruff --select=F841 --fix .` +] +lint.mccabe.max-complexity = 34 diff --git a/sc2reader/__init__.py b/sc2reader/__init__.py index 0bcf512a..49b76657 100644 --- a/sc2reader/__init__.py +++ b/sc2reader/__init__.py @@ -1,26 +1,24 @@ -# -*- coding: utf-8 -*- """ - sc2reader - ~~~~~~~~~~~ +sc2reader +~~~~~~~~~~~ - A library for loading data from Starcraft II game resources. +A library for loading data from Starcraft II game resources. - SC2Factory methods called on the package will be delegated to the default - SC2Factory. To default to a cached factory set one or more of the following - variables in your environment: +SC2Factory methods called on the package will be delegated to the default +SC2Factory. To default to a cached factory set one or more of the following +variables in your environment: - SC2READER_CACHE_DIR = '/absolute/path/to/existing/cache/directory/' - SC2READER_CACHE_MAX_SIZE = MAXIMUM_CACHE_ENTRIES_TO_HOLD_IN_MEMORY + SC2READER_CACHE_DIR = '/absolute/path/to/existing/cache/directory/' + SC2READER_CACHE_MAX_SIZE = MAXIMUM_CACHE_ENTRIES_TO_HOLD_IN_MEMORY - You can also set the default factory via setFactory, useFileCache, useDictCache, - or useDoubleCache functions. +You can also set the default factory via setFactory, useFileCache, useDictCache, +or useDoubleCache functions. - :copyright: (c) 2011 by Graylin Kim. - :license: MIT, see LICENSE for more details. +:copyright: (c) 2011 by Graylin Kim. +:license: MIT, see LICENSE for more details. """ -from __future__ import absolute_import, print_function, unicode_literals, division -__version__ = "0.8.0" +__version__ = "1.8.0" import os import sys @@ -99,8 +97,8 @@ def useDoubleCache(cache_dir, cache_max_size=0, **options): # Allow environment variables to activate caching -cache_dir = os.getenv('SC2READER_CACHE_DIR') -cache_max_size = os.getenv('SC2READER_CACHE_MAX_SIZE') +cache_dir = os.getenv("SC2READER_CACHE_DIR") +cache_max_size = os.getenv("SC2READER_CACHE_MAX_SIZE") if cache_dir and cache_max_size: useDoubleCache(cache_dir, cache_max_size) elif cache_dir: diff --git a/sc2reader/constants.py b/sc2reader/constants.py index aa3e0ade..a1ae473f 100644 --- a/sc2reader/constants.py +++ b/sc2reader/constants.py @@ -1,5 +1,5 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division +import json +import pkgutil # These are found in Repack-MPQ/fileset.{locale}#Mods#Core.SC2Mod#{locale}.SC2Data/LocalizedData/Editor/EditorCategoryStrings.txt # EDSTR_CATEGORY_Race @@ -7,43 +7,34 @@ # The ??? means that I don't know what language it is. # If multiple languages use the same set they should be comma separated LOCALIZED_RACES = { - # enUS - 'Terran': 'Terran', - 'Protoss': 'Protoss', - 'Zerg': 'Zerg', - + "Terran": "Terran", + "Protoss": "Protoss", + "Zerg": "Zerg", # ruRU - 'Терран': 'Terran', - 'Протосс': 'Protoss', - 'Зерг': 'Zerg', - + "Терран": "Terran", + "Протосс": "Protoss", + "Зерг": "Zerg", # koKR - '테란': 'Terran', - '프로토스': 'Protoss', - '저그': 'Zerg', - + "테란": "Terran", + "프로토스": "Protoss", + "저그": "Zerg", # plPL - 'Terranie': 'Terran', - 'Protosi': 'Protoss', - 'Zergi': 'Zerg', - + "Terranie": "Terran", + "Protosi": "Protoss", + "Zergi": "Zerg", # zhCH - '人类': 'Terran', - '星灵': 'Protoss', - '异虫': 'Zerg', - + "人类": "Terran", + "星灵": "Protoss", + "异虫": "Zerg", # zhTW - '人類': 'Terran', - '神族': 'Protoss', - '蟲族': 'Zerg', - + "人類": "Terran", + "神族": "Protoss", + "蟲族": "Zerg", # ??? - 'Terrano': 'Terran', - + "Terrano": "Terran", # deDE - 'Terraner': 'Terran', - + "Terraner": "Terran", # esES - Spanish # esMX - Latin American # frFR - French - France @@ -51,131 +42,70 @@ # ptBR - Brazilian Portuguese } -MESSAGE_CODES = { - '0': 'All', - '2': 'Allies', - '128': 'Header', - '125': 'Ping', -} +MESSAGE_CODES = {"0": "All", "2": "Allies", "128": "Header", "125": "Ping"} GAME_SPEED_FACTOR = { - 'WoL': { - 'Slower': 0.6, - 'Slow': 0.8, - 'Normal': 1.0, - 'Fast': 1.2, - 'Faster': 1.4 - }, - 'HotS': { - 'Slower': 0.6, - 'Slow': 0.8, - 'Normal': 1.0, - 'Fast': 1.2, - 'Faster': 1.4 - }, - 'LotV': { - 'Slower': 0.2, - 'Slow': 0.4, - 'Normal': 0.6, - 'Fast': 0.8, - 'Faster': 1.0 - }, + "WoL": {"Slower": 0.6, "Slow": 0.8, "Normal": 1.0, "Fast": 1.2, "Faster": 1.4}, + "HotS": {"Slower": 0.6, "Slow": 0.8, "Normal": 1.0, "Fast": 1.2, "Faster": 1.4}, + "LotV": {"Slower": 0.2, "Slow": 0.4, "Normal": 0.6, "Fast": 0.8, "Faster": 1.0}, } GATEWAY_CODES = { - 'US': 'Americas', - 'KR': 'Asia', - 'EU': 'Europe', - 'SG': 'South East Asia', - 'XX': 'Public Test', + "US": "Americas", + "KR": "Asia", + "EU": "Europe", + "SG": "South East Asia", + "XX": "Public Test", } -GATEWAY_LOOKUP = { - 0: '', - 1: 'us', - 2: 'eu', - 3: 'kr', - 5: 'cn', - 6: 'sea', - 98: 'xx', -} +GATEWAY_LOOKUP = {0: "", 1: "us", 2: "eu", 3: "kr", 5: "cn", 6: "sea", 98: "xx"} COLOR_CODES = { - 'B4141E': 'Red', - '0042FF': 'Blue', - '1CA7EA': 'Teal', - 'EBE129': 'Yellow', - '540081': 'Purple', - 'FE8A0E': 'Orange', - '168000': 'Green', - 'CCA6FC': 'Light Pink', - '1F01C9': 'Violet', - '525494': 'Light Grey', - '106246': 'Dark Green', - '4E2A04': 'Brown', - '96FF91': 'Light Green', - '232323': 'Dark Grey', - 'E55BB0': 'Pink', - 'FFFFFF': 'White', - '000000': 'Black', + "B4141E": "Red", + "0042FF": "Blue", + "1CA7EA": "Teal", + "EBE129": "Yellow", + "540081": "Purple", + "FE8A0E": "Orange", + "168000": "Green", + "CCA6FC": "Light Pink", + "1F01C9": "Violet", + "525494": "Light Grey", + "106246": "Dark Green", + "4E2A04": "Brown", + "96FF91": "Light Green", + "232323": "Dark Grey", + "E55BB0": "Pink", + "FFFFFF": "White", + "000000": "Black", } COLOR_CODES_INV = dict(zip(COLOR_CODES.values(), COLOR_CODES.keys())) SUBREGIONS = { # United States - 'us': { - 1: 'us', - 2: 'la', - }, - + "us": {1: "us", 2: "la"}, # Europe - 'eu': { - 1: 'eu', - 2: 'ru', - }, - + "eu": {1: "eu", 2: "ru"}, # Korea - appear to both map to same place - 'kr': { - 1: 'kr', - 2: 'tw', - }, - + "kr": {1: "kr", 2: "tw"}, # Taiwan - appear to both map to same place - 'tw': { - 1: 'kr', - 2: 'tw', - }, - + "tw": {1: "kr", 2: "tw"}, # China - different url scheme (www.battlenet.com.cn)? - 'cn': { - 1: 'cn', - }, - + "cn": {1: "cn"}, # South East Asia - 'sea': { - 1: 'sea', - }, - + "sea": {1: "sea"}, # Singapore - 'sg': { - 1: 'sg', - }, - + "sg": {1: "sg"}, # Public Test - 'xx': { - 1: 'xx', - }, + "xx": {1: "xx"}, } -import json -import pkgutil - -attributes_json = pkgutil.get_data('sc2reader.data', 'attributes.json').decode('utf8') +attributes_json = pkgutil.get_data("sc2reader.data", "attributes.json").decode("utf8") attributes_dict = json.loads(attributes_json) LOBBY_PROPERTIES = dict() -for key, value in attributes_dict.get('attributes', dict()).items(): +for key, value in attributes_dict.get("attributes", dict()).items(): LOBBY_PROPERTIES[int(key)] = value diff --git a/sc2reader/data/HOWTO.md b/sc2reader/data/HOWTO.md index ab67031d..828e5e28 100644 --- a/sc2reader/data/HOWTO.md +++ b/sc2reader/data/HOWTO.md @@ -14,3 +14,6 @@ At the time of writing, the latest build version is 53644. e.g. `python3 sc2reader/generate_build_data.py LotV 53644 balance_data/ sc2reader/` This will generate the necessary data files to support the new build version (namely, `53644_abilities.csv`, `53644_units.csv`, and updated versions of `ability_lookup.csv` and `unit_lookup.csv`). 4. Finally, modify `sc2reader/data/__init__.py` and `sc2reader/resources.py` to register support for the new build version. + +If you are not able to see the correct expansion for the balance data, you may need to authenticate. See the instructions at +https://github.com/ggtracker/sc2reader/issues/98#issuecomment-542554588 on how to do that diff --git a/sc2reader/data/LotV/76114_abilities.csv b/sc2reader/data/LotV/76114_abilities.csv new file mode 100644 index 00000000..cf1d1ae1 --- /dev/null +++ b/sc2reader/data/LotV/76114_abilities.csv @@ -0,0 +1,411 @@ +39,Taunt +40,stop +42,move +45,attack +60,SprayTerran +61,SprayZerg +62,SprayProtoss +63,SalvageShared +65,GhostHoldFire +66,GhostWeaponsFree +68,Explode +69,FleetBeaconResearch +70,FungalGrowth +71,GuardianShield +72,MULERepair +73,ZerglingTrain +74,NexusTrainMothership +75,Feedback +76,MassRecall +78,HallucinationArchon +79,HallucinationColossus +80,HallucinationHighTemplar +81,HallucinationImmortal +82,HallucinationPhoenix +83,HallucinationProbe +84,HallucinationStalker +85,HallucinationVoidRay +86,HallucinationWarpPrism +87,HallucinationZealot +88,MULEGather +90,CalldownMULE +91,GravitonBeam +95,SpawnChangeling +102,Rally +103,ProgressRally +104,RallyCommand +105,RallyNexus +106,RallyHatchery +107,RoachWarrenResearch +109,InfestedTerrans +110,NeuralParasite +111,SpawnLarva +112,StimpackMarauder +113,SupplyDrop +117,UltraliskCavernResearch +119,SCVHarvest +120,ProbeHarvest +122,que1 +123,que5 +124,que5CancelToSelection +126,que5Addon +127,BuildInProgress +128,Repair +129,TerranBuild +131,Stimpack +132,GhostCloak +134,MedivacHeal +135,SiegeMode +136,Unsiege +137,BansheeCloak +138,MedivacTransport +139,ScannerSweep +140,Yamato +141,AssaultMode +142,FighterMode +143,BunkerTransport +144,CommandCenterTransport +145,CommandCenterLiftOff +146,CommandCenterLand +147,BarracksFlyingBuild +148,BarracksLiftOff +149,FactoryFlyingBuild +150,FactoryLiftOff +151,StarportFlyingBuild +152,StarportLiftOff +153,FactoryLand +154,StarportLand +155,CommandCenterTrain +156,BarracksLand +157,SupplyDepotLower +158,SupplyDepotRaise +159,BarracksTrain +160,FactoryTrain +161,StarportTrain +162,EngineeringBayResearch +164,GhostAcademyTrain +165,BarracksTechLabResearch +166,FactoryTechLabResearch +167,StarportTechLabResearch +168,GhostAcademyResearch +169,ArmoryResearch +170,ProtossBuild +171,WarpPrismTransport +172,GatewayTrain +173,StargateTrain +174,RoboticsFacilityTrain +175,NexusTrain +176,PsiStorm +177,HangarQueue5 +179,CarrierTrain +180,ForgeResearch +181,RoboticsBayResearch +182,TemplarArchiveResearch +183,ZergBuild +184,DroneHarvest +185,EvolutionChamberResearch +186,UpgradeToLair +187,UpgradeToHive +188,UpgradeToGreaterSpire +189,HiveResearch +190,SpawningPoolResearch +191,HydraliskDenResearch +192,GreaterSpireResearch +193,LarvaTrain +194,MorphToBroodLord +195,BurrowBanelingDown +196,BurrowBanelingUp +197,BurrowDroneDown +198,BurrowDroneUp +199,BurrowHydraliskDown +200,BurrowHydraliskUp +201,BurrowRoachDown +202,BurrowRoachUp +203,BurrowZerglingDown +204,BurrowZerglingUp +205,BurrowInfestorTerranDown +206,BurrowInfestorTerranUp +207,RedstoneLavaCritterBurrow +208,RedstoneLavaCritterInjuredBurrow +209,RedstoneLavaCritterUnburrow +210,RedstoneLavaCritterInjuredUnburrow +211,OverlordTransport +214,WarpGateTrain +215,BurrowQueenDown +216,BurrowQueenUp +217,NydusCanalTransport +218,Blink +219,BurrowInfestorDown +220,BurrowInfestorUp +221,MorphToOverseer +222,UpgradeToPlanetaryFortress +223,InfestationPitResearch +224,BanelingNestResearch +225,BurrowUltraliskDown +226,BurrowUltraliskUp +227,UpgradeToOrbital +228,UpgradeToWarpGate +229,MorphBackToGateway +230,OrbitalLiftOff +231,OrbitalCommandLand +232,ForceField +233,PhasingMode +234,TransportMode +235,FusionCoreResearch +236,CyberneticsCoreResearch +237,TwilightCouncilResearch +238,TacNukeStrike +241,EMP +243,HiveTrain +245,Transfusion +254,AttackRedirect +255,StimpackRedirect +256,StimpackMarauderRedirect +258,StopRedirect +259,GenerateCreep +260,QueenBuild +261,SpineCrawlerUproot +262,SporeCrawlerUproot +263,SpineCrawlerRoot +264,SporeCrawlerRoot +265,CreepTumorBurrowedBuild +266,BuildAutoTurret +267,ArchonWarp +268,NydusNetworkBuild +270,Charge +274,Contaminate +277,que5Passive +278,que5PassiveCancelToSelection +281,RavagerCorrosiveBile +282,ShieldBatteryRechargeChanneled +303,BurrowLurkerMPDown +304,BurrowLurkerMPUp +307,BurrowRavagerDown +308,BurrowRavagerUp +309,MorphToRavager +310,MorphToTransportOverlord +312,ThorNormalMode +317,DigesterCreepSpray +321,MorphToMothership +346,XelNagaHealingShrine +355,MothershipCoreMassRecall +357,MorphToHellion +367,MorphToHellionTank +375,MorphToSwarmHostBurrowedMP +376,MorphToSwarmHostMP +378,attackProtossBuilding +380,stopProtossBuilding +381,BlindingCloud +383,Yoink +386,ViperConsumeStructure +389,TestZerg +390,VolatileBurstBuilding +397,WidowMineBurrow +398,WidowMineUnburrow +399,WidowMineAttack +400,TornadoMissile +403,HallucinationOracle +404,MedivacSpeedBoost +405,ExtendingBridgeNEWide8Out +406,ExtendingBridgeNEWide8 +407,ExtendingBridgeNWWide8Out +408,ExtendingBridgeNWWide8 +409,ExtendingBridgeNEWide10Out +410,ExtendingBridgeNEWide10 +411,ExtendingBridgeNWWide10Out +412,ExtendingBridgeNWWide10 +413,ExtendingBridgeNEWide12Out +414,ExtendingBridgeNEWide12 +415,ExtendingBridgeNWWide12Out +416,ExtendingBridgeNWWide12 +418,CritterFlee +419,OracleRevelation +427,MothershipCorePurifyNexus +428,XelNaga_Caverns_DoorE +429,XelNaga_Caverns_DoorEOpened +430,XelNaga_Caverns_DoorN +431,XelNaga_Caverns_DoorNE +432,XelNaga_Caverns_DoorNEOpened +433,XelNaga_Caverns_DoorNOpened +434,XelNaga_Caverns_DoorNW +435,XelNaga_Caverns_DoorNWOpened +436,XelNaga_Caverns_DoorS +437,XelNaga_Caverns_DoorSE +438,XelNaga_Caverns_DoorSEOpened +439,XelNaga_Caverns_DoorSOpened +440,XelNaga_Caverns_DoorSW +441,XelNaga_Caverns_DoorSWOpened +442,XelNaga_Caverns_DoorW +443,XelNaga_Caverns_DoorWOpened +444,XelNaga_Caverns_Floating_BridgeNE8Out +445,XelNaga_Caverns_Floating_BridgeNE8 +446,XelNaga_Caverns_Floating_BridgeNW8Out +447,XelNaga_Caverns_Floating_BridgeNW8 +448,XelNaga_Caverns_Floating_BridgeNE10Out +449,XelNaga_Caverns_Floating_BridgeNE10 +450,XelNaga_Caverns_Floating_BridgeNW10Out +451,XelNaga_Caverns_Floating_BridgeNW10 +452,XelNaga_Caverns_Floating_BridgeNE12Out +453,XelNaga_Caverns_Floating_BridgeNE12 +454,XelNaga_Caverns_Floating_BridgeNW12Out +455,XelNaga_Caverns_Floating_BridgeNW12 +456,XelNaga_Caverns_Floating_BridgeH8Out +457,XelNaga_Caverns_Floating_BridgeH8 +458,XelNaga_Caverns_Floating_BridgeV8Out +459,XelNaga_Caverns_Floating_BridgeV8 +460,XelNaga_Caverns_Floating_BridgeH10Out +461,XelNaga_Caverns_Floating_BridgeH10 +462,XelNaga_Caverns_Floating_BridgeV10Out +463,XelNaga_Caverns_Floating_BridgeV10 +464,XelNaga_Caverns_Floating_BridgeH12Out +465,XelNaga_Caverns_Floating_BridgeH12 +466,XelNaga_Caverns_Floating_BridgeV12Out +467,XelNaga_Caverns_Floating_BridgeV12 +468,TemporalField +494,SnowRefinery_Terran_ExtendingBridgeNEShort8Out +495,SnowRefinery_Terran_ExtendingBridgeNEShort8 +496,SnowRefinery_Terran_ExtendingBridgeNWShort8Out +497,SnowRefinery_Terran_ExtendingBridgeNWShort8 +519,CausticSpray +522,MorphToLurker +526,PurificationNovaTargeted +528,LockOn +530,LockOnCancel +532,Hyperjump +534,ThorAPMode +537,NydusWormTransport +538,OracleWeapon +544,LocustMPFlyingSwoop +545,HallucinationDisruptor +546,HallucinationAdept +547,VoidRaySwarmDamageBoost +548,SeekerDummyChannel +549,AiurLightBridgeNE8Out +550,AiurLightBridgeNE8 +551,AiurLightBridgeNE10Out +552,AiurLightBridgeNE10 +553,AiurLightBridgeNE12Out +554,AiurLightBridgeNE12 +555,AiurLightBridgeNW8Out +556,AiurLightBridgeNW8 +557,AiurLightBridgeNW10Out +558,AiurLightBridgeNW10 +559,AiurLightBridgeNW12Out +560,AiurLightBridgeNW12 +573,ShakurasLightBridgeNE8Out +574,ShakurasLightBridgeNE8 +575,ShakurasLightBridgeNE10Out +576,ShakurasLightBridgeNE10 +577,ShakurasLightBridgeNE12Out +578,ShakurasLightBridgeNE12 +579,ShakurasLightBridgeNW8Out +580,ShakurasLightBridgeNW8 +581,ShakurasLightBridgeNW10Out +582,ShakurasLightBridgeNW10 +583,ShakurasLightBridgeNW12Out +584,ShakurasLightBridgeNW12 +585,VoidMPImmortalReviveRebuild +587,ArbiterMPStasisField +588,ArbiterMPRecall +589,CorsairMPDisruptionWeb +590,MorphToGuardianMP +591,MorphToDevourerMP +592,DefilerMPConsume +593,DefilerMPDarkSwarm +594,DefilerMPPlague +595,DefilerMPBurrow +596,DefilerMPUnburrow +597,QueenMPEnsnare +598,QueenMPSpawnBroodlings +599,QueenMPInfestCommandCenter +603,OracleBuild +607,ParasiticBomb +608,AdeptPhaseShift +611,LurkerHoldFire +612,LurkerRemoveHoldFire +615,LiberatorAGTarget +616,LiberatorAATarget +618,AiurLightBridgeAbandonedNE8Out +619,AiurLightBridgeAbandonedNE8 +620,AiurLightBridgeAbandonedNE10Out +621,AiurLightBridgeAbandonedNE10 +622,AiurLightBridgeAbandonedNE12Out +623,AiurLightBridgeAbandonedNE12 +624,AiurLightBridgeAbandonedNW8Out +625,AiurLightBridgeAbandonedNW8 +626,AiurLightBridgeAbandonedNW10Out +627,AiurLightBridgeAbandonedNW10 +628,AiurLightBridgeAbandonedNW12Out +629,AiurLightBridgeAbandonedNW12 +630,KD8Charge +633,AdeptPhaseShiftCancel +634,AdeptShadePhaseShiftCancel +635,SlaynElementalGrab +637,PortCity_Bridge_UnitNE8Out +638,PortCity_Bridge_UnitNE8 +639,PortCity_Bridge_UnitSE8Out +640,PortCity_Bridge_UnitSE8 +641,PortCity_Bridge_UnitNW8Out +642,PortCity_Bridge_UnitNW8 +643,PortCity_Bridge_UnitSW8Out +644,PortCity_Bridge_UnitSW8 +645,PortCity_Bridge_UnitNE10Out +646,PortCity_Bridge_UnitNE10 +647,PortCity_Bridge_UnitSE10Out +648,PortCity_Bridge_UnitSE10 +649,PortCity_Bridge_UnitNW10Out +650,PortCity_Bridge_UnitNW10 +651,PortCity_Bridge_UnitSW10Out +652,PortCity_Bridge_UnitSW10 +653,PortCity_Bridge_UnitNE12Out +654,PortCity_Bridge_UnitNE12 +655,PortCity_Bridge_UnitSE12Out +656,PortCity_Bridge_UnitSE12 +657,PortCity_Bridge_UnitNW12Out +658,PortCity_Bridge_UnitNW12 +659,PortCity_Bridge_UnitSW12Out +660,PortCity_Bridge_UnitSW12 +661,PortCity_Bridge_UnitN8Out +662,PortCity_Bridge_UnitN8 +663,PortCity_Bridge_UnitS8Out +664,PortCity_Bridge_UnitS8 +665,PortCity_Bridge_UnitE8Out +666,PortCity_Bridge_UnitE8 +667,PortCity_Bridge_UnitW8Out +668,PortCity_Bridge_UnitW8 +669,PortCity_Bridge_UnitN10Out +670,PortCity_Bridge_UnitN10 +671,PortCity_Bridge_UnitS10Out +672,PortCity_Bridge_UnitS10 +673,PortCity_Bridge_UnitE10Out +674,PortCity_Bridge_UnitE10 +675,PortCity_Bridge_UnitW10Out +676,PortCity_Bridge_UnitW10 +677,PortCity_Bridge_UnitN12Out +678,PortCity_Bridge_UnitN12 +679,PortCity_Bridge_UnitS12Out +680,PortCity_Bridge_UnitS12 +681,PortCity_Bridge_UnitE12Out +682,PortCity_Bridge_UnitE12 +683,PortCity_Bridge_UnitW12Out +684,PortCity_Bridge_UnitW12 +687,DarkTemplarBlink +690,BattlecruiserAttack +692,BattlecruiserMove +694,BattlecruiserStop +696,SpawnLocustsTargeted +697,ViperParasiticBombRelay +698,ParasiticBombRelayDodge +699,VoidRaySwarmDamageBoostCancel +703,ChannelSnipe +706,DarkShrineResearch +707,LurkerDenMPResearch +708,ObserverSiegeMorphtoObserver +709,ObserverMorphtoObserverSiege +710,OverseerMorphtoOverseerSiegeMode +711,OverseerSiegeModeMorphtoOverseer +712,RavenScramblerMissile +714,RavenRepairDroneHeal +715,RavenShredderMissile +716,ChronoBoostEnergyCost +717,NexusMassRecall diff --git a/sc2reader/data/LotV/76114_units.csv b/sc2reader/data/LotV/76114_units.csv new file mode 100644 index 00000000..6c7af845 --- /dev/null +++ b/sc2reader/data/LotV/76114_units.csv @@ -0,0 +1,1023 @@ +3,System_Snapshot_Dummy +21,Ball +22,StereoscopicOptionsUnit +23,Colossus +24,TechLab +25,Reactor +27,InfestorTerran +28,BanelingCocoon +29,Baneling +30,Mothership +31,PointDefenseDrone +32,Changeling +33,ChangelingZealot +34,ChangelingMarineShield +35,ChangelingMarine +36,ChangelingZerglingWings +37,ChangelingZergling +39,CommandCenter +40,SupplyDepot +41,Refinery +42,Barracks +43,EngineeringBay +44,MissileTurret +45,Bunker +46,SensorTower +47,GhostAcademy +48,Factory +49,Starport +51,Armory +52,FusionCore +53,AutoTurret +54,SiegeTankSieged +55,SiegeTank +56,VikingAssault +57,VikingFighter +58,CommandCenterFlying +59,BarracksTechLab +60,BarracksReactor +61,FactoryTechLab +62,FactoryReactor +63,StarportTechLab +64,StarportReactor +65,FactoryFlying +66,StarportFlying +67,SCV +68,BarracksFlying +69,SupplyDepotLowered +70,Marine +71,Reaper +72,Ghost +73,Marauder +74,Thor +75,Hellion +76,Medivac +77,Banshee +78,Raven +79,Battlecruiser +80,Nuke +81,Nexus +82,Pylon +83,Assimilator +84,Gateway +85,Forge +86,FleetBeacon +87,TwilightCouncil +88,PhotonCannon +89,Stargate +90,TemplarArchive +91,DarkShrine +92,RoboticsBay +93,RoboticsFacility +94,CyberneticsCore +95,Zealot +96,Stalker +97,HighTemplar +98,DarkTemplar +99,Sentry +100,Phoenix +101,Carrier +102,VoidRay +103,WarpPrism +104,Observer +105,Immortal +106,Probe +107,Interceptor +108,Hatchery +109,CreepTumor +110,Extractor +111,SpawningPool +112,EvolutionChamber +113,HydraliskDen +114,Spire +115,UltraliskCavern +116,InfestationPit +117,NydusNetwork +118,BanelingNest +119,RoachWarren +120,SpineCrawler +121,SporeCrawler +122,Lair +123,Hive +124,GreaterSpire +125,Egg +126,Drone +127,Zergling +128,Overlord +129,Hydralisk +130,Mutalisk +131,Ultralisk +132,Roach +133,Infestor +134,Corruptor +135,BroodLordCocoon +136,BroodLord +137,BanelingBurrowed +138,DroneBurrowed +139,HydraliskBurrowed +140,RoachBurrowed +141,ZerglingBurrowed +142,InfestorTerranBurrowed +143,RedstoneLavaCritterBurrowed +144,RedstoneLavaCritterInjuredBurrowed +145,RedstoneLavaCritter +146,RedstoneLavaCritterInjured +147,QueenBurrowed +148,Queen +149,InfestorBurrowed +150,OverlordCocoon +151,Overseer +152,PlanetaryFortress +153,UltraliskBurrowed +154,OrbitalCommand +155,WarpGate +156,OrbitalCommandFlying +157,ForceField +158,WarpPrismPhasing +159,CreepTumorBurrowed +160,CreepTumorQueen +161,SpineCrawlerUprooted +162,SporeCrawlerUprooted +163,Archon +164,NydusCanal +165,BroodlingEscort +166,GhostAlternate +167,GhostNova +168,RichMineralField +169,RichMineralField750 +170,Ursadon +172,LurkerMPBurrowed +173,LurkerMP +174,LurkerDenMP +175,LurkerMPEgg +176,NydusCanalAttacker +177,OverlordTransport +178,Ravager +179,RavagerBurrowed +180,RavagerCocoon +181,TransportOverlordCocoon +182,XelNagaTower +184,Oracle +185,Tempest +187,InfestedTerransEgg +188,Larva +189,OverseerSiegeMode +191,ReaperPlaceholder +192,MarineACGluescreenDummy +193,FirebatACGluescreenDummy +194,MedicACGluescreenDummy +195,MarauderACGluescreenDummy +196,VultureACGluescreenDummy +197,SiegeTankACGluescreenDummy +198,VikingACGluescreenDummy +199,BansheeACGluescreenDummy +200,BattlecruiserACGluescreenDummy +201,OrbitalCommandACGluescreenDummy +202,BunkerACGluescreenDummy +203,BunkerUpgradedACGluescreenDummy +204,MissileTurretACGluescreenDummy +205,HellbatACGluescreenDummy +206,GoliathACGluescreenDummy +207,CycloneACGluescreenDummy +208,WraithACGluescreenDummy +209,ScienceVesselACGluescreenDummy +210,HerculesACGluescreenDummy +211,ThorACGluescreenDummy +212,PerditionTurretACGluescreenDummy +213,FlamingBettyACGluescreenDummy +214,DevastationTurretACGluescreenDummy +215,BlasterBillyACGluescreenDummy +216,SpinningDizzyACGluescreenDummy +217,ZerglingKerriganACGluescreenDummy +218,RaptorACGluescreenDummy +219,QueenCoopACGluescreenDummy +220,HydraliskACGluescreenDummy +221,HydraliskLurkerACGluescreenDummy +222,MutaliskBroodlordACGluescreenDummy +223,BroodLordACGluescreenDummy +224,UltraliskACGluescreenDummy +225,TorrasqueACGluescreenDummy +226,OverseerACGluescreenDummy +227,LurkerACGluescreenDummy +228,SpineCrawlerACGluescreenDummy +229,SporeCrawlerACGluescreenDummy +230,NydusNetworkACGluescreenDummy +231,OmegaNetworkACGluescreenDummy +232,ZerglingZagaraACGluescreenDummy +233,SwarmlingACGluescreenDummy +234,QueenZagaraACGluescreenDummy +235,BanelingACGluescreenDummy +236,SplitterlingACGluescreenDummy +237,AberrationACGluescreenDummy +238,ScourgeACGluescreenDummy +239,CorruptorACGluescreenDummy +240,OverseerZagaraACGluescreenDummy +241,BileLauncherACGluescreenDummy +242,SwarmQueenACGluescreenDummy +243,RoachACGluescreenDummy +244,RoachVileACGluescreenDummy +245,RavagerACGluescreenDummy +246,SwarmHostACGluescreenDummy +247,MutaliskACGluescreenDummy +248,GuardianACGluescreenDummy +249,DevourerACGluescreenDummy +250,ViperACGluescreenDummy +251,BrutaliskACGluescreenDummy +252,LeviathanACGluescreenDummy +253,ZealotACGluescreenDummy +254,ZealotAiurACGluescreenDummy +255,DragoonACGluescreenDummy +256,HighTemplarACGluescreenDummy +257,ArchonACGluescreenDummy +258,ImmortalACGluescreenDummy +259,ObserverACGluescreenDummy +260,PhoenixAiurACGluescreenDummy +261,ReaverACGluescreenDummy +262,TempestACGluescreenDummy +263,PhotonCannonACGluescreenDummy +264,ZealotVorazunACGluescreenDummy +265,ZealotShakurasACGluescreenDummy +266,StalkerShakurasACGluescreenDummy +267,DarkTemplarShakurasACGluescreenDummy +268,CorsairACGluescreenDummy +269,VoidRayACGluescreenDummy +270,VoidRayShakurasACGluescreenDummy +271,OracleACGluescreenDummy +272,DarkArchonACGluescreenDummy +273,DarkPylonACGluescreenDummy +274,ZealotPurifierACGluescreenDummy +275,SentryPurifierACGluescreenDummy +276,ImmortalKaraxACGluescreenDummy +277,ColossusACGluescreenDummy +278,ColossusPurifierACGluescreenDummy +279,PhoenixPurifierACGluescreenDummy +280,CarrierACGluescreenDummy +281,CarrierAiurACGluescreenDummy +282,KhaydarinMonolithACGluescreenDummy +283,ShieldBatteryACGluescreenDummy +284,EliteMarineACGluescreenDummy +285,MarauderCommandoACGluescreenDummy +286,SpecOpsGhostACGluescreenDummy +287,HellbatRangerACGluescreenDummy +288,StrikeGoliathACGluescreenDummy +289,HeavySiegeTankACGluescreenDummy +290,RaidLiberatorACGluescreenDummy +291,RavenTypeIIACGluescreenDummy +292,CovertBansheeACGluescreenDummy +293,RailgunTurretACGluescreenDummy +294,BlackOpsMissileTurretACGluescreenDummy +295,SupplicantACGluescreenDummy +296,StalkerTaldarimACGluescreenDummy +297,SentryTaldarimACGluescreenDummy +298,HighTemplarTaldarimACGluescreenDummy +299,ImmortalTaldarimACGluescreenDummy +300,ColossusTaldarimACGluescreenDummy +301,WarpPrismTaldarimACGluescreenDummy +302,PhotonCannonTaldarimACGluescreenDummy +303,StukovInfestedCivilianACGluescreenDummy +304,StukovInfestedMarineACGluescreenDummy +305,StukovInfestedSiegeTankACGluescreenDummy +306,StukovInfestedDiamondbackACGluescreenDummy +307,StukovInfestedBansheeACGluescreenDummy +308,SILiberatorACGluescreenDummy +309,StukovInfestedBunkerACGluescreenDummy +310,StukovInfestedMissileTurretACGluescreenDummy +311,StukovBroodQueenACGluescreenDummy +312,ZealotFenixACGluescreenDummy +313,SentryFenixACGluescreenDummy +314,AdeptFenixACGluescreenDummy +315,ImmortalFenixACGluescreenDummy +316,ColossusFenixACGluescreenDummy +317,DisruptorACGluescreenDummy +318,ObserverFenixACGluescreenDummy +319,ScoutACGluescreenDummy +320,CarrierFenixACGluescreenDummy +321,PhotonCannonFenixACGluescreenDummy +322,PrimalZerglingACGluescreenDummy +323,RavasaurACGluescreenDummy +324,PrimalRoachACGluescreenDummy +325,FireRoachACGluescreenDummy +326,PrimalGuardianACGluescreenDummy +327,PrimalHydraliskACGluescreenDummy +328,PrimalMutaliskACGluescreenDummy +329,PrimalImpalerACGluescreenDummy +330,PrimalSwarmHostACGluescreenDummy +331,CreeperHostACGluescreenDummy +332,PrimalUltraliskACGluescreenDummy +333,TyrannozorACGluescreenDummy +334,PrimalWurmACGluescreenDummy +335,HHReaperACGluescreenDummy +336,HHWidowMineACGluescreenDummy +337,HHHellionTankACGluescreenDummy +338,HHWraithACGluescreenDummy +339,HHVikingACGluescreenDummy +340,HHBattlecruiserACGluescreenDummy +341,HHRavenACGluescreenDummy +342,HHBomberPlatformACGluescreenDummy +343,HHMercStarportACGluescreenDummy +344,HHMissileTurretACGluescreenDummy +345,TychusReaperACGluescreenDummy +346,TychusFirebatACGluescreenDummy +347,TychusSpectreACGluescreenDummy +348,TychusMedicACGluescreenDummy +349,TychusMarauderACGluescreenDummy +350,TychusWarhoundACGluescreenDummy +351,TychusHERCACGluescreenDummy +352,TychusGhostACGluescreenDummy +353,TychusSCVAutoTurretACGluescreenDummy +354,ZeratulStalkerACGluescreenDummy +355,ZeratulSentryACGluescreenDummy +356,ZeratulDarkTemplarACGluescreenDummy +357,ZeratulImmortalACGluescreenDummy +358,ZeratulObserverACGluescreenDummy +359,ZeratulDisruptorACGluescreenDummy +360,ZeratulWarpPrismACGluescreenDummy +361,ZeratulPhotonCannonACGluescreenDummy +362,MechaZerglingACGluescreenDummy +363,MechaBanelingACGluescreenDummy +364,MechaHydraliskACGluescreenDummy +365,MechaInfestorACGluescreenDummy +366,MechaCorruptorACGluescreenDummy +367,MechaUltraliskACGluescreenDummy +368,MechaOverseerACGluescreenDummy +369,MechaLurkerACGluescreenDummy +370,MechaBattlecarrierLordACGluescreenDummy +371,MechaSpineCrawlerACGluescreenDummy +372,MechaSporeCrawlerACGluescreenDummy +374,RenegadeLongboltMissileWeapon +375,NeedleSpinesWeapon +376,CorruptionWeapon +377,InfestedTerransWeapon +378,NeuralParasiteWeapon +379,PointDefenseDroneReleaseWeapon +380,HunterSeekerWeapon +381,MULE +383,ThorAAWeapon +384,PunisherGrenadesLMWeapon +385,VikingFighterWeapon +386,ATALaserBatteryLMWeapon +387,ATSLaserBatteryLMWeapon +388,LongboltMissileWeapon +389,D8ChargeWeapon +390,YamatoWeapon +391,IonCannonsWeapon +392,AcidSalivaWeapon +393,SpineCrawlerWeapon +394,SporeCrawlerWeapon +395,GlaiveWurmWeapon +396,GlaiveWurmM2Weapon +397,GlaiveWurmM3Weapon +398,StalkerWeapon +399,EMP2Weapon +400,BacklashRocketsLMWeapon +401,PhotonCannonWeapon +402,ParasiteSporeWeapon +404,Broodling +405,BroodLordBWeapon +408,AutoTurretReleaseWeapon +409,LarvaReleaseMissile +410,AcidSpinesWeapon +411,FrenzyWeapon +412,ContaminateWeapon +424,BeaconArmy +425,BeaconDefend +426,BeaconAttack +427,BeaconHarass +428,BeaconIdle +429,BeaconAuto +430,BeaconDetect +431,BeaconScout +432,BeaconClaim +433,BeaconExpand +434,BeaconRally +435,BeaconCustom1 +436,BeaconCustom2 +437,BeaconCustom3 +438,BeaconCustom4 +443,LiberatorAG +445,PreviewBunkerUpgraded +446,HellionTank +447,Cyclone +448,WidowMine +449,Liberator +451,Adept +452,Disruptor +453,SwarmHostMP +454,Viper +455,ShieldBattery +456,HighTemplarSkinPreview +457,MothershipCore +458,Viking +467,AssimilatorRich +468,RichVespeneGeyser +469,ExtractorRich +470,InhibitorZoneSmall +471,InhibitorZoneMedium +472,InhibitorZoneLarge +473,RavagerCorrosiveBileMissile +474,RavagerWeaponMissile +475,RefineryRich +476,RenegadeMissileTurret +477,Rocks2x2NonConjoined +478,FungalGrowthMissile +479,NeuralParasiteTentacleMissile +480,Beacon_Protoss +481,Beacon_ProtossSmall +482,Beacon_Terran +483,Beacon_TerranSmall +484,Beacon_Zerg +485,Beacon_ZergSmall +486,Lyote +487,CarrionBird +488,KarakMale +489,KarakFemale +490,UrsadakFemaleExotic +491,UrsadakMale +492,UrsadakFemale +493,UrsadakCalf +494,UrsadakMaleExotic +495,UtilityBot +496,CommentatorBot1 +497,CommentatorBot2 +498,CommentatorBot3 +499,CommentatorBot4 +500,Scantipede +501,Dog +502,Sheep +503,Cow +504,InfestedTerransEggPlacement +505,InfestorTerransWeapon +506,MineralField +507,MineralField450 +508,MineralField750 +509,MineralFieldOpaque +510,MineralFieldOpaque900 +511,VespeneGeyser +512,SpacePlatformGeyser +513,DestructibleSearchlight +514,DestructibleBullhornLights +515,DestructibleStreetlight +516,DestructibleSpacePlatformSign +517,DestructibleStoreFrontCityProps +518,DestructibleBillboardTall +519,DestructibleBillboardScrollingText +520,DestructibleSpacePlatformBarrier +521,DestructibleSignsDirectional +522,DestructibleSignsConstruction +523,DestructibleSignsFunny +524,DestructibleSignsIcons +525,DestructibleSignsWarning +526,DestructibleGarage +527,DestructibleGarageLarge +528,DestructibleTrafficSignal +529,TrafficSignal +530,BraxisAlphaDestructible1x1 +531,BraxisAlphaDestructible2x2 +532,DestructibleDebris4x4 +533,DestructibleDebris6x6 +534,DestructibleRock2x4Vertical +535,DestructibleRock2x4Horizontal +536,DestructibleRock2x6Vertical +537,DestructibleRock2x6Horizontal +538,DestructibleRock4x4 +539,DestructibleRock6x6 +540,DestructibleRampDiagonalHugeULBR +541,DestructibleRampDiagonalHugeBLUR +542,DestructibleRampVerticalHuge +543,DestructibleRampHorizontalHuge +544,DestructibleDebrisRampDiagonalHugeULBR +545,DestructibleDebrisRampDiagonalHugeBLUR +546,WarpPrismSkinPreview +547,SiegeTankSkinPreview +548,ThorAP +549,ThorAALance +550,LiberatorSkinPreview +551,OverlordGenerateCreepKeybind +552,MengskStatueAlone +553,MengskStatue +554,WolfStatue +555,GlobeStatue +556,Weapon +557,GlaiveWurmBounceWeapon +558,BroodLordWeapon +559,BroodLordAWeapon +560,CreepBlocker1x1 +561,PermanentCreepBlocker1x1 +562,PathingBlocker1x1 +563,PathingBlocker2x2 +564,AutoTestAttackTargetGround +565,AutoTestAttackTargetAir +566,AutoTestAttacker +567,HelperEmitterSelectionArrow +568,MultiKillObject +569,ShapeGolfball +570,ShapeCone +571,ShapeCube +572,ShapeCylinder +573,ShapeDodecahedron +574,ShapeIcosahedron +575,ShapeOctahedron +576,ShapePyramid +577,ShapeRoundedCube +578,ShapeSphere +579,ShapeTetrahedron +580,ShapeThickTorus +581,ShapeThinTorus +582,ShapeTorus +583,Shape4PointStar +584,Shape5PointStar +585,Shape6PointStar +586,Shape8PointStar +587,ShapeArrowPointer +588,ShapeBowl +589,ShapeBox +590,ShapeCapsule +591,ShapeCrescentMoon +592,ShapeDecahedron +593,ShapeDiamond +594,ShapeFootball +595,ShapeGemstone +596,ShapeHeart +597,ShapeJack +598,ShapePlusSign +599,ShapeShamrock +600,ShapeSpade +601,ShapeTube +602,ShapeEgg +603,ShapeYenSign +604,ShapeX +605,ShapeWatermelon +606,ShapeWonSign +607,ShapeTennisball +608,ShapeStrawberry +609,ShapeSmileyFace +610,ShapeSoccerball +611,ShapeRainbow +612,ShapeSadFace +613,ShapePoundSign +614,ShapePear +615,ShapePineapple +616,ShapeOrange +617,ShapePeanut +618,ShapeO +619,ShapeLemon +620,ShapeMoneyBag +621,ShapeHorseshoe +622,ShapeHockeyStick +623,ShapeHockeyPuck +624,ShapeHand +625,ShapeGolfClub +626,ShapeGrape +627,ShapeEuroSign +628,ShapeDollarSign +629,ShapeBasketball +630,ShapeCarrot +631,ShapeCherry +632,ShapeBaseball +633,ShapeBaseballBat +634,ShapeBanana +635,ShapeApple +636,ShapeCashLarge +637,ShapeCashMedium +638,ShapeCashSmall +639,ShapeFootballColored +640,ShapeLemonSmall +641,ShapeOrangeSmall +642,ShapeTreasureChestOpen +643,ShapeTreasureChestClosed +644,ShapeWatermelonSmall +645,UnbuildableRocksDestructible +646,UnbuildableBricksDestructible +647,UnbuildablePlatesDestructible +648,Debris2x2NonConjoined +649,EnemyPathingBlocker1x1 +650,EnemyPathingBlocker2x2 +651,EnemyPathingBlocker4x4 +652,EnemyPathingBlocker8x8 +653,EnemyPathingBlocker16x16 +654,ScopeTest +655,SentryACGluescreenDummy +656,StukovInfestedTrooperACGluescreenDummy +672,CollapsibleTerranTowerDebris +673,DebrisRampLeft +674,DebrisRampRight +678,LocustMP +679,CollapsibleRockTowerDebris +680,NydusCanalCreeper +681,SwarmHostBurrowedMP +682,WarHound +683,WidowMineBurrowed +684,ExtendingBridgeNEWide8Out +685,ExtendingBridgeNEWide8 +686,ExtendingBridgeNWWide8Out +687,ExtendingBridgeNWWide8 +688,ExtendingBridgeNEWide10Out +689,ExtendingBridgeNEWide10 +690,ExtendingBridgeNWWide10Out +691,ExtendingBridgeNWWide10 +692,ExtendingBridgeNEWide12Out +693,ExtendingBridgeNEWide12 +694,ExtendingBridgeNWWide12Out +695,ExtendingBridgeNWWide12 +697,CollapsibleRockTowerDebrisRampRight +698,CollapsibleRockTowerDebrisRampLeft +699,XelNaga_Caverns_DoorE +700,XelNaga_Caverns_DoorEOpened +701,XelNaga_Caverns_DoorN +702,XelNaga_Caverns_DoorNE +703,XelNaga_Caverns_DoorNEOpened +704,XelNaga_Caverns_DoorNOpened +705,XelNaga_Caverns_DoorNW +706,XelNaga_Caverns_DoorNWOpened +707,XelNaga_Caverns_DoorS +708,XelNaga_Caverns_DoorSE +709,XelNaga_Caverns_DoorSEOpened +710,XelNaga_Caverns_DoorSOpened +711,XelNaga_Caverns_DoorSW +712,XelNaga_Caverns_DoorSWOpened +713,XelNaga_Caverns_DoorW +714,XelNaga_Caverns_DoorWOpened +715,XelNaga_Caverns_Floating_BridgeNE8Out +716,XelNaga_Caverns_Floating_BridgeNE8 +717,XelNaga_Caverns_Floating_BridgeNW8Out +718,XelNaga_Caverns_Floating_BridgeNW8 +719,XelNaga_Caverns_Floating_BridgeNE10Out +720,XelNaga_Caverns_Floating_BridgeNE10 +721,XelNaga_Caverns_Floating_BridgeNW10Out +722,XelNaga_Caverns_Floating_BridgeNW10 +723,XelNaga_Caverns_Floating_BridgeNE12Out +724,XelNaga_Caverns_Floating_BridgeNE12 +725,XelNaga_Caverns_Floating_BridgeNW12Out +726,XelNaga_Caverns_Floating_BridgeNW12 +727,XelNaga_Caverns_Floating_BridgeH8Out +728,XelNaga_Caverns_Floating_BridgeH8 +729,XelNaga_Caverns_Floating_BridgeV8Out +730,XelNaga_Caverns_Floating_BridgeV8 +731,XelNaga_Caverns_Floating_BridgeH10Out +732,XelNaga_Caverns_Floating_BridgeH10 +733,XelNaga_Caverns_Floating_BridgeV10Out +734,XelNaga_Caverns_Floating_BridgeV10 +735,XelNaga_Caverns_Floating_BridgeH12Out +736,XelNaga_Caverns_Floating_BridgeH12 +737,XelNaga_Caverns_Floating_BridgeV12Out +738,XelNaga_Caverns_Floating_BridgeV12 +741,CollapsibleTerranTowerPushUnitRampLeft +742,CollapsibleTerranTowerPushUnitRampRight +745,CollapsibleRockTowerPushUnit +746,CollapsibleTerranTowerPushUnit +747,CollapsibleRockTowerPushUnitRampRight +748,CollapsibleRockTowerPushUnitRampLeft +749,DigesterCreepSprayTargetUnit +750,DigesterCreepSprayUnit +751,NydusCanalAttackerWeapon +752,ViperConsumeStructureWeapon +755,ResourceBlocker +756,TempestWeapon +757,YoinkMissile +761,YoinkVikingAirMissile +763,YoinkVikingGroundMissile +765,YoinkSiegeTankMissile +767,WarHoundWeapon +769,EyeStalkWeapon +772,WidowMineWeapon +773,WidowMineAirWeapon +774,MothershipCoreWeaponWeapon +775,TornadoMissileWeapon +776,TornadoMissileDummyWeapon +777,TalonsMissileWeapon +778,CreepTumorMissile +779,LocustMPEggAMissileWeapon +780,LocustMPEggBMissileWeapon +781,LocustMPWeapon +783,RepulsorCannonWeapon +787,CollapsibleRockTowerDiagonal +788,CollapsibleTerranTowerDiagonal +789,CollapsibleTerranTowerRampLeft +790,CollapsibleTerranTowerRampRight +791,Ice2x2NonConjoined +792,IceProtossCrates +793,ProtossCrates +794,TowerMine +795,PickupPalletGas +796,PickupPalletMinerals +797,PickupScrapSalvage1x1 +798,PickupScrapSalvage2x2 +799,PickupScrapSalvage3x3 +800,RoughTerrain +801,UnbuildableBricksSmallUnit +802,UnbuildablePlatesSmallUnit +803,UnbuildablePlatesUnit +804,UnbuildableRocksSmallUnit +805,XelNagaHealingShrine +806,InvisibleTargetDummy +807,ProtossVespeneGeyser +808,CollapsibleRockTower +809,CollapsibleTerranTower +810,ThornLizard +811,CleaningBot +812,DestructibleRock6x6Weak +813,ProtossSnakeSegmentDemo +814,PhysicsCapsule +815,PhysicsCube +816,PhysicsCylinder +817,PhysicsKnot +818,PhysicsL +819,PhysicsPrimitives +820,PhysicsSphere +821,PhysicsStar +822,CreepBlocker4x4 +823,DestructibleCityDebris2x4Vertical +824,DestructibleCityDebris2x4Horizontal +825,DestructibleCityDebris2x6Vertical +826,DestructibleCityDebris2x6Horizontal +827,DestructibleCityDebris4x4 +828,DestructibleCityDebris6x6 +829,DestructibleCityDebrisHugeDiagonalBLUR +830,DestructibleCityDebrisHugeDiagonalULBR +831,TestZerg +832,PathingBlockerRadius1 +833,DestructibleRockEx12x4Vertical +834,DestructibleRockEx12x4Horizontal +835,DestructibleRockEx12x6Vertical +836,DestructibleRockEx12x6Horizontal +837,DestructibleRockEx14x4 +838,DestructibleRockEx16x6 +839,DestructibleRockEx1DiagonalHugeULBR +840,DestructibleRockEx1DiagonalHugeBLUR +841,DestructibleRockEx1VerticalHuge +842,DestructibleRockEx1HorizontalHuge +843,DestructibleIce2x4Vertical +844,DestructibleIce2x4Horizontal +845,DestructibleIce2x6Vertical +846,DestructibleIce2x6Horizontal +847,DestructibleIce4x4 +848,DestructibleIce6x6 +849,DestructibleIceDiagonalHugeULBR +850,DestructibleIceDiagonalHugeBLUR +851,DestructibleIceVerticalHuge +852,DestructibleIceHorizontalHuge +853,DesertPlanetSearchlight +854,DesertPlanetStreetlight +855,UnbuildableBricksUnit +856,UnbuildableRocksUnit +857,ZerusDestructibleArch +858,Artosilope +859,Anteplott +860,LabBot +861,Crabeetle +862,CollapsibleRockTowerRampRight +863,CollapsibleRockTowerRampLeft +864,LabMineralField +865,LabMineralField750 +880,CollapsibleRockTowerDebrisRampLeftGreen +881,CollapsibleRockTowerDebrisRampRightGreen +882,SnowRefinery_Terran_ExtendingBridgeNEShort8Out +883,SnowRefinery_Terran_ExtendingBridgeNEShort8 +884,SnowRefinery_Terran_ExtendingBridgeNWShort8Out +885,SnowRefinery_Terran_ExtendingBridgeNWShort8 +890,Tarsonis_DoorN +891,Tarsonis_DoorNLowered +892,Tarsonis_DoorNE +893,Tarsonis_DoorNELowered +894,Tarsonis_DoorE +895,Tarsonis_DoorELowered +896,Tarsonis_DoorNW +897,Tarsonis_DoorNWLowered +898,CompoundMansion_DoorN +899,CompoundMansion_DoorNLowered +900,CompoundMansion_DoorNE +901,CompoundMansion_DoorNELowered +902,CompoundMansion_DoorE +903,CompoundMansion_DoorELowered +904,CompoundMansion_DoorNW +905,CompoundMansion_DoorNWLowered +907,LocustMPFlying +908,AiurLightBridgeNE8Out +909,AiurLightBridgeNE8 +910,AiurLightBridgeNE10Out +911,AiurLightBridgeNE10 +912,AiurLightBridgeNE12Out +913,AiurLightBridgeNE12 +914,AiurLightBridgeNW8Out +915,AiurLightBridgeNW8 +916,AiurLightBridgeNW10Out +917,AiurLightBridgeNW10 +918,AiurLightBridgeNW12Out +919,AiurLightBridgeNW12 +920,AiurTempleBridgeNE8Out +922,AiurTempleBridgeNE10Out +924,AiurTempleBridgeNE12Out +926,AiurTempleBridgeNW8Out +928,AiurTempleBridgeNW10Out +930,AiurTempleBridgeNW12Out +932,ShakurasLightBridgeNE8Out +933,ShakurasLightBridgeNE8 +934,ShakurasLightBridgeNE10Out +935,ShakurasLightBridgeNE10 +936,ShakurasLightBridgeNE12Out +937,ShakurasLightBridgeNE12 +938,ShakurasLightBridgeNW8Out +939,ShakurasLightBridgeNW8 +940,ShakurasLightBridgeNW10Out +941,ShakurasLightBridgeNW10 +942,ShakurasLightBridgeNW12Out +943,ShakurasLightBridgeNW12 +944,VoidMPImmortalReviveCorpse +945,GuardianCocoonMP +946,GuardianMP +947,DevourerCocoonMP +948,DevourerMP +949,DefilerMPBurrowed +950,DefilerMP +951,OracleStasisTrap +952,DisruptorPhased +953,AiurLightBridgeAbandonedNE8Out +954,AiurLightBridgeAbandonedNE8 +955,AiurLightBridgeAbandonedNE10Out +956,AiurLightBridgeAbandonedNE10 +957,AiurLightBridgeAbandonedNE12Out +958,AiurLightBridgeAbandonedNE12 +959,AiurLightBridgeAbandonedNW8Out +960,AiurLightBridgeAbandonedNW8 +961,AiurLightBridgeAbandonedNW10Out +962,AiurLightBridgeAbandonedNW10 +963,AiurLightBridgeAbandonedNW12Out +964,AiurLightBridgeAbandonedNW12 +965,CollapsiblePurifierTowerDebris +966,PortCity_Bridge_UnitNE8Out +967,PortCity_Bridge_UnitNE8 +968,PortCity_Bridge_UnitSE8Out +969,PortCity_Bridge_UnitSE8 +970,PortCity_Bridge_UnitNW8Out +971,PortCity_Bridge_UnitNW8 +972,PortCity_Bridge_UnitSW8Out +973,PortCity_Bridge_UnitSW8 +974,PortCity_Bridge_UnitNE10Out +975,PortCity_Bridge_UnitNE10 +976,PortCity_Bridge_UnitSE10Out +977,PortCity_Bridge_UnitSE10 +978,PortCity_Bridge_UnitNW10Out +979,PortCity_Bridge_UnitNW10 +980,PortCity_Bridge_UnitSW10Out +981,PortCity_Bridge_UnitSW10 +982,PortCity_Bridge_UnitNE12Out +983,PortCity_Bridge_UnitNE12 +984,PortCity_Bridge_UnitSE12Out +985,PortCity_Bridge_UnitSE12 +986,PortCity_Bridge_UnitNW12Out +987,PortCity_Bridge_UnitNW12 +988,PortCity_Bridge_UnitSW12Out +989,PortCity_Bridge_UnitSW12 +990,PortCity_Bridge_UnitN8Out +991,PortCity_Bridge_UnitN8 +992,PortCity_Bridge_UnitS8Out +993,PortCity_Bridge_UnitS8 +994,PortCity_Bridge_UnitE8Out +995,PortCity_Bridge_UnitE8 +996,PortCity_Bridge_UnitW8Out +997,PortCity_Bridge_UnitW8 +998,PortCity_Bridge_UnitN10Out +999,PortCity_Bridge_UnitN10 +1000,PortCity_Bridge_UnitS10Out +1001,PortCity_Bridge_UnitS10 +1002,PortCity_Bridge_UnitE10Out +1003,PortCity_Bridge_UnitE10 +1004,PortCity_Bridge_UnitW10Out +1005,PortCity_Bridge_UnitW10 +1006,PortCity_Bridge_UnitN12Out +1007,PortCity_Bridge_UnitN12 +1008,PortCity_Bridge_UnitS12Out +1009,PortCity_Bridge_UnitS12 +1010,PortCity_Bridge_UnitE12Out +1011,PortCity_Bridge_UnitE12 +1012,PortCity_Bridge_UnitW12Out +1013,PortCity_Bridge_UnitW12 +1014,PurifierRichMineralField +1015,PurifierRichMineralField750 +1016,CollapsibleRockTowerPushUnitRampLeftGreen +1017,CollapsibleRockTowerPushUnitRampRightGreen +1032,CollapsiblePurifierTowerPushUnit +1034,LocustMPPrecursor +1035,ReleaseInterceptorsBeacon +1036,AdeptPhaseShift +1037,HydraliskImpaleMissile +1038,CycloneMissileLargeAir +1039,CycloneMissile +1040,CycloneMissileLarge +1041,OracleWeapon +1042,TempestWeaponGround +1043,ScoutMPAirWeaponLeft +1044,ScoutMPAirWeaponRight +1045,ArbiterMPWeaponMissile +1046,GuardianMPWeapon +1047,DevourerMPWeaponMissile +1048,DefilerMPDarkSwarmWeapon +1049,QueenMPEnsnareMissile +1050,QueenMPSpawnBroodlingsMissile +1051,LightningBombWeapon +1052,HERCPlacement +1053,GrappleWeapon +1056,CausticSprayMissile +1057,ParasiticBombMissile +1058,ParasiticBombDummy +1059,AdeptWeapon +1060,AdeptUpgradeWeapon +1061,LiberatorMissile +1062,LiberatorDamageMissile +1063,LiberatorAGMissile +1064,KD8Charge +1065,KD8ChargeWeapon +1067,SlaynElementalGrabWeapon +1068,SlaynElementalGrabAirUnit +1069,SlaynElementalGrabGroundUnit +1070,SlaynElementalWeapon +1075,CollapsibleRockTowerRampLeftGreen +1076,CollapsibleRockTowerRampRightGreen +1077,DestructibleExpeditionGate6x6 +1078,DestructibleZergInfestation3x3 +1079,HERC +1080,Moopy +1081,Replicant +1082,SeekerMissile +1083,AiurTempleBridgeDestructibleNE8Out +1084,AiurTempleBridgeDestructibleNE10Out +1085,AiurTempleBridgeDestructibleNE12Out +1086,AiurTempleBridgeDestructibleNW8Out +1087,AiurTempleBridgeDestructibleNW10Out +1088,AiurTempleBridgeDestructibleNW12Out +1089,AiurTempleBridgeDestructibleSW8Out +1090,AiurTempleBridgeDestructibleSW10Out +1091,AiurTempleBridgeDestructibleSW12Out +1092,AiurTempleBridgeDestructibleSE8Out +1093,AiurTempleBridgeDestructibleSE10Out +1094,AiurTempleBridgeDestructibleSE12Out +1096,FlyoverUnit +1097,CorsairMP +1098,ScoutMP +1100,ArbiterMP +1101,ScourgeMP +1102,DefilerMPPlagueWeapon +1103,QueenMP +1104,XelNagaDestructibleRampBlocker6S +1105,XelNagaDestructibleRampBlocker6SE +1106,XelNagaDestructibleRampBlocker6E +1107,XelNagaDestructibleRampBlocker6NE +1108,XelNagaDestructibleRampBlocker6N +1109,XelNagaDestructibleRampBlocker6NW +1110,XelNagaDestructibleRampBlocker6W +1111,XelNagaDestructibleRampBlocker6SW +1112,XelNagaDestructibleRampBlocker8S +1113,XelNagaDestructibleRampBlocker8SE +1114,XelNagaDestructibleRampBlocker8E +1115,XelNagaDestructibleRampBlocker8NE +1116,XelNagaDestructibleRampBlocker8N +1117,XelNagaDestructibleRampBlocker8NW +1118,XelNagaDestructibleRampBlocker8W +1119,XelNagaDestructibleRampBlocker8SW +1120,XelNagaDestructibleBlocker6S +1121,XelNagaDestructibleBlocker6SE +1122,XelNagaDestructibleBlocker6E +1123,XelNagaDestructibleBlocker6NE +1124,XelNagaDestructibleBlocker6N +1125,XelNagaDestructibleBlocker6NW +1126,XelNagaDestructibleBlocker6W +1127,XelNagaDestructibleBlocker6SW +1128,XelNagaDestructibleBlocker8S +1129,XelNagaDestructibleBlocker8SE +1130,XelNagaDestructibleBlocker8E +1131,XelNagaDestructibleBlocker8NE +1132,XelNagaDestructibleBlocker8N +1133,XelNagaDestructibleBlocker8NW +1134,XelNagaDestructibleBlocker8W +1135,XelNagaDestructibleBlocker8SW +1136,ReptileCrate +1137,SlaynSwarmHostSpawnFlyer +1138,SlaynElemental +1139,PurifierVespeneGeyser +1140,ShakurasVespeneGeyser +1141,CollapsiblePurifierTowerDiagonal +1142,CreepOnlyBlocker4x4 +1143,BattleStationMineralField +1144,BattleStationMineralField750 +1145,PurifierMineralField +1146,PurifierMineralField750 +1147,Beacon_Nova +1148,Beacon_NovaSmall +1149,Ursula +1150,Elsecaro_Colonist_Hut +1151,SnowGlazeStarterMP +1152,PylonOvercharged +1153,ObserverSiegeMode +1154,RavenRepairDrone +1156,ParasiticBombRelayDummy +1157,BypassArmorDrone +1158,AdeptPiercingWeapon +1159,HighTemplarWeaponMissile +1160,CycloneMissileLargeAirAlternative +1161,RavenScramblerMissile +1162,RavenRepairDroneReleaseWeapon +1163,RavenShredderMissileWeapon +1164,InfestedAcidSpinesWeapon +1165,InfestorEnsnareAttackMissile +1166,SNARE_PLACEHOLDER +1169,CorrosiveParasiteWeapon diff --git a/sc2reader/data/LotV/77379_abilities.csv b/sc2reader/data/LotV/77379_abilities.csv new file mode 100644 index 00000000..b06e856c --- /dev/null +++ b/sc2reader/data/LotV/77379_abilities.csv @@ -0,0 +1,411 @@ +39,Taunt +40,stop +42,move +45,attack +60,SprayTerran +61,SprayZerg +62,SprayProtoss +63,SalvageShared +65,GhostHoldFire +66,GhostWeaponsFree +68,Explode +69,FleetBeaconResearch +70,FungalGrowth +71,GuardianShield +72,MULERepair +73,ZerglingTrain +74,NexusTrainMothership +75,Feedback +76,MassRecall +78,HallucinationArchon +79,HallucinationColossus +80,HallucinationHighTemplar +81,HallucinationImmortal +82,HallucinationPhoenix +83,HallucinationProbe +84,HallucinationStalker +85,HallucinationVoidRay +86,HallucinationWarpPrism +87,HallucinationZealot +88,MULEGather +90,CalldownMULE +91,GravitonBeam +95,SpawnChangeling +102,Rally +103,ProgressRally +104,RallyCommand +105,RallyNexus +106,RallyHatchery +107,RoachWarrenResearch +110,NeuralParasite +111,SpawnLarva +112,StimpackMarauder +113,SupplyDrop +117,UltraliskCavernResearch +119,SCVHarvest +120,ProbeHarvest +122,que1 +123,que5 +124,que5CancelToSelection +126,que5Addon +127,BuildInProgress +128,Repair +129,TerranBuild +131,Stimpack +132,GhostCloak +134,MedivacHeal +135,SiegeMode +136,Unsiege +137,BansheeCloak +138,MedivacTransport +139,ScannerSweep +140,Yamato +141,AssaultMode +142,FighterMode +143,BunkerTransport +144,CommandCenterTransport +145,CommandCenterLiftOff +146,CommandCenterLand +147,BarracksFlyingBuild +148,BarracksLiftOff +149,FactoryFlyingBuild +150,FactoryLiftOff +151,StarportFlyingBuild +152,StarportLiftOff +153,FactoryLand +154,StarportLand +155,CommandCenterTrain +156,BarracksLand +157,SupplyDepotLower +158,SupplyDepotRaise +159,BarracksTrain +160,FactoryTrain +161,StarportTrain +162,EngineeringBayResearch +164,GhostAcademyTrain +165,BarracksTechLabResearch +166,FactoryTechLabResearch +167,StarportTechLabResearch +168,GhostAcademyResearch +169,ArmoryResearch +170,ProtossBuild +171,WarpPrismTransport +172,GatewayTrain +173,StargateTrain +174,RoboticsFacilityTrain +175,NexusTrain +176,PsiStorm +177,HangarQueue5 +179,CarrierTrain +180,ForgeResearch +181,RoboticsBayResearch +182,TemplarArchiveResearch +183,ZergBuild +184,DroneHarvest +185,EvolutionChamberResearch +186,UpgradeToLair +187,UpgradeToHive +188,UpgradeToGreaterSpire +189,HiveResearch +190,SpawningPoolResearch +191,HydraliskDenResearch +192,GreaterSpireResearch +193,LarvaTrain +194,MorphToBroodLord +195,BurrowBanelingDown +196,BurrowBanelingUp +197,BurrowDroneDown +198,BurrowDroneUp +199,BurrowHydraliskDown +200,BurrowHydraliskUp +201,BurrowRoachDown +202,BurrowRoachUp +203,BurrowZerglingDown +204,BurrowZerglingUp +205,BurrowInfestorTerranDown +206,BurrowInfestorTerranUp +207,RedstoneLavaCritterBurrow +208,RedstoneLavaCritterInjuredBurrow +209,RedstoneLavaCritterUnburrow +210,RedstoneLavaCritterInjuredUnburrow +211,OverlordTransport +214,WarpGateTrain +215,BurrowQueenDown +216,BurrowQueenUp +217,NydusCanalTransport +218,Blink +219,BurrowInfestorDown +220,BurrowInfestorUp +221,MorphToOverseer +222,UpgradeToPlanetaryFortress +223,InfestationPitResearch +224,BanelingNestResearch +225,BurrowUltraliskDown +226,BurrowUltraliskUp +227,UpgradeToOrbital +228,UpgradeToWarpGate +229,MorphBackToGateway +230,OrbitalLiftOff +231,OrbitalCommandLand +232,ForceField +233,PhasingMode +234,TransportMode +235,FusionCoreResearch +236,CyberneticsCoreResearch +237,TwilightCouncilResearch +238,TacNukeStrike +241,EMP +243,HiveTrain +245,Transfusion +254,AttackRedirect +255,StimpackRedirect +256,StimpackMarauderRedirect +258,StopRedirect +259,GenerateCreep +260,QueenBuild +261,SpineCrawlerUproot +262,SporeCrawlerUproot +263,SpineCrawlerRoot +264,SporeCrawlerRoot +265,CreepTumorBurrowedBuild +266,BuildAutoTurret +267,ArchonWarp +268,NydusNetworkBuild +270,Charge +274,Contaminate +277,que5Passive +278,que5PassiveCancelToSelection +281,RavagerCorrosiveBile +282,ShieldBatteryRechargeChanneled +303,BurrowLurkerMPDown +304,BurrowLurkerMPUp +307,BurrowRavagerDown +308,BurrowRavagerUp +309,MorphToRavager +310,MorphToTransportOverlord +312,ThorNormalMode +317,DigesterCreepSpray +321,MorphToMothership +346,XelNagaHealingShrine +355,MothershipCoreMassRecall +357,MorphToHellion +367,MorphToHellionTank +375,MorphToSwarmHostBurrowedMP +376,MorphToSwarmHostMP +378,attackProtossBuilding +380,stopProtossBuilding +381,BlindingCloud +383,Yoink +386,ViperConsumeStructure +389,TestZerg +390,VolatileBurstBuilding +397,WidowMineBurrow +398,WidowMineUnburrow +399,WidowMineAttack +400,TornadoMissile +403,HallucinationOracle +404,MedivacSpeedBoost +405,ExtendingBridgeNEWide8Out +406,ExtendingBridgeNEWide8 +407,ExtendingBridgeNWWide8Out +408,ExtendingBridgeNWWide8 +409,ExtendingBridgeNEWide10Out +410,ExtendingBridgeNEWide10 +411,ExtendingBridgeNWWide10Out +412,ExtendingBridgeNWWide10 +413,ExtendingBridgeNEWide12Out +414,ExtendingBridgeNEWide12 +415,ExtendingBridgeNWWide12Out +416,ExtendingBridgeNWWide12 +418,CritterFlee +419,OracleRevelation +427,MothershipCorePurifyNexus +428,XelNaga_Caverns_DoorE +429,XelNaga_Caverns_DoorEOpened +430,XelNaga_Caverns_DoorN +431,XelNaga_Caverns_DoorNE +432,XelNaga_Caverns_DoorNEOpened +433,XelNaga_Caverns_DoorNOpened +434,XelNaga_Caverns_DoorNW +435,XelNaga_Caverns_DoorNWOpened +436,XelNaga_Caverns_DoorS +437,XelNaga_Caverns_DoorSE +438,XelNaga_Caverns_DoorSEOpened +439,XelNaga_Caverns_DoorSOpened +440,XelNaga_Caverns_DoorSW +441,XelNaga_Caverns_DoorSWOpened +442,XelNaga_Caverns_DoorW +443,XelNaga_Caverns_DoorWOpened +444,XelNaga_Caverns_Floating_BridgeNE8Out +445,XelNaga_Caverns_Floating_BridgeNE8 +446,XelNaga_Caverns_Floating_BridgeNW8Out +447,XelNaga_Caverns_Floating_BridgeNW8 +448,XelNaga_Caverns_Floating_BridgeNE10Out +449,XelNaga_Caverns_Floating_BridgeNE10 +450,XelNaga_Caverns_Floating_BridgeNW10Out +451,XelNaga_Caverns_Floating_BridgeNW10 +452,XelNaga_Caverns_Floating_BridgeNE12Out +453,XelNaga_Caverns_Floating_BridgeNE12 +454,XelNaga_Caverns_Floating_BridgeNW12Out +455,XelNaga_Caverns_Floating_BridgeNW12 +456,XelNaga_Caverns_Floating_BridgeH8Out +457,XelNaga_Caverns_Floating_BridgeH8 +458,XelNaga_Caverns_Floating_BridgeV8Out +459,XelNaga_Caverns_Floating_BridgeV8 +460,XelNaga_Caverns_Floating_BridgeH10Out +461,XelNaga_Caverns_Floating_BridgeH10 +462,XelNaga_Caverns_Floating_BridgeV10Out +463,XelNaga_Caverns_Floating_BridgeV10 +464,XelNaga_Caverns_Floating_BridgeH12Out +465,XelNaga_Caverns_Floating_BridgeH12 +466,XelNaga_Caverns_Floating_BridgeV12Out +467,XelNaga_Caverns_Floating_BridgeV12 +468,TemporalField +494,SnowRefinery_Terran_ExtendingBridgeNEShort8Out +495,SnowRefinery_Terran_ExtendingBridgeNEShort8 +496,SnowRefinery_Terran_ExtendingBridgeNWShort8Out +497,SnowRefinery_Terran_ExtendingBridgeNWShort8 +519,CausticSpray +522,MorphToLurker +526,PurificationNovaTargeted +528,LockOn +530,LockOnCancel +532,Hyperjump +534,ThorAPMode +537,NydusWormTransport +538,OracleWeapon +544,LocustMPFlyingSwoop +545,HallucinationDisruptor +546,HallucinationAdept +547,VoidRaySwarmDamageBoost +548,SeekerDummyChannel +549,AiurLightBridgeNE8Out +550,AiurLightBridgeNE8 +551,AiurLightBridgeNE10Out +552,AiurLightBridgeNE10 +553,AiurLightBridgeNE12Out +554,AiurLightBridgeNE12 +555,AiurLightBridgeNW8Out +556,AiurLightBridgeNW8 +557,AiurLightBridgeNW10Out +558,AiurLightBridgeNW10 +559,AiurLightBridgeNW12Out +560,AiurLightBridgeNW12 +573,ShakurasLightBridgeNE8Out +574,ShakurasLightBridgeNE8 +575,ShakurasLightBridgeNE10Out +576,ShakurasLightBridgeNE10 +577,ShakurasLightBridgeNE12Out +578,ShakurasLightBridgeNE12 +579,ShakurasLightBridgeNW8Out +580,ShakurasLightBridgeNW8 +581,ShakurasLightBridgeNW10Out +582,ShakurasLightBridgeNW10 +583,ShakurasLightBridgeNW12Out +584,ShakurasLightBridgeNW12 +585,VoidMPImmortalReviveRebuild +587,ArbiterMPStasisField +588,ArbiterMPRecall +589,CorsairMPDisruptionWeb +590,MorphToGuardianMP +591,MorphToDevourerMP +592,DefilerMPConsume +593,DefilerMPDarkSwarm +594,DefilerMPPlague +595,DefilerMPBurrow +596,DefilerMPUnburrow +597,QueenMPEnsnare +598,QueenMPSpawnBroodlings +599,QueenMPInfestCommandCenter +603,OracleBuild +607,ParasiticBomb +608,AdeptPhaseShift +611,LurkerHoldFire +612,LurkerRemoveHoldFire +615,LiberatorAGTarget +616,LiberatorAATarget +618,AiurLightBridgeAbandonedNE8Out +619,AiurLightBridgeAbandonedNE8 +620,AiurLightBridgeAbandonedNE10Out +621,AiurLightBridgeAbandonedNE10 +622,AiurLightBridgeAbandonedNE12Out +623,AiurLightBridgeAbandonedNE12 +624,AiurLightBridgeAbandonedNW8Out +625,AiurLightBridgeAbandonedNW8 +626,AiurLightBridgeAbandonedNW10Out +627,AiurLightBridgeAbandonedNW10 +628,AiurLightBridgeAbandonedNW12Out +629,AiurLightBridgeAbandonedNW12 +630,KD8Charge +633,AdeptPhaseShiftCancel +634,AdeptShadePhaseShiftCancel +635,SlaynElementalGrab +637,PortCity_Bridge_UnitNE8Out +638,PortCity_Bridge_UnitNE8 +639,PortCity_Bridge_UnitSE8Out +640,PortCity_Bridge_UnitSE8 +641,PortCity_Bridge_UnitNW8Out +642,PortCity_Bridge_UnitNW8 +643,PortCity_Bridge_UnitSW8Out +644,PortCity_Bridge_UnitSW8 +645,PortCity_Bridge_UnitNE10Out +646,PortCity_Bridge_UnitNE10 +647,PortCity_Bridge_UnitSE10Out +648,PortCity_Bridge_UnitSE10 +649,PortCity_Bridge_UnitNW10Out +650,PortCity_Bridge_UnitNW10 +651,PortCity_Bridge_UnitSW10Out +652,PortCity_Bridge_UnitSW10 +653,PortCity_Bridge_UnitNE12Out +654,PortCity_Bridge_UnitNE12 +655,PortCity_Bridge_UnitSE12Out +656,PortCity_Bridge_UnitSE12 +657,PortCity_Bridge_UnitNW12Out +658,PortCity_Bridge_UnitNW12 +659,PortCity_Bridge_UnitSW12Out +660,PortCity_Bridge_UnitSW12 +661,PortCity_Bridge_UnitN8Out +662,PortCity_Bridge_UnitN8 +663,PortCity_Bridge_UnitS8Out +664,PortCity_Bridge_UnitS8 +665,PortCity_Bridge_UnitE8Out +666,PortCity_Bridge_UnitE8 +667,PortCity_Bridge_UnitW8Out +668,PortCity_Bridge_UnitW8 +669,PortCity_Bridge_UnitN10Out +670,PortCity_Bridge_UnitN10 +671,PortCity_Bridge_UnitS10Out +672,PortCity_Bridge_UnitS10 +673,PortCity_Bridge_UnitE10Out +674,PortCity_Bridge_UnitE10 +675,PortCity_Bridge_UnitW10Out +676,PortCity_Bridge_UnitW10 +677,PortCity_Bridge_UnitN12Out +678,PortCity_Bridge_UnitN12 +679,PortCity_Bridge_UnitS12Out +680,PortCity_Bridge_UnitS12 +681,PortCity_Bridge_UnitE12Out +682,PortCity_Bridge_UnitE12 +683,PortCity_Bridge_UnitW12Out +684,PortCity_Bridge_UnitW12 +687,DarkTemplarBlink +690,BattlecruiserAttack +692,BattlecruiserMove +694,BattlecruiserStop +696,AmorphousArmorcloud +697,SpawnLocustsTargeted +698,ViperParasiticBombRelay +699,ParasiticBombRelayDodge +700,VoidRaySwarmDamageBoostCancel +704,ChannelSnipe +707,DarkShrineResearch +708,LurkerDenMPResearch +709,ObserverSiegeMorphtoObserver +710,ObserverMorphtoObserverSiege +711,OverseerMorphtoOverseerSiegeMode +712,OverseerSiegeModeMorphtoOverseer +713,RavenScramblerMissile +715,RavenRepairDroneHeal +716,RavenShredderMissile +717,ChronoBoostEnergyCost +718,NexusMassRecall diff --git a/sc2reader/data/LotV/77379_units.csv b/sc2reader/data/LotV/77379_units.csv new file mode 100644 index 00000000..51c81189 --- /dev/null +++ b/sc2reader/data/LotV/77379_units.csv @@ -0,0 +1,1038 @@ +3,System_Snapshot_Dummy +21,Ball +22,StereoscopicOptionsUnit +23,Colossus +24,TechLab +25,Reactor +27,InfestorTerran +28,BanelingCocoon +29,Baneling +30,Mothership +31,PointDefenseDrone +32,Changeling +33,ChangelingZealot +34,ChangelingMarineShield +35,ChangelingMarine +36,ChangelingZerglingWings +37,ChangelingZergling +39,CommandCenter +40,SupplyDepot +41,Refinery +42,Barracks +43,EngineeringBay +44,MissileTurret +45,Bunker +46,RefineryRich +47,SensorTower +48,GhostAcademy +49,Factory +50,Starport +52,Armory +53,FusionCore +54,AutoTurret +55,SiegeTankSieged +56,SiegeTank +57,VikingAssault +58,VikingFighter +59,CommandCenterFlying +60,BarracksTechLab +61,BarracksReactor +62,FactoryTechLab +63,FactoryReactor +64,StarportTechLab +65,StarportReactor +66,FactoryFlying +67,StarportFlying +68,SCV +69,BarracksFlying +70,SupplyDepotLowered +71,Marine +72,Reaper +73,Ghost +74,Marauder +75,Thor +76,Hellion +77,Medivac +78,Banshee +79,Raven +80,Battlecruiser +81,Nuke +82,Nexus +83,Pylon +84,Assimilator +85,Gateway +86,Forge +87,FleetBeacon +88,TwilightCouncil +89,PhotonCannon +90,Stargate +91,TemplarArchive +92,DarkShrine +93,RoboticsBay +94,RoboticsFacility +95,CyberneticsCore +96,Zealot +97,Stalker +98,HighTemplar +99,DarkTemplar +100,Sentry +101,Phoenix +102,Carrier +103,VoidRay +104,WarpPrism +105,Observer +106,Immortal +107,Probe +108,Interceptor +109,Hatchery +110,CreepTumor +111,Extractor +112,SpawningPool +113,EvolutionChamber +114,HydraliskDen +115,Spire +116,UltraliskCavern +117,InfestationPit +118,NydusNetwork +119,BanelingNest +120,RoachWarren +121,SpineCrawler +122,SporeCrawler +123,Lair +124,Hive +125,GreaterSpire +126,Egg +127,Drone +128,Zergling +129,Overlord +130,Hydralisk +131,Mutalisk +132,Ultralisk +133,Roach +134,Infestor +135,Corruptor +136,BroodLordCocoon +137,BroodLord +138,BanelingBurrowed +139,DroneBurrowed +140,HydraliskBurrowed +141,RoachBurrowed +142,ZerglingBurrowed +143,InfestorTerranBurrowed +144,RedstoneLavaCritterBurrowed +145,RedstoneLavaCritterInjuredBurrowed +146,RedstoneLavaCritter +147,RedstoneLavaCritterInjured +148,QueenBurrowed +149,Queen +150,InfestorBurrowed +151,OverlordCocoon +152,Overseer +153,PlanetaryFortress +154,UltraliskBurrowed +155,OrbitalCommand +156,WarpGate +157,OrbitalCommandFlying +158,ForceField +159,WarpPrismPhasing +160,CreepTumorBurrowed +161,CreepTumorQueen +162,SpineCrawlerUprooted +163,SporeCrawlerUprooted +164,Archon +165,NydusCanal +166,BroodlingEscort +167,GhostAlternate +168,GhostNova +169,RichMineralField +170,RichMineralField750 +171,Ursadon +173,LurkerMPBurrowed +174,LurkerMP +175,LurkerDenMP +176,LurkerMPEgg +177,NydusCanalAttacker +178,OverlordTransport +179,Ravager +180,RavagerBurrowed +181,RavagerCocoon +182,TransportOverlordCocoon +183,XelNagaTower +185,Oracle +186,Tempest +188,InfestedTerransEgg +189,Larva +190,OverseerSiegeMode +192,ReaperPlaceholder +193,MarineACGluescreenDummy +194,FirebatACGluescreenDummy +195,MedicACGluescreenDummy +196,MarauderACGluescreenDummy +197,VultureACGluescreenDummy +198,SiegeTankACGluescreenDummy +199,VikingACGluescreenDummy +200,BansheeACGluescreenDummy +201,BattlecruiserACGluescreenDummy +202,OrbitalCommandACGluescreenDummy +203,BunkerACGluescreenDummy +204,BunkerUpgradedACGluescreenDummy +205,MissileTurretACGluescreenDummy +206,HellbatACGluescreenDummy +207,GoliathACGluescreenDummy +208,CycloneACGluescreenDummy +209,WraithACGluescreenDummy +210,ScienceVesselACGluescreenDummy +211,HerculesACGluescreenDummy +212,ThorACGluescreenDummy +213,PerditionTurretACGluescreenDummy +214,FlamingBettyACGluescreenDummy +215,DevastationTurretACGluescreenDummy +216,BlasterBillyACGluescreenDummy +217,SpinningDizzyACGluescreenDummy +218,ZerglingKerriganACGluescreenDummy +219,RaptorACGluescreenDummy +220,QueenCoopACGluescreenDummy +221,HydraliskACGluescreenDummy +222,HydraliskLurkerACGluescreenDummy +223,MutaliskBroodlordACGluescreenDummy +224,BroodLordACGluescreenDummy +225,UltraliskACGluescreenDummy +226,TorrasqueACGluescreenDummy +227,OverseerACGluescreenDummy +228,LurkerACGluescreenDummy +229,SpineCrawlerACGluescreenDummy +230,SporeCrawlerACGluescreenDummy +231,NydusNetworkACGluescreenDummy +232,OmegaNetworkACGluescreenDummy +233,ZerglingZagaraACGluescreenDummy +234,SwarmlingACGluescreenDummy +235,QueenZagaraACGluescreenDummy +236,BanelingACGluescreenDummy +237,SplitterlingACGluescreenDummy +238,AberrationACGluescreenDummy +239,ScourgeACGluescreenDummy +240,CorruptorACGluescreenDummy +241,OverseerZagaraACGluescreenDummy +242,BileLauncherACGluescreenDummy +243,SwarmQueenACGluescreenDummy +244,RoachACGluescreenDummy +245,RoachVileACGluescreenDummy +246,RavagerACGluescreenDummy +247,SwarmHostACGluescreenDummy +248,MutaliskACGluescreenDummy +249,GuardianACGluescreenDummy +250,DevourerACGluescreenDummy +251,ViperACGluescreenDummy +252,BrutaliskACGluescreenDummy +253,LeviathanACGluescreenDummy +254,ZealotACGluescreenDummy +255,ZealotAiurACGluescreenDummy +256,DragoonACGluescreenDummy +257,HighTemplarACGluescreenDummy +258,ArchonACGluescreenDummy +259,ImmortalACGluescreenDummy +260,ObserverACGluescreenDummy +261,PhoenixAiurACGluescreenDummy +262,ReaverACGluescreenDummy +263,TempestACGluescreenDummy +264,PhotonCannonACGluescreenDummy +265,ZealotVorazunACGluescreenDummy +266,ZealotShakurasACGluescreenDummy +267,StalkerShakurasACGluescreenDummy +268,DarkTemplarShakurasACGluescreenDummy +269,CorsairACGluescreenDummy +270,VoidRayACGluescreenDummy +271,VoidRayShakurasACGluescreenDummy +272,OracleACGluescreenDummy +273,DarkArchonACGluescreenDummy +274,DarkPylonACGluescreenDummy +275,ZealotPurifierACGluescreenDummy +276,SentryPurifierACGluescreenDummy +277,ImmortalKaraxACGluescreenDummy +278,ColossusACGluescreenDummy +279,ColossusPurifierACGluescreenDummy +280,PhoenixPurifierACGluescreenDummy +281,CarrierACGluescreenDummy +282,CarrierAiurACGluescreenDummy +283,KhaydarinMonolithACGluescreenDummy +284,ShieldBatteryACGluescreenDummy +285,EliteMarineACGluescreenDummy +286,MarauderCommandoACGluescreenDummy +287,SpecOpsGhostACGluescreenDummy +288,HellbatRangerACGluescreenDummy +289,StrikeGoliathACGluescreenDummy +290,HeavySiegeTankACGluescreenDummy +291,RaidLiberatorACGluescreenDummy +292,RavenTypeIIACGluescreenDummy +293,CovertBansheeACGluescreenDummy +294,RailgunTurretACGluescreenDummy +295,BlackOpsMissileTurretACGluescreenDummy +296,SupplicantACGluescreenDummy +297,StalkerTaldarimACGluescreenDummy +298,SentryTaldarimACGluescreenDummy +299,HighTemplarTaldarimACGluescreenDummy +300,ImmortalTaldarimACGluescreenDummy +301,ColossusTaldarimACGluescreenDummy +302,WarpPrismTaldarimACGluescreenDummy +303,PhotonCannonTaldarimACGluescreenDummy +304,StukovInfestedCivilianACGluescreenDummy +305,StukovInfestedMarineACGluescreenDummy +306,StukovInfestedSiegeTankACGluescreenDummy +307,StukovInfestedDiamondbackACGluescreenDummy +308,StukovInfestedBansheeACGluescreenDummy +309,SILiberatorACGluescreenDummy +310,StukovInfestedBunkerACGluescreenDummy +311,StukovInfestedMissileTurretACGluescreenDummy +312,StukovBroodQueenACGluescreenDummy +313,ZealotFenixACGluescreenDummy +314,SentryFenixACGluescreenDummy +315,AdeptFenixACGluescreenDummy +316,ImmortalFenixACGluescreenDummy +317,ColossusFenixACGluescreenDummy +318,DisruptorACGluescreenDummy +319,ObserverFenixACGluescreenDummy +320,ScoutACGluescreenDummy +321,CarrierFenixACGluescreenDummy +322,PhotonCannonFenixACGluescreenDummy +323,PrimalZerglingACGluescreenDummy +324,RavasaurACGluescreenDummy +325,PrimalRoachACGluescreenDummy +326,FireRoachACGluescreenDummy +327,PrimalGuardianACGluescreenDummy +328,PrimalHydraliskACGluescreenDummy +329,PrimalMutaliskACGluescreenDummy +330,PrimalImpalerACGluescreenDummy +331,PrimalSwarmHostACGluescreenDummy +332,CreeperHostACGluescreenDummy +333,PrimalUltraliskACGluescreenDummy +334,TyrannozorACGluescreenDummy +335,PrimalWurmACGluescreenDummy +336,HHReaperACGluescreenDummy +337,HHWidowMineACGluescreenDummy +338,HHHellionTankACGluescreenDummy +339,HHWraithACGluescreenDummy +340,HHVikingACGluescreenDummy +341,HHBattlecruiserACGluescreenDummy +342,HHRavenACGluescreenDummy +343,HHBomberPlatformACGluescreenDummy +344,HHMercStarportACGluescreenDummy +345,HHMissileTurretACGluescreenDummy +346,TychusReaperACGluescreenDummy +347,TychusFirebatACGluescreenDummy +348,TychusSpectreACGluescreenDummy +349,TychusMedicACGluescreenDummy +350,TychusMarauderACGluescreenDummy +351,TychusWarhoundACGluescreenDummy +352,TychusHERCACGluescreenDummy +353,TychusGhostACGluescreenDummy +354,TychusSCVAutoTurretACGluescreenDummy +355,ZeratulStalkerACGluescreenDummy +356,ZeratulSentryACGluescreenDummy +357,ZeratulDarkTemplarACGluescreenDummy +358,ZeratulImmortalACGluescreenDummy +359,ZeratulObserverACGluescreenDummy +360,ZeratulDisruptorACGluescreenDummy +361,ZeratulWarpPrismACGluescreenDummy +362,ZeratulPhotonCannonACGluescreenDummy +363,MechaZerglingACGluescreenDummy +364,MechaBanelingACGluescreenDummy +365,MechaHydraliskACGluescreenDummy +366,MechaInfestorACGluescreenDummy +367,MechaCorruptorACGluescreenDummy +368,MechaUltraliskACGluescreenDummy +369,MechaOverseerACGluescreenDummy +370,MechaLurkerACGluescreenDummy +371,MechaBattlecarrierLordACGluescreenDummy +372,MechaSpineCrawlerACGluescreenDummy +373,MechaSporeCrawlerACGluescreenDummy +374,TrooperMengskACGluescreenDummy +375,MedivacMengskACGluescreenDummy +376,BlimpMengskACGluescreenDummy +377,MarauderMengskACGluescreenDummy +378,GhostMengskACGluescreenDummy +379,SiegeTankMengskACGluescreenDummy +380,ThorMengskACGluescreenDummy +381,VikingMengskACGluescreenDummy +382,BattlecruiserMengskACGluescreenDummy +383,BunkerDepotMengskACGluescreenDummy +384,MissileTurretMengskACGluescreenDummy +385,ArtilleryMengskACGluescreenDummy +387,RenegadeLongboltMissileWeapon +388,NeedleSpinesWeapon +389,CorruptionWeapon +390,InfestedTerransWeapon +391,NeuralParasiteWeapon +392,PointDefenseDroneReleaseWeapon +393,HunterSeekerWeapon +394,MULE +396,ThorAAWeapon +397,PunisherGrenadesLMWeapon +398,VikingFighterWeapon +399,ATALaserBatteryLMWeapon +400,ATSLaserBatteryLMWeapon +401,LongboltMissileWeapon +402,D8ChargeWeapon +403,YamatoWeapon +404,IonCannonsWeapon +405,AcidSalivaWeapon +406,SpineCrawlerWeapon +407,SporeCrawlerWeapon +408,GlaiveWurmWeapon +409,GlaiveWurmM2Weapon +410,GlaiveWurmM3Weapon +411,StalkerWeapon +412,EMP2Weapon +413,BacklashRocketsLMWeapon +414,PhotonCannonWeapon +415,ParasiteSporeWeapon +417,Broodling +418,BroodLordBWeapon +421,AutoTurretReleaseWeapon +422,LarvaReleaseMissile +423,AcidSpinesWeapon +424,FrenzyWeapon +425,ContaminateWeapon +437,BeaconArmy +438,BeaconDefend +439,BeaconAttack +440,BeaconHarass +441,BeaconIdle +442,BeaconAuto +443,BeaconDetect +444,BeaconScout +445,BeaconClaim +446,BeaconExpand +447,BeaconRally +448,BeaconCustom1 +449,BeaconCustom2 +450,BeaconCustom3 +451,BeaconCustom4 +456,LiberatorAG +458,PreviewBunkerUpgraded +459,HellionTank +460,Cyclone +461,WidowMine +462,Liberator +464,Adept +465,Disruptor +466,SwarmHostMP +467,Viper +468,ShieldBattery +469,HighTemplarSkinPreview +470,MothershipCore +471,Viking +481,InhibitorZoneSmall +482,InhibitorZoneMedium +483,InhibitorZoneLarge +484,AccelerationZoneSmall +485,AccelerationZoneMedium +486,AccelerationZoneLarge +487,AssimilatorRich +488,RichVespeneGeyser +489,ExtractorRich +490,RavagerCorrosiveBileMissile +491,RavagerWeaponMissile +492,RenegadeMissileTurret +493,Rocks2x2NonConjoined +494,FungalGrowthMissile +495,NeuralParasiteTentacleMissile +496,Beacon_Protoss +497,Beacon_ProtossSmall +498,Beacon_Terran +499,Beacon_TerranSmall +500,Beacon_Zerg +501,Beacon_ZergSmall +502,Lyote +503,CarrionBird +504,KarakMale +505,KarakFemale +506,UrsadakFemaleExotic +507,UrsadakMale +508,UrsadakFemale +509,UrsadakCalf +510,UrsadakMaleExotic +511,UtilityBot +512,CommentatorBot1 +513,CommentatorBot2 +514,CommentatorBot3 +515,CommentatorBot4 +516,Scantipede +517,Dog +518,Sheep +519,Cow +520,InfestedTerransEggPlacement +521,InfestorTerransWeapon +522,MineralField +523,MineralField450 +524,MineralField750 +525,MineralFieldOpaque +526,MineralFieldOpaque900 +527,VespeneGeyser +528,SpacePlatformGeyser +529,DestructibleSearchlight +530,DestructibleBullhornLights +531,DestructibleStreetlight +532,DestructibleSpacePlatformSign +533,DestructibleStoreFrontCityProps +534,DestructibleBillboardTall +535,DestructibleBillboardScrollingText +536,DestructibleSpacePlatformBarrier +537,DestructibleSignsDirectional +538,DestructibleSignsConstruction +539,DestructibleSignsFunny +540,DestructibleSignsIcons +541,DestructibleSignsWarning +542,DestructibleGarage +543,DestructibleGarageLarge +544,DestructibleTrafficSignal +545,TrafficSignal +546,BraxisAlphaDestructible1x1 +547,BraxisAlphaDestructible2x2 +548,DestructibleDebris4x4 +549,DestructibleDebris6x6 +550,DestructibleRock2x4Vertical +551,DestructibleRock2x4Horizontal +552,DestructibleRock2x6Vertical +553,DestructibleRock2x6Horizontal +554,DestructibleRock4x4 +555,DestructibleRock6x6 +556,DestructibleRampDiagonalHugeULBR +557,DestructibleRampDiagonalHugeBLUR +558,DestructibleRampVerticalHuge +559,DestructibleRampHorizontalHuge +560,DestructibleDebrisRampDiagonalHugeULBR +561,DestructibleDebrisRampDiagonalHugeBLUR +562,WarpPrismSkinPreview +563,SiegeTankSkinPreview +564,ThorAP +565,ThorAALance +566,LiberatorSkinPreview +567,OverlordGenerateCreepKeybind +568,MengskStatueAlone +569,MengskStatue +570,WolfStatue +571,GlobeStatue +572,Weapon +573,GlaiveWurmBounceWeapon +574,BroodLordWeapon +575,BroodLordAWeapon +576,CreepBlocker1x1 +577,PermanentCreepBlocker1x1 +578,PathingBlocker1x1 +579,PathingBlocker2x2 +580,AutoTestAttackTargetGround +581,AutoTestAttackTargetAir +582,AutoTestAttacker +583,HelperEmitterSelectionArrow +584,MultiKillObject +585,ShapeGolfball +586,ShapeCone +587,ShapeCube +588,ShapeCylinder +589,ShapeDodecahedron +590,ShapeIcosahedron +591,ShapeOctahedron +592,ShapePyramid +593,ShapeRoundedCube +594,ShapeSphere +595,ShapeTetrahedron +596,ShapeThickTorus +597,ShapeThinTorus +598,ShapeTorus +599,Shape4PointStar +600,Shape5PointStar +601,Shape6PointStar +602,Shape8PointStar +603,ShapeArrowPointer +604,ShapeBowl +605,ShapeBox +606,ShapeCapsule +607,ShapeCrescentMoon +608,ShapeDecahedron +609,ShapeDiamond +610,ShapeFootball +611,ShapeGemstone +612,ShapeHeart +613,ShapeJack +614,ShapePlusSign +615,ShapeShamrock +616,ShapeSpade +617,ShapeTube +618,ShapeEgg +619,ShapeYenSign +620,ShapeX +621,ShapeWatermelon +622,ShapeWonSign +623,ShapeTennisball +624,ShapeStrawberry +625,ShapeSmileyFace +626,ShapeSoccerball +627,ShapeRainbow +628,ShapeSadFace +629,ShapePoundSign +630,ShapePear +631,ShapePineapple +632,ShapeOrange +633,ShapePeanut +634,ShapeO +635,ShapeLemon +636,ShapeMoneyBag +637,ShapeHorseshoe +638,ShapeHockeyStick +639,ShapeHockeyPuck +640,ShapeHand +641,ShapeGolfClub +642,ShapeGrape +643,ShapeEuroSign +644,ShapeDollarSign +645,ShapeBasketball +646,ShapeCarrot +647,ShapeCherry +648,ShapeBaseball +649,ShapeBaseballBat +650,ShapeBanana +651,ShapeApple +652,ShapeCashLarge +653,ShapeCashMedium +654,ShapeCashSmall +655,ShapeFootballColored +656,ShapeLemonSmall +657,ShapeOrangeSmall +658,ShapeTreasureChestOpen +659,ShapeTreasureChestClosed +660,ShapeWatermelonSmall +661,UnbuildableRocksDestructible +662,UnbuildableBricksDestructible +663,UnbuildablePlatesDestructible +664,Debris2x2NonConjoined +665,EnemyPathingBlocker1x1 +666,EnemyPathingBlocker2x2 +667,EnemyPathingBlocker4x4 +668,EnemyPathingBlocker8x8 +669,EnemyPathingBlocker16x16 +670,ScopeTest +671,SentryACGluescreenDummy +672,StukovInfestedTrooperACGluescreenDummy +688,CollapsibleTerranTowerDebris +689,DebrisRampLeft +690,DebrisRampRight +694,LocustMP +695,CollapsibleRockTowerDebris +696,NydusCanalCreeper +697,SwarmHostBurrowedMP +698,WarHound +699,WidowMineBurrowed +700,ExtendingBridgeNEWide8Out +701,ExtendingBridgeNEWide8 +702,ExtendingBridgeNWWide8Out +703,ExtendingBridgeNWWide8 +704,ExtendingBridgeNEWide10Out +705,ExtendingBridgeNEWide10 +706,ExtendingBridgeNWWide10Out +707,ExtendingBridgeNWWide10 +708,ExtendingBridgeNEWide12Out +709,ExtendingBridgeNEWide12 +710,ExtendingBridgeNWWide12Out +711,ExtendingBridgeNWWide12 +713,CollapsibleRockTowerDebrisRampRight +714,CollapsibleRockTowerDebrisRampLeft +715,XelNaga_Caverns_DoorE +716,XelNaga_Caverns_DoorEOpened +717,XelNaga_Caverns_DoorN +718,XelNaga_Caverns_DoorNE +719,XelNaga_Caverns_DoorNEOpened +720,XelNaga_Caverns_DoorNOpened +721,XelNaga_Caverns_DoorNW +722,XelNaga_Caverns_DoorNWOpened +723,XelNaga_Caverns_DoorS +724,XelNaga_Caverns_DoorSE +725,XelNaga_Caverns_DoorSEOpened +726,XelNaga_Caverns_DoorSOpened +727,XelNaga_Caverns_DoorSW +728,XelNaga_Caverns_DoorSWOpened +729,XelNaga_Caverns_DoorW +730,XelNaga_Caverns_DoorWOpened +731,XelNaga_Caverns_Floating_BridgeNE8Out +732,XelNaga_Caverns_Floating_BridgeNE8 +733,XelNaga_Caverns_Floating_BridgeNW8Out +734,XelNaga_Caverns_Floating_BridgeNW8 +735,XelNaga_Caverns_Floating_BridgeNE10Out +736,XelNaga_Caverns_Floating_BridgeNE10 +737,XelNaga_Caverns_Floating_BridgeNW10Out +738,XelNaga_Caverns_Floating_BridgeNW10 +739,XelNaga_Caverns_Floating_BridgeNE12Out +740,XelNaga_Caverns_Floating_BridgeNE12 +741,XelNaga_Caverns_Floating_BridgeNW12Out +742,XelNaga_Caverns_Floating_BridgeNW12 +743,XelNaga_Caverns_Floating_BridgeH8Out +744,XelNaga_Caverns_Floating_BridgeH8 +745,XelNaga_Caverns_Floating_BridgeV8Out +746,XelNaga_Caverns_Floating_BridgeV8 +747,XelNaga_Caverns_Floating_BridgeH10Out +748,XelNaga_Caverns_Floating_BridgeH10 +749,XelNaga_Caverns_Floating_BridgeV10Out +750,XelNaga_Caverns_Floating_BridgeV10 +751,XelNaga_Caverns_Floating_BridgeH12Out +752,XelNaga_Caverns_Floating_BridgeH12 +753,XelNaga_Caverns_Floating_BridgeV12Out +754,XelNaga_Caverns_Floating_BridgeV12 +757,CollapsibleTerranTowerPushUnitRampLeft +758,CollapsibleTerranTowerPushUnitRampRight +761,CollapsibleRockTowerPushUnit +762,CollapsibleTerranTowerPushUnit +763,CollapsibleRockTowerPushUnitRampRight +764,CollapsibleRockTowerPushUnitRampLeft +765,DigesterCreepSprayTargetUnit +766,DigesterCreepSprayUnit +767,NydusCanalAttackerWeapon +768,ViperConsumeStructureWeapon +771,ResourceBlocker +772,TempestWeapon +773,YoinkMissile +777,YoinkVikingAirMissile +779,YoinkVikingGroundMissile +781,YoinkSiegeTankMissile +783,WarHoundWeapon +785,EyeStalkWeapon +788,WidowMineWeapon +789,WidowMineAirWeapon +790,MothershipCoreWeaponWeapon +791,TornadoMissileWeapon +792,TornadoMissileDummyWeapon +793,TalonsMissileWeapon +794,CreepTumorMissile +795,LocustMPEggAMissileWeapon +796,LocustMPEggBMissileWeapon +797,LocustMPWeapon +799,RepulsorCannonWeapon +803,CollapsibleRockTowerDiagonal +804,CollapsibleTerranTowerDiagonal +805,CollapsibleTerranTowerRampLeft +806,CollapsibleTerranTowerRampRight +807,Ice2x2NonConjoined +808,IceProtossCrates +809,ProtossCrates +810,TowerMine +811,PickupPalletGas +812,PickupPalletMinerals +813,PickupScrapSalvage1x1 +814,PickupScrapSalvage2x2 +815,PickupScrapSalvage3x3 +816,RoughTerrain +817,UnbuildableBricksSmallUnit +818,UnbuildablePlatesSmallUnit +819,UnbuildablePlatesUnit +820,UnbuildableRocksSmallUnit +821,XelNagaHealingShrine +822,InvisibleTargetDummy +823,ProtossVespeneGeyser +824,CollapsibleRockTower +825,CollapsibleTerranTower +826,ThornLizard +827,CleaningBot +828,DestructibleRock6x6Weak +829,ProtossSnakeSegmentDemo +830,PhysicsCapsule +831,PhysicsCube +832,PhysicsCylinder +833,PhysicsKnot +834,PhysicsL +835,PhysicsPrimitives +836,PhysicsSphere +837,PhysicsStar +838,CreepBlocker4x4 +839,DestructibleCityDebris2x4Vertical +840,DestructibleCityDebris2x4Horizontal +841,DestructibleCityDebris2x6Vertical +842,DestructibleCityDebris2x6Horizontal +843,DestructibleCityDebris4x4 +844,DestructibleCityDebris6x6 +845,DestructibleCityDebrisHugeDiagonalBLUR +846,DestructibleCityDebrisHugeDiagonalULBR +847,TestZerg +848,PathingBlockerRadius1 +849,DestructibleRockEx12x4Vertical +850,DestructibleRockEx12x4Horizontal +851,DestructibleRockEx12x6Vertical +852,DestructibleRockEx12x6Horizontal +853,DestructibleRockEx14x4 +854,DestructibleRockEx16x6 +855,DestructibleRockEx1DiagonalHugeULBR +856,DestructibleRockEx1DiagonalHugeBLUR +857,DestructibleRockEx1VerticalHuge +858,DestructibleRockEx1HorizontalHuge +859,DestructibleIce2x4Vertical +860,DestructibleIce2x4Horizontal +861,DestructibleIce2x6Vertical +862,DestructibleIce2x6Horizontal +863,DestructibleIce4x4 +864,DestructibleIce6x6 +865,DestructibleIceDiagonalHugeULBR +866,DestructibleIceDiagonalHugeBLUR +867,DestructibleIceVerticalHuge +868,DestructibleIceHorizontalHuge +869,DesertPlanetSearchlight +870,DesertPlanetStreetlight +871,UnbuildableBricksUnit +872,UnbuildableRocksUnit +873,ZerusDestructibleArch +874,Artosilope +875,Anteplott +876,LabBot +877,Crabeetle +878,CollapsibleRockTowerRampRight +879,CollapsibleRockTowerRampLeft +880,LabMineralField +881,LabMineralField750 +896,CollapsibleRockTowerDebrisRampLeftGreen +897,CollapsibleRockTowerDebrisRampRightGreen +898,SnowRefinery_Terran_ExtendingBridgeNEShort8Out +899,SnowRefinery_Terran_ExtendingBridgeNEShort8 +900,SnowRefinery_Terran_ExtendingBridgeNWShort8Out +901,SnowRefinery_Terran_ExtendingBridgeNWShort8 +906,Tarsonis_DoorN +907,Tarsonis_DoorNLowered +908,Tarsonis_DoorNE +909,Tarsonis_DoorNELowered +910,Tarsonis_DoorE +911,Tarsonis_DoorELowered +912,Tarsonis_DoorNW +913,Tarsonis_DoorNWLowered +914,CompoundMansion_DoorN +915,CompoundMansion_DoorNLowered +916,CompoundMansion_DoorNE +917,CompoundMansion_DoorNELowered +918,CompoundMansion_DoorE +919,CompoundMansion_DoorELowered +920,CompoundMansion_DoorNW +921,CompoundMansion_DoorNWLowered +923,LocustMPFlying +924,AiurLightBridgeNE8Out +925,AiurLightBridgeNE8 +926,AiurLightBridgeNE10Out +927,AiurLightBridgeNE10 +928,AiurLightBridgeNE12Out +929,AiurLightBridgeNE12 +930,AiurLightBridgeNW8Out +931,AiurLightBridgeNW8 +932,AiurLightBridgeNW10Out +933,AiurLightBridgeNW10 +934,AiurLightBridgeNW12Out +935,AiurLightBridgeNW12 +936,AiurTempleBridgeNE8Out +938,AiurTempleBridgeNE10Out +940,AiurTempleBridgeNE12Out +942,AiurTempleBridgeNW8Out +944,AiurTempleBridgeNW10Out +946,AiurTempleBridgeNW12Out +948,ShakurasLightBridgeNE8Out +949,ShakurasLightBridgeNE8 +950,ShakurasLightBridgeNE10Out +951,ShakurasLightBridgeNE10 +952,ShakurasLightBridgeNE12Out +953,ShakurasLightBridgeNE12 +954,ShakurasLightBridgeNW8Out +955,ShakurasLightBridgeNW8 +956,ShakurasLightBridgeNW10Out +957,ShakurasLightBridgeNW10 +958,ShakurasLightBridgeNW12Out +959,ShakurasLightBridgeNW12 +960,VoidMPImmortalReviveCorpse +961,GuardianCocoonMP +962,GuardianMP +963,DevourerCocoonMP +964,DevourerMP +965,DefilerMPBurrowed +966,DefilerMP +967,OracleStasisTrap +968,DisruptorPhased +969,AiurLightBridgeAbandonedNE8Out +970,AiurLightBridgeAbandonedNE8 +971,AiurLightBridgeAbandonedNE10Out +972,AiurLightBridgeAbandonedNE10 +973,AiurLightBridgeAbandonedNE12Out +974,AiurLightBridgeAbandonedNE12 +975,AiurLightBridgeAbandonedNW8Out +976,AiurLightBridgeAbandonedNW8 +977,AiurLightBridgeAbandonedNW10Out +978,AiurLightBridgeAbandonedNW10 +979,AiurLightBridgeAbandonedNW12Out +980,AiurLightBridgeAbandonedNW12 +981,CollapsiblePurifierTowerDebris +982,PortCity_Bridge_UnitNE8Out +983,PortCity_Bridge_UnitNE8 +984,PortCity_Bridge_UnitSE8Out +985,PortCity_Bridge_UnitSE8 +986,PortCity_Bridge_UnitNW8Out +987,PortCity_Bridge_UnitNW8 +988,PortCity_Bridge_UnitSW8Out +989,PortCity_Bridge_UnitSW8 +990,PortCity_Bridge_UnitNE10Out +991,PortCity_Bridge_UnitNE10 +992,PortCity_Bridge_UnitSE10Out +993,PortCity_Bridge_UnitSE10 +994,PortCity_Bridge_UnitNW10Out +995,PortCity_Bridge_UnitNW10 +996,PortCity_Bridge_UnitSW10Out +997,PortCity_Bridge_UnitSW10 +998,PortCity_Bridge_UnitNE12Out +999,PortCity_Bridge_UnitNE12 +1000,PortCity_Bridge_UnitSE12Out +1001,PortCity_Bridge_UnitSE12 +1002,PortCity_Bridge_UnitNW12Out +1003,PortCity_Bridge_UnitNW12 +1004,PortCity_Bridge_UnitSW12Out +1005,PortCity_Bridge_UnitSW12 +1006,PortCity_Bridge_UnitN8Out +1007,PortCity_Bridge_UnitN8 +1008,PortCity_Bridge_UnitS8Out +1009,PortCity_Bridge_UnitS8 +1010,PortCity_Bridge_UnitE8Out +1011,PortCity_Bridge_UnitE8 +1012,PortCity_Bridge_UnitW8Out +1013,PortCity_Bridge_UnitW8 +1014,PortCity_Bridge_UnitN10Out +1015,PortCity_Bridge_UnitN10 +1016,PortCity_Bridge_UnitS10Out +1017,PortCity_Bridge_UnitS10 +1018,PortCity_Bridge_UnitE10Out +1019,PortCity_Bridge_UnitE10 +1020,PortCity_Bridge_UnitW10Out +1021,PortCity_Bridge_UnitW10 +1022,PortCity_Bridge_UnitN12Out +1023,PortCity_Bridge_UnitN12 +1024,PortCity_Bridge_UnitS12Out +1025,PortCity_Bridge_UnitS12 +1026,PortCity_Bridge_UnitE12Out +1027,PortCity_Bridge_UnitE12 +1028,PortCity_Bridge_UnitW12Out +1029,PortCity_Bridge_UnitW12 +1030,PurifierRichMineralField +1031,PurifierRichMineralField750 +1032,CollapsibleRockTowerPushUnitRampLeftGreen +1033,CollapsibleRockTowerPushUnitRampRightGreen +1048,CollapsiblePurifierTowerPushUnit +1050,LocustMPPrecursor +1051,ReleaseInterceptorsBeacon +1052,AdeptPhaseShift +1053,HydraliskImpaleMissile +1054,CycloneMissileLargeAir +1055,CycloneMissile +1056,CycloneMissileLarge +1057,OracleWeapon +1058,TempestWeaponGround +1059,ScoutMPAirWeaponLeft +1060,ScoutMPAirWeaponRight +1061,ArbiterMPWeaponMissile +1062,GuardianMPWeapon +1063,DevourerMPWeaponMissile +1064,DefilerMPDarkSwarmWeapon +1065,QueenMPEnsnareMissile +1066,QueenMPSpawnBroodlingsMissile +1067,LightningBombWeapon +1068,HERCPlacement +1069,GrappleWeapon +1072,CausticSprayMissile +1073,ParasiticBombMissile +1074,ParasiticBombDummy +1075,AdeptWeapon +1076,AdeptUpgradeWeapon +1077,LiberatorMissile +1078,LiberatorDamageMissile +1079,LiberatorAGMissile +1080,KD8Charge +1081,KD8ChargeWeapon +1083,SlaynElementalGrabWeapon +1084,SlaynElementalGrabAirUnit +1085,SlaynElementalGrabGroundUnit +1086,SlaynElementalWeapon +1091,CollapsibleRockTowerRampLeftGreen +1092,CollapsibleRockTowerRampRightGreen +1093,DestructibleExpeditionGate6x6 +1094,DestructibleZergInfestation3x3 +1095,HERC +1096,Moopy +1097,Replicant +1098,SeekerMissile +1099,AiurTempleBridgeDestructibleNE8Out +1100,AiurTempleBridgeDestructibleNE10Out +1101,AiurTempleBridgeDestructibleNE12Out +1102,AiurTempleBridgeDestructibleNW8Out +1103,AiurTempleBridgeDestructibleNW10Out +1104,AiurTempleBridgeDestructibleNW12Out +1105,AiurTempleBridgeDestructibleSW8Out +1106,AiurTempleBridgeDestructibleSW10Out +1107,AiurTempleBridgeDestructibleSW12Out +1108,AiurTempleBridgeDestructibleSE8Out +1109,AiurTempleBridgeDestructibleSE10Out +1110,AiurTempleBridgeDestructibleSE12Out +1112,FlyoverUnit +1113,CorsairMP +1114,ScoutMP +1116,ArbiterMP +1117,ScourgeMP +1118,DefilerMPPlagueWeapon +1119,QueenMP +1120,XelNagaDestructibleRampBlocker6S +1121,XelNagaDestructibleRampBlocker6SE +1122,XelNagaDestructibleRampBlocker6E +1123,XelNagaDestructibleRampBlocker6NE +1124,XelNagaDestructibleRampBlocker6N +1125,XelNagaDestructibleRampBlocker6NW +1126,XelNagaDestructibleRampBlocker6W +1127,XelNagaDestructibleRampBlocker6SW +1128,XelNagaDestructibleRampBlocker8S +1129,XelNagaDestructibleRampBlocker8SE +1130,XelNagaDestructibleRampBlocker8E +1131,XelNagaDestructibleRampBlocker8NE +1132,XelNagaDestructibleRampBlocker8N +1133,XelNagaDestructibleRampBlocker8NW +1134,XelNagaDestructibleRampBlocker8W +1135,XelNagaDestructibleRampBlocker8SW +1136,XelNagaDestructibleBlocker6S +1137,XelNagaDestructibleBlocker6SE +1138,XelNagaDestructibleBlocker6E +1139,XelNagaDestructibleBlocker6NE +1140,XelNagaDestructibleBlocker6N +1141,XelNagaDestructibleBlocker6NW +1142,XelNagaDestructibleBlocker6W +1143,XelNagaDestructibleBlocker6SW +1144,XelNagaDestructibleBlocker8S +1145,XelNagaDestructibleBlocker8SE +1146,XelNagaDestructibleBlocker8E +1147,XelNagaDestructibleBlocker8NE +1148,XelNagaDestructibleBlocker8N +1149,XelNagaDestructibleBlocker8NW +1150,XelNagaDestructibleBlocker8W +1151,XelNagaDestructibleBlocker8SW +1152,ReptileCrate +1153,SlaynSwarmHostSpawnFlyer +1154,SlaynElemental +1155,PurifierVespeneGeyser +1156,ShakurasVespeneGeyser +1157,CollapsiblePurifierTowerDiagonal +1158,CreepOnlyBlocker4x4 +1159,BattleStationMineralField +1160,BattleStationMineralField750 +1161,PurifierMineralField +1162,PurifierMineralField750 +1163,Beacon_Nova +1164,Beacon_NovaSmall +1165,Ursula +1166,Elsecaro_Colonist_Hut +1167,SnowGlazeStarterMP +1168,PylonOvercharged +1169,ObserverSiegeMode +1170,RavenRepairDrone +1172,ParasiticBombRelayDummy +1173,BypassArmorDrone +1174,AdeptPiercingWeapon +1175,HighTemplarWeaponMissile +1176,CycloneMissileLargeAirAlternative +1177,RavenScramblerMissile +1178,RavenRepairDroneReleaseWeapon +1179,RavenShredderMissileWeapon +1180,InfestedAcidSpinesWeapon +1181,InfestorEnsnareAttackMissile +1182,SNARE_PLACEHOLDER +1185,CorrosiveParasiteWeapon diff --git a/sc2reader/data/LotV/80949_abilities.csv b/sc2reader/data/LotV/80949_abilities.csv new file mode 100644 index 00000000..8444506e --- /dev/null +++ b/sc2reader/data/LotV/80949_abilities.csv @@ -0,0 +1,409 @@ +40,Taunt +41,stop +43,move +46,attack +62,SprayTerran +63,SprayZerg +64,SprayProtoss +65,SalvageShared +67,GhostHoldFire +68,GhostWeaponsFree +70,Explode +71,FleetBeaconResearch +72,FungalGrowth +73,GuardianShield +74,MULERepair +75,ZerglingTrain +76,NexusTrainMothership +77,Feedback +78,MassRecall +80,HallucinationArchon +81,HallucinationColossus +82,HallucinationHighTemplar +83,HallucinationImmortal +84,HallucinationPhoenix +85,HallucinationProbe +86,HallucinationStalker +87,HallucinationVoidRay +88,HallucinationWarpPrism +89,HallucinationZealot +90,MULEGather +92,CalldownMULE +93,GravitonBeam +97,SpawnChangeling +104,Rally +105,ProgressRally +106,RallyCommand +107,RallyNexus +108,RallyHatchery +109,RoachWarrenResearch +112,NeuralParasite +113,SpawnLarva +114,StimpackMarauder +115,SupplyDrop +119,UltraliskCavernResearch +121,SCVHarvest +122,ProbeHarvest +124,que1 +125,que5 +126,que5CancelToSelection +128,que5Addon +129,BuildInProgress +130,Repair +131,TerranBuild +133,Stimpack +134,GhostCloak +136,MedivacHeal +137,SiegeMode +138,Unsiege +139,BansheeCloak +140,MedivacTransport +141,ScannerSweep +142,Yamato +143,AssaultMode +144,FighterMode +145,BunkerTransport +146,CommandCenterTransport +147,CommandCenterLiftOff +148,CommandCenterLand +149,BarracksFlyingBuild +150,BarracksLiftOff +151,FactoryFlyingBuild +152,FactoryLiftOff +153,StarportFlyingBuild +154,StarportLiftOff +155,FactoryLand +156,StarportLand +157,CommandCenterTrain +158,BarracksLand +159,SupplyDepotLower +160,SupplyDepotRaise +161,BarracksTrain +162,FactoryTrain +163,StarportTrain +164,EngineeringBayResearch +166,GhostAcademyTrain +167,BarracksTechLabResearch +168,FactoryTechLabResearch +169,StarportTechLabResearch +170,GhostAcademyResearch +171,ArmoryResearch +172,ProtossBuild +173,WarpPrismTransport +174,GatewayTrain +175,StargateTrain +176,RoboticsFacilityTrain +177,NexusTrain +178,PsiStorm +179,HangarQueue5 +181,CarrierTrain +182,ForgeResearch +183,RoboticsBayResearch +184,TemplarArchiveResearch +185,ZergBuild +186,DroneHarvest +187,EvolutionChamberResearch +188,UpgradeToLair +189,UpgradeToHive +190,UpgradeToGreaterSpire +191,HiveResearch +192,SpawningPoolResearch +193,HydraliskDenResearch +194,GreaterSpireResearch +195,LarvaTrain +196,MorphToBroodLord +197,BurrowBanelingDown +198,BurrowBanelingUp +199,BurrowDroneDown +200,BurrowDroneUp +201,BurrowHydraliskDown +202,BurrowHydraliskUp +203,BurrowRoachDown +204,BurrowRoachUp +205,BurrowZerglingDown +206,BurrowZerglingUp +207,BurrowInfestorTerranDown +208,BurrowInfestorTerranUp +209,RedstoneLavaCritterBurrow +210,RedstoneLavaCritterInjuredBurrow +211,RedstoneLavaCritterUnburrow +212,RedstoneLavaCritterInjuredUnburrow +213,OverlordTransport +216,WarpGateTrain +217,BurrowQueenDown +218,BurrowQueenUp +219,NydusCanalTransport +220,Blink +221,BurrowInfestorDown +222,BurrowInfestorUp +223,MorphToOverseer +224,UpgradeToPlanetaryFortress +225,InfestationPitResearch +226,BanelingNestResearch +227,BurrowUltraliskDown +228,BurrowUltraliskUp +229,UpgradeToOrbital +230,UpgradeToWarpGate +231,MorphBackToGateway +232,OrbitalLiftOff +233,OrbitalCommandLand +234,ForceField +235,PhasingMode +236,TransportMode +237,FusionCoreResearch +238,CyberneticsCoreResearch +239,TwilightCouncilResearch +240,TacNukeStrike +243,EMP +245,HiveTrain +247,Transfusion +256,AttackRedirect +257,StimpackRedirect +258,StimpackMarauderRedirect +260,StopRedirect +261,GenerateCreep +262,QueenBuild +263,SpineCrawlerUproot +264,SporeCrawlerUproot +265,SpineCrawlerRoot +266,SporeCrawlerRoot +267,CreepTumorBurrowedBuild +268,BuildAutoTurret +269,ArchonWarp +270,NydusNetworkBuild +272,Charge +276,Contaminate +279,que5Passive +280,que5PassiveCancelToSelection +283,RavagerCorrosiveBile +305,BurrowLurkerMPDown +306,BurrowLurkerMPUp +309,BurrowRavagerDown +310,BurrowRavagerUp +311,MorphToRavager +312,MorphToTransportOverlord +314,ThorNormalMode +319,DigesterCreepSpray +323,MorphToMothership +348,XelNagaHealingShrine +357,MothershipCoreMassRecall +359,MorphToHellion +369,MorphToHellionTank +377,MorphToSwarmHostBurrowedMP +378,MorphToSwarmHostMP +383,BlindingCloud +385,Yoink +388,ViperConsumeStructure +391,TestZerg +392,VolatileBurstBuilding +399,WidowMineBurrow +400,WidowMineUnburrow +401,WidowMineAttack +402,TornadoMissile +405,HallucinationOracle +406,MedivacSpeedBoost +407,ExtendingBridgeNEWide8Out +408,ExtendingBridgeNEWide8 +409,ExtendingBridgeNWWide8Out +410,ExtendingBridgeNWWide8 +411,ExtendingBridgeNEWide10Out +412,ExtendingBridgeNEWide10 +413,ExtendingBridgeNWWide10Out +414,ExtendingBridgeNWWide10 +415,ExtendingBridgeNEWide12Out +416,ExtendingBridgeNEWide12 +417,ExtendingBridgeNWWide12Out +418,ExtendingBridgeNWWide12 +420,CritterFlee +421,OracleRevelation +429,MothershipCorePurifyNexus +430,XelNaga_Caverns_DoorE +431,XelNaga_Caverns_DoorEOpened +432,XelNaga_Caverns_DoorN +433,XelNaga_Caverns_DoorNE +434,XelNaga_Caverns_DoorNEOpened +435,XelNaga_Caverns_DoorNOpened +436,XelNaga_Caverns_DoorNW +437,XelNaga_Caverns_DoorNWOpened +438,XelNaga_Caverns_DoorS +439,XelNaga_Caverns_DoorSE +440,XelNaga_Caverns_DoorSEOpened +441,XelNaga_Caverns_DoorSOpened +442,XelNaga_Caverns_DoorSW +443,XelNaga_Caverns_DoorSWOpened +444,XelNaga_Caverns_DoorW +445,XelNaga_Caverns_DoorWOpened +446,XelNaga_Caverns_Floating_BridgeNE8Out +447,XelNaga_Caverns_Floating_BridgeNE8 +448,XelNaga_Caverns_Floating_BridgeNW8Out +449,XelNaga_Caverns_Floating_BridgeNW8 +450,XelNaga_Caverns_Floating_BridgeNE10Out +451,XelNaga_Caverns_Floating_BridgeNE10 +452,XelNaga_Caverns_Floating_BridgeNW10Out +453,XelNaga_Caverns_Floating_BridgeNW10 +454,XelNaga_Caverns_Floating_BridgeNE12Out +455,XelNaga_Caverns_Floating_BridgeNE12 +456,XelNaga_Caverns_Floating_BridgeNW12Out +457,XelNaga_Caverns_Floating_BridgeNW12 +458,XelNaga_Caverns_Floating_BridgeH8Out +459,XelNaga_Caverns_Floating_BridgeH8 +460,XelNaga_Caverns_Floating_BridgeV8Out +461,XelNaga_Caverns_Floating_BridgeV8 +462,XelNaga_Caverns_Floating_BridgeH10Out +463,XelNaga_Caverns_Floating_BridgeH10 +464,XelNaga_Caverns_Floating_BridgeV10Out +465,XelNaga_Caverns_Floating_BridgeV10 +466,XelNaga_Caverns_Floating_BridgeH12Out +467,XelNaga_Caverns_Floating_BridgeH12 +468,XelNaga_Caverns_Floating_BridgeV12Out +469,XelNaga_Caverns_Floating_BridgeV12 +470,TemporalField +496,SnowRefinery_Terran_ExtendingBridgeNEShort8Out +497,SnowRefinery_Terran_ExtendingBridgeNEShort8 +498,SnowRefinery_Terran_ExtendingBridgeNWShort8Out +499,SnowRefinery_Terran_ExtendingBridgeNWShort8 +521,CausticSpray +524,MorphToLurker +528,PurificationNovaTargeted +530,LockOn +532,LockOnCancel +534,Hyperjump +536,ThorAPMode +539,NydusWormTransport +540,OracleWeapon +546,LocustMPFlyingSwoop +547,HallucinationDisruptor +548,HallucinationAdept +549,VoidRaySwarmDamageBoost +550,SeekerDummyChannel +551,AiurLightBridgeNE8Out +552,AiurLightBridgeNE8 +553,AiurLightBridgeNE10Out +554,AiurLightBridgeNE10 +555,AiurLightBridgeNE12Out +556,AiurLightBridgeNE12 +557,AiurLightBridgeNW8Out +558,AiurLightBridgeNW8 +559,AiurLightBridgeNW10Out +560,AiurLightBridgeNW10 +561,AiurLightBridgeNW12Out +562,AiurLightBridgeNW12 +575,ShakurasLightBridgeNE8Out +576,ShakurasLightBridgeNE8 +577,ShakurasLightBridgeNE10Out +578,ShakurasLightBridgeNE10 +579,ShakurasLightBridgeNE12Out +580,ShakurasLightBridgeNE12 +581,ShakurasLightBridgeNW8Out +582,ShakurasLightBridgeNW8 +583,ShakurasLightBridgeNW10Out +584,ShakurasLightBridgeNW10 +585,ShakurasLightBridgeNW12Out +586,ShakurasLightBridgeNW12 +587,VoidMPImmortalReviveRebuild +589,ArbiterMPStasisField +590,ArbiterMPRecall +591,CorsairMPDisruptionWeb +592,MorphToGuardianMP +593,MorphToDevourerMP +594,DefilerMPConsume +595,DefilerMPDarkSwarm +596,DefilerMPPlague +597,DefilerMPBurrow +598,DefilerMPUnburrow +599,QueenMPEnsnare +600,QueenMPSpawnBroodlings +601,QueenMPInfestCommandCenter +605,OracleBuild +609,ParasiticBomb +610,AdeptPhaseShift +613,LurkerHoldFire +614,LurkerRemoveHoldFire +617,LiberatorAGTarget +618,LiberatorAATarget +620,AiurLightBridgeAbandonedNE8Out +621,AiurLightBridgeAbandonedNE8 +622,AiurLightBridgeAbandonedNE10Out +623,AiurLightBridgeAbandonedNE10 +624,AiurLightBridgeAbandonedNE12Out +625,AiurLightBridgeAbandonedNE12 +626,AiurLightBridgeAbandonedNW8Out +627,AiurLightBridgeAbandonedNW8 +628,AiurLightBridgeAbandonedNW10Out +629,AiurLightBridgeAbandonedNW10 +630,AiurLightBridgeAbandonedNW12Out +631,AiurLightBridgeAbandonedNW12 +632,KD8Charge +635,AdeptPhaseShiftCancel +636,AdeptShadePhaseShiftCancel +637,SlaynElementalGrab +639,PortCity_Bridge_UnitNE8Out +640,PortCity_Bridge_UnitNE8 +641,PortCity_Bridge_UnitSE8Out +642,PortCity_Bridge_UnitSE8 +643,PortCity_Bridge_UnitNW8Out +644,PortCity_Bridge_UnitNW8 +645,PortCity_Bridge_UnitSW8Out +646,PortCity_Bridge_UnitSW8 +647,PortCity_Bridge_UnitNE10Out +648,PortCity_Bridge_UnitNE10 +649,PortCity_Bridge_UnitSE10Out +650,PortCity_Bridge_UnitSE10 +651,PortCity_Bridge_UnitNW10Out +652,PortCity_Bridge_UnitNW10 +653,PortCity_Bridge_UnitSW10Out +654,PortCity_Bridge_UnitSW10 +655,PortCity_Bridge_UnitNE12Out +656,PortCity_Bridge_UnitNE12 +657,PortCity_Bridge_UnitSE12Out +658,PortCity_Bridge_UnitSE12 +659,PortCity_Bridge_UnitNW12Out +660,PortCity_Bridge_UnitNW12 +661,PortCity_Bridge_UnitSW12Out +662,PortCity_Bridge_UnitSW12 +663,PortCity_Bridge_UnitN8Out +664,PortCity_Bridge_UnitN8 +665,PortCity_Bridge_UnitS8Out +666,PortCity_Bridge_UnitS8 +667,PortCity_Bridge_UnitE8Out +668,PortCity_Bridge_UnitE8 +669,PortCity_Bridge_UnitW8Out +670,PortCity_Bridge_UnitW8 +671,PortCity_Bridge_UnitN10Out +672,PortCity_Bridge_UnitN10 +673,PortCity_Bridge_UnitS10Out +674,PortCity_Bridge_UnitS10 +675,PortCity_Bridge_UnitE10Out +676,PortCity_Bridge_UnitE10 +677,PortCity_Bridge_UnitW10Out +678,PortCity_Bridge_UnitW10 +679,PortCity_Bridge_UnitN12Out +680,PortCity_Bridge_UnitN12 +681,PortCity_Bridge_UnitS12Out +682,PortCity_Bridge_UnitS12 +683,PortCity_Bridge_UnitE12Out +684,PortCity_Bridge_UnitE12 +685,PortCity_Bridge_UnitW12Out +686,PortCity_Bridge_UnitW12 +689,DarkTemplarBlink +693,BattlecruiserAttack +695,BattlecruiserMove +697,BattlecruiserStop +698,BatteryOvercharge +700,AmorphousArmorcloud +702,SpawnLocustsTargeted +703,ViperParasiticBombRelay +704,ParasiticBombRelayDodge +705,VoidRaySwarmDamageBoostCancel +709,ChannelSnipe +712,DarkShrineResearch +713,LurkerDenMPResearch +714,ObserverSiegeMorphtoObserver +715,ObserverMorphtoObserverSiege +716,OverseerMorphtoOverseerSiegeMode +717,OverseerSiegeModeMorphtoOverseer +718,RavenScramblerMissile +720,RavenRepairDroneHeal +721,RavenShredderMissile +722,ChronoBoostEnergyCost +723,NexusMassRecall diff --git a/sc2reader/data/LotV/80949_units.csv b/sc2reader/data/LotV/80949_units.csv new file mode 100644 index 00000000..19aa551f --- /dev/null +++ b/sc2reader/data/LotV/80949_units.csv @@ -0,0 +1,1058 @@ +3,System_Snapshot_Dummy +21,Ball +22,StereoscopicOptionsUnit +23,Colossus +24,TechLab +25,Reactor +27,InfestorTerran +28,BanelingCocoon +29,Baneling +30,Mothership +31,PointDefenseDrone +32,Changeling +33,ChangelingZealot +34,ChangelingMarineShield +35,ChangelingMarine +36,ChangelingZerglingWings +37,ChangelingZergling +39,CommandCenter +40,SupplyDepot +41,Refinery +42,Barracks +43,EngineeringBay +44,MissileTurret +45,Bunker +46,RefineryRich +47,SensorTower +48,GhostAcademy +49,Factory +50,Starport +52,Armory +53,FusionCore +54,AutoTurret +55,SiegeTankSieged +56,SiegeTank +57,VikingAssault +58,VikingFighter +59,CommandCenterFlying +60,BarracksTechLab +61,BarracksReactor +62,FactoryTechLab +63,FactoryReactor +64,StarportTechLab +65,StarportReactor +66,FactoryFlying +67,StarportFlying +68,SCV +69,BarracksFlying +70,SupplyDepotLowered +71,Marine +72,Reaper +73,Ghost +74,Marauder +75,Thor +76,Hellion +77,Medivac +78,Banshee +79,Raven +80,Battlecruiser +81,Nuke +82,Nexus +83,Pylon +84,Assimilator +85,Gateway +86,Forge +87,FleetBeacon +88,TwilightCouncil +89,PhotonCannon +90,Stargate +91,TemplarArchive +92,DarkShrine +93,RoboticsBay +94,RoboticsFacility +95,CyberneticsCore +96,Zealot +97,Stalker +98,HighTemplar +99,DarkTemplar +100,Sentry +101,Phoenix +102,Carrier +103,VoidRay +104,WarpPrism +105,Observer +106,Immortal +107,Probe +108,Interceptor +109,Hatchery +110,CreepTumor +111,Extractor +112,SpawningPool +113,EvolutionChamber +114,HydraliskDen +115,Spire +116,UltraliskCavern +117,InfestationPit +118,NydusNetwork +119,BanelingNest +120,RoachWarren +121,SpineCrawler +122,SporeCrawler +123,Lair +124,Hive +125,GreaterSpire +126,Egg +127,Drone +128,Zergling +129,Overlord +130,Hydralisk +131,Mutalisk +132,Ultralisk +133,Roach +134,Infestor +135,Corruptor +136,BroodLordCocoon +137,BroodLord +138,BanelingBurrowed +139,DroneBurrowed +140,HydraliskBurrowed +141,RoachBurrowed +142,ZerglingBurrowed +143,InfestorTerranBurrowed +144,RedstoneLavaCritterBurrowed +145,RedstoneLavaCritterInjuredBurrowed +146,RedstoneLavaCritter +147,RedstoneLavaCritterInjured +148,QueenBurrowed +149,Queen +150,InfestorBurrowed +151,OverlordCocoon +152,Overseer +153,PlanetaryFortress +154,UltraliskBurrowed +155,OrbitalCommand +156,WarpGate +157,OrbitalCommandFlying +158,ForceField +159,WarpPrismPhasing +160,CreepTumorBurrowed +161,CreepTumorQueen +162,SpineCrawlerUprooted +163,SporeCrawlerUprooted +164,Archon +165,NydusCanal +166,BroodlingEscort +167,GhostAlternate +168,GhostNova +169,RichMineralField +170,RichMineralField750 +171,Ursadon +173,LurkerMPBurrowed +174,LurkerMP +175,LurkerDenMP +176,LurkerMPEgg +177,NydusCanalAttacker +178,OverlordTransport +179,Ravager +180,RavagerBurrowed +181,RavagerCocoon +182,TransportOverlordCocoon +183,XelNagaTower +185,Oracle +186,Tempest +188,InfestedTerransEgg +189,Larva +190,OverseerSiegeMode +192,ReaperPlaceholder +193,MarineACGluescreenDummy +194,FirebatACGluescreenDummy +195,MedicACGluescreenDummy +196,MarauderACGluescreenDummy +197,VultureACGluescreenDummy +198,SiegeTankACGluescreenDummy +199,VikingACGluescreenDummy +200,BansheeACGluescreenDummy +201,BattlecruiserACGluescreenDummy +202,OrbitalCommandACGluescreenDummy +203,BunkerACGluescreenDummy +204,BunkerUpgradedACGluescreenDummy +205,MissileTurretACGluescreenDummy +206,HellbatACGluescreenDummy +207,GoliathACGluescreenDummy +208,CycloneACGluescreenDummy +209,WraithACGluescreenDummy +210,ScienceVesselACGluescreenDummy +211,HerculesACGluescreenDummy +212,ThorACGluescreenDummy +213,PerditionTurretACGluescreenDummy +214,FlamingBettyACGluescreenDummy +215,DevastationTurretACGluescreenDummy +216,BlasterBillyACGluescreenDummy +217,SpinningDizzyACGluescreenDummy +218,ZerglingKerriganACGluescreenDummy +219,RaptorACGluescreenDummy +220,QueenCoopACGluescreenDummy +221,HydraliskACGluescreenDummy +222,HydraliskLurkerACGluescreenDummy +223,MutaliskBroodlordACGluescreenDummy +224,BroodLordACGluescreenDummy +225,UltraliskACGluescreenDummy +226,TorrasqueACGluescreenDummy +227,OverseerACGluescreenDummy +228,LurkerACGluescreenDummy +229,SpineCrawlerACGluescreenDummy +230,SporeCrawlerACGluescreenDummy +231,NydusNetworkACGluescreenDummy +232,OmegaNetworkACGluescreenDummy +233,ZerglingZagaraACGluescreenDummy +234,SwarmlingACGluescreenDummy +235,QueenZagaraACGluescreenDummy +236,BanelingACGluescreenDummy +237,SplitterlingACGluescreenDummy +238,AberrationACGluescreenDummy +239,ScourgeACGluescreenDummy +240,CorruptorACGluescreenDummy +241,OverseerZagaraACGluescreenDummy +242,BileLauncherACGluescreenDummy +243,SwarmQueenACGluescreenDummy +244,RoachACGluescreenDummy +245,RoachVileACGluescreenDummy +246,RavagerACGluescreenDummy +247,SwarmHostACGluescreenDummy +248,MutaliskACGluescreenDummy +249,GuardianACGluescreenDummy +250,DevourerACGluescreenDummy +251,ViperACGluescreenDummy +252,BrutaliskACGluescreenDummy +253,LeviathanACGluescreenDummy +254,ZealotACGluescreenDummy +255,ZealotAiurACGluescreenDummy +256,DragoonACGluescreenDummy +257,HighTemplarACGluescreenDummy +258,ArchonACGluescreenDummy +259,ImmortalACGluescreenDummy +260,ObserverACGluescreenDummy +261,PhoenixAiurACGluescreenDummy +262,ReaverACGluescreenDummy +263,TempestACGluescreenDummy +264,PhotonCannonACGluescreenDummy +265,ZealotVorazunACGluescreenDummy +266,ZealotShakurasACGluescreenDummy +267,StalkerShakurasACGluescreenDummy +268,DarkTemplarShakurasACGluescreenDummy +269,CorsairACGluescreenDummy +270,VoidRayACGluescreenDummy +271,VoidRayShakurasACGluescreenDummy +272,OracleACGluescreenDummy +273,DarkArchonACGluescreenDummy +274,DarkPylonACGluescreenDummy +275,ZealotPurifierACGluescreenDummy +276,SentryPurifierACGluescreenDummy +277,ImmortalKaraxACGluescreenDummy +278,ColossusACGluescreenDummy +279,ColossusPurifierACGluescreenDummy +280,PhoenixPurifierACGluescreenDummy +281,CarrierACGluescreenDummy +282,CarrierAiurACGluescreenDummy +283,KhaydarinMonolithACGluescreenDummy +284,ShieldBatteryACGluescreenDummy +285,EliteMarineACGluescreenDummy +286,MarauderCommandoACGluescreenDummy +287,SpecOpsGhostACGluescreenDummy +288,HellbatRangerACGluescreenDummy +289,StrikeGoliathACGluescreenDummy +290,HeavySiegeTankACGluescreenDummy +291,RaidLiberatorACGluescreenDummy +292,RavenTypeIIACGluescreenDummy +293,CovertBansheeACGluescreenDummy +294,RailgunTurretACGluescreenDummy +295,BlackOpsMissileTurretACGluescreenDummy +296,SupplicantACGluescreenDummy +297,StalkerTaldarimACGluescreenDummy +298,SentryTaldarimACGluescreenDummy +299,HighTemplarTaldarimACGluescreenDummy +300,ImmortalTaldarimACGluescreenDummy +301,ColossusTaldarimACGluescreenDummy +302,WarpPrismTaldarimACGluescreenDummy +303,PhotonCannonTaldarimACGluescreenDummy +304,StukovInfestedCivilianACGluescreenDummy +305,StukovInfestedMarineACGluescreenDummy +306,StukovInfestedSiegeTankACGluescreenDummy +307,StukovInfestedDiamondbackACGluescreenDummy +308,StukovInfestedBansheeACGluescreenDummy +309,SILiberatorACGluescreenDummy +310,StukovInfestedBunkerACGluescreenDummy +311,StukovInfestedMissileTurretACGluescreenDummy +312,StukovBroodQueenACGluescreenDummy +313,ZealotFenixACGluescreenDummy +314,SentryFenixACGluescreenDummy +315,AdeptFenixACGluescreenDummy +316,ImmortalFenixACGluescreenDummy +317,ColossusFenixACGluescreenDummy +318,DisruptorACGluescreenDummy +319,ObserverFenixACGluescreenDummy +320,ScoutACGluescreenDummy +321,CarrierFenixACGluescreenDummy +322,PhotonCannonFenixACGluescreenDummy +323,PrimalZerglingACGluescreenDummy +324,RavasaurACGluescreenDummy +325,PrimalRoachACGluescreenDummy +326,FireRoachACGluescreenDummy +327,PrimalGuardianACGluescreenDummy +328,PrimalHydraliskACGluescreenDummy +329,PrimalMutaliskACGluescreenDummy +330,PrimalImpalerACGluescreenDummy +331,PrimalSwarmHostACGluescreenDummy +332,CreeperHostACGluescreenDummy +333,PrimalUltraliskACGluescreenDummy +334,TyrannozorACGluescreenDummy +335,PrimalWurmACGluescreenDummy +336,HHReaperACGluescreenDummy +337,HHWidowMineACGluescreenDummy +338,HHHellionTankACGluescreenDummy +339,HHWraithACGluescreenDummy +340,HHVikingACGluescreenDummy +341,HHBattlecruiserACGluescreenDummy +342,HHRavenACGluescreenDummy +343,HHBomberPlatformACGluescreenDummy +344,HHMercStarportACGluescreenDummy +345,HHMissileTurretACGluescreenDummy +346,TychusReaperACGluescreenDummy +347,TychusFirebatACGluescreenDummy +348,TychusSpectreACGluescreenDummy +349,TychusMedicACGluescreenDummy +350,TychusMarauderACGluescreenDummy +351,TychusWarhoundACGluescreenDummy +352,TychusHERCACGluescreenDummy +353,TychusGhostACGluescreenDummy +354,TychusSCVAutoTurretACGluescreenDummy +355,ZeratulStalkerACGluescreenDummy +356,ZeratulSentryACGluescreenDummy +357,ZeratulDarkTemplarACGluescreenDummy +358,ZeratulImmortalACGluescreenDummy +359,ZeratulObserverACGluescreenDummy +360,ZeratulDisruptorACGluescreenDummy +361,ZeratulWarpPrismACGluescreenDummy +362,ZeratulPhotonCannonACGluescreenDummy +363,MechaZerglingACGluescreenDummy +364,MechaBanelingACGluescreenDummy +365,MechaHydraliskACGluescreenDummy +366,MechaInfestorACGluescreenDummy +367,MechaCorruptorACGluescreenDummy +368,MechaUltraliskACGluescreenDummy +369,MechaOverseerACGluescreenDummy +370,MechaLurkerACGluescreenDummy +371,MechaBattlecarrierLordACGluescreenDummy +372,MechaSpineCrawlerACGluescreenDummy +373,MechaSporeCrawlerACGluescreenDummy +374,TrooperMengskACGluescreenDummy +375,MedivacMengskACGluescreenDummy +376,BlimpMengskACGluescreenDummy +377,MarauderMengskACGluescreenDummy +378,GhostMengskACGluescreenDummy +379,SiegeTankMengskACGluescreenDummy +380,ThorMengskACGluescreenDummy +381,VikingMengskACGluescreenDummy +382,BattlecruiserMengskACGluescreenDummy +383,BunkerDepotMengskACGluescreenDummy +384,MissileTurretMengskACGluescreenDummy +385,ArtilleryMengskACGluescreenDummy +387,RenegadeLongboltMissileWeapon +388,LoadOutSpray@1 +389,LoadOutSpray@2 +390,LoadOutSpray@3 +391,LoadOutSpray@4 +392,LoadOutSpray@5 +393,LoadOutSpray@6 +394,LoadOutSpray@7 +395,LoadOutSpray@8 +396,LoadOutSpray@9 +397,LoadOutSpray@10 +398,LoadOutSpray@11 +399,LoadOutSpray@12 +400,LoadOutSpray@13 +401,LoadOutSpray@14 +402,NeedleSpinesWeapon +403,CorruptionWeapon +404,InfestedTerransWeapon +405,NeuralParasiteWeapon +406,PointDefenseDroneReleaseWeapon +407,HunterSeekerWeapon +408,MULE +410,ThorAAWeapon +411,PunisherGrenadesLMWeapon +412,VikingFighterWeapon +413,ATALaserBatteryLMWeapon +414,ATSLaserBatteryLMWeapon +415,LongboltMissileWeapon +416,D8ChargeWeapon +417,YamatoWeapon +418,IonCannonsWeapon +419,AcidSalivaWeapon +420,SpineCrawlerWeapon +421,SporeCrawlerWeapon +422,GlaiveWurmWeapon +423,GlaiveWurmM2Weapon +424,GlaiveWurmM3Weapon +425,StalkerWeapon +426,EMP2Weapon +427,BacklashRocketsLMWeapon +428,PhotonCannonWeapon +429,ParasiteSporeWeapon +431,Broodling +432,BroodLordBWeapon +435,AutoTurretReleaseWeapon +436,LarvaReleaseMissile +437,AcidSpinesWeapon +438,FrenzyWeapon +439,ContaminateWeapon +451,BeaconArmy +452,BeaconDefend +453,BeaconAttack +454,BeaconHarass +455,BeaconIdle +456,BeaconAuto +457,BeaconDetect +458,BeaconScout +459,BeaconClaim +460,BeaconExpand +461,BeaconRally +462,BeaconCustom1 +463,BeaconCustom2 +464,BeaconCustom3 +465,BeaconCustom4 +470,LiberatorAG +472,PreviewBunkerUpgraded +473,HellionTank +474,Cyclone +475,WidowMine +476,Liberator +478,Adept +479,Disruptor +480,SwarmHostMP +481,Viper +482,ShieldBattery +483,HighTemplarSkinPreview +484,MothershipCore +485,Viking +498,InhibitorZoneSmall +499,InhibitorZoneMedium +500,InhibitorZoneLarge +501,AccelerationZoneSmall +502,AccelerationZoneMedium +503,AccelerationZoneLarge +504,AccelerationZoneFlyingSmall +505,AccelerationZoneFlyingMedium +506,AccelerationZoneFlyingLarge +507,InhibitorZoneFlyingSmall +508,InhibitorZoneFlyingMedium +509,InhibitorZoneFlyingLarge +510,AssimilatorRich +511,RichVespeneGeyser +512,ExtractorRich +513,RavagerCorrosiveBileMissile +514,RavagerWeaponMissile +515,RenegadeMissileTurret +516,Rocks2x2NonConjoined +517,FungalGrowthMissile +518,NeuralParasiteTentacleMissile +519,Beacon_Protoss +520,Beacon_ProtossSmall +521,Beacon_Terran +522,Beacon_TerranSmall +523,Beacon_Zerg +524,Beacon_ZergSmall +525,Lyote +526,CarrionBird +527,KarakMale +528,KarakFemale +529,UrsadakFemaleExotic +530,UrsadakMale +531,UrsadakFemale +532,UrsadakCalf +533,UrsadakMaleExotic +534,UtilityBot +535,CommentatorBot1 +536,CommentatorBot2 +537,CommentatorBot3 +538,CommentatorBot4 +539,Scantipede +540,Dog +541,Sheep +542,Cow +543,InfestedTerransEggPlacement +544,InfestorTerransWeapon +545,MineralField +546,MineralField450 +547,MineralField750 +548,MineralFieldOpaque +549,MineralFieldOpaque900 +550,VespeneGeyser +551,SpacePlatformGeyser +552,DestructibleSearchlight +553,DestructibleBullhornLights +554,DestructibleStreetlight +555,DestructibleSpacePlatformSign +556,DestructibleStoreFrontCityProps +557,DestructibleBillboardTall +558,DestructibleBillboardScrollingText +559,DestructibleSpacePlatformBarrier +560,DestructibleSignsDirectional +561,DestructibleSignsConstruction +562,DestructibleSignsFunny +563,DestructibleSignsIcons +564,DestructibleSignsWarning +565,DestructibleGarage +566,DestructibleGarageLarge +567,DestructibleTrafficSignal +568,TrafficSignal +569,BraxisAlphaDestructible1x1 +570,BraxisAlphaDestructible2x2 +571,DestructibleDebris4x4 +572,DestructibleDebris6x6 +573,DestructibleRock2x4Vertical +574,DestructibleRock2x4Horizontal +575,DestructibleRock2x6Vertical +576,DestructibleRock2x6Horizontal +577,DestructibleRock4x4 +578,DestructibleRock6x6 +579,DestructibleRampDiagonalHugeULBR +580,DestructibleRampDiagonalHugeBLUR +581,DestructibleRampVerticalHuge +582,DestructibleRampHorizontalHuge +583,DestructibleDebrisRampDiagonalHugeULBR +584,DestructibleDebrisRampDiagonalHugeBLUR +585,WarpPrismSkinPreview +586,SiegeTankSkinPreview +587,ThorAP +588,ThorAALance +589,LiberatorSkinPreview +590,OverlordGenerateCreepKeybind +591,MengskStatueAlone +592,MengskStatue +593,WolfStatue +594,GlobeStatue +595,Weapon +596,GlaiveWurmBounceWeapon +597,BroodLordWeapon +598,BroodLordAWeapon +599,CreepBlocker1x1 +600,PermanentCreepBlocker1x1 +601,PathingBlocker1x1 +602,PathingBlocker2x2 +603,AutoTestAttackTargetGround +604,AutoTestAttackTargetAir +605,AutoTestAttacker +606,HelperEmitterSelectionArrow +607,MultiKillObject +608,ShapeGolfball +609,ShapeCone +610,ShapeCube +611,ShapeCylinder +612,ShapeDodecahedron +613,ShapeIcosahedron +614,ShapeOctahedron +615,ShapePyramid +616,ShapeRoundedCube +617,ShapeSphere +618,ShapeTetrahedron +619,ShapeThickTorus +620,ShapeThinTorus +621,ShapeTorus +622,Shape4PointStar +623,Shape5PointStar +624,Shape6PointStar +625,Shape8PointStar +626,ShapeArrowPointer +627,ShapeBowl +628,ShapeBox +629,ShapeCapsule +630,ShapeCrescentMoon +631,ShapeDecahedron +632,ShapeDiamond +633,ShapeFootball +634,ShapeGemstone +635,ShapeHeart +636,ShapeJack +637,ShapePlusSign +638,ShapeShamrock +639,ShapeSpade +640,ShapeTube +641,ShapeEgg +642,ShapeYenSign +643,ShapeX +644,ShapeWatermelon +645,ShapeWonSign +646,ShapeTennisball +647,ShapeStrawberry +648,ShapeSmileyFace +649,ShapeSoccerball +650,ShapeRainbow +651,ShapeSadFace +652,ShapePoundSign +653,ShapePear +654,ShapePineapple +655,ShapeOrange +656,ShapePeanut +657,ShapeO +658,ShapeLemon +659,ShapeMoneyBag +660,ShapeHorseshoe +661,ShapeHockeyStick +662,ShapeHockeyPuck +663,ShapeHand +664,ShapeGolfClub +665,ShapeGrape +666,ShapeEuroSign +667,ShapeDollarSign +668,ShapeBasketball +669,ShapeCarrot +670,ShapeCherry +671,ShapeBaseball +672,ShapeBaseballBat +673,ShapeBanana +674,ShapeApple +675,ShapeCashLarge +676,ShapeCashMedium +677,ShapeCashSmall +678,ShapeFootballColored +679,ShapeLemonSmall +680,ShapeOrangeSmall +681,ShapeTreasureChestOpen +682,ShapeTreasureChestClosed +683,ShapeWatermelonSmall +684,UnbuildableRocksDestructible +685,UnbuildableBricksDestructible +686,UnbuildablePlatesDestructible +687,Debris2x2NonConjoined +688,EnemyPathingBlocker1x1 +689,EnemyPathingBlocker2x2 +690,EnemyPathingBlocker4x4 +691,EnemyPathingBlocker8x8 +692,EnemyPathingBlocker16x16 +693,ScopeTest +694,SentryACGluescreenDummy +695,StukovInfestedTrooperACGluescreenDummy +711,CollapsibleTerranTowerDebris +712,DebrisRampLeft +713,DebrisRampRight +717,LocustMP +718,CollapsibleRockTowerDebris +719,NydusCanalCreeper +720,SwarmHostBurrowedMP +721,WarHound +722,WidowMineBurrowed +723,ExtendingBridgeNEWide8Out +724,ExtendingBridgeNEWide8 +725,ExtendingBridgeNWWide8Out +726,ExtendingBridgeNWWide8 +727,ExtendingBridgeNEWide10Out +728,ExtendingBridgeNEWide10 +729,ExtendingBridgeNWWide10Out +730,ExtendingBridgeNWWide10 +731,ExtendingBridgeNEWide12Out +732,ExtendingBridgeNEWide12 +733,ExtendingBridgeNWWide12Out +734,ExtendingBridgeNWWide12 +736,CollapsibleRockTowerDebrisRampRight +737,CollapsibleRockTowerDebrisRampLeft +738,XelNaga_Caverns_DoorE +739,XelNaga_Caverns_DoorEOpened +740,XelNaga_Caverns_DoorN +741,XelNaga_Caverns_DoorNE +742,XelNaga_Caverns_DoorNEOpened +743,XelNaga_Caverns_DoorNOpened +744,XelNaga_Caverns_DoorNW +745,XelNaga_Caverns_DoorNWOpened +746,XelNaga_Caverns_DoorS +747,XelNaga_Caverns_DoorSE +748,XelNaga_Caverns_DoorSEOpened +749,XelNaga_Caverns_DoorSOpened +750,XelNaga_Caverns_DoorSW +751,XelNaga_Caverns_DoorSWOpened +752,XelNaga_Caverns_DoorW +753,XelNaga_Caverns_DoorWOpened +754,XelNaga_Caverns_Floating_BridgeNE8Out +755,XelNaga_Caverns_Floating_BridgeNE8 +756,XelNaga_Caverns_Floating_BridgeNW8Out +757,XelNaga_Caverns_Floating_BridgeNW8 +758,XelNaga_Caverns_Floating_BridgeNE10Out +759,XelNaga_Caverns_Floating_BridgeNE10 +760,XelNaga_Caverns_Floating_BridgeNW10Out +761,XelNaga_Caverns_Floating_BridgeNW10 +762,XelNaga_Caverns_Floating_BridgeNE12Out +763,XelNaga_Caverns_Floating_BridgeNE12 +764,XelNaga_Caverns_Floating_BridgeNW12Out +765,XelNaga_Caverns_Floating_BridgeNW12 +766,XelNaga_Caverns_Floating_BridgeH8Out +767,XelNaga_Caverns_Floating_BridgeH8 +768,XelNaga_Caverns_Floating_BridgeV8Out +769,XelNaga_Caverns_Floating_BridgeV8 +770,XelNaga_Caverns_Floating_BridgeH10Out +771,XelNaga_Caverns_Floating_BridgeH10 +772,XelNaga_Caverns_Floating_BridgeV10Out +773,XelNaga_Caverns_Floating_BridgeV10 +774,XelNaga_Caverns_Floating_BridgeH12Out +775,XelNaga_Caverns_Floating_BridgeH12 +776,XelNaga_Caverns_Floating_BridgeV12Out +777,XelNaga_Caverns_Floating_BridgeV12 +780,CollapsibleTerranTowerPushUnitRampLeft +781,CollapsibleTerranTowerPushUnitRampRight +784,CollapsibleRockTowerPushUnit +785,CollapsibleTerranTowerPushUnit +786,CollapsibleRockTowerPushUnitRampRight +787,CollapsibleRockTowerPushUnitRampLeft +788,DigesterCreepSprayTargetUnit +789,DigesterCreepSprayUnit +790,NydusCanalAttackerWeapon +791,ViperConsumeStructureWeapon +794,ResourceBlocker +795,TempestWeapon +796,YoinkMissile +800,YoinkVikingAirMissile +802,YoinkVikingGroundMissile +804,YoinkSiegeTankMissile +806,WarHoundWeapon +808,EyeStalkWeapon +811,WidowMineWeapon +812,WidowMineAirWeapon +813,MothershipCoreWeaponWeapon +814,TornadoMissileWeapon +815,TornadoMissileDummyWeapon +816,TalonsMissileWeapon +817,CreepTumorMissile +818,LocustMPEggAMissileWeapon +819,LocustMPEggBMissileWeapon +820,LocustMPWeapon +822,RepulsorCannonWeapon +826,CollapsibleRockTowerDiagonal +827,CollapsibleTerranTowerDiagonal +828,CollapsibleTerranTowerRampLeft +829,CollapsibleTerranTowerRampRight +830,Ice2x2NonConjoined +831,IceProtossCrates +832,ProtossCrates +833,TowerMine +834,PickupPalletGas +835,PickupPalletMinerals +836,PickupScrapSalvage1x1 +837,PickupScrapSalvage2x2 +838,PickupScrapSalvage3x3 +839,RoughTerrain +840,UnbuildableBricksSmallUnit +841,UnbuildablePlatesSmallUnit +842,UnbuildablePlatesUnit +843,UnbuildableRocksSmallUnit +844,XelNagaHealingShrine +845,InvisibleTargetDummy +846,ProtossVespeneGeyser +847,CollapsibleRockTower +848,CollapsibleTerranTower +849,ThornLizard +850,CleaningBot +851,DestructibleRock6x6Weak +852,ProtossSnakeSegmentDemo +853,PhysicsCapsule +854,PhysicsCube +855,PhysicsCylinder +856,PhysicsKnot +857,PhysicsL +858,PhysicsPrimitives +859,PhysicsSphere +860,PhysicsStar +861,CreepBlocker4x4 +862,DestructibleCityDebris2x4Vertical +863,DestructibleCityDebris2x4Horizontal +864,DestructibleCityDebris2x6Vertical +865,DestructibleCityDebris2x6Horizontal +866,DestructibleCityDebris4x4 +867,DestructibleCityDebris6x6 +868,DestructibleCityDebrisHugeDiagonalBLUR +869,DestructibleCityDebrisHugeDiagonalULBR +870,TestZerg +871,PathingBlockerRadius1 +872,DestructibleRockEx12x4Vertical +873,DestructibleRockEx12x4Horizontal +874,DestructibleRockEx12x6Vertical +875,DestructibleRockEx12x6Horizontal +876,DestructibleRockEx14x4 +877,DestructibleRockEx16x6 +878,DestructibleRockEx1DiagonalHugeULBR +879,DestructibleRockEx1DiagonalHugeBLUR +880,DestructibleRockEx1VerticalHuge +881,DestructibleRockEx1HorizontalHuge +882,DestructibleIce2x4Vertical +883,DestructibleIce2x4Horizontal +884,DestructibleIce2x6Vertical +885,DestructibleIce2x6Horizontal +886,DestructibleIce4x4 +887,DestructibleIce6x6 +888,DestructibleIceDiagonalHugeULBR +889,DestructibleIceDiagonalHugeBLUR +890,DestructibleIceVerticalHuge +891,DestructibleIceHorizontalHuge +892,DesertPlanetSearchlight +893,DesertPlanetStreetlight +894,UnbuildableBricksUnit +895,UnbuildableRocksUnit +896,ZerusDestructibleArch +897,Artosilope +898,Anteplott +899,LabBot +900,Crabeetle +901,CollapsibleRockTowerRampRight +902,CollapsibleRockTowerRampLeft +903,LabMineralField +904,LabMineralField750 +919,CollapsibleRockTowerDebrisRampLeftGreen +920,CollapsibleRockTowerDebrisRampRightGreen +921,SnowRefinery_Terran_ExtendingBridgeNEShort8Out +922,SnowRefinery_Terran_ExtendingBridgeNEShort8 +923,SnowRefinery_Terran_ExtendingBridgeNWShort8Out +924,SnowRefinery_Terran_ExtendingBridgeNWShort8 +929,Tarsonis_DoorN +930,Tarsonis_DoorNLowered +931,Tarsonis_DoorNE +932,Tarsonis_DoorNELowered +933,Tarsonis_DoorE +934,Tarsonis_DoorELowered +935,Tarsonis_DoorNW +936,Tarsonis_DoorNWLowered +937,CompoundMansion_DoorN +938,CompoundMansion_DoorNLowered +939,CompoundMansion_DoorNE +940,CompoundMansion_DoorNELowered +941,CompoundMansion_DoorE +942,CompoundMansion_DoorELowered +943,CompoundMansion_DoorNW +944,CompoundMansion_DoorNWLowered +946,LocustMPFlying +947,AiurLightBridgeNE8Out +948,AiurLightBridgeNE8 +949,AiurLightBridgeNE10Out +950,AiurLightBridgeNE10 +951,AiurLightBridgeNE12Out +952,AiurLightBridgeNE12 +953,AiurLightBridgeNW8Out +954,AiurLightBridgeNW8 +955,AiurLightBridgeNW10Out +956,AiurLightBridgeNW10 +957,AiurLightBridgeNW12Out +958,AiurLightBridgeNW12 +959,AiurTempleBridgeNE8Out +961,AiurTempleBridgeNE10Out +963,AiurTempleBridgeNE12Out +965,AiurTempleBridgeNW8Out +967,AiurTempleBridgeNW10Out +969,AiurTempleBridgeNW12Out +971,ShakurasLightBridgeNE8Out +972,ShakurasLightBridgeNE8 +973,ShakurasLightBridgeNE10Out +974,ShakurasLightBridgeNE10 +975,ShakurasLightBridgeNE12Out +976,ShakurasLightBridgeNE12 +977,ShakurasLightBridgeNW8Out +978,ShakurasLightBridgeNW8 +979,ShakurasLightBridgeNW10Out +980,ShakurasLightBridgeNW10 +981,ShakurasLightBridgeNW12Out +982,ShakurasLightBridgeNW12 +983,VoidMPImmortalReviveCorpse +984,GuardianCocoonMP +985,GuardianMP +986,DevourerCocoonMP +987,DevourerMP +988,DefilerMPBurrowed +989,DefilerMP +990,OracleStasisTrap +991,DisruptorPhased +992,AiurLightBridgeAbandonedNE8Out +993,AiurLightBridgeAbandonedNE8 +994,AiurLightBridgeAbandonedNE10Out +995,AiurLightBridgeAbandonedNE10 +996,AiurLightBridgeAbandonedNE12Out +997,AiurLightBridgeAbandonedNE12 +998,AiurLightBridgeAbandonedNW8Out +999,AiurLightBridgeAbandonedNW8 +1000,AiurLightBridgeAbandonedNW10Out +1001,AiurLightBridgeAbandonedNW10 +1002,AiurLightBridgeAbandonedNW12Out +1003,AiurLightBridgeAbandonedNW12 +1004,CollapsiblePurifierTowerDebris +1005,PortCity_Bridge_UnitNE8Out +1006,PortCity_Bridge_UnitNE8 +1007,PortCity_Bridge_UnitSE8Out +1008,PortCity_Bridge_UnitSE8 +1009,PortCity_Bridge_UnitNW8Out +1010,PortCity_Bridge_UnitNW8 +1011,PortCity_Bridge_UnitSW8Out +1012,PortCity_Bridge_UnitSW8 +1013,PortCity_Bridge_UnitNE10Out +1014,PortCity_Bridge_UnitNE10 +1015,PortCity_Bridge_UnitSE10Out +1016,PortCity_Bridge_UnitSE10 +1017,PortCity_Bridge_UnitNW10Out +1018,PortCity_Bridge_UnitNW10 +1019,PortCity_Bridge_UnitSW10Out +1020,PortCity_Bridge_UnitSW10 +1021,PortCity_Bridge_UnitNE12Out +1022,PortCity_Bridge_UnitNE12 +1023,PortCity_Bridge_UnitSE12Out +1024,PortCity_Bridge_UnitSE12 +1025,PortCity_Bridge_UnitNW12Out +1026,PortCity_Bridge_UnitNW12 +1027,PortCity_Bridge_UnitSW12Out +1028,PortCity_Bridge_UnitSW12 +1029,PortCity_Bridge_UnitN8Out +1030,PortCity_Bridge_UnitN8 +1031,PortCity_Bridge_UnitS8Out +1032,PortCity_Bridge_UnitS8 +1033,PortCity_Bridge_UnitE8Out +1034,PortCity_Bridge_UnitE8 +1035,PortCity_Bridge_UnitW8Out +1036,PortCity_Bridge_UnitW8 +1037,PortCity_Bridge_UnitN10Out +1038,PortCity_Bridge_UnitN10 +1039,PortCity_Bridge_UnitS10Out +1040,PortCity_Bridge_UnitS10 +1041,PortCity_Bridge_UnitE10Out +1042,PortCity_Bridge_UnitE10 +1043,PortCity_Bridge_UnitW10Out +1044,PortCity_Bridge_UnitW10 +1045,PortCity_Bridge_UnitN12Out +1046,PortCity_Bridge_UnitN12 +1047,PortCity_Bridge_UnitS12Out +1048,PortCity_Bridge_UnitS12 +1049,PortCity_Bridge_UnitE12Out +1050,PortCity_Bridge_UnitE12 +1051,PortCity_Bridge_UnitW12Out +1052,PortCity_Bridge_UnitW12 +1053,PurifierRichMineralField +1054,PurifierRichMineralField750 +1055,CollapsibleRockTowerPushUnitRampLeftGreen +1056,CollapsibleRockTowerPushUnitRampRightGreen +1071,CollapsiblePurifierTowerPushUnit +1073,LocustMPPrecursor +1074,ReleaseInterceptorsBeacon +1075,AdeptPhaseShift +1076,HydraliskImpaleMissile +1077,CycloneMissileLargeAir +1078,CycloneMissile +1079,CycloneMissileLarge +1080,OracleWeapon +1081,TempestWeaponGround +1082,ScoutMPAirWeaponLeft +1083,ScoutMPAirWeaponRight +1084,ArbiterMPWeaponMissile +1085,GuardianMPWeapon +1086,DevourerMPWeaponMissile +1087,DefilerMPDarkSwarmWeapon +1088,QueenMPEnsnareMissile +1089,QueenMPSpawnBroodlingsMissile +1090,LightningBombWeapon +1091,HERCPlacement +1092,GrappleWeapon +1095,CausticSprayMissile +1096,ParasiticBombMissile +1097,ParasiticBombDummy +1098,AdeptWeapon +1099,AdeptUpgradeWeapon +1100,LiberatorMissile +1101,LiberatorDamageMissile +1102,LiberatorAGMissile +1103,KD8Charge +1104,KD8ChargeWeapon +1106,SlaynElementalGrabWeapon +1107,SlaynElementalGrabAirUnit +1108,SlaynElementalGrabGroundUnit +1109,SlaynElementalWeapon +1114,CollapsibleRockTowerRampLeftGreen +1115,CollapsibleRockTowerRampRightGreen +1116,DestructibleExpeditionGate6x6 +1117,DestructibleZergInfestation3x3 +1118,HERC +1119,Moopy +1120,Replicant +1121,SeekerMissile +1122,AiurTempleBridgeDestructibleNE8Out +1123,AiurTempleBridgeDestructibleNE10Out +1124,AiurTempleBridgeDestructibleNE12Out +1125,AiurTempleBridgeDestructibleNW8Out +1126,AiurTempleBridgeDestructibleNW10Out +1127,AiurTempleBridgeDestructibleNW12Out +1128,AiurTempleBridgeDestructibleSW8Out +1129,AiurTempleBridgeDestructibleSW10Out +1130,AiurTempleBridgeDestructibleSW12Out +1131,AiurTempleBridgeDestructibleSE8Out +1132,AiurTempleBridgeDestructibleSE10Out +1133,AiurTempleBridgeDestructibleSE12Out +1135,FlyoverUnit +1136,CorsairMP +1137,ScoutMP +1139,ArbiterMP +1140,ScourgeMP +1141,DefilerMPPlagueWeapon +1142,QueenMP +1143,XelNagaDestructibleRampBlocker6S +1144,XelNagaDestructibleRampBlocker6SE +1145,XelNagaDestructibleRampBlocker6E +1146,XelNagaDestructibleRampBlocker6NE +1147,XelNagaDestructibleRampBlocker6N +1148,XelNagaDestructibleRampBlocker6NW +1149,XelNagaDestructibleRampBlocker6W +1150,XelNagaDestructibleRampBlocker6SW +1151,XelNagaDestructibleRampBlocker8S +1152,XelNagaDestructibleRampBlocker8SE +1153,XelNagaDestructibleRampBlocker8E +1154,XelNagaDestructibleRampBlocker8NE +1155,XelNagaDestructibleRampBlocker8N +1156,XelNagaDestructibleRampBlocker8NW +1157,XelNagaDestructibleRampBlocker8W +1158,XelNagaDestructibleRampBlocker8SW +1159,XelNagaDestructibleBlocker6S +1160,XelNagaDestructibleBlocker6SE +1161,XelNagaDestructibleBlocker6E +1162,XelNagaDestructibleBlocker6NE +1163,XelNagaDestructibleBlocker6N +1164,XelNagaDestructibleBlocker6NW +1165,XelNagaDestructibleBlocker6W +1166,XelNagaDestructibleBlocker6SW +1167,XelNagaDestructibleBlocker8S +1168,XelNagaDestructibleBlocker8SE +1169,XelNagaDestructibleBlocker8E +1170,XelNagaDestructibleBlocker8NE +1171,XelNagaDestructibleBlocker8N +1172,XelNagaDestructibleBlocker8NW +1173,XelNagaDestructibleBlocker8W +1174,XelNagaDestructibleBlocker8SW +1175,ReptileCrate +1176,SlaynSwarmHostSpawnFlyer +1177,SlaynElemental +1178,PurifierVespeneGeyser +1179,ShakurasVespeneGeyser +1180,CollapsiblePurifierTowerDiagonal +1181,CreepOnlyBlocker4x4 +1182,BattleStationMineralField +1183,BattleStationMineralField750 +1184,PurifierMineralField +1185,PurifierMineralField750 +1186,Beacon_Nova +1187,Beacon_NovaSmall +1188,Ursula +1189,Elsecaro_Colonist_Hut +1190,SnowGlazeStarterMP +1191,PylonOvercharged +1192,ObserverSiegeMode +1193,RavenRepairDrone +1195,ParasiticBombRelayDummy +1196,BypassArmorDrone +1197,AdeptPiercingWeapon +1198,HighTemplarWeaponMissile +1199,CycloneMissileLargeAirAlternative +1200,RavenScramblerMissile +1201,RavenRepairDroneReleaseWeapon +1202,RavenShredderMissileWeapon +1203,InfestedAcidSpinesWeapon +1204,InfestorEnsnareAttackMissile +1205,SNARE_PLACEHOLDER +1208,CorrosiveParasiteWeapon diff --git a/sc2reader/data/LotV/89720_abilities.csv b/sc2reader/data/LotV/89720_abilities.csv new file mode 100644 index 00000000..b6bf64d9 --- /dev/null +++ b/sc2reader/data/LotV/89720_abilities.csv @@ -0,0 +1,409 @@ +40,Taunt +41,stop +43,move +46,attack +62,SprayTerran +63,SprayZerg +64,SprayProtoss +65,SalvageShared +67,GhostHoldFire +68,GhostWeaponsFree +70,Explode +71,FleetBeaconResearch +72,FungalGrowth +73,GuardianShield +74,MULERepair +76,NexusTrainMothership +77,Feedback +78,MassRecall +80,HallucinationArchon +81,HallucinationColossus +82,HallucinationHighTemplar +83,HallucinationImmortal +84,HallucinationPhoenix +85,HallucinationProbe +86,HallucinationStalker +87,HallucinationVoidRay +88,HallucinationWarpPrism +89,HallucinationZealot +90,MULEGather +92,CalldownMULE +93,GravitonBeam +97,SpawnChangeling +104,Rally +105,ProgressRally +106,RallyCommand +107,RallyNexus +108,RallyHatchery +109,RoachWarrenResearch +112,NeuralParasite +113,SpawnLarva +114,StimpackMarauder +115,SupplyDrop +119,UltraliskCavernResearch +121,SCVHarvest +122,ProbeHarvest +124,que1 +125,que5 +126,que5CancelToSelection +128,que5Addon +129,BuildInProgress +130,Repair +131,TerranBuild +133,Stimpack +134,GhostCloak +136,MedivacHeal +137,SiegeMode +138,Unsiege +139,BansheeCloak +140,MedivacTransport +141,ScannerSweep +142,Yamato +143,AssaultMode +144,FighterMode +145,BunkerTransport +146,CommandCenterTransport +147,CommandCenterLiftOff +148,CommandCenterLand +149,BarracksBuild +150,BarracksLiftOff +151,FactoryFlyingBuild +152,FactoryLiftOff +153,StarportBuild +154,StarportLiftOff +155,FactoryLand +156,StarportLand +157,OrbitalCommandTrain +158,BarracksLand +159,SupplyDepotLower +160,SupplyDepotRaise +161,BarracksTrain +162,FactoryTrain +163,StarportTrain +164,EngineeringBayResearch +166,GhostAcademyTrain +167,BarracksTechLabResearch +168,FactoryTechLabResearch +169,StarportTechLabResearch +170,GhostAcademyResearch +171,ArmoryResearch +172,ProtossBuild +173,WarpPrismTransport +174,GatewayTrain +175,StargateTrain +176,RoboticsFacilityTrain +177,NexusTrain +178,PsiStorm +179,HangarQueue5 +181,CarrierTrain +182,ForgeResearch +183,RoboticsBayResearch +184,TemplarArchiveResearch +185,ZergBuild +186,DroneHarvest +187,EvolutionChamberResearch +188,UpgradeToLair +189,UpgradeToHive +190,UpgradeToGreaterSpire +191,HiveResearch +192,SpawningPoolResearch +193,HydraliskDenResearch +194,GreaterSpireResearch +195,LarvaTrain +196,MorphToBroodLord +197,BurrowBanelingDown +198,BurrowBanelingUp +199,BurrowDroneDown +200,BurrowDroneUp +201,BurrowHydraliskDown +202,BurrowHydraliskUp +203,BurrowRoachDown +204,BurrowRoachUp +205,BurrowZerglingDown +206,BurrowZerglingUp +207,BurrowInfestorTerranDown +208,BurrowInfestorTerranUp +209,RedstoneLavaCritterBurrow +210,RedstoneLavaCritterInjuredBurrow +211,RedstoneLavaCritterUnburrow +212,RedstoneLavaCritterInjuredUnburrow +213,OverlordTransport +216,WarpGateTrain +217,BurrowQueenDown +218,BurrowQueenUp +219,NydusCanalTransport +220,Blink +221,BurrowInfestorDown +222,BurrowInfestorUp +223,MorphToOverseer +224,UpgradeToPlanetaryFortress +225,InfestationPitResearch +226,BanelingNestResearch +227,BurrowUltraliskDown +228,BurrowUltraliskUp +229,UpgradeToOrbital +230,UpgradeToWarpGate +231,MorphBackToGateway +232,OrbitalLiftOff +233,OrbitalCommandLand +234,ForceField +235,PhasingMode +236,TransportMode +237,FusionCoreResearch +238,CyberneticsCoreResearch +239,TwilightCouncilResearch +240,TacNukeStrike +243,EMP +245,HiveTrain +247,Transfusion +256,AttackRedirect +257,StimpackRedirect +258,StimpackMarauderRedirect +260,StopRedirect +261,GenerateCreep +262,QueenBuild +263,SpineCrawlerUproot +264,SporeCrawlerUproot +265,SpineCrawlerRoot +266,SporeCrawlerRoot +267,CreepTumorBurrowedBuild +268,BuildAutoTurret +269,ArchonWarp +270,NydusNetworkBuild +272,Charge +276,Contaminate +279,que5Passive +280,que5PassiveCancelToSelection +283,RavagerCorrosiveBile +305,BurrowLurkerMPDown +306,BurrowLurkerMPUp +309,BurrowRavagerDown +310,BurrowRavagerUp +311,MorphToRavager +312,MorphToTransportOverlord +314,ThorNormalMode +319,DigesterCreepSpray +323,MorphToMothership +348,XelNagaHealingShrine +357,MothershipCoreMassRecall +359,MorphToHellion +369,MorphToHellionTank +377,MorphToSwarmHostBurrowedMP +378,MorphToSwarmHostMP +383,BlindingCloud +385,Yoink +388,ViperConsumeStructure +391,TestZerg +392,VolatileBurstBuilding +399,WidowMineBurrow +400,WidowMineUnburrow +401,WidowMineAttack +402,TornadoMissile +405,HallucinationOracle +406,MedivacSpeedBoost +407,ExtendingBridgeNEWide8Out +408,ExtendingBridgeNEWide8 +409,ExtendingBridgeNWWide8Out +410,ExtendingBridgeNWWide8 +411,ExtendingBridgeNEWide10Out +412,ExtendingBridgeNEWide10 +413,ExtendingBridgeNWWide10Out +414,ExtendingBridgeNWWide10 +415,ExtendingBridgeNEWide12Out +416,ExtendingBridgeNEWide12 +417,ExtendingBridgeNWWide12Out +418,ExtendingBridgeNWWide12 +420,CritterFlee +421,OracleRevelation +429,MothershipCorePurifyNexus +430,XelNaga_Caverns_DoorE +431,XelNaga_Caverns_DoorEOpened +432,XelNaga_Caverns_DoorN +433,XelNaga_Caverns_DoorNE +434,XelNaga_Caverns_DoorNEOpened +435,XelNaga_Caverns_DoorNOpened +436,XelNaga_Caverns_DoorNW +437,XelNaga_Caverns_DoorNWOpened +438,XelNaga_Caverns_DoorS +439,XelNaga_Caverns_DoorSE +440,XelNaga_Caverns_DoorSEOpened +441,XelNaga_Caverns_DoorSOpened +442,XelNaga_Caverns_DoorSW +443,XelNaga_Caverns_DoorSWOpened +444,XelNaga_Caverns_DoorW +445,XelNaga_Caverns_DoorWOpened +446,XelNaga_Caverns_Floating_BridgeNE8Out +447,XelNaga_Caverns_Floating_BridgeNE8 +448,XelNaga_Caverns_Floating_BridgeNW8Out +449,XelNaga_Caverns_Floating_BridgeNW8 +450,XelNaga_Caverns_Floating_BridgeNE10Out +451,XelNaga_Caverns_Floating_BridgeNE10 +452,XelNaga_Caverns_Floating_BridgeNW10Out +453,XelNaga_Caverns_Floating_BridgeNW10 +454,XelNaga_Caverns_Floating_BridgeNE12Out +455,XelNaga_Caverns_Floating_BridgeNE12 +456,XelNaga_Caverns_Floating_BridgeNW12Out +457,XelNaga_Caverns_Floating_BridgeNW12 +458,XelNaga_Caverns_Floating_BridgeH8Out +459,XelNaga_Caverns_Floating_BridgeH8 +460,XelNaga_Caverns_Floating_BridgeV8Out +461,XelNaga_Caverns_Floating_BridgeV8 +462,XelNaga_Caverns_Floating_BridgeH10Out +463,XelNaga_Caverns_Floating_BridgeH10 +464,XelNaga_Caverns_Floating_BridgeV10Out +465,XelNaga_Caverns_Floating_BridgeV10 +466,XelNaga_Caverns_Floating_BridgeH12Out +467,XelNaga_Caverns_Floating_BridgeH12 +468,XelNaga_Caverns_Floating_BridgeV12Out +469,XelNaga_Caverns_Floating_BridgeV12 +470,TemporalField +496,SnowRefinery_Terran_ExtendingBridgeNEShort8Out +497,SnowRefinery_Terran_ExtendingBridgeNEShort8 +498,SnowRefinery_Terran_ExtendingBridgeNWShort8Out +499,SnowRefinery_Terran_ExtendingBridgeNWShort8 +521,CausticSpray +524,MorphToLurker +528,PurificationNovaTargeted +530,LockOn +532,LockOnCancel +534,Hyperjump +536,ThorAPMode +539,NydusWormTransport +540,OracleWeapon +546,LocustMPFlyingSwoop +547,HallucinationDisruptor +548,HallucinationAdept +549,VoidRaySwarmDamageBoost +550,SeekerDummyChannel +551,AiurLightBridgeNE8Out +552,AiurLightBridgeNE8 +553,AiurLightBridgeNE10Out +554,AiurLightBridgeNE10 +555,AiurLightBridgeNE12Out +556,AiurLightBridgeNE12 +557,AiurLightBridgeNW8Out +558,AiurLightBridgeNW8 +559,AiurLightBridgeNW10Out +560,AiurLightBridgeNW10 +561,AiurLightBridgeNW12Out +562,AiurLightBridgeNW12 +575,ShakurasLightBridgeNE8Out +576,ShakurasLightBridgeNE8 +577,ShakurasLightBridgeNE10Out +578,ShakurasLightBridgeNE10 +579,ShakurasLightBridgeNE12Out +580,ShakurasLightBridgeNE12 +581,ShakurasLightBridgeNW8Out +582,ShakurasLightBridgeNW8 +583,ShakurasLightBridgeNW10Out +584,ShakurasLightBridgeNW10 +585,ShakurasLightBridgeNW12Out +586,ShakurasLightBridgeNW12 +587,VoidMPImmortalReviveRebuild +589,ArbiterMPStasisField +590,ArbiterMPRecall +591,CorsairMPDisruptionWeb +592,MorphToGuardianMP +593,MorphToDevourerMP +594,DefilerMPConsume +595,DefilerMPDarkSwarm +596,DefilerMPPlague +597,DefilerMPBurrow +598,DefilerMPUnburrow +599,QueenMPEnsnare +600,QueenMPSpawnBroodlings +601,QueenMPInfestCommandCenter +605,OracleBuild +609,ParasiticBomb +610,AdeptPhaseShift +613,LurkerHoldFire +614,LurkerRemoveHoldFire +617,LiberatorAGTarget +618,LiberatorAATarget +620,AiurLightBridgeAbandonedNE8Out +621,AiurLightBridgeAbandonedNE8 +622,AiurLightBridgeAbandonedNE10Out +623,AiurLightBridgeAbandonedNE10 +624,AiurLightBridgeAbandonedNE12Out +625,AiurLightBridgeAbandonedNE12 +626,AiurLightBridgeAbandonedNW8Out +627,AiurLightBridgeAbandonedNW8 +628,AiurLightBridgeAbandonedNW10Out +629,AiurLightBridgeAbandonedNW10 +630,AiurLightBridgeAbandonedNW12Out +631,AiurLightBridgeAbandonedNW12 +632,KD8Charge +635,AdeptPhaseShiftCancel +636,AdeptShadePhaseShiftCancel +637,SlaynElementalGrab +639,PortCity_Bridge_UnitNE8Out +640,PortCity_Bridge_UnitNE8 +641,PortCity_Bridge_UnitSE8Out +642,PortCity_Bridge_UnitSE8 +643,PortCity_Bridge_UnitNW8Out +644,PortCity_Bridge_UnitNW8 +645,PortCity_Bridge_UnitSW8Out +646,PortCity_Bridge_UnitSW8 +647,PortCity_Bridge_UnitNE10Out +648,PortCity_Bridge_UnitNE10 +649,PortCity_Bridge_UnitSE10Out +650,PortCity_Bridge_UnitSE10 +651,PortCity_Bridge_UnitNW10Out +652,PortCity_Bridge_UnitNW10 +653,PortCity_Bridge_UnitSW10Out +654,PortCity_Bridge_UnitSW10 +655,PortCity_Bridge_UnitNE12Out +656,PortCity_Bridge_UnitNE12 +657,PortCity_Bridge_UnitSE12Out +658,PortCity_Bridge_UnitSE12 +659,PortCity_Bridge_UnitNW12Out +660,PortCity_Bridge_UnitNW12 +661,PortCity_Bridge_UnitSW12Out +662,PortCity_Bridge_UnitSW12 +663,PortCity_Bridge_UnitN8Out +664,PortCity_Bridge_UnitN8 +665,PortCity_Bridge_UnitS8Out +666,PortCity_Bridge_UnitS8 +667,PortCity_Bridge_UnitE8Out +668,PortCity_Bridge_UnitE8 +669,PortCity_Bridge_UnitW8Out +670,PortCity_Bridge_UnitW8 +671,PortCity_Bridge_UnitN10Out +672,PortCity_Bridge_UnitN10 +673,PortCity_Bridge_UnitS10Out +674,PortCity_Bridge_UnitS10 +675,PortCity_Bridge_UnitE10Out +676,PortCity_Bridge_UnitE10 +677,PortCity_Bridge_UnitW10Out +678,PortCity_Bridge_UnitW10 +679,PortCity_Bridge_UnitN12Out +680,PortCity_Bridge_UnitN12 +681,PortCity_Bridge_UnitS12Out +682,PortCity_Bridge_UnitS12 +683,PortCity_Bridge_UnitE12Out +684,PortCity_Bridge_UnitE12 +685,PortCity_Bridge_UnitW12Out +686,PortCity_Bridge_UnitW12 +689,DarkTemplarBlink +693,BattlecruiserAttack +695,BattlecruiserMove +697,BattlecruiserStop +698,BatteryOvercharge +700,AmorphousArmorcloud +702,SpawnLocustsTargeted +703,ViperParasiticBombRelay +704,ParasiticBombRelayDodge +705,VoidRaySwarmDamageBoostCancel +709,ChannelSnipe +712,DarkShrineResearch +713,LurkerDenMPResearch +714,ObserverSiegeMorphtoObserver +715,ObserverMorphtoObserverSiege +716,OverseerMorphtoOverseerSiegeMode +717,OverseerSiegeModeMorphtoOverseer +718,RavenScramblerMissile +720,RavenRepairDroneHeal +721,RavenShredderMissile +722,ChronoBoostEnergyCost +723,NexusMassRecall +729,MorphToBaneling diff --git a/sc2reader/data/LotV/89720_units.csv b/sc2reader/data/LotV/89720_units.csv new file mode 100644 index 00000000..19aa551f --- /dev/null +++ b/sc2reader/data/LotV/89720_units.csv @@ -0,0 +1,1058 @@ +3,System_Snapshot_Dummy +21,Ball +22,StereoscopicOptionsUnit +23,Colossus +24,TechLab +25,Reactor +27,InfestorTerran +28,BanelingCocoon +29,Baneling +30,Mothership +31,PointDefenseDrone +32,Changeling +33,ChangelingZealot +34,ChangelingMarineShield +35,ChangelingMarine +36,ChangelingZerglingWings +37,ChangelingZergling +39,CommandCenter +40,SupplyDepot +41,Refinery +42,Barracks +43,EngineeringBay +44,MissileTurret +45,Bunker +46,RefineryRich +47,SensorTower +48,GhostAcademy +49,Factory +50,Starport +52,Armory +53,FusionCore +54,AutoTurret +55,SiegeTankSieged +56,SiegeTank +57,VikingAssault +58,VikingFighter +59,CommandCenterFlying +60,BarracksTechLab +61,BarracksReactor +62,FactoryTechLab +63,FactoryReactor +64,StarportTechLab +65,StarportReactor +66,FactoryFlying +67,StarportFlying +68,SCV +69,BarracksFlying +70,SupplyDepotLowered +71,Marine +72,Reaper +73,Ghost +74,Marauder +75,Thor +76,Hellion +77,Medivac +78,Banshee +79,Raven +80,Battlecruiser +81,Nuke +82,Nexus +83,Pylon +84,Assimilator +85,Gateway +86,Forge +87,FleetBeacon +88,TwilightCouncil +89,PhotonCannon +90,Stargate +91,TemplarArchive +92,DarkShrine +93,RoboticsBay +94,RoboticsFacility +95,CyberneticsCore +96,Zealot +97,Stalker +98,HighTemplar +99,DarkTemplar +100,Sentry +101,Phoenix +102,Carrier +103,VoidRay +104,WarpPrism +105,Observer +106,Immortal +107,Probe +108,Interceptor +109,Hatchery +110,CreepTumor +111,Extractor +112,SpawningPool +113,EvolutionChamber +114,HydraliskDen +115,Spire +116,UltraliskCavern +117,InfestationPit +118,NydusNetwork +119,BanelingNest +120,RoachWarren +121,SpineCrawler +122,SporeCrawler +123,Lair +124,Hive +125,GreaterSpire +126,Egg +127,Drone +128,Zergling +129,Overlord +130,Hydralisk +131,Mutalisk +132,Ultralisk +133,Roach +134,Infestor +135,Corruptor +136,BroodLordCocoon +137,BroodLord +138,BanelingBurrowed +139,DroneBurrowed +140,HydraliskBurrowed +141,RoachBurrowed +142,ZerglingBurrowed +143,InfestorTerranBurrowed +144,RedstoneLavaCritterBurrowed +145,RedstoneLavaCritterInjuredBurrowed +146,RedstoneLavaCritter +147,RedstoneLavaCritterInjured +148,QueenBurrowed +149,Queen +150,InfestorBurrowed +151,OverlordCocoon +152,Overseer +153,PlanetaryFortress +154,UltraliskBurrowed +155,OrbitalCommand +156,WarpGate +157,OrbitalCommandFlying +158,ForceField +159,WarpPrismPhasing +160,CreepTumorBurrowed +161,CreepTumorQueen +162,SpineCrawlerUprooted +163,SporeCrawlerUprooted +164,Archon +165,NydusCanal +166,BroodlingEscort +167,GhostAlternate +168,GhostNova +169,RichMineralField +170,RichMineralField750 +171,Ursadon +173,LurkerMPBurrowed +174,LurkerMP +175,LurkerDenMP +176,LurkerMPEgg +177,NydusCanalAttacker +178,OverlordTransport +179,Ravager +180,RavagerBurrowed +181,RavagerCocoon +182,TransportOverlordCocoon +183,XelNagaTower +185,Oracle +186,Tempest +188,InfestedTerransEgg +189,Larva +190,OverseerSiegeMode +192,ReaperPlaceholder +193,MarineACGluescreenDummy +194,FirebatACGluescreenDummy +195,MedicACGluescreenDummy +196,MarauderACGluescreenDummy +197,VultureACGluescreenDummy +198,SiegeTankACGluescreenDummy +199,VikingACGluescreenDummy +200,BansheeACGluescreenDummy +201,BattlecruiserACGluescreenDummy +202,OrbitalCommandACGluescreenDummy +203,BunkerACGluescreenDummy +204,BunkerUpgradedACGluescreenDummy +205,MissileTurretACGluescreenDummy +206,HellbatACGluescreenDummy +207,GoliathACGluescreenDummy +208,CycloneACGluescreenDummy +209,WraithACGluescreenDummy +210,ScienceVesselACGluescreenDummy +211,HerculesACGluescreenDummy +212,ThorACGluescreenDummy +213,PerditionTurretACGluescreenDummy +214,FlamingBettyACGluescreenDummy +215,DevastationTurretACGluescreenDummy +216,BlasterBillyACGluescreenDummy +217,SpinningDizzyACGluescreenDummy +218,ZerglingKerriganACGluescreenDummy +219,RaptorACGluescreenDummy +220,QueenCoopACGluescreenDummy +221,HydraliskACGluescreenDummy +222,HydraliskLurkerACGluescreenDummy +223,MutaliskBroodlordACGluescreenDummy +224,BroodLordACGluescreenDummy +225,UltraliskACGluescreenDummy +226,TorrasqueACGluescreenDummy +227,OverseerACGluescreenDummy +228,LurkerACGluescreenDummy +229,SpineCrawlerACGluescreenDummy +230,SporeCrawlerACGluescreenDummy +231,NydusNetworkACGluescreenDummy +232,OmegaNetworkACGluescreenDummy +233,ZerglingZagaraACGluescreenDummy +234,SwarmlingACGluescreenDummy +235,QueenZagaraACGluescreenDummy +236,BanelingACGluescreenDummy +237,SplitterlingACGluescreenDummy +238,AberrationACGluescreenDummy +239,ScourgeACGluescreenDummy +240,CorruptorACGluescreenDummy +241,OverseerZagaraACGluescreenDummy +242,BileLauncherACGluescreenDummy +243,SwarmQueenACGluescreenDummy +244,RoachACGluescreenDummy +245,RoachVileACGluescreenDummy +246,RavagerACGluescreenDummy +247,SwarmHostACGluescreenDummy +248,MutaliskACGluescreenDummy +249,GuardianACGluescreenDummy +250,DevourerACGluescreenDummy +251,ViperACGluescreenDummy +252,BrutaliskACGluescreenDummy +253,LeviathanACGluescreenDummy +254,ZealotACGluescreenDummy +255,ZealotAiurACGluescreenDummy +256,DragoonACGluescreenDummy +257,HighTemplarACGluescreenDummy +258,ArchonACGluescreenDummy +259,ImmortalACGluescreenDummy +260,ObserverACGluescreenDummy +261,PhoenixAiurACGluescreenDummy +262,ReaverACGluescreenDummy +263,TempestACGluescreenDummy +264,PhotonCannonACGluescreenDummy +265,ZealotVorazunACGluescreenDummy +266,ZealotShakurasACGluescreenDummy +267,StalkerShakurasACGluescreenDummy +268,DarkTemplarShakurasACGluescreenDummy +269,CorsairACGluescreenDummy +270,VoidRayACGluescreenDummy +271,VoidRayShakurasACGluescreenDummy +272,OracleACGluescreenDummy +273,DarkArchonACGluescreenDummy +274,DarkPylonACGluescreenDummy +275,ZealotPurifierACGluescreenDummy +276,SentryPurifierACGluescreenDummy +277,ImmortalKaraxACGluescreenDummy +278,ColossusACGluescreenDummy +279,ColossusPurifierACGluescreenDummy +280,PhoenixPurifierACGluescreenDummy +281,CarrierACGluescreenDummy +282,CarrierAiurACGluescreenDummy +283,KhaydarinMonolithACGluescreenDummy +284,ShieldBatteryACGluescreenDummy +285,EliteMarineACGluescreenDummy +286,MarauderCommandoACGluescreenDummy +287,SpecOpsGhostACGluescreenDummy +288,HellbatRangerACGluescreenDummy +289,StrikeGoliathACGluescreenDummy +290,HeavySiegeTankACGluescreenDummy +291,RaidLiberatorACGluescreenDummy +292,RavenTypeIIACGluescreenDummy +293,CovertBansheeACGluescreenDummy +294,RailgunTurretACGluescreenDummy +295,BlackOpsMissileTurretACGluescreenDummy +296,SupplicantACGluescreenDummy +297,StalkerTaldarimACGluescreenDummy +298,SentryTaldarimACGluescreenDummy +299,HighTemplarTaldarimACGluescreenDummy +300,ImmortalTaldarimACGluescreenDummy +301,ColossusTaldarimACGluescreenDummy +302,WarpPrismTaldarimACGluescreenDummy +303,PhotonCannonTaldarimACGluescreenDummy +304,StukovInfestedCivilianACGluescreenDummy +305,StukovInfestedMarineACGluescreenDummy +306,StukovInfestedSiegeTankACGluescreenDummy +307,StukovInfestedDiamondbackACGluescreenDummy +308,StukovInfestedBansheeACGluescreenDummy +309,SILiberatorACGluescreenDummy +310,StukovInfestedBunkerACGluescreenDummy +311,StukovInfestedMissileTurretACGluescreenDummy +312,StukovBroodQueenACGluescreenDummy +313,ZealotFenixACGluescreenDummy +314,SentryFenixACGluescreenDummy +315,AdeptFenixACGluescreenDummy +316,ImmortalFenixACGluescreenDummy +317,ColossusFenixACGluescreenDummy +318,DisruptorACGluescreenDummy +319,ObserverFenixACGluescreenDummy +320,ScoutACGluescreenDummy +321,CarrierFenixACGluescreenDummy +322,PhotonCannonFenixACGluescreenDummy +323,PrimalZerglingACGluescreenDummy +324,RavasaurACGluescreenDummy +325,PrimalRoachACGluescreenDummy +326,FireRoachACGluescreenDummy +327,PrimalGuardianACGluescreenDummy +328,PrimalHydraliskACGluescreenDummy +329,PrimalMutaliskACGluescreenDummy +330,PrimalImpalerACGluescreenDummy +331,PrimalSwarmHostACGluescreenDummy +332,CreeperHostACGluescreenDummy +333,PrimalUltraliskACGluescreenDummy +334,TyrannozorACGluescreenDummy +335,PrimalWurmACGluescreenDummy +336,HHReaperACGluescreenDummy +337,HHWidowMineACGluescreenDummy +338,HHHellionTankACGluescreenDummy +339,HHWraithACGluescreenDummy +340,HHVikingACGluescreenDummy +341,HHBattlecruiserACGluescreenDummy +342,HHRavenACGluescreenDummy +343,HHBomberPlatformACGluescreenDummy +344,HHMercStarportACGluescreenDummy +345,HHMissileTurretACGluescreenDummy +346,TychusReaperACGluescreenDummy +347,TychusFirebatACGluescreenDummy +348,TychusSpectreACGluescreenDummy +349,TychusMedicACGluescreenDummy +350,TychusMarauderACGluescreenDummy +351,TychusWarhoundACGluescreenDummy +352,TychusHERCACGluescreenDummy +353,TychusGhostACGluescreenDummy +354,TychusSCVAutoTurretACGluescreenDummy +355,ZeratulStalkerACGluescreenDummy +356,ZeratulSentryACGluescreenDummy +357,ZeratulDarkTemplarACGluescreenDummy +358,ZeratulImmortalACGluescreenDummy +359,ZeratulObserverACGluescreenDummy +360,ZeratulDisruptorACGluescreenDummy +361,ZeratulWarpPrismACGluescreenDummy +362,ZeratulPhotonCannonACGluescreenDummy +363,MechaZerglingACGluescreenDummy +364,MechaBanelingACGluescreenDummy +365,MechaHydraliskACGluescreenDummy +366,MechaInfestorACGluescreenDummy +367,MechaCorruptorACGluescreenDummy +368,MechaUltraliskACGluescreenDummy +369,MechaOverseerACGluescreenDummy +370,MechaLurkerACGluescreenDummy +371,MechaBattlecarrierLordACGluescreenDummy +372,MechaSpineCrawlerACGluescreenDummy +373,MechaSporeCrawlerACGluescreenDummy +374,TrooperMengskACGluescreenDummy +375,MedivacMengskACGluescreenDummy +376,BlimpMengskACGluescreenDummy +377,MarauderMengskACGluescreenDummy +378,GhostMengskACGluescreenDummy +379,SiegeTankMengskACGluescreenDummy +380,ThorMengskACGluescreenDummy +381,VikingMengskACGluescreenDummy +382,BattlecruiserMengskACGluescreenDummy +383,BunkerDepotMengskACGluescreenDummy +384,MissileTurretMengskACGluescreenDummy +385,ArtilleryMengskACGluescreenDummy +387,RenegadeLongboltMissileWeapon +388,LoadOutSpray@1 +389,LoadOutSpray@2 +390,LoadOutSpray@3 +391,LoadOutSpray@4 +392,LoadOutSpray@5 +393,LoadOutSpray@6 +394,LoadOutSpray@7 +395,LoadOutSpray@8 +396,LoadOutSpray@9 +397,LoadOutSpray@10 +398,LoadOutSpray@11 +399,LoadOutSpray@12 +400,LoadOutSpray@13 +401,LoadOutSpray@14 +402,NeedleSpinesWeapon +403,CorruptionWeapon +404,InfestedTerransWeapon +405,NeuralParasiteWeapon +406,PointDefenseDroneReleaseWeapon +407,HunterSeekerWeapon +408,MULE +410,ThorAAWeapon +411,PunisherGrenadesLMWeapon +412,VikingFighterWeapon +413,ATALaserBatteryLMWeapon +414,ATSLaserBatteryLMWeapon +415,LongboltMissileWeapon +416,D8ChargeWeapon +417,YamatoWeapon +418,IonCannonsWeapon +419,AcidSalivaWeapon +420,SpineCrawlerWeapon +421,SporeCrawlerWeapon +422,GlaiveWurmWeapon +423,GlaiveWurmM2Weapon +424,GlaiveWurmM3Weapon +425,StalkerWeapon +426,EMP2Weapon +427,BacklashRocketsLMWeapon +428,PhotonCannonWeapon +429,ParasiteSporeWeapon +431,Broodling +432,BroodLordBWeapon +435,AutoTurretReleaseWeapon +436,LarvaReleaseMissile +437,AcidSpinesWeapon +438,FrenzyWeapon +439,ContaminateWeapon +451,BeaconArmy +452,BeaconDefend +453,BeaconAttack +454,BeaconHarass +455,BeaconIdle +456,BeaconAuto +457,BeaconDetect +458,BeaconScout +459,BeaconClaim +460,BeaconExpand +461,BeaconRally +462,BeaconCustom1 +463,BeaconCustom2 +464,BeaconCustom3 +465,BeaconCustom4 +470,LiberatorAG +472,PreviewBunkerUpgraded +473,HellionTank +474,Cyclone +475,WidowMine +476,Liberator +478,Adept +479,Disruptor +480,SwarmHostMP +481,Viper +482,ShieldBattery +483,HighTemplarSkinPreview +484,MothershipCore +485,Viking +498,InhibitorZoneSmall +499,InhibitorZoneMedium +500,InhibitorZoneLarge +501,AccelerationZoneSmall +502,AccelerationZoneMedium +503,AccelerationZoneLarge +504,AccelerationZoneFlyingSmall +505,AccelerationZoneFlyingMedium +506,AccelerationZoneFlyingLarge +507,InhibitorZoneFlyingSmall +508,InhibitorZoneFlyingMedium +509,InhibitorZoneFlyingLarge +510,AssimilatorRich +511,RichVespeneGeyser +512,ExtractorRich +513,RavagerCorrosiveBileMissile +514,RavagerWeaponMissile +515,RenegadeMissileTurret +516,Rocks2x2NonConjoined +517,FungalGrowthMissile +518,NeuralParasiteTentacleMissile +519,Beacon_Protoss +520,Beacon_ProtossSmall +521,Beacon_Terran +522,Beacon_TerranSmall +523,Beacon_Zerg +524,Beacon_ZergSmall +525,Lyote +526,CarrionBird +527,KarakMale +528,KarakFemale +529,UrsadakFemaleExotic +530,UrsadakMale +531,UrsadakFemale +532,UrsadakCalf +533,UrsadakMaleExotic +534,UtilityBot +535,CommentatorBot1 +536,CommentatorBot2 +537,CommentatorBot3 +538,CommentatorBot4 +539,Scantipede +540,Dog +541,Sheep +542,Cow +543,InfestedTerransEggPlacement +544,InfestorTerransWeapon +545,MineralField +546,MineralField450 +547,MineralField750 +548,MineralFieldOpaque +549,MineralFieldOpaque900 +550,VespeneGeyser +551,SpacePlatformGeyser +552,DestructibleSearchlight +553,DestructibleBullhornLights +554,DestructibleStreetlight +555,DestructibleSpacePlatformSign +556,DestructibleStoreFrontCityProps +557,DestructibleBillboardTall +558,DestructibleBillboardScrollingText +559,DestructibleSpacePlatformBarrier +560,DestructibleSignsDirectional +561,DestructibleSignsConstruction +562,DestructibleSignsFunny +563,DestructibleSignsIcons +564,DestructibleSignsWarning +565,DestructibleGarage +566,DestructibleGarageLarge +567,DestructibleTrafficSignal +568,TrafficSignal +569,BraxisAlphaDestructible1x1 +570,BraxisAlphaDestructible2x2 +571,DestructibleDebris4x4 +572,DestructibleDebris6x6 +573,DestructibleRock2x4Vertical +574,DestructibleRock2x4Horizontal +575,DestructibleRock2x6Vertical +576,DestructibleRock2x6Horizontal +577,DestructibleRock4x4 +578,DestructibleRock6x6 +579,DestructibleRampDiagonalHugeULBR +580,DestructibleRampDiagonalHugeBLUR +581,DestructibleRampVerticalHuge +582,DestructibleRampHorizontalHuge +583,DestructibleDebrisRampDiagonalHugeULBR +584,DestructibleDebrisRampDiagonalHugeBLUR +585,WarpPrismSkinPreview +586,SiegeTankSkinPreview +587,ThorAP +588,ThorAALance +589,LiberatorSkinPreview +590,OverlordGenerateCreepKeybind +591,MengskStatueAlone +592,MengskStatue +593,WolfStatue +594,GlobeStatue +595,Weapon +596,GlaiveWurmBounceWeapon +597,BroodLordWeapon +598,BroodLordAWeapon +599,CreepBlocker1x1 +600,PermanentCreepBlocker1x1 +601,PathingBlocker1x1 +602,PathingBlocker2x2 +603,AutoTestAttackTargetGround +604,AutoTestAttackTargetAir +605,AutoTestAttacker +606,HelperEmitterSelectionArrow +607,MultiKillObject +608,ShapeGolfball +609,ShapeCone +610,ShapeCube +611,ShapeCylinder +612,ShapeDodecahedron +613,ShapeIcosahedron +614,ShapeOctahedron +615,ShapePyramid +616,ShapeRoundedCube +617,ShapeSphere +618,ShapeTetrahedron +619,ShapeThickTorus +620,ShapeThinTorus +621,ShapeTorus +622,Shape4PointStar +623,Shape5PointStar +624,Shape6PointStar +625,Shape8PointStar +626,ShapeArrowPointer +627,ShapeBowl +628,ShapeBox +629,ShapeCapsule +630,ShapeCrescentMoon +631,ShapeDecahedron +632,ShapeDiamond +633,ShapeFootball +634,ShapeGemstone +635,ShapeHeart +636,ShapeJack +637,ShapePlusSign +638,ShapeShamrock +639,ShapeSpade +640,ShapeTube +641,ShapeEgg +642,ShapeYenSign +643,ShapeX +644,ShapeWatermelon +645,ShapeWonSign +646,ShapeTennisball +647,ShapeStrawberry +648,ShapeSmileyFace +649,ShapeSoccerball +650,ShapeRainbow +651,ShapeSadFace +652,ShapePoundSign +653,ShapePear +654,ShapePineapple +655,ShapeOrange +656,ShapePeanut +657,ShapeO +658,ShapeLemon +659,ShapeMoneyBag +660,ShapeHorseshoe +661,ShapeHockeyStick +662,ShapeHockeyPuck +663,ShapeHand +664,ShapeGolfClub +665,ShapeGrape +666,ShapeEuroSign +667,ShapeDollarSign +668,ShapeBasketball +669,ShapeCarrot +670,ShapeCherry +671,ShapeBaseball +672,ShapeBaseballBat +673,ShapeBanana +674,ShapeApple +675,ShapeCashLarge +676,ShapeCashMedium +677,ShapeCashSmall +678,ShapeFootballColored +679,ShapeLemonSmall +680,ShapeOrangeSmall +681,ShapeTreasureChestOpen +682,ShapeTreasureChestClosed +683,ShapeWatermelonSmall +684,UnbuildableRocksDestructible +685,UnbuildableBricksDestructible +686,UnbuildablePlatesDestructible +687,Debris2x2NonConjoined +688,EnemyPathingBlocker1x1 +689,EnemyPathingBlocker2x2 +690,EnemyPathingBlocker4x4 +691,EnemyPathingBlocker8x8 +692,EnemyPathingBlocker16x16 +693,ScopeTest +694,SentryACGluescreenDummy +695,StukovInfestedTrooperACGluescreenDummy +711,CollapsibleTerranTowerDebris +712,DebrisRampLeft +713,DebrisRampRight +717,LocustMP +718,CollapsibleRockTowerDebris +719,NydusCanalCreeper +720,SwarmHostBurrowedMP +721,WarHound +722,WidowMineBurrowed +723,ExtendingBridgeNEWide8Out +724,ExtendingBridgeNEWide8 +725,ExtendingBridgeNWWide8Out +726,ExtendingBridgeNWWide8 +727,ExtendingBridgeNEWide10Out +728,ExtendingBridgeNEWide10 +729,ExtendingBridgeNWWide10Out +730,ExtendingBridgeNWWide10 +731,ExtendingBridgeNEWide12Out +732,ExtendingBridgeNEWide12 +733,ExtendingBridgeNWWide12Out +734,ExtendingBridgeNWWide12 +736,CollapsibleRockTowerDebrisRampRight +737,CollapsibleRockTowerDebrisRampLeft +738,XelNaga_Caverns_DoorE +739,XelNaga_Caverns_DoorEOpened +740,XelNaga_Caverns_DoorN +741,XelNaga_Caverns_DoorNE +742,XelNaga_Caverns_DoorNEOpened +743,XelNaga_Caverns_DoorNOpened +744,XelNaga_Caverns_DoorNW +745,XelNaga_Caverns_DoorNWOpened +746,XelNaga_Caverns_DoorS +747,XelNaga_Caverns_DoorSE +748,XelNaga_Caverns_DoorSEOpened +749,XelNaga_Caverns_DoorSOpened +750,XelNaga_Caverns_DoorSW +751,XelNaga_Caverns_DoorSWOpened +752,XelNaga_Caverns_DoorW +753,XelNaga_Caverns_DoorWOpened +754,XelNaga_Caverns_Floating_BridgeNE8Out +755,XelNaga_Caverns_Floating_BridgeNE8 +756,XelNaga_Caverns_Floating_BridgeNW8Out +757,XelNaga_Caverns_Floating_BridgeNW8 +758,XelNaga_Caverns_Floating_BridgeNE10Out +759,XelNaga_Caverns_Floating_BridgeNE10 +760,XelNaga_Caverns_Floating_BridgeNW10Out +761,XelNaga_Caverns_Floating_BridgeNW10 +762,XelNaga_Caverns_Floating_BridgeNE12Out +763,XelNaga_Caverns_Floating_BridgeNE12 +764,XelNaga_Caverns_Floating_BridgeNW12Out +765,XelNaga_Caverns_Floating_BridgeNW12 +766,XelNaga_Caverns_Floating_BridgeH8Out +767,XelNaga_Caverns_Floating_BridgeH8 +768,XelNaga_Caverns_Floating_BridgeV8Out +769,XelNaga_Caverns_Floating_BridgeV8 +770,XelNaga_Caverns_Floating_BridgeH10Out +771,XelNaga_Caverns_Floating_BridgeH10 +772,XelNaga_Caverns_Floating_BridgeV10Out +773,XelNaga_Caverns_Floating_BridgeV10 +774,XelNaga_Caverns_Floating_BridgeH12Out +775,XelNaga_Caverns_Floating_BridgeH12 +776,XelNaga_Caverns_Floating_BridgeV12Out +777,XelNaga_Caverns_Floating_BridgeV12 +780,CollapsibleTerranTowerPushUnitRampLeft +781,CollapsibleTerranTowerPushUnitRampRight +784,CollapsibleRockTowerPushUnit +785,CollapsibleTerranTowerPushUnit +786,CollapsibleRockTowerPushUnitRampRight +787,CollapsibleRockTowerPushUnitRampLeft +788,DigesterCreepSprayTargetUnit +789,DigesterCreepSprayUnit +790,NydusCanalAttackerWeapon +791,ViperConsumeStructureWeapon +794,ResourceBlocker +795,TempestWeapon +796,YoinkMissile +800,YoinkVikingAirMissile +802,YoinkVikingGroundMissile +804,YoinkSiegeTankMissile +806,WarHoundWeapon +808,EyeStalkWeapon +811,WidowMineWeapon +812,WidowMineAirWeapon +813,MothershipCoreWeaponWeapon +814,TornadoMissileWeapon +815,TornadoMissileDummyWeapon +816,TalonsMissileWeapon +817,CreepTumorMissile +818,LocustMPEggAMissileWeapon +819,LocustMPEggBMissileWeapon +820,LocustMPWeapon +822,RepulsorCannonWeapon +826,CollapsibleRockTowerDiagonal +827,CollapsibleTerranTowerDiagonal +828,CollapsibleTerranTowerRampLeft +829,CollapsibleTerranTowerRampRight +830,Ice2x2NonConjoined +831,IceProtossCrates +832,ProtossCrates +833,TowerMine +834,PickupPalletGas +835,PickupPalletMinerals +836,PickupScrapSalvage1x1 +837,PickupScrapSalvage2x2 +838,PickupScrapSalvage3x3 +839,RoughTerrain +840,UnbuildableBricksSmallUnit +841,UnbuildablePlatesSmallUnit +842,UnbuildablePlatesUnit +843,UnbuildableRocksSmallUnit +844,XelNagaHealingShrine +845,InvisibleTargetDummy +846,ProtossVespeneGeyser +847,CollapsibleRockTower +848,CollapsibleTerranTower +849,ThornLizard +850,CleaningBot +851,DestructibleRock6x6Weak +852,ProtossSnakeSegmentDemo +853,PhysicsCapsule +854,PhysicsCube +855,PhysicsCylinder +856,PhysicsKnot +857,PhysicsL +858,PhysicsPrimitives +859,PhysicsSphere +860,PhysicsStar +861,CreepBlocker4x4 +862,DestructibleCityDebris2x4Vertical +863,DestructibleCityDebris2x4Horizontal +864,DestructibleCityDebris2x6Vertical +865,DestructibleCityDebris2x6Horizontal +866,DestructibleCityDebris4x4 +867,DestructibleCityDebris6x6 +868,DestructibleCityDebrisHugeDiagonalBLUR +869,DestructibleCityDebrisHugeDiagonalULBR +870,TestZerg +871,PathingBlockerRadius1 +872,DestructibleRockEx12x4Vertical +873,DestructibleRockEx12x4Horizontal +874,DestructibleRockEx12x6Vertical +875,DestructibleRockEx12x6Horizontal +876,DestructibleRockEx14x4 +877,DestructibleRockEx16x6 +878,DestructibleRockEx1DiagonalHugeULBR +879,DestructibleRockEx1DiagonalHugeBLUR +880,DestructibleRockEx1VerticalHuge +881,DestructibleRockEx1HorizontalHuge +882,DestructibleIce2x4Vertical +883,DestructibleIce2x4Horizontal +884,DestructibleIce2x6Vertical +885,DestructibleIce2x6Horizontal +886,DestructibleIce4x4 +887,DestructibleIce6x6 +888,DestructibleIceDiagonalHugeULBR +889,DestructibleIceDiagonalHugeBLUR +890,DestructibleIceVerticalHuge +891,DestructibleIceHorizontalHuge +892,DesertPlanetSearchlight +893,DesertPlanetStreetlight +894,UnbuildableBricksUnit +895,UnbuildableRocksUnit +896,ZerusDestructibleArch +897,Artosilope +898,Anteplott +899,LabBot +900,Crabeetle +901,CollapsibleRockTowerRampRight +902,CollapsibleRockTowerRampLeft +903,LabMineralField +904,LabMineralField750 +919,CollapsibleRockTowerDebrisRampLeftGreen +920,CollapsibleRockTowerDebrisRampRightGreen +921,SnowRefinery_Terran_ExtendingBridgeNEShort8Out +922,SnowRefinery_Terran_ExtendingBridgeNEShort8 +923,SnowRefinery_Terran_ExtendingBridgeNWShort8Out +924,SnowRefinery_Terran_ExtendingBridgeNWShort8 +929,Tarsonis_DoorN +930,Tarsonis_DoorNLowered +931,Tarsonis_DoorNE +932,Tarsonis_DoorNELowered +933,Tarsonis_DoorE +934,Tarsonis_DoorELowered +935,Tarsonis_DoorNW +936,Tarsonis_DoorNWLowered +937,CompoundMansion_DoorN +938,CompoundMansion_DoorNLowered +939,CompoundMansion_DoorNE +940,CompoundMansion_DoorNELowered +941,CompoundMansion_DoorE +942,CompoundMansion_DoorELowered +943,CompoundMansion_DoorNW +944,CompoundMansion_DoorNWLowered +946,LocustMPFlying +947,AiurLightBridgeNE8Out +948,AiurLightBridgeNE8 +949,AiurLightBridgeNE10Out +950,AiurLightBridgeNE10 +951,AiurLightBridgeNE12Out +952,AiurLightBridgeNE12 +953,AiurLightBridgeNW8Out +954,AiurLightBridgeNW8 +955,AiurLightBridgeNW10Out +956,AiurLightBridgeNW10 +957,AiurLightBridgeNW12Out +958,AiurLightBridgeNW12 +959,AiurTempleBridgeNE8Out +961,AiurTempleBridgeNE10Out +963,AiurTempleBridgeNE12Out +965,AiurTempleBridgeNW8Out +967,AiurTempleBridgeNW10Out +969,AiurTempleBridgeNW12Out +971,ShakurasLightBridgeNE8Out +972,ShakurasLightBridgeNE8 +973,ShakurasLightBridgeNE10Out +974,ShakurasLightBridgeNE10 +975,ShakurasLightBridgeNE12Out +976,ShakurasLightBridgeNE12 +977,ShakurasLightBridgeNW8Out +978,ShakurasLightBridgeNW8 +979,ShakurasLightBridgeNW10Out +980,ShakurasLightBridgeNW10 +981,ShakurasLightBridgeNW12Out +982,ShakurasLightBridgeNW12 +983,VoidMPImmortalReviveCorpse +984,GuardianCocoonMP +985,GuardianMP +986,DevourerCocoonMP +987,DevourerMP +988,DefilerMPBurrowed +989,DefilerMP +990,OracleStasisTrap +991,DisruptorPhased +992,AiurLightBridgeAbandonedNE8Out +993,AiurLightBridgeAbandonedNE8 +994,AiurLightBridgeAbandonedNE10Out +995,AiurLightBridgeAbandonedNE10 +996,AiurLightBridgeAbandonedNE12Out +997,AiurLightBridgeAbandonedNE12 +998,AiurLightBridgeAbandonedNW8Out +999,AiurLightBridgeAbandonedNW8 +1000,AiurLightBridgeAbandonedNW10Out +1001,AiurLightBridgeAbandonedNW10 +1002,AiurLightBridgeAbandonedNW12Out +1003,AiurLightBridgeAbandonedNW12 +1004,CollapsiblePurifierTowerDebris +1005,PortCity_Bridge_UnitNE8Out +1006,PortCity_Bridge_UnitNE8 +1007,PortCity_Bridge_UnitSE8Out +1008,PortCity_Bridge_UnitSE8 +1009,PortCity_Bridge_UnitNW8Out +1010,PortCity_Bridge_UnitNW8 +1011,PortCity_Bridge_UnitSW8Out +1012,PortCity_Bridge_UnitSW8 +1013,PortCity_Bridge_UnitNE10Out +1014,PortCity_Bridge_UnitNE10 +1015,PortCity_Bridge_UnitSE10Out +1016,PortCity_Bridge_UnitSE10 +1017,PortCity_Bridge_UnitNW10Out +1018,PortCity_Bridge_UnitNW10 +1019,PortCity_Bridge_UnitSW10Out +1020,PortCity_Bridge_UnitSW10 +1021,PortCity_Bridge_UnitNE12Out +1022,PortCity_Bridge_UnitNE12 +1023,PortCity_Bridge_UnitSE12Out +1024,PortCity_Bridge_UnitSE12 +1025,PortCity_Bridge_UnitNW12Out +1026,PortCity_Bridge_UnitNW12 +1027,PortCity_Bridge_UnitSW12Out +1028,PortCity_Bridge_UnitSW12 +1029,PortCity_Bridge_UnitN8Out +1030,PortCity_Bridge_UnitN8 +1031,PortCity_Bridge_UnitS8Out +1032,PortCity_Bridge_UnitS8 +1033,PortCity_Bridge_UnitE8Out +1034,PortCity_Bridge_UnitE8 +1035,PortCity_Bridge_UnitW8Out +1036,PortCity_Bridge_UnitW8 +1037,PortCity_Bridge_UnitN10Out +1038,PortCity_Bridge_UnitN10 +1039,PortCity_Bridge_UnitS10Out +1040,PortCity_Bridge_UnitS10 +1041,PortCity_Bridge_UnitE10Out +1042,PortCity_Bridge_UnitE10 +1043,PortCity_Bridge_UnitW10Out +1044,PortCity_Bridge_UnitW10 +1045,PortCity_Bridge_UnitN12Out +1046,PortCity_Bridge_UnitN12 +1047,PortCity_Bridge_UnitS12Out +1048,PortCity_Bridge_UnitS12 +1049,PortCity_Bridge_UnitE12Out +1050,PortCity_Bridge_UnitE12 +1051,PortCity_Bridge_UnitW12Out +1052,PortCity_Bridge_UnitW12 +1053,PurifierRichMineralField +1054,PurifierRichMineralField750 +1055,CollapsibleRockTowerPushUnitRampLeftGreen +1056,CollapsibleRockTowerPushUnitRampRightGreen +1071,CollapsiblePurifierTowerPushUnit +1073,LocustMPPrecursor +1074,ReleaseInterceptorsBeacon +1075,AdeptPhaseShift +1076,HydraliskImpaleMissile +1077,CycloneMissileLargeAir +1078,CycloneMissile +1079,CycloneMissileLarge +1080,OracleWeapon +1081,TempestWeaponGround +1082,ScoutMPAirWeaponLeft +1083,ScoutMPAirWeaponRight +1084,ArbiterMPWeaponMissile +1085,GuardianMPWeapon +1086,DevourerMPWeaponMissile +1087,DefilerMPDarkSwarmWeapon +1088,QueenMPEnsnareMissile +1089,QueenMPSpawnBroodlingsMissile +1090,LightningBombWeapon +1091,HERCPlacement +1092,GrappleWeapon +1095,CausticSprayMissile +1096,ParasiticBombMissile +1097,ParasiticBombDummy +1098,AdeptWeapon +1099,AdeptUpgradeWeapon +1100,LiberatorMissile +1101,LiberatorDamageMissile +1102,LiberatorAGMissile +1103,KD8Charge +1104,KD8ChargeWeapon +1106,SlaynElementalGrabWeapon +1107,SlaynElementalGrabAirUnit +1108,SlaynElementalGrabGroundUnit +1109,SlaynElementalWeapon +1114,CollapsibleRockTowerRampLeftGreen +1115,CollapsibleRockTowerRampRightGreen +1116,DestructibleExpeditionGate6x6 +1117,DestructibleZergInfestation3x3 +1118,HERC +1119,Moopy +1120,Replicant +1121,SeekerMissile +1122,AiurTempleBridgeDestructibleNE8Out +1123,AiurTempleBridgeDestructibleNE10Out +1124,AiurTempleBridgeDestructibleNE12Out +1125,AiurTempleBridgeDestructibleNW8Out +1126,AiurTempleBridgeDestructibleNW10Out +1127,AiurTempleBridgeDestructibleNW12Out +1128,AiurTempleBridgeDestructibleSW8Out +1129,AiurTempleBridgeDestructibleSW10Out +1130,AiurTempleBridgeDestructibleSW12Out +1131,AiurTempleBridgeDestructibleSE8Out +1132,AiurTempleBridgeDestructibleSE10Out +1133,AiurTempleBridgeDestructibleSE12Out +1135,FlyoverUnit +1136,CorsairMP +1137,ScoutMP +1139,ArbiterMP +1140,ScourgeMP +1141,DefilerMPPlagueWeapon +1142,QueenMP +1143,XelNagaDestructibleRampBlocker6S +1144,XelNagaDestructibleRampBlocker6SE +1145,XelNagaDestructibleRampBlocker6E +1146,XelNagaDestructibleRampBlocker6NE +1147,XelNagaDestructibleRampBlocker6N +1148,XelNagaDestructibleRampBlocker6NW +1149,XelNagaDestructibleRampBlocker6W +1150,XelNagaDestructibleRampBlocker6SW +1151,XelNagaDestructibleRampBlocker8S +1152,XelNagaDestructibleRampBlocker8SE +1153,XelNagaDestructibleRampBlocker8E +1154,XelNagaDestructibleRampBlocker8NE +1155,XelNagaDestructibleRampBlocker8N +1156,XelNagaDestructibleRampBlocker8NW +1157,XelNagaDestructibleRampBlocker8W +1158,XelNagaDestructibleRampBlocker8SW +1159,XelNagaDestructibleBlocker6S +1160,XelNagaDestructibleBlocker6SE +1161,XelNagaDestructibleBlocker6E +1162,XelNagaDestructibleBlocker6NE +1163,XelNagaDestructibleBlocker6N +1164,XelNagaDestructibleBlocker6NW +1165,XelNagaDestructibleBlocker6W +1166,XelNagaDestructibleBlocker6SW +1167,XelNagaDestructibleBlocker8S +1168,XelNagaDestructibleBlocker8SE +1169,XelNagaDestructibleBlocker8E +1170,XelNagaDestructibleBlocker8NE +1171,XelNagaDestructibleBlocker8N +1172,XelNagaDestructibleBlocker8NW +1173,XelNagaDestructibleBlocker8W +1174,XelNagaDestructibleBlocker8SW +1175,ReptileCrate +1176,SlaynSwarmHostSpawnFlyer +1177,SlaynElemental +1178,PurifierVespeneGeyser +1179,ShakurasVespeneGeyser +1180,CollapsiblePurifierTowerDiagonal +1181,CreepOnlyBlocker4x4 +1182,BattleStationMineralField +1183,BattleStationMineralField750 +1184,PurifierMineralField +1185,PurifierMineralField750 +1186,Beacon_Nova +1187,Beacon_NovaSmall +1188,Ursula +1189,Elsecaro_Colonist_Hut +1190,SnowGlazeStarterMP +1191,PylonOvercharged +1192,ObserverSiegeMode +1193,RavenRepairDrone +1195,ParasiticBombRelayDummy +1196,BypassArmorDrone +1197,AdeptPiercingWeapon +1198,HighTemplarWeaponMissile +1199,CycloneMissileLargeAirAlternative +1200,RavenScramblerMissile +1201,RavenRepairDroneReleaseWeapon +1202,RavenShredderMissileWeapon +1203,InfestedAcidSpinesWeapon +1204,InfestorEnsnareAttackMissile +1205,SNARE_PLACEHOLDER +1208,CorrosiveParasiteWeapon diff --git a/sc2reader/data/__init__.py b/sc2reader/data/__init__.py index 7a3d4ecb..d97e4885 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 @@ -12,33 +9,38 @@ from sc2reader.log_utils import loggable try: - cmp # Python 2 + cmp # Python 2 except NameError: cmp = lambda a, b: (a > b) - (a < b) # noqa Python 3 ABIL_LOOKUP = dict() -for entry in pkgutil.get_data('sc2reader.data', 'ability_lookup.csv').decode('utf8').split('\n'): +for entry in ( + pkgutil.get_data("sc2reader.data", "ability_lookup.csv").decode("utf8").splitlines() +): if not entry: continue - str_id, abilities = entry.split(',', 1) - ABIL_LOOKUP[str_id] = abilities.split(',') + str_id, abilities = entry.split(",", 1) + ABIL_LOOKUP[str_id] = abilities.split(",") UNIT_LOOKUP = dict() -for entry in pkgutil.get_data('sc2reader.data', 'unit_lookup.csv').decode('utf8').split('\n'): +for entry in ( + pkgutil.get_data("sc2reader.data", "unit_lookup.csv").decode("utf8").splitlines() +): if not entry: continue - str_id, title = entry.strip().split(',') + str_id, title = entry.strip().split(",") UNIT_LOOKUP[str_id] = title -unit_data = pkgutil.get_data('sc2reader.data', 'unit_info.json').decode('utf8') +unit_data = pkgutil.get_data("sc2reader.data", "unit_info.json").decode("utf8") unit_lookup = json.loads(unit_data) -command_data = pkgutil.get_data('sc2reader.data', 'train_commands.json').decode('utf8') +command_data = pkgutil.get_data("sc2reader.data", "train_commands.json").decode("utf8") train_commands = json.loads(command_data) -class Unit(object): +class Unit: """Represents an in-game unit.""" + def __init__(self, unit_id): #: A reference to the player that currently owns this unit. Only available for 2.0.8+ replays. self.owner = None @@ -79,7 +81,7 @@ def __init__(self, unit_id): #: The unique in-game id for this unit. The id can sometimes be zero because #: TargetUnitCommandEvents will create a new unit with id zero when a unit - #: behind the fog of war is targetted. + #: behind the fog of war is targeted. self.id = unit_id #: A reference to the unit type this unit is current in. @@ -120,14 +122,18 @@ def is_type(self, unit_type, strict=True): else: if isinstance(unit_type, int): if self._type_class: - return unit_type in [utype.id for utype in self.type_history.values()] + return unit_type in [ + utype.id for utype in self.type_history.values() + ] else: return unit_type == 0 elif isinstance(unit_type, Unit): return unit_type in self.type_history.values() else: if self._type_class: - return unit_type in [utype.str_id for utype in self.type_history.values()] + return unit_type in [ + utype.str_id for utype in self.type_history.values() + ] else: return unit_type is None @@ -142,46 +148,46 @@ def title(self): @property def type(self): - """ The internal type id of the current unit type of this unit. None if no type is assigned""" + """The internal type id of the current unit type of this unit. None if no type is assigned""" return self._type_class.id if self._type_class else None @property def race(self): - """ The race of this unit. One of Terran, Protoss, Zerg, Neutral, or None""" + """The race of this unit. One of Terran, Protoss, Zerg, Neutral, or None""" return self._type_class.race if self._type_class else None @property def minerals(self): - """ The mineral cost of the unit. None if no type is assigned""" + """The mineral cost of the unit. None if no type is assigned""" return self._type_class.minerals if self._type_class else None @property def vespene(self): - """ The vespene cost of the unit. None if no type is assigned""" + """The vespene cost of the unit. None if no type is assigned""" return self._type_class.vespene if self._type_class else None @property def supply(self): - """ The supply used by this unit. Negative for supply providers. None if no type is assigned """ + """The supply used by this unit. Negative for supply providers. None if no type is assigned""" return self._type_class.supply if self._type_class else None @property def is_worker(self): - """ Boolean flagging units as worker units. SCV, MULE, Drone, Probe """ + """Boolean flagging units as worker units. SCV, MULE, Drone, Probe""" return self._type_class.is_worker if self._type_class else False @property def is_building(self): - """ Boolean flagging units as buildings. """ + """Boolean flagging units as buildings.""" return self._type_class.is_building if self._type_class else False @property def is_army(self): - """ Boolean flagging units as army units. """ + """Boolean flagging units as army units.""" 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) @@ -211,10 +217,23 @@ def __repr__(self): return str(self) -class UnitType(object): - """ Represents an in game unit type """ - def __init__(self, type_id, str_id=None, name=None, title=None, race=None, minerals=0, - vespene=0, supply=0, is_building=False, is_worker=False, is_army=False): +class UnitType: + """Represents an in game unit type""" + + def __init__( + self, + type_id, + str_id=None, + name=None, + title=None, + race=None, + minerals=0, + vespene=0, + supply=0, + is_building=False, + is_worker=False, + is_army=False, + ): #: The internal integer id representing this unit type self.id = type_id @@ -249,9 +268,12 @@ def __init__(self, type_id, str_id=None, name=None, title=None, race=None, miner self.is_army = is_army -class Ability(object): - """ Represents an in-game ability """ - def __init__(self, id, name=None, title=None, is_build=False, build_time=0, build_unit=None): +class Ability: + """Represents an in-game ability""" + + def __init__( + self, id, name=None, title=None, is_build=False, build_time=0, build_unit=None + ): #: The internal integer id representing this ability. self.id = id @@ -272,17 +294,18 @@ def __init__(self, id, name=None, title=None, is_build=False, build_time=0, buil @loggable -class Build(object): +class Build: """ :param build_id: The build number identifying this dataset. - The datapack for a particualr group of builds. Maps internal integer ids + The datapack for a particular group of builds. Maps internal integer ids to :class:`Unit` and :class:`Ability` types. Also contains builder methods for creating new units and changing their types. - All build data is valid for standard games only. For arcade maps milage + All build data is valid for standard games only. For arcade maps mileage may vary. """ + def __init__(self, build_id): #: The integer id of the build self.id = build_id @@ -315,21 +338,44 @@ def change_type(self, unit, new_type, frame): unit_type = self.units[new_type] 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(unit, new_type, frame, self.id)) + self.logger.error( + f"Unable to change type of {unit} to {new_type} [frame {frame}]; unit type not found in build {self.id}" + ) - def add_ability(self, ability_id, name, title=None, is_build=False, build_time=None, build_unit=None): + def add_ability( + self, + ability_id, + name, + title=None, + is_build=False, + build_time=None, + build_unit=None, + ): ability = Ability( ability_id, name=name, title=title or name, is_build=is_build, build_time=build_time, - build_unit=build_unit + build_unit=build_unit, ) setattr(self, name, ability) self.abilities[ability_id] = ability - def add_unit_type(self, type_id, str_id, name, title=None, race='Neutral', minerals=0, vespene=0, supply=0, is_building=False, is_worker=False, is_army=False): + def add_unit_type( + self, + type_id, + str_id, + name, + title=None, + race="Neutral", + minerals=0, + vespene=0, + supply=0, + is_building=False, + is_worker=False, + is_army=False, + ): unit = UnitType( type_id, str_id=str_id, @@ -351,40 +397,46 @@ def add_unit_type(self, type_id, str_id, name, title=None, race='Neutral', miner def load_build(expansion, version): build = Build(version) - unit_file = '{0}/{1}_units.csv'.format(expansion, version) - for entry in pkgutil.get_data('sc2reader.data', unit_file).decode('utf8').split('\n'): + unit_file = f"{expansion}/{version}_units.csv" + for entry in ( + pkgutil.get_data("sc2reader.data", unit_file).decode("utf8").splitlines() + ): if not entry: continue - int_id, str_id = entry.strip().split(',') + int_id, str_id = entry.strip().split(",") unit_type = int(int_id, 10) title = UNIT_LOOKUP[str_id] values = dict(type_id=unit_type, str_id=str_id, name=title) - for race in ('Protoss', 'Terran', 'Zerg'): + for race in ("Protoss", "Terran", "Zerg"): if title.lower() in unit_lookup[race]: values.update(unit_lookup[race][title.lower()]) - values['race'] = race + values["race"] = race break build.add_unit_type(**values) - abil_file = '{0}/{1}_abilities.csv'.format(expansion, version) - 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'): + 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").splitlines() + ): if not entry: continue - int_id_base, str_id = entry.strip().split(',') + int_id_base, str_id = entry.strip().split(",") int_id_base = int(int_id_base, 10) << 5 abils = ABIL_LOOKUP[str_id] - real_abils = [(i, abil) for i, abil in enumerate(abils) if abil.strip() != ''] + real_abils = [(i, abil) for i, abil in enumerate(abils) if abil.strip() != ""] if len(real_abils) == 0: real_abils = [(0, str_id)] for index, ability_name in real_abils: - unit_name, build_time = train_commands.get(ability_name, ('', 0)) - if 'Hallucinated' in unit_name: # Not really sure how to handle hallucinations + unit_name, build_time = train_commands.get(ability_name, ("", 0)) + if ( + "Hallucinated" in unit_name + ): # Not really sure how to handle hallucinations unit_name = unit_name[12:] build.add_ability( @@ -392,26 +444,40 @@ def load_build(expansion, version): name=ability_name, is_build=bool(unit_name), build_unit=getattr(build, unit_name, None), - build_time=build_time + build_time=build_time, ) return build + # Load the WoL Data wol_builds = dict() -for version in ('16117', '17326', '18092', '19458', '22612', '24944'): - wol_builds[version] = load_build('WoL', version) +for version in ("16117", "17326", "18092", "19458", "22612", "24944"): + wol_builds[version] = load_build("WoL", version) # Load HotS Data hots_builds = dict() -for version in ('base', '23925', '24247', '24764'): - hots_builds[version] = load_build('HotS', version) -hots_builds['38215'] = load_build('LotV', 'base') -hots_builds['38215'].id = '38215' +for version in ("base", "23925", "24247", "24764"): + hots_builds[version] = load_build("HotS", version) +hots_builds["38215"] = load_build("LotV", "base") +hots_builds["38215"].id = "38215" # Load LotV Data lotv_builds = dict() -for version in ('base', '44401', '47185', '48258', '53644', '54724', '59587', '70154'): - lotv_builds[version] = load_build('LotV', version) - -datapacks = builds = {'WoL': wol_builds, 'HotS': hots_builds, 'LotV': lotv_builds} +for version in ( + "base", + "44401", + "47185", + "48258", + "53644", + "54724", + "59587", + "70154", + "76114", + "77379", + "80949", + "89720", +): + lotv_builds[version] = load_build("LotV", version) + +datapacks = builds = {"WoL": wol_builds, "HotS": hots_builds, "LotV": lotv_builds} diff --git a/sc2reader/data/ability_lookup.csv b/sc2reader/data/ability_lookup.csv index 09b69177..4eaee18f 100755 --- a/sc2reader/data/ability_lookup.csv +++ b/sc2reader/data/ability_lookup.csv @@ -127,7 +127,7 @@ FactoryLand,LandFactory,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, FactoryLiftOff,LiftFactory,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, FactoryReactorMorph,BuildReactorFactory,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, FactoryTechLabMorph,BuildTechLabFactory,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, -FactoryTechLabResearch,ResearchSiegeTech,ResearchInfernalPreIgniter,Research250mmStrikeCannons,ResearchTransformationServos,ResearchDrillingClaws,,ResearchSmartServos,,ResearchCycloneRapidFireLaunchers,,,,,,,,,,,,,,,,,,,,,,CancelFactoryTechLabResearch, +FactoryTechLabResearch,ResearchSiegeTech,ResearchInfernalPreIgniter,Research250mmStrikeCannons,ResearchTransformationServos,ResearchDrillingClaws,,ResearchSmartServos,,ResearchCycloneRapidFireLaunchers,ResearchCycloneLockOnDamageUpgrade,,,,,,,,,,,,,,,,,,,,,CancelFactoryTechLabResearch, FactoryTrain,,BuildSiegeTank,,,BuildThor,BuildHellion,BuildBattleHellion,TrainCyclone,,,,,BuildWarHound,,,,,,,,,,,,BuildWidowMine,,,,,,CancelFactoryTrain, Feedback,Feedback,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, FighterMode,FighterMode,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, @@ -137,10 +137,10 @@ ForceField,ForceField,CancelForceField,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ForgeResearch,UpgradeGroundWeapons1,UpgradeGroundWeapons2,UpgradeGroundWeapons3,UpgradeGroundArmor1,UpgradeGroundArmor2,UpgradeGroundArmor3,UpgradeShields1,UpgradeShields2,UpgradesShields3,,,,,,,,,,,,,,,,,,,,,,CancelForgeResearch, Frenzy,Frenzy,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, FungalGrowth,FungalGrowth,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, -FusionCoreResearch,ResearchWeaponRefit,ResearchBehemothReactor,,,,,,,,,,,,,,,,,,,,,,,,,,,,,CancelFusionCoreResearch, +FusionCoreResearch,ResearchWeaponRefit,ResearchBehemothReactor,ResearchMedivacIncreaseSpeedBoost,,,,,,,,,,,,,,,,,,,,,,,,,,,,CancelFusionCoreResearch, GatewayTrain,TrainZealot,TrainStalker,,TrainHighTemplar,TrainDarkTemplar,TrainSentry,TrainAdept,,,,,,,,,,,,,,,,,,,,,,,,CancelGatewayTrain, GenerateCreep,GenerateCreep,StopGenerateCreep,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, -GhostAcademyResearch,ResearchPersonalCloaking,ResearchMoebiusReactor,,,,,,,,,,,,,,,,,,,,,,,,,,,,,CancelGhostAcademyResearch, +GhostAcademyResearch,ResearchPersonalCloaking,ResearchMoebiusReactor,ResearchEnhancedShockwaves,,,,,,,,,,,,,,,,,,,,,,,,,,,,CancelGhostAcademyResearch, GhostCloak,CloakGhost,DecloakGhost,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, GhostHoldFire,HoldFireGhost,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, GhostWeaponsFree,GWeaponsFreeGhost,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, @@ -161,7 +161,7 @@ HangarQueue5,CancelLast,CancelSlot,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, HerdInteract,Herd,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, HoldFire,Stop,HoldFire,Cheer,Dance,,,,,,,,,,,,,,,,,,,,,,,,,,,, HydraliskDenResearch,ResearchEvolveGroovedSpines,ResearchEvolveMuscularAugments,EvolveGroovedSpines,EvolveMuscularAugments,,,,,,,,,,,,,,,,,,,,,,,,,,,CancelHydraliskDenResearch, -InfestationPitResearch,,,EvolvePathogenGlands,EvolveNeuralParasite,EvolveEnduringLocusts,,,,,,,,,,,,,,,,,,,,,,,,,,CancelInfestationPitResearch, +InfestationPitResearch,,,EvolvePathogenGlands,EvolveNeuralParasite,EvolveEnduringLocusts,ResearchMicrobialShroud,,,,,,,,,,,,,,,,,,,,,,,,,CancelInfestationPitResearch, InfestedTerrans,SpawnInfestedTerran,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, InfestedTerransLayEgg,SpawnInfestedTerran,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, InvulnerabilityShield,InvulnerabilityShield,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, @@ -329,7 +329,7 @@ TrainQueen,TrainQueen,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,CancelTrainQueen, Transfusion,QueenTransfusion,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, TransportMode,TransportMode,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, TwilightCouncilResearch,ResearchCharge,ResearchBlink,ResearchAdeptPiercingAttack,,,,,,,,,,,,,,,,,,,,,,,,,,,,CancelTwilightCouncilResearch, -UltraliskCavernResearch,,,EvolveChitinousPlating,EvolveBurrowCharge,,,,,,,,,,,,,,,,,,,,,,,,,,,CancelUltraliskCavernResearch, +UltraliskCavernResearch,ResearchAnabolicSynthesis,,EvolveChitinousPlating,EvolveBurrowCharge,,,,,,,,,,,,,,,,,,,,,,,,,,,CancelUltraliskCavernResearch, UltraliskWeaponCooldown,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, Unsiege,TankMode,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, UpgradeToGreaterSpire,MorphToGreaterSpire,CancelMorphToGreaterSpire,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, @@ -518,7 +518,7 @@ LocustMPFlyingSwoopAttack,LocustMPFlyingSwoopAttack MorphToTransportOverlord,MorphToTransportOverlord,Cancel BypassArmor,BypassArmor BypassArmorDroneCU,BypassArmorDroneCU -ChannelSnipe,ChannelSnipe +ChannelSnipe,ChannelSnipe,Cancel LockOnAir,LockOnAir PurificationNovaTargetted,PurificationNovaTargetted SnowRefinery_Terran_ExtendingBridgeNEShort8Out,SnowRefinery_Terran_ExtendingBridgeNEShort8Out @@ -861,3 +861,9 @@ NexusMassRecall,NexusMassRecall OverlordSingleTransport,Load,,UnloadAt ParasiticBombRelayDodge,ParasiticBombRelayDodge ViperParasiticBombRelay,ViperParasiticBombRelay +BattlecruiserStop,Stop +BattlecruiserAttack,BattlecruiserAttack +BattlecruiserMove,Move,Patrol,HoldPos +AmorphousArmorcloud,AmorphousArmorcloud +BatteryOvercharge,BatteryOvercharge +MorphToBaneling,MorphToBaneling,Cancel diff --git a/sc2reader/data/attributes.json b/sc2reader/data/attributes.json index 773be8c3..7922c1cc 100644 --- a/sc2reader/data/attributes.json +++ b/sc2reader/data/attributes.json @@ -292,6 +292,8 @@ "Team", { "T1": "Team 1", + "T10": "Team 10", + "T11": "Team 11", "T2": "Team 2", "T3": "Team 3", "T4": "Team 4", @@ -299,9 +301,7 @@ "T6": "Team 6", "T7": "Team 7", "T8": "Team 8", - "T9": "Team 9", - "T10": "Team 10", - "T11": "Team 11" + "T9": "Team 9" } ], "3000": [ @@ -317,8 +317,12 @@ "3001": [ "Race", { + "InfT": "Infested Terran", + "PZrg": "Primal Zerg", "Prot": "Protoss", "RAND": "Random", + "TerH": "Terran Horner", + "TerT": "Terran Tychus", "Terr": "Terran", "Zerg": "Zerg" } @@ -705,11 +709,13 @@ "Arta": "Artanis", "Deha": "Dehaka", "Feni": "Fenix", - "Horn": "Horner", + "Horn": "Han & Horner", "Kara": "Karax", "Kerr": "Kerrigan", + "Meng": "Mengsk", "Nova": "Nova", "Rayn": "Raynor", + "Stet": "Stetmann", "Stuk": "Stukov", "Swan": "Swann", "Tych": "Tychus", @@ -757,6 +763,142 @@ "90": "90 Minutes" } ], + "3016": [ + "Commander Mastery Level", + { + "0": "0", + "1": "1", + "10": "10", + "100": "100", + "11": "11", + "12": "12", + "13": "13", + "14": "14", + "15": "15", + "16": "16", + "17": "17", + "18": "18", + "19": "19", + "2": "2", + "20": "20", + "21": "21", + "22": "22", + "23": "23", + "24": "24", + "25": "25", + "26": "26", + "27": "27", + "28": "28", + "29": "29", + "3": "3", + "30": "30", + "31": "31", + "32": "32", + "33": "33", + "34": "34", + "35": "35", + "36": "36", + "37": "37", + "38": "38", + "39": "39", + "4": "4", + "40": "40", + "41": "41", + "42": "42", + "43": "43", + "44": "44", + "45": "45", + "46": "46", + "47": "47", + "48": "48", + "49": "49", + "5": "5", + "50": "50", + "51": "51", + "52": "52", + "53": "53", + "54": "54", + "55": "55", + "56": "56", + "57": "57", + "58": "58", + "59": "59", + "6": "6", + "60": "60", + "61": "61", + "62": "62", + "63": "63", + "64": "64", + "65": "65", + "66": "66", + "67": "67", + "68": "68", + "69": "69", + "7": "7", + "70": "70", + "71": "71", + "72": "72", + "73": "73", + "74": "74", + "75": "75", + "76": "76", + "77": "77", + "78": "78", + "79": "79", + "8": "8", + "80": "80", + "81": "81", + "82": "82", + "83": "83", + "84": "84", + "85": "85", + "86": "86", + "87": "87", + "88": "88", + "89": "89", + "9": "9", + "90": "90", + "91": "91", + "92": "92", + "93": "93", + "94": "94", + "95": "95", + "96": "96", + "97": "97", + "98": "98", + "99": "99" + } + ], + "3017": [ + "Commander Mastery Tier", + { + "0": "0", + "1": "1", + "10": "10", + "2": "2", + "3": "3", + "4": "4", + "5": "5", + "6": "6", + "7": "7", + "8": "8", + "9": "9" + } + ], + "3019": [ + "Random Commander", + { + "no": "Not Random", + "yes": "Random" + } + ], + "3020": [ + "Commander Is Trial", + { + "no": "Not Trial", + "yes": "Trial" + } + ], "3102": [ "AI Build", { @@ -1568,7 +1710,251 @@ "no": "Not Ready", "yes": "Ready" } + ], + "5000": [ + "Commander Mastery Talent", + { + "0": "0", + "1": "1", + "10": "10", + "11": "11", + "12": "12", + "13": "13", + "14": "14", + "15": "15", + "16": "16", + "17": "17", + "18": "18", + "19": "19", + "2": "2", + "20": "20", + "21": "21", + "22": "22", + "23": "23", + "24": "24", + "25": "25", + "26": "26", + "27": "27", + "28": "28", + "29": "29", + "3": "3", + "30": "30", + "4": "4", + "5": "5", + "6": "6", + "7": "7", + "8": "8", + "9": "9" + } + ], + "5001": [ + "Commander Mastery Talent", + { + "0": "0", + "1": "1", + "10": "10", + "11": "11", + "12": "12", + "13": "13", + "14": "14", + "15": "15", + "16": "16", + "17": "17", + "18": "18", + "19": "19", + "2": "2", + "20": "20", + "21": "21", + "22": "22", + "23": "23", + "24": "24", + "25": "25", + "26": "26", + "27": "27", + "28": "28", + "29": "29", + "3": "3", + "30": "30", + "4": "4", + "5": "5", + "6": "6", + "7": "7", + "8": "8", + "9": "9" + } + ], + "5002": [ + "Commander Mastery Talent", + { + "0": "0", + "1": "1", + "10": "10", + "11": "11", + "12": "12", + "13": "13", + "14": "14", + "15": "15", + "16": "16", + "17": "17", + "18": "18", + "19": "19", + "2": "2", + "20": "20", + "21": "21", + "22": "22", + "23": "23", + "24": "24", + "25": "25", + "26": "26", + "27": "27", + "28": "28", + "29": "29", + "3": "3", + "30": "30", + "4": "4", + "5": "5", + "6": "6", + "7": "7", + "8": "8", + "9": "9" + } + ], + "5003": [ + "Commander Mastery Talent", + { + "0": "0", + "1": "1", + "10": "10", + "11": "11", + "12": "12", + "13": "13", + "14": "14", + "15": "15", + "16": "16", + "17": "17", + "18": "18", + "19": "19", + "2": "2", + "20": "20", + "21": "21", + "22": "22", + "23": "23", + "24": "24", + "25": "25", + "26": "26", + "27": "27", + "28": "28", + "29": "29", + "3": "3", + "30": "30", + "4": "4", + "5": "5", + "6": "6", + "7": "7", + "8": "8", + "9": "9" + } + ], + "5004": [ + "Commander Mastery Talent", + { + "0": "0", + "1": "1", + "10": "10", + "11": "11", + "12": "12", + "13": "13", + "14": "14", + "15": "15", + "16": "16", + "17": "17", + "18": "18", + "19": "19", + "2": "2", + "20": "20", + "21": "21", + "22": "22", + "23": "23", + "24": "24", + "25": "25", + "26": "26", + "27": "27", + "28": "28", + "29": "29", + "3": "3", + "30": "30", + "4": "4", + "5": "5", + "6": "6", + "7": "7", + "8": "8", + "9": "9" + } + ], + "5005": [ + "Commander Mastery Talent", + { + "0": "0", + "1": "1", + "10": "10", + "11": "11", + "12": "12", + "13": "13", + "14": "14", + "15": "15", + "16": "16", + "17": "17", + "18": "18", + "19": "19", + "2": "2", + "20": "20", + "21": "21", + "22": "22", + "23": "23", + "24": "24", + "25": "25", + "26": "26", + "27": "27", + "28": "28", + "29": "29", + "3": "3", + "30": "30", + "4": "4", + "5": "5", + "6": "6", + "7": "7", + "8": "8", + "9": "9" + } + ], + "5100": [ + "Brutal Plus Level", + { + "0": "0", + "1": "1", + "2": "2", + "3": "3", + "4": "4", + "5": "5", + "6": "6" + } + ], + "5200": [ + "Brutal Plus Is Retry", + { + "no": "No", + "yes": "Yes" + } + ], + "5300": [ + "Commander Prestige Level", + { + "0": "0", + "1": "1", + "2": "2", + "3": "3" + } ] }, - "decisions": "(dp0\nc__builtin__\nfrozenset\np1\n((lp2\nS'Hard'\np3\naVHarder\np4\na(I3004\nS'Hard'\np5\ntp6\natp7\nRp8\ng4\nsg1\n((lp9\n(I2001\nS'1v1'\np10\ntp11\naS'1 v 1'\np12\naV1v1\np13\natp14\nRp15\ng13\nsg1\n((lp16\n(I3104\nS'AB04'\np17\ntp18\naS'Agressive Push'\np19\naVAggressive Push\np20\natp21\nRp22\ng20\nsg1\n((lp23\nS'Agressive Push'\np24\naVAggressive Push\np25\na(I3199\nS'AB04'\np26\ntp27\natp28\nRp29\ng25\nsg1\n((lp30\nV6v6\np31\naS'6 v 6'\np32\na(I2001\nS'6v6'\np33\ntp34\natp35\nRp36\ng31\nsg1\n((lp37\nS'Agressive Push'\np38\na(I3102\nS'AB04'\np39\ntp40\naVAggressive Push\np41\natp42\nRp43\ng41\nsg1\n((lp44\nI2003\naVTeams2v2\np45\naS'Team'\np46\natp47\nRp48\ng45\nsg1\n((lp49\nVLadder\np50\naS'Automated Match Making'\np51\na(I3009\nS'Amm'\np52\ntp53\natp54\nRp55\ng50\nsg1\n((lp56\n(I2001\nS'5v5'\np57\ntp58\naS'5 v 5'\np59\naV5v5\np60\natp61\nRp62\ng60\nsg1\n((lp63\nVFree For All Teams\np64\naS'Free For All Archon'\np65\na(I2000\nVFFAT\np66\ntp67\natp68\nRp69\ng65\nsg1\n((lp70\nI3141\naVAI Build (Terran)\np71\naS'AI Build'\np72\natp73\nRp74\ng71\nsg1\n((lp75\n(I2001\nS'3v3'\np76\ntp77\naS'3 v 3'\np78\naV3v3\np79\natp80\nRp81\ng79\nsg1\n((lp82\n(I3168\nS'AB04'\np83\ntp84\naS'Agressive Push'\np85\naVAggressive Push\np86\natp87\nRp88\ng86\nsg1\n((lp89\n(I3200\nS'AB04'\np90\ntp91\naS'Agressive Push'\np92\naVAggressive Push\np93\natp94\nRp95\ng93\nsg1\n((lp96\nVAI Build (Protoss)\np97\naI3174\naS'AI Build'\np98\natp99\nRp100\ng97\nsg1\n((lp101\nS'Very Hard'\np102\naVElite\np103\na(I3004\nS'VyHd'\np104\ntp105\natp106\nRp107\ng103\nsg1\n((lp108\nS'Agressive Push'\np109\naVAggressive Push\np110\na(I3167\nS'AB04'\np111\ntp112\natp113\nRp114\ng110\nsg1\n((lp115\nI3204\naS'AI Build'\np116\naVAI Build (Zerg)\np117\natp118\nRp119\ng117\nsg1\n((lp120\nVInsane\np121\naS'Cheater 3 (Insane)'\np122\na(I3004\nS'Insa'\np123\ntp124\natp125\nRp126\ng121\nsg1\n((lp127\n(I3007\nS'Watc'\np128\ntp129\naS'Observer'\np130\naS'Watcher'\np131\natp132\nRp133\ng130\nsg1\n((lp134\nI3205\naVAI Build (Zerg)\np135\naS'AI Build'\np136\natp137\nRp138\ng135\nsg1\n((lp139\nVTeams5v5\np140\naS'Team'\np141\naI2007\natp142\nRp143\ng140\nsg1\n((lp144\nI3171\naVAI Build (Protoss)\np145\naS'AI Build'\np146\natp147\nRp148\ng145\nsg1\n((lp149\nS'Unknown'\np150\naI2012\naS'Team'\np151\natp152\nRp153\ng151\nsg1\n((lp154\nI3173\naS'AI Build'\np155\naVAI Build (Protoss)\np156\natp157\nRp158\ng156\nsg1\n((lp159\nVAI Build (Terran)\np160\naI3142\naS'AI Build'\np161\natp162\nRp163\ng160\nsg1\n((lp164\nI3172\naVAI Build (Protoss)\np165\naS'AI Build'\np166\natp167\nRp168\ng165\nsg1\n((lp169\nS'Level 1 (Very Easy)'\np170\na(I3004\nS'VyEy'\np171\ntp172\naVVery Easy\np173\natp174\nRp175\ng173\nsg1\n((lp176\nS'Agressive Push'\np177\naVAggressive Push\np178\na(I3135\nS'AB04'\np179\ntp180\natp181\nRp182\ng178\nsg1\n((lp183\nV2v2\np184\naS'2 v 2'\np185\na(I2001\nS'2v2'\np186\ntp187\natp188\nRp189\ng184\nsg1\n((lp190\nS'Agressive Push'\np191\na(I3166\nS'AB04'\np192\ntp193\naVAggressive Push\np194\natp195\nRp196\ng194\nsg1\n((lp197\nVTeamsFFA\np198\naI2006\naS'Team'\np199\natp200\nRp201\ng198\nsg1\n((lp202\nS'AI Build'\np203\naVAI Build (Terran)\np204\naI3143\natp205\nRp206\ng204\nsg1\n((lp207\nVTeams7v7\np208\naI2011\naS'Team'\np209\natp210\nRp211\ng208\nsg1\n((lp212\nVMedium\np213\naS'Level 3 (Medium)'\np214\na(I3004\nS'Medi'\np215\ntp216\natp217\nRp218\ng213\nsg1\n((lp219\nI3140\naS'AI Build'\np220\naVAI Build (Terran)\np221\natp222\nRp223\ng221\nsg1\n((lp224\nVTeams4v4\np225\naI2005\naS'Team'\np226\natp227\nRp228\ng225\nsg1\n((lp229\nS'Agressive Push'\np230\na(I3198\nS'AB04'\np231\ntp232\naVAggressive Push\np233\natp234\nRp235\ng233\nsg1\n((lp236\n(I3136\nS'AB04'\np237\ntp238\naS'Agressive Push'\np239\naVAggressive Push\np240\natp241\nRp242\ng240\nsg1\n((lp243\nI2008\naVTeams6v6\np244\naS'Team'\np245\natp246\nRp247\ng244\nsg1\n((lp248\nS'Agressive Push'\np249\naVAggressive Push\np250\na(I3103\nS'AB04'\np251\ntp252\natp253\nRp254\ng250\nsg1\n((lp255\nV4v4\np256\naS'4 v 4'\np257\na(I2001\nS'4v4'\np258\ntp259\natp260\nRp261\ng256\nsg1\n((lp262\nS'Agressive Push'\np263\na(I3134\nS'AB04'\np264\ntp265\naVAggressive Push\np266\natp267\nRp268\ng266\nsg1\n((lp269\nVTeams1v1\np270\naI2002\naS'Team'\np271\natp272\nRp273\ng270\nsg1\n((lp274\nI3139\naS'AI Build'\np275\naVAI Build (Terran)\np276\natp277\nRp278\ng276\nsg1\n((lp279\nS'AI Build'\np280\naVAI Build (Zerg)\np281\naI3207\natp282\nRp283\ng281\nsg1\n((lp284\n(I2001\nS'FFA'\np285\ntp286\naS'Free For All'\np287\naVFFA\np288\natp289\nRp290\ng288\nsg1\n((lp291\nVAI Build (Zerg)\np292\naI3206\naS'AI Build'\np293\natp294\nRp295\ng292\nsg1\n((lp296\nVTeams3v3\np297\naI2004\naS'Team'\np298\natp299\nRp300\ng297\nsg1\n((lp301\nVAI Build (Protoss)\np302\naS'AI Build'\np303\naI3175\natp304\nRp305\ng302\nsg1\n((lp306\nS'Level 2 (Easy)'\np307\na(I3004\nS'Easy'\np308\ntp309\naVEasy\np310\natp311\nRp312\ng310\nsg1\n((lp313\nI3203\naS'AI Build'\np314\naVAI Build (Zerg)\np315\natp316\nRp317\ng315\ns." + "decisions": "(dp0\nc__builtin__\nfrozenset\np1\n((lp2\nS'Hard'\np3\naVHarder\np4\na(I3004\nS'Hard'\np5\ntp6\natp7\nRp8\ng4\nsg1\n((lp9\n(I2001\nS'1v1'\np10\ntp11\naS'1 v 1'\np12\naV1v1\np13\natp14\nRp15\ng13\nsg1\n((lp16\nVUnknown\np17\naI2003\naVTeams2v2\np18\natp19\nRp20\ng18\nsg1\n((lp21\nI3009\naVGame Mode\np22\nag17\natp23\nRp24\ng22\nsg1\n((lp25\n(I3104\nS'AB04'\np26\ntp27\naS'Agressive Push'\np28\naVAggressive Push\np29\natp30\nRp31\ng29\nsg1\n((lp32\nI2001\nag17\naVTeams\np33\natp34\nRp35\ng33\nsg1\n((lp36\ng17\naVTeams4v4\np37\naI2005\natp38\nRp39\ng37\nsg1\n((lp40\nS'Agressive Push'\np41\naVAggressive Push\np42\na(I3199\nS'AB04'\np43\ntp44\natp45\nRp46\ng42\nsg1\n((lp47\nV6v6\np48\naS'6 v 6'\np49\na(I2001\nS'6v6'\np50\ntp51\natp52\nRp53\ng48\nsg1\n((lp54\nS'Agressive Push'\np55\na(I3102\nS'AB04'\np56\ntp57\naVAggressive Push\np58\natp59\nRp60\ng58\nsg1\n((lp61\nI4001\nag17\naVUsing Custom Observer UI\np62\natp63\nRp64\ng62\nsg1\n((lp65\nI2003\naVTeams2v2\np66\naS'Team'\np67\natp68\nRp69\ng66\nsg1\n((lp70\nVLadder\np71\naS'Automated Match Making'\np72\na(I3009\nS'Amm'\np73\ntp74\natp75\nRp76\ng71\nsg1\n((lp77\n(I2001\nS'5v5'\np78\ntp79\naS'5 v 5'\np80\naV5v5\np81\natp82\nRp83\ng81\nsg1\n((lp84\nVFree For All Teams\np85\naS'Free For All Archon'\np86\na(I2000\nVFFAT\np87\ntp88\natp89\nRp90\ng86\nsg1\n((lp91\ng17\naVGame Duration\np92\naI3015\natp93\nRp94\ng92\nsg1\n((lp95\nI2008\nag17\naVTeams6v6\np96\natp97\nRp98\ng96\nsg1\n((lp99\nVHorner\np100\na(I3013\nVHorn\np101\ntp102\naS'Han & Horner'\np103\natp104\nRp105\ng103\nsg1\n((lp106\nI3141\naVAI Build (Terran)\np107\naS'AI Build'\np108\natp109\nRp110\ng107\nsg1\n((lp111\nI3008\nag17\naVObserver Type\np112\natp113\nRp114\ng112\nsg1\n((lp115\n(I2001\nS'3v3'\np116\ntp117\naS'3 v 3'\np118\naV3v3\np119\natp120\nRp121\ng119\nsg1\n((lp122\n(I3168\nS'AB04'\np123\ntp124\naS'Agressive Push'\np125\naVAggressive Push\np126\natp127\nRp128\ng126\nsg1\n((lp129\n(I3200\nS'AB04'\np130\ntp131\naS'Agressive Push'\np132\naVAggressive Push\np133\natp134\nRp135\ng133\nsg1\n((lp136\nVAI Build (Protoss)\np137\naI3174\naS'AI Build'\np138\natp139\nRp140\ng137\nsg1\n((lp141\nS'Very Hard'\np142\naVElite\np143\na(I3004\nS'VyHd'\np144\ntp145\natp146\nRp147\ng143\nsg1\n((lp148\nS'Agressive Push'\np149\naVAggressive Push\np150\na(I3167\nS'AB04'\np151\ntp152\natp153\nRp154\ng150\nsg1\n((lp155\nVTeams5v5\np156\nag17\naI2007\natp157\nRp158\ng156\nsg1\n((lp159\nI3204\naS'AI Build'\np160\naVAI Build (Zerg)\np161\natp162\nRp163\ng161\nsg1\n((lp164\nVInsane\np165\naS'Cheater 3 (Insane)'\np166\na(I3004\nS'Insa'\np167\ntp168\natp169\nRp170\ng165\nsg1\n((lp171\n(I3007\nS'Watc'\np172\ntp173\naS'Observer'\np174\naS'Watcher'\np175\natp176\nRp177\ng174\nsg1\n((lp178\nI3205\naVAI Build (Zerg)\np179\naS'AI Build'\np180\natp181\nRp182\ng179\nsg1\n((lp183\nVTeams5v5\np184\naS'Team'\np185\naI2007\natp186\nRp187\ng184\nsg1\n((lp188\nI3171\naVAI Build (Protoss)\np189\naS'AI Build'\np190\natp191\nRp192\ng189\nsg1\n((lp193\nI1000\naVRules\np194\nag17\natp195\nRp196\ng194\nsg1\n((lp197\nS'Unknown'\np198\naI2012\naS'Team'\np199\natp200\nRp201\ng199\nsg1\n((lp202\ng17\naVTandem Leader Slot\np203\naI3012\natp204\nRp205\ng203\nsg1\n((lp206\ng17\naI3011\naVPlayer Logo Index\np207\natp208\nRp209\ng207\nsg1\n((lp210\nI1001\naVPremade Game\np211\nag17\natp212\nRp213\ng211\nsg1\n((lp214\nI3173\naS'AI Build'\np215\naVAI Build (Protoss)\np216\natp217\nRp218\ng216\nsg1\n((lp219\nVAI Build (Terran)\np220\naI3142\naS'AI Build'\np221\natp222\nRp223\ng220\nsg1\n((lp224\nI3172\naVAI Build (Protoss)\np225\naS'AI Build'\np226\natp227\nRp228\ng225\nsg1\n((lp229\nS'Level 1 (Very Easy)'\np230\na(I3004\nS'VyEy'\np231\ntp232\naVVery Easy\np233\natp234\nRp235\ng233\nsg1\n((lp236\nS'Agressive Push'\np237\naVAggressive Push\np238\na(I3135\nS'AB04'\np239\ntp240\natp241\nRp242\ng238\nsg1\n((lp243\nV2v2\np244\naS'2 v 2'\np245\na(I2001\nS'2v2'\np246\ntp247\natp248\nRp249\ng244\nsg1\n((lp250\nS'Agressive Push'\np251\na(I3166\nS'AB04'\np252\ntp253\naVAggressive Push\np254\natp255\nRp256\ng254\nsg1\n((lp257\nVTeamsFFA\np258\naI2006\naS'Team'\np259\natp260\nRp261\ng258\nsg1\n((lp262\nS'AI Build'\np263\naVAI Build (Terran)\np264\naI3143\natp265\nRp266\ng264\nsg1\n((lp267\nVTeams7v7\np268\naI2011\naS'Team'\np269\natp270\nRp271\ng268\nsg1\n((lp272\nVTeams3v3\np273\nag17\naI2004\natp274\nRp275\ng273\nsg1\n((lp276\nI3000\naVGame Speed\np277\nag17\natp278\nRp279\ng277\nsg1\n((lp280\nVMedium\np281\naS'Level 3 (Medium)'\np282\na(I3004\nS'Medi'\np283\ntp284\natp285\nRp286\ng281\nsg1\n((lp287\nI3140\naS'AI Build'\np288\naVAI Build (Terran)\np289\natp290\nRp291\ng289\nsg1\n((lp292\nVTeams4v4\np293\naI2005\naS'Team'\np294\natp295\nRp296\ng293\nsg1\n((lp297\nS'Agressive Push'\np298\na(I3198\nS'AB04'\np299\ntp300\naVAggressive Push\np301\natp302\nRp303\ng301\nsg1\n((lp304\nVLocked Alliances\np305\nag17\naI3010\natp306\nRp307\ng305\nsg1\n((lp308\nVReady\np309\nag17\naI4005\natp310\nRp311\ng309\nsg1\n((lp312\ng17\naVLobby Delay\np313\naI3006\natp314\nRp315\ng313\nsg1\n((lp316\n(I3136\nS'AB04'\np317\ntp318\naS'Agressive Push'\np319\naVAggressive Push\np320\natp321\nRp322\ng320\nsg1\n((lp323\nI2008\naVTeams6v6\np324\naS'Team'\np325\natp326\nRp327\ng324\nsg1\n((lp328\nS'Agressive Push'\np329\naVAggressive Push\np330\na(I3103\nS'AB04'\np331\ntp332\natp333\nRp334\ng330\nsg1\n((lp335\nV4v4\np336\naS'4 v 4'\np337\na(I2001\nS'4v4'\np338\ntp339\natp340\nRp341\ng336\nsg1\n((lp342\nS'Agressive Push'\np343\na(I3134\nS'AB04'\np344\ntp345\naVAggressive Push\np346\natp347\nRp348\ng346\nsg1\n((lp349\nVTeams1v1\np350\naI2002\naS'Team'\np351\natp352\nRp353\ng350\nsg1\n((lp354\nVParticipant Role\np355\nag17\naI3007\natp356\nRp357\ng355\nsg1\n((lp358\nI3139\naS'AI Build'\np359\naVAI Build (Terran)\np360\natp361\nRp362\ng360\nsg1\n((lp363\nI4000\nag17\naVGame Privacy\np364\natp365\nRp366\ng364\nsg1\n((lp367\nS'AI Build'\np368\naVAI Build (Zerg)\np369\naI3207\natp370\nRp371\ng369\nsg1\n((lp372\n(I2001\nS'FFA'\np373\ntp374\naS'Free For All'\np375\naVFFA\np376\natp377\nRp378\ng376\nsg1\n((lp379\nVAI Build (Zerg)\np380\naI3206\naS'AI Build'\np381\natp382\nRp383\ng380\nsg1\n((lp384\nVTeams3v3\np385\naI2004\naS'Team'\np386\natp387\nRp388\ng385\nsg1\n((lp389\nVAI Build (Protoss)\np390\naS'AI Build'\np391\naI3175\natp392\nRp393\ng390\nsg1\n((lp394\nS'Level 2 (Easy)'\np395\na(I3004\nS'Easy'\np396\ntp397\naVEasy\np398\natp399\nRp400\ng398\nsg1\n((lp401\nVTeams1v1\np402\nag17\naI2002\natp403\nRp404\ng402\nsg1\n((lp405\nI3203\naS'AI Build'\np406\naVAI Build (Zerg)\np407\natp408\nRp409\ng407\ns." } diff --git a/sc2reader/data/create_lookup.py b/sc2reader/data/create_lookup.py index 73623836..427d1e27 100755 --- a/sc2reader/data/create_lookup.py +++ b/sc2reader/data/create_lookup.py @@ -1,14 +1,14 @@ 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 + 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('|') + ability, commands = line.strip("\r\n ").split("|", 1) + abilities[ability] = commands.split("|") -with open('new_lookup.csv', 'w') as out: +with open("new_lookup.csv", "w") as out: for ability, commands in sorted(abilities.items()): - out.write(','.join([ability]+commands)+'\n') + out.write(",".join([ability] + commands) + "\n") diff --git a/sc2reader/data/unit_info.json b/sc2reader/data/unit_info.json index 81cf8669..15d02ff6 100644 --- a/sc2reader/data/unit_info.json +++ b/sc2reader/data/unit_info.json @@ -224,9 +224,15 @@ }, "ravager": { "is_army": true, - "minerals": 75, - "vespene": 25, - "supply": 2 + "minerals": 100, + "vespene": 100, + "supply": 3 + }, + "ravagercocoon": { + "is_army": true, + "minerals": 100, + "vespene": 100, + "supply": 3 }, "roach": { "is_army": true, diff --git a/sc2reader/data/unit_lookup.csv b/sc2reader/data/unit_lookup.csv index 7327ef0d..2284dd18 100755 --- a/sc2reader/data/unit_lookup.csv +++ b/sc2reader/data/unit_lookup.csv @@ -1020,3 +1020,65 @@ ZeratulStalkerACGluescreenDummy,ZeratulStalkerACGluescreenDummy ZeratulPhotonCannonACGluescreenDummy,ZeratulPhotonCannonACGluescreenDummy Viking,Viking TychusReaperACGluescreenDummy,TychusReaperACGluescreenDummy +MechaZerglingACGluescreenDummy,MechaZerglingACGluescreenDummy +MechaBanelingACGluescreenDummy,MechaBanelingACGluescreenDummy +MechaHydraliskACGluescreenDummy,MechaHydraliskACGluescreenDummy +MechaInfestorACGluescreenDummy,MechaInfestorACGluescreenDummy +MechaCorruptorACGluescreenDummy,MechaCorruptorACGluescreenDummy +MechaUltraliskACGluescreenDummy,MechaUltraliskACGluescreenDummy +MechaOverseerACGluescreenDummy,MechaOverseerACGluescreenDummy +MechaLurkerACGluescreenDummy,MechaLurkerACGluescreenDummy +MechaBattlecarrierLordACGluescreenDummy,MechaBattlecarrierLordACGluescreenDummy +MechaSpineCrawlerACGluescreenDummy,MechaSpineCrawlerACGluescreenDummy +MechaSporeCrawlerACGluescreenDummy,MechaSporeCrawlerACGluescreenDummy +PreviewBunkerUpgraded,PreviewBunkerUpgraded +AssimilatorRich,AssimilatorRich +ExtractorRich,ExtractorRich +InhibitorZoneSmall,InhibitorZoneSmall +InhibitorZoneMedium,InhibitorZoneMedium +InhibitorZoneLarge,InhibitorZoneLarge +RefineryRich,RefineryRich +MineralField450,MineralField450 +MineralFieldOpaque,MineralFieldOpaque +MineralFieldOpaque900,MineralFieldOpaque900 +CollapsibleRockTowerDebrisRampLeftGreen,CollapsibleRockTowerDebrisRampLeftGreen +CollapsibleRockTowerDebrisRampRightGreen,CollapsibleRockTowerDebrisRampRightGreen +CollapsibleRockTowerPushUnitRampLeftGreen,CollapsibleRockTowerPushUnitRampLeftGreen +CollapsibleRockTowerPushUnitRampRightGreen,CollapsibleRockTowerPushUnitRampRightGreen +CollapsibleRockTowerRampLeftGreen,CollapsibleRockTowerRampLeftGreen +CollapsibleRockTowerRampRightGreen,CollapsibleRockTowerRampRightGreen +TrooperMengskACGluescreenDummy,TrooperMengskACGluescreenDummy +MedivacMengskACGluescreenDummy,MedivacMengskACGluescreenDummy +BlimpMengskACGluescreenDummy,BlimpMengskACGluescreenDummy +MarauderMengskACGluescreenDummy,MarauderMengskACGluescreenDummy +GhostMengskACGluescreenDummy,GhostMengskACGluescreenDummy +SiegeTankMengskACGluescreenDummy,SiegeTankMengskACGluescreenDummy +ThorMengskACGluescreenDummy,ThorMengskACGluescreenDummy +VikingMengskACGluescreenDummy,VikingMengskACGluescreenDummy +BattlecruiserMengskACGluescreenDummy,BattlecruiserMengskACGluescreenDummy +BunkerDepotMengskACGluescreenDummy,BunkerDepotMengskACGluescreenDummy +MissileTurretMengskACGluescreenDummy,MissileTurretMengskACGluescreenDummy +ArtilleryMengskACGluescreenDummy,ArtilleryMengskACGluescreenDummy +AccelerationZoneSmall,AccelerationZoneSmall +AccelerationZoneMedium,AccelerationZoneMedium +AccelerationZoneLarge,AccelerationZoneLarge +LoadOutSpray@1,LoadOutSpray@1 +LoadOutSpray@2,LoadOutSpray@2 +LoadOutSpray@3,LoadOutSpray@3 +LoadOutSpray@4,LoadOutSpray@4 +LoadOutSpray@5,LoadOutSpray@5 +LoadOutSpray@6,LoadOutSpray@6 +LoadOutSpray@7,LoadOutSpray@7 +LoadOutSpray@8,LoadOutSpray@8 +LoadOutSpray@9,LoadOutSpray@9 +LoadOutSpray@10,LoadOutSpray@10 +LoadOutSpray@11,LoadOutSpray@11 +LoadOutSpray@12,LoadOutSpray@12 +LoadOutSpray@13,LoadOutSpray@13 +LoadOutSpray@14,LoadOutSpray@14 +AccelerationZoneFlyingSmall,AccelerationZoneFlyingSmall +AccelerationZoneFlyingMedium,AccelerationZoneFlyingMedium +AccelerationZoneFlyingLarge,AccelerationZoneFlyingLarge +InhibitorZoneFlyingSmall,InhibitorZoneFlyingSmall +InhibitorZoneFlyingMedium,InhibitorZoneFlyingMedium +InhibitorZoneFlyingLarge,InhibitorZoneFlyingLarge diff --git a/sc2reader/decoders.py b/sc2reader/decoders.py index b2ff35f9..ed726356 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. @@ -20,7 +17,7 @@ class ByteDecoder(object): Used to unpack parse byte aligned files. """ - #: The Bytes object used internaly for reading from the + #: The Bytes object used internally for reading from the #: decoder contents. cStringIO is faster than managing our #: own string access in python. For PyPy installations a #: managed string implementation might be faster. @@ -31,10 +28,11 @@ class ByteDecoder(object): _contents = "" def __init__(self, contents, endian): - """ Accepts both strings and files implementing ``read()`` and + """ + Accepts both strings and files implementing ``read()`` and decodes them in the specified endian format. """ - if hasattr(contents, 'read'): + if hasattr(contents, "read"): self._contents = contents.read() else: self._contents = contents @@ -49,66 +47,91 @@ def __init__(self, contents, endian): # decode the endian value if necessary self.endian = endian.lower() - if self.endian.lower() == 'little': + if self.endian.lower() == "little": self.endian = "<" - elif self.endian.lower() == 'big': + elif self.endian.lower() == "big": self.endian = ">" - elif self.endian not in ('<', '>'): - raise ValueError("Endian must be one of 'little', '<', 'big', or '>' but was: "+self.endian) + elif self.endian not in ("<", ">"): + raise ValueError( + "Endian must be one of 'little', '<', 'big', or '>' but was: " + + self.endian + ) # Pre-compiling - self._unpack_int = struct.Struct(str(self.endian+'I')).unpack - self._unpack_short = struct.Struct(str(self.endian+'H')).unpack - self._unpack_longlong = struct.Struct(str(self.endian+'Q')).unpack - self._unpack_bytes = lambda bytes: bytes if self.endian == '>' else bytes[::-1] + self._unpack_int = struct.Struct(str(self.endian + "I")).unpack + self._unpack_short = struct.Struct(str(self.endian + "H")).unpack + self._unpack_longlong = struct.Struct(str(self.endian + "Q")).unpack + self._unpack_bytes = lambda bytes: bytes if self.endian == ">" else bytes[::-1] def done(self): - """ Returns true when all bytes have been decoded """ + """ + Returns true when all bytes have been decoded + """ return self.tell() == self.length def read_range(self, start, end): - """ Returns the raw byte string from the indicated address range """ + """ + Returns the raw byte string from the indicated address range + """ return self._contents[start:end] def peek(self, count): - """ Returns the raw byte string for the next ``count`` bytes """ + """ + Returns the raw byte string for the next ``count`` bytes + """ start = self.tell() - return self._contents[start:start+count] + return self._contents[start : start + count] def read_uint8(self): - """ Returns the next byte as an unsigned integer """ + """ + Returns the next byte as an unsigned integer + """ return ord(self.read(1)) def read_uint16(self): - """ Returns the next two bytes as an unsigned integer """ + """ + Returns the next two bytes as an unsigned integer + """ return self._unpack_short(self.read(2))[0] def read_uint32(self): - """ Returns the next four bytes as an unsigned integer """ + """ + Returns the next four bytes as an unsigned integer + """ return self._unpack_int(self.read(4))[0] def read_uint64(self): - """ Returns the next eight bytes as an unsigned integer """ + """ + Returns the next eight bytes as an unsigned integer + """ return self._unpack_longlong(self.read(8))[0] def read_bytes(self, count): - """ Returns the next ``count`` bytes as a byte string """ + """ + Returns the next ``count`` bytes as a byte string + """ return self._unpack_bytes(self.read(count)) def read_uint(self, count): - """ Returns the next ``count`` bytes as an unsigned integer """ - unpack = struct.Struct(str(self.endian+'B'*count)).unpack + """ + Returns the next ``count`` bytes as an unsigned integer + """ + unpack = struct.Struct(str(self.endian + "B" * count)).unpack uint = 0 for byte in unpack(self.read(count)): uint = uint << 8 | byte return uint - def read_string(self, count, encoding='utf8'): - """ Read a string in given encoding (default utf8) that is ``count`` bytes long """ + def read_string(self, count, encoding="utf8"): + """ + Read a string in given encoding (default utf8) that is ``count`` bytes long + """ return self.read_bytes(count).decode(encoding) - def read_cstring(self, encoding='utf8'): - """ Read a NULL byte terminated character string decoded with given encoding (default utf8). Ignores endian. """ + def read_cstring(self, encoding="utf8"): + """ + Read a NULL byte terminated character string decoded with given encoding (default utf8). Ignores endian. + """ cstring = BytesIO() while True: c = self.read(1) @@ -118,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 @@ -128,6 +151,7 @@ class BitPackedDecoder(object): bits and not in bytes. """ + #: The ByteDecoder used internally to read byte #: aligned values. _buffer = None @@ -153,7 +177,7 @@ class BitPackedDecoder(object): _bit_masks = list(zip(_lo_masks, _hi_masks)) def __init__(self, contents): - self._buffer = ByteDecoder(contents, endian='BIG') + self._buffer = ByteDecoder(contents, endian="BIG") # Partially expose the ByteBuffer interface self.length = self._buffer.length @@ -166,16 +190,22 @@ def __init__(self, contents): self.read_bool = functools.partial(self.read_bits, 1) def done(self): - """ Returns true when all bytes in the buffer have been used""" + """ + Returns true when all bytes in the buffer have been used + """ return self.tell() == self.length def byte_align(self): - """ Moves cursor to the beginning of the next byte """ + """ + Moves cursor to the beginning of the next byte + """ self._next_byte = None self._bit_shift = 0 def read_uint8(self): - """ Returns the next 8 bits as an unsigned integer """ + """ + Returns the next 8 bits as an unsigned integer + """ data = ord(self._buffer.read(1)) if self._bit_shift != 0: @@ -188,49 +218,57 @@ def read_uint8(self): return data def read_uint16(self): - """ Returns the next 16 bits as an unsigned integer """ + """ + Returns the next 16 bits as an unsigned integer + """ data = self._buffer.read_uint16() if self._bit_shift != 0: lo_mask, hi_mask = self._bit_masks[self._bit_shift] hi_bits = (self._next_byte & hi_mask) << 8 - mi_bits = (data & 0xFF00) >> (8-self._bit_shift) - lo_bits = (data & lo_mask) + mi_bits = (data & 0xFF00) >> (8 - self._bit_shift) + lo_bits = data & lo_mask self._next_byte = data & 0xFF data = hi_bits | mi_bits | lo_bits return data def read_uint32(self): - """ Returns the next 32 bits as an unsigned integer """ + """ + Returns the next 32 bits as an unsigned integer + """ data = self._buffer.read_uint32() if self._bit_shift != 0: lo_mask, hi_mask = self._bit_masks[self._bit_shift] hi_bits = (self._next_byte & hi_mask) << 24 - mi_bits = (data & 0xFFFFFF00) >> (8-self._bit_shift) - lo_bits = (data & lo_mask) + mi_bits = (data & 0xFFFFFF00) >> (8 - self._bit_shift) + lo_bits = data & lo_mask self._next_byte = data & 0xFF data = hi_bits | mi_bits | lo_bits return data def read_uint64(self): - """ Returns the next 64 bits as an unsigned integer """ + """Returns + the next 64 bits as an unsigned integer + """ data = self._buffer.read_uint64() if self._bit_shift != 0: lo_mask, hi_mask = self._bit_masks[self._bit_shift] hi_bits = (self._next_byte & hi_mask) << 56 - mi_bits = (data & 0xFFFFFFFFFFFFFF00) >> (8-self._bit_shift) - lo_bits = (data & lo_mask) + mi_bits = (data & 0xFFFFFFFFFFFFFF00) >> (8 - self._bit_shift) + lo_bits = data & lo_mask self._next_byte = data & 0xFF data = hi_bits | mi_bits | lo_bits return data def read_vint(self): - """ Reads a signed integer of variable length """ + """ + Reads a signed integer of variable length + """ byte = ord(self._buffer.read(1)) negative = byte & 0x01 result = (byte & 0x7F) >> 1 @@ -242,25 +280,33 @@ def read_vint(self): return -result if negative else result def read_aligned_bytes(self, count): - """ Skips to the beginning of the next byte and returns the next ``count`` bytes as a byte string """ + """ + Skips to the beginning of the next byte and returns the next ``count`` bytes as a byte string + """ self.byte_align() return self._buffer.read_bytes(count) - def read_aligned_string(self, count, encoding='utf8'): - """ Skips to the beginning of the next byte and returns the next ``count`` bytes decoded with encoding (default utf8) """ + def read_aligned_string(self, count, encoding="utf8"): + """ + Skips to the beginning of the next byte and returns the next ``count`` bytes decoded with encoding (default utf8) + """ self.byte_align() return self._buffer.read_string(count, encoding) def read_bytes(self, count): - """ Returns the next ``count*8`` bits as a byte string """ + """ + Returns the next ``count*8`` bits as a byte string + """ data = self._buffer.read_bytes(count) if self._bit_shift != 0: 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): - temp_buffer.write(struct.pack(str("B"), prev_byte & hi_mask | next_byte & lo_mask)) + for next_byte in struct.unpack("B" * count, data): + temp_buffer.write( + struct.pack("B", prev_byte & hi_mask | next_byte & lo_mask) + ) prev_byte = next_byte self._next_byte = prev_byte @@ -270,14 +316,16 @@ def read_bytes(self, count): return data def read_bits(self, count): - """ Returns the next ``count`` bits as an unsigned integer """ + """Returns + the next ``count`` bits as an unsigned integer + """ result = 0 bits = count bit_shift = self._bit_shift # If we've got a byte in progress use it first if bit_shift != 0: - bits_left = 8-bit_shift + bits_left = 8 - bit_shift if bits_left < bits: bits -= bits_left @@ -291,7 +339,7 @@ def read_bits(self, count): # Then grab any additional whole bytes as needed if bits >= 8: - bytes = int(bits/8) + bytes = int(bits / 8) if bytes == 1: bits -= 8 @@ -306,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 @@ -319,7 +367,9 @@ def read_bits(self, count): return result def read_frames(self): - """ Reads a frame count as an unsigned integer """ + """ + Reads a frame count as an unsigned integer + """ byte = self.read_uint8() time, additional_bytes = byte >> 2, byte & 0x03 if additional_bytes == 0: @@ -332,8 +382,9 @@ def read_frames(self): return time << 24 | self.read_uint16() << 8 | self.read_uint8() def read_struct(self, datatype=None): - """ Reads a nested data structure. If the type is not specified the - first byte is used as the type identifier. + """ + Reads a nested data structure. If the type is not specified + the first byte is used as the type identifier. """ self.byte_align() datatype = ord(self._buffer.read(1)) if datatype is None else datatype @@ -359,7 +410,7 @@ 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)) @@ -374,6 +425,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 cd72973c..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 @@ -15,6 +12,7 @@ def setGameEngine(engine): module.register_plugin = engine.register_plugin module.register_plugins = engine.register_plugins + _default_engine = GameEngine() _default_engine.register_plugin(plugins.GameHeartNormalizer()) _default_engine.register_plugin(plugins.ContextLoader()) diff --git a/sc2reader/engine/engine.py b/sc2reader/engine/engine.py index 65caced1..96b7f759 100644 --- a/sc2reader/engine/engine.py +++ b/sc2reader/engine/engine.py @@ -1,117 +1,123 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import collections -from sc2reader.events import * +from sc2reader.events import ( + CommandEvent, + ControlGroupEvent, + Event, + GameEvent, + MessageEvent, + TrackerEvent, +) from sc2reader.engine.events import InitGameEvent, EndGameEvent, PluginExit -class GameEngine(object): - """ GameEngine Specification - -------------------------- +class GameEngine: + """ + GameEngine Specification + -------------------------- - The game engine runs through all the events for a given replay in - chronological order. For each event, event handlers from registered - plugins are executed in order of plugin registration from most general - to most specific. + The game engine runs through all the events for a given replay in + chronological order. For each event, event handlers from registered + plugins are executed in order of plugin registration from most general + to most specific. - Example Usage:: + Example Usage:: - class Plugin1(): - def handleCommandEvent(self, event, replay): - pass + class Plugin1(): + def handleCommandEvent(self, event, replay): + pass - class Plugin2(): - def handleEvent(self, event, replay): - pass + class Plugin2(): + def handleEvent(self, event, replay): + pass - def handleTargetUnitCommandEvent(self, event, replay): - pass + def handleTargetUnitCommandEvent(self, event, replay): + pass - ... + ... - engine = GameEngine(plugins=[Plugin1(), Plugin2()], **options) - engine.register_plugins(Plugin3(), Plugin(4)) - engine.reigster_plugin(Plugin(5)) - engine.run(replay) + engine = GameEngine(plugins=[Plugin1(), Plugin2()], **options) + engine.register_plugins(Plugin3(), Plugin(4)) + engine.reigster_plugin(Plugin(5)) + engine.run(replay) - Calls functions in the following order for a ``TargetUnitCommandEvent``:: + Calls functions in the following order for a ``TargetUnitCommandEvent``:: - Plugin1.handleCommandEvent(event, replay) - Plugin2.handleEvent(event, replay) - Plugin2.handleTargetUnitCommandEvent(event, replay) + Plugin1.handleCommandEvent(event, replay) + Plugin2.handleEvent(event, replay) + Plugin2.handleTargetUnitCommandEvent(event, replay) - Plugin Specification - ------------------------- + Plugin Specification + ------------------------- - Plugins can opt in to handle events with methods in the format: + Plugins can opt in to handle events with methods in the format: - def handleEventName(self, event, replay) + def handleEventName(self, event, replay) - In addition to handling specific event types, plugins can also - handle events more generally by handling built-in parent classes - from the list below:: + In addition to handling specific event types, plugins can also + handle events more generally by handling built-in parent classes + from the list below:: - * handleEvent - called for every single event of all types - * handleMessageEvent - called for events in replay.message.events - * handleGameEvent - called for events in replay.game.events - * handleTrackerEvent - called for events in replay.tracker.events - * handleCommandEvent - called for all types of command events - * handleControlGroupEvent - called for all player control group events + * handleEvent - called for every single event of all types + * handleMessageEvent - called for events in replay.message.events + * handleGameEvent - called for events in replay.game.events + * handleTrackerEvent - called for events in replay.tracker.events + * handleCommandEvent - called for all types of command events + * handleControlGroupEvent - called for all player control group events - Plugins may also handle optional ``InitGame`` and ``EndGame`` events generated - by the GameEngine before and after processing all the events: + Plugins may also handle optional ``InitGame`` and ``EndGame`` events generated + by the GameEngine before and after processing all the events: - * handleInitGame - is called prior to processing a new replay to provide - an opportunity for the plugin to clear internal state and set up any - replay state necessary. + * handleInitGame - is called prior to processing a new replay to provide + an opportunity for the plugin to clear internal state and set up any + replay state necessary. - * handleEndGame - is called after all events have been processed and - can be used to perform post processing on aggrated data or clean up - intermediate data caches. + * handleEndGame - is called after all events have been processed and + can be used to perform post processing on aggregated data or clean up + intermediate data caches. - Event handlers can choose to ``yield`` additional events which will be injected - into the event stream directly after the event currently being processed. This - feature allows for message passing between plugins. An ExpansionTracker plugin - could notify all other plugins of a new ExpansionEvent that they could opt to - process:: + Event handlers can choose to ``yield`` additional events which will be injected + into the event stream directly after the event currently being processed. This + feature allows for message passing between plugins. An ExpansionTracker plugin + could notify all other plugins of a new ExpansionEvent that they could opt to + process:: - def handleUnitDoneEvent(self, event, replay): - if event.unit.name == 'Nexus': - yield ExpansionEvent(event.frame, event.unit) - .... + def handleUnitDoneEvent(self, event, replay): + if event.unit.name == 'Nexus': + yield ExpansionEvent(event.frame, event.unit) + .... - If a plugin wishes to stop processing a replay it can yield a PluginExit event before returning:: + If a plugin wishes to stop processing a replay it can yield a PluginExit event before returning:: - def handleEvent(self, event, replay): - if len(replay.tracker_events) == 0: - yield PluginExit(self, code=0, details=dict(msg="tracker events required")) - return - ... + def handleEvent(self, event, replay): + if len(replay.tracker_events) == 0: + yield PluginExit(self, code=0, details=dict(msg="tracker events required")) + return + ... - def handleCommandEvent(self, event, replay): - try: - possibly_throwing_error() - catch Error as e: - logger.error(e) - yield PluginExit(self, code=0, details=dict(msg="Unexpected exception")) + def handleCommandEvent(self, event, replay): + try: + possibly_throwing_error() + catch Error as e: + logger.error(e) + yield PluginExit(self, code=0, details=dict(msg="Unexpected exception")) - The GameEngine will intercept this event and remove the plugin from the list of - active plugins for this replay. The exit code and details will be available from the - replay:: + The GameEngine will intercept this event and remove the plugin from the list of + active plugins for this replay. The exit code and details will be available from the + replay:: - code, details = replay.plugins['MyPlugin'] + code, details = replay.plugins['MyPlugin'] - If your plugin depends on another plugin, it is a good idea to implement handlePluginExit - and be alerted if the plugin that you require fails. This way you can exit gracefully. You - can also check to see if the plugin name is in ``replay.plugin_failures``:: + If your plugin depends on another plugin, it is a good idea to implement handlePluginExit + and be alerted if the plugin that you require fails. This way you can exit gracefully. You + can also check to see if the plugin name is in ``replay.plugin_failures``:: - if 'RequiredPlugin' in replay.plugin_failures: - code, details = replay.plugins['RequiredPlugin'] - message = "RequiredPlugin failed with code: {0}. Cannot continue.".format(code) - yield PluginExit(self, code=1, details=dict(msg=message)) + if 'RequiredPlugin' in replay.plugin_failures: + code, details = replay.plugins['RequiredPlugin'] + message = "RequiredPlugin failed with code: {0}. Cannot continue.".format(code) + yield PluginExit(self, code=1, details=dict(msg=message)) """ + def __init__(self, plugins=[]): self._plugins = list() self.register_plugins(*plugins) @@ -124,7 +130,7 @@ def register_plugins(self, *plugins): self.register_plugin(plugin) def plugins(self): - return self._plugins + return self._plugins def run(self, replay): # A map of [event.name] => event handlers in plugin registration order @@ -152,7 +158,7 @@ def run(self, replay): while len(event_queue) > 0: event = event_queue.popleft() - if event.name == 'PluginExit': + if event.name == "PluginExit": # Remove the plugin and reset the handlers. plugins.remove(event.plugin) handlers.clear() @@ -174,18 +180,20 @@ def run(self, replay): new_events = collections.deque() for event_handler in event_handlers: try: - for new_event in (event_handler(event, replay) or []): - if new_event.name == 'PluginExit': + for new_event in event_handler(event, replay) or []: + if new_event.name == "PluginExit": new_events.append(new_event) break else: new_events.appendleft(new_event) except Exception as e: - if event_handler.__self__.name in ['ContextLoader']: + if event_handler.__self__.name in ["ContextLoader"]: # Certain built in plugins should probably still cause total failure raise # Maybe?? else: - new_event = PluginExit(event_handler.__self__, code=1, details=dict(error=e)) + new_event = PluginExit( + event_handler.__self__, code=1, details=dict(error=e) + ) new_events.append(new_event) event_queue.extendleft(new_events) @@ -195,22 +203,26 @@ def run(self, replay): replay.plugin_result[plugin.name] = (0, dict()) def _get_event_handlers(self, event, plugins): - return sum([self._get_plugin_event_handlers(plugin, event) for plugin in plugins], []) + return sum( + (self._get_plugin_event_handlers(plugin, event) for plugin in plugins), [] + ) def _get_plugin_event_handlers(self, plugin, event): handlers = list() - if isinstance(event, Event) and hasattr(plugin, 'handleEvent'): - handlers.append(getattr(plugin, 'handleEvent', None)) - if isinstance(event, MessageEvent) and hasattr(plugin, 'handleMessageEvent'): - handlers.append(getattr(plugin, 'handleMessageEvent', None)) - if isinstance(event, GameEvent) and hasattr(plugin, 'handleGameEvent'): - handlers.append(getattr(plugin, 'handleGameEvent', None)) - if isinstance(event, TrackerEvent) and hasattr(plugin, 'handleTrackerEvent'): - handlers.append(getattr(plugin, 'handleTrackerEvent', None)) - if isinstance(event, CommandEvent) and hasattr(plugin, 'handleCommandEvent'): - handlers.append(getattr(plugin, 'handleCommandEvent', None)) - if isinstance(event, ControlGroupEvent) and hasattr(plugin, 'handleControlGroupEvent'): - handlers.append(getattr(plugin, 'handleControlGroupEvent', None)) - if hasattr(plugin, 'handle'+event.name): - handlers.append(getattr(plugin, 'handle'+event.name, None)) + if isinstance(event, Event) and hasattr(plugin, "handleEvent"): + handlers.append(getattr(plugin, "handleEvent", None)) + if isinstance(event, MessageEvent) and hasattr(plugin, "handleMessageEvent"): + handlers.append(getattr(plugin, "handleMessageEvent", None)) + if isinstance(event, GameEvent) and hasattr(plugin, "handleGameEvent"): + handlers.append(getattr(plugin, "handleGameEvent", None)) + if isinstance(event, TrackerEvent) and hasattr(plugin, "handleTrackerEvent"): + handlers.append(getattr(plugin, "handleTrackerEvent", None)) + if isinstance(event, CommandEvent) and hasattr(plugin, "handleCommandEvent"): + handlers.append(getattr(plugin, "handleCommandEvent", None)) + if isinstance(event, ControlGroupEvent) and hasattr( + plugin, "handleControlGroupEvent" + ): + handlers.append(getattr(plugin, "handleControlGroupEvent", None)) + if hasattr(plugin, "handle" + event.name): + handlers.append(getattr(plugin, "handle" + event.name, None)) return handlers diff --git a/sc2reader/engine/events.py b/sc2reader/engine/events.py index 44387e52..fc6d4728 100644 --- a/sc2reader/engine/events.py +++ b/sc2reader/engine/events.py @@ -1,17 +1,13 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division +class InitGameEvent: + name = "InitGame" -class InitGameEvent(object): - name = 'InitGame' +class EndGameEvent: + name = "EndGame" -class EndGameEvent(object): - name = 'EndGame' - - -class PluginExit(object): - name = 'PluginExit' +class PluginExit: + name = "PluginExit" def __init__(self, plugin, code=0, details=None): self.plugin = plugin diff --git a/sc2reader/engine/plugins/__init__.py b/sc2reader/engine/plugins/__init__.py index 15e77ff3..ca62c70c 100644 --- a/sc2reader/engine/plugins/__init__.py +++ b/sc2reader/engine/plugins/__init__.py @@ -1,10 +1,6 @@ -# -*- 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 from sc2reader.engine.plugins.supply import SupplyTracker from sc2reader.engine.plugins.creeptracker import CreepTracker from sc2reader.engine.plugins.gameheart import GameHeartNormalizer - diff --git a/sc2reader/engine/plugins/apm.py b/sc2reader/engine/plugins/apm.py index 526bf028..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. @@ -15,7 +12,8 @@ class APMTracker(object): APM is 0 for games under 1 minute in length. """ - name = 'APMTracker' + + name = "APMTracker" def handleInitGame(self, event, replay): for human in replay.humans: @@ -25,15 +23,15 @@ def handleInitGame(self, event, replay): def handleControlGroupEvent(self, event, replay): event.player.aps[event.second] += 1.4 - event.player.apm[int(event.second/60)] += 1.4 + event.player.apm[int(event.second / 60)] += 1.4 def handleSelectionEvent(self, event, replay): event.player.aps[event.second] += 1.4 - event.player.apm[int(event.second/60)] += 1.4 + event.player.apm[int(event.second / 60)] += 1.4 def handleCommandEvent(self, event, replay): event.player.aps[event.second] += 1.4 - event.player.apm[int(event.second/60)] += 1.4 + event.player.apm[int(event.second / 60)] += 1.4 def handlePlayerLeaveEvent(self, event, replay): event.player.seconds_played = event.second @@ -41,6 +39,8 @@ def handlePlayerLeaveEvent(self, event, replay): def handleEndGame(self, event, replay): for human in replay.humans: if len(human.apm.keys()) > 0: - human.avg_apm = sum(human.aps.values())/float(human.seconds_played)*60 + human.avg_apm = ( + sum(human.aps.values()) / float(human.seconds_played) * 60 + ) else: human.avg_apm = 0 diff --git a/sc2reader/engine/plugins/context.py b/sc2reader/engine/plugins/context.py index 6b5362bc..38f8b3d2 100644 --- a/sc2reader/engine/plugins/context.py +++ b/sc2reader/engine/plugins/context.py @@ -1,14 +1,12 @@ -# -*- 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): - name = 'ContextLoader' +class ContextLoader: + name = "ContextLoader" def handleInitGame(self, event, replay): replay.units = set() @@ -32,17 +30,21 @@ def handleCommandEvent(self, event, replay): if event.player.pid in self.last_target_ability_event: del self.last_target_ability_event[event.player.pid] - if not getattr(replay, 'marked_error', None): + if not getattr(replay, "marked_error", None): replay.marked_error = True event.logger.error(replay.filename) event.logger.error("Release String: " + replay.release_string) for player in replay.players: try: - event.logger.error("\t"+unicode(player).encode('ascii', 'ignore')) + event.logger.error( + "\t" + unicode(player).encode("ascii", "ignore") + ) except NameError: # unicode() is not defined in Python 3 - event.logger.error("\t"+player.__str__()) + event.logger.error("\t" + player.__str__()) - self.logger.error("{0}\t{1}\tMissing ability {2:X} from {3}".format(event.frame, event.player.name, event.ability_id, replay.datapack.__class__.__name__)) + self.logger.error( + f"{event.frame}\t{event.player.name}\tMissing ability {event.ability_id:X} from {replay.datapack.__class__.__name__}" + ) else: event.ability = replay.datapack.abilities[event.ability_id] @@ -51,7 +53,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 @@ -61,13 +63,19 @@ def handleTargetUnitCommandEvent(self, event, replay): if event.target_unit_id in replay.objects: event.target = replay.objects[event.target_unit_id] - if not replay.tracker_events and not event.target.is_type(event.target_unit_type): - replay.datapack.change_type(event.target, event.target_unit_type, event.frame) + if not replay.tracker_events and not event.target.is_type( + event.target_unit_type + ): + replay.datapack.change_type( + event.target, event.target_unit_type, event.frame + ) else: # Often when the target_unit_id is not in replay.objects it is 0 because it # is a target building/destructable hidden by fog of war. Perhaps we can match # it through the fog using location? - unit = replay.datapack.create_unit(event.target_unit_id, event.target_unit_type, event.frame) + unit = replay.datapack.create_unit( + event.target_unit_id, event.target_unit_type, event.frame + ) event.target = unit replay.objects[event.target_unit_id] = unit @@ -78,7 +86,9 @@ def handleUpdateTargetUnitCommandEvent(self, event, replay): if event.player.pid in self.last_target_ability_event: # store corresponding TargetUnitCommandEvent data in this event # currently using for *MacroTracker only, so only need ability name - event.ability_name = self.last_target_ability_event[event.player.pid].ability_name + event.ability_name = self.last_target_ability_event[ + event.player.pid + ].ability_name self.handleTargetUnitCommandEvent(event, replay) @@ -88,14 +98,23 @@ def handleSelectionEvent(self, event, replay): units = list() # TODO: Blizzard calls these subgroup flags but that doesn't make sense right now - for (unit_id, unit_type, subgroup_flags, intra_subgroup_flags) in event.new_unit_info: + for ( + unit_id, + unit_type, + subgroup_flags, + intra_subgroup_flags, + ) in event.new_unit_info: # If we don't have access to tracker events, use selection events to create # new units and track unit type changes. It won't be perfect, but it is better # than nothing. if not replay.tracker_events: # Starting at 23925 the default viking mode is assault. Most people expect # the default viking mode to be figher so fudge it a bit here. - if replay.versions[1] == 2 and replay.build >= 23925 and unit_type == 71: + if ( + replay.versions[1] == 2 + and replay.build >= 23925 + and unit_type == 71 + ): unit_type = 72 if unit_id in replay.objects: @@ -109,13 +128,12 @@ def handleSelectionEvent(self, event, replay): # If we have tracker events, the unit must already exist and must already # have the correct unit type. elif unit_id in replay.objects: - unit = replay.objects[unit_id] + unit = replay.objects[unit_id] # Except when it doesn't. else: - unit = replay.datapack.create_unit(unit_id, unit_type, event.frame) - replay.objects[unit_id] = unit - + unit = replay.datapack.create_unit(unit_id, unit_type, event.frame) + replay.objects[unit_id] = unit # Selection events hold flags on units (like hallucination) unit.apply_flags(intra_subgroup_flags) @@ -126,7 +144,7 @@ def handleSelectionEvent(self, event, replay): def handleResourceTradeEvent(self, event, replay): event.sender = event.player - event.recipient = replay.players[event.recipient_id] + event.recipient = replay.player[event.recipient_id] def handleHijackReplayGameEvent(self, event, replay): replay.resume_from_replay = True @@ -148,7 +166,9 @@ def handleUnitBornEvent(self, event, replay): event.unit = replay.objects[event.unit_id] else: # TODO: How to tell if something is hallucination? - event.unit = replay.datapack.create_unit(event.unit_id, event.unit_type_name, event.frame) + event.unit = replay.datapack.create_unit( + event.unit_id, event.unit_type_name, event.frame + ) replay.objects[event.unit_id] = event.unit replay.active_units[event.unit_id_index] = event.unit @@ -171,9 +191,13 @@ def handleUnitDiedEvent(self, event, replay): if event.unit_id_index in replay.active_units: 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(event.killer_pid, Length(seconds=event.second), event.frame)) + self.logger.error( + f"Unable to delete unit index {event.unit_id_index} at {Length(seconds=event.second)} [{event.frame}], index not active." + ) else: - self.logger.error("Unit {0} died at {1} [{2}] before it was born!".format(event.unit_id, Length(seconds=event.second), event.frame)) + self.logger.error( + f"Unit {event.unit_id} died at {Length(seconds=event.second)} [{event.frame}] before it was born!" + ) if event.killing_player_id in replay.player: event.killing_player = event.killer = replay.player[event.killing_player_id] @@ -181,7 +205,9 @@ def handleUnitDiedEvent(self, event, replay): event.unit.killing_player = event.unit.killed_by = event.killing_player 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(event.killing_player_id, Length(seconds=event.second), event.frame)) + self.logger.error( + f"Unknown killing player id {event.killing_player_id} at {Length(seconds=event.second)} [{event.frame}]" + ) if event.killing_unit_id in replay.objects: event.killing_unit = replay.objects[event.killing_unit_id] @@ -189,7 +215,9 @@ def handleUnitDiedEvent(self, event, replay): event.unit.killing_unit = event.killing_unit 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(event.killing_unit_id, Length(seconds=event.second), event.frame)) + self.logger.error( + f"Unknown killing unit id {event.killing_unit_id} at {Length(seconds=event.second)} [{event.frame}]" + ) def handleUnitOwnerChangeEvent(self, event, replay): self.load_tracker_controller(event, replay) @@ -201,9 +229,11 @@ def handleUnitOwnerChangeEvent(self, event, replay): if event.unit_id in replay.objects: event.unit = replay.objects[event.unit_id] else: - self.logger.error("Unit {0} owner changed at {1} [{2}] before it was born!".format(event.unit_id, Length(seconds=event.second), event.frame)) + self.logger.error( + f"Unit {event.unit_id} owner changed at {Length(seconds=event.second)} [{event.frame}] before it was born!" + ) - if event.unit_upkeeper: + if event.unit_upkeeper and event.unit: if event.unit.owner: event.unit.owner.units.remove(event.unit) event.unit.owner = event.unit_upkeeper @@ -217,7 +247,9 @@ def handleUnitTypeChangeEvent(self, event, replay): event.unit = replay.objects[event.unit_id] 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(event.unit_id, Length(seconds=event.second))) + self.logger.error( + f"Unit {event.unit_id} type changed at {Length(seconds=event.second)} before it was born!" + ) def handleUpgradeCompleteEvent(self, event, replay): self.load_tracker_player(event, replay) @@ -235,7 +267,9 @@ def handleUnitInitEvent(self, event, replay): event.unit = replay.objects[event.unit_id] else: # TODO: How to tell if something is hallucination? - event.unit = replay.datapack.create_unit(event.unit_id, event.unit_type_name, event.frame) + event.unit = replay.datapack.create_unit( + event.unit_id, event.unit_type_name, event.frame + ) replay.objects[event.unit_id] = event.unit replay.active_units[event.unit_id_index] = event.unit @@ -254,7 +288,9 @@ def handleUnitDoneEvent(self, event, replay): event.unit = replay.objects[event.unit_id] event.unit.finished_at = event.frame else: - self.logger.error("Unit {0} done at {1} [{2}] before it was started!".format(event.killer_pid, Length(seconds=event.second), event.frame)) + self.logger.error( + f"Unit {event.unit_id} done at {Length(seconds=event.second)} [{event.frame}] before it was started!" + ) def handleUnitPositionsEvent(self, event, replay): if not replay.datapack: @@ -266,15 +302,21 @@ def handleUnitPositionsEvent(self, event, replay): unit.location = (x, y) 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(event.killer_pid, Length(seconds=event.second), event.frame)) + self.logger.error( + f"Unit at active_unit index {unit_index} moved at {Length(seconds=event.second)} [{event.frame}] but it doesn't exist!" + ) def load_message_game_player(self, event, replay): - if replay.versions[1] == 1 or (replay.versions[1] == 2 and replay.build < 24247): + if replay.versions[1] == 1 or ( + replay.versions[1] == 2 and replay.build < 24247 + ): if event.pid in replay.entity: event.player = replay.entity[event.pid] event.player.events.append(event) elif event.pid != 16: - self.logger.error("Bad pid ({0}) for event {1} at {2} [{3}].".format(event.pid, event.__class__, Length(seconds=event.second), event.frame)) + self.logger.error( + f"Bad pid ({event.pid}) for event {event.__class__} at {Length(seconds=event.second)} [{event.frame}]." + ) else: pass # This is a global event @@ -283,7 +325,9 @@ def load_message_game_player(self, event, replay): event.player = replay.human[event.pid] event.player.events.append(event) elif event.pid != 16: - self.logger.error("Bad pid ({0}) for event {1} at {2} [{3}].".format(event.pid, event.__class__, Length(seconds=event.second), event.frame)) + self.logger.error( + f"Bad pid ({event.pid}) for event {event.__class__} at {Length(seconds=event.second)} [{event.frame}]." + ) else: pass # This is a global event @@ -291,16 +335,22 @@ def load_tracker_player(self, event, replay): if event.pid in replay.entity: event.player = replay.entity[event.pid] else: - self.logger.error("Bad pid ({0}) for event {1} at {2} [{3}].".format(event.pid, event.__class__, Length(seconds=event.second), event.frame)) + self.logger.error( + f"Bad pid ({event.pid}) for event {event.__class__} at {Length(seconds=event.second)} [{event.frame}]." + ) def load_tracker_upkeeper(self, event, replay): if event.upkeep_pid in replay.entity: 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(event.upkeep_pid, event.__class__, Length(seconds=event.second), event.frame)) + self.logger.error( + f"Bad upkeep_pid ({event.upkeep_pid}) for event {event.__class__} at {Length(seconds=event.second)} [{event.frame}]." + ) def load_tracker_controller(self, event, replay): if event.control_pid in replay.entity: 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(event.control_pid, event.__class__, Length(seconds=event.second), event.frame)) + self.logger.error( + f"Bad control_pid ({event.control_pid}) for event {event.__class__} at {Length(seconds=event.second)} [{event.frame}]." + ) diff --git a/sc2reader/engine/plugins/creeptracker.py b/sc2reader/engine/plugins/creeptracker.py index 7f35f868..7125924d 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: @@ -20,82 +17,97 @@ from collections import defaultdict 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 This uses the creep_tracker class to calculate the features - ''' - name = 'CreepTracker' + """ + + name = "CreepTracker" def handleInitGame(self, event, replay): - try: - if len( replay.tracker_events) ==0 : - return - if replay.map is None: - replay.load_map() - self.creepTracker = creep_tracker(replay) - for player in replay.players: - if player.play_race[0] == 'Z': - self.creepTracker.init_cgu_lists(player.pid) - except Exception as e: - print("Whoa! {}".format(e)) - pass + try: + if len(replay.tracker_events) == 0: + return + if replay.map is None: + replay.load_map() + self.creepTracker = creep_tracker(replay) + for player in replay.players: + if player.play_race[0] == "Z": + self.creepTracker.init_cgu_lists(player.pid) + except Exception as 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)) - pass - + try: + self.creepTracker.remove_from_list(event.unit_id, event.second) + except Exception as e: + print(f"Whoa! {e}") + pass - def handleUnitInitEvent(self,event,replay): - try: - if event.unit_type_name in ["CreepTumor", "Hatchery","NydusCanal"] : - self.creepTracker.add_to_list(event.control_pid,event.unit_id,\ - (event.x, event.y), event.unit_type_name,event.second) - except Exception as e: - print("Whoa! {}".format(e)) - pass + def handleUnitInitEvent(self, event, replay): + try: + if event.unit_type_name in ["CreepTumor", "Hatchery", "NydusCanal"]: + self.creepTracker.add_to_list( + event.control_pid, + event.unit_id, + (event.x, event.y), + event.unit_type_name, + event.second, + ) + except Exception as e: + print(f"Whoa! {e}") + pass - def handleUnitBornEvent(self,event,replay): - try: - if event.unit_type_name== "Hatchery": - self.creepTracker.add_to_list(event.control_pid, event.unit_id,\ - (event.x,event.y),event.unit_type_name,event.second) - except Exception as e: - print("Whoa! {}".format(e)) - pass + def handleUnitBornEvent(self, event, replay): + try: + if event.unit_type_name == "Hatchery": + self.creepTracker.add_to_list( + event.control_pid, + event.unit_id, + (event.x, event.y), + event.unit_type_name, + event.second, + ) + except Exception as e: + print(f"Whoa! {e}") + pass def handleEndGame(self, event, replay): - try: - if len( replay.tracker_events) ==0 : - return - for player in replay.players: - if player.play_race[0] == 'Z': - self.creepTracker.reduce_cgu_per_minute(player.pid) - player.creep_spread_by_minute = self.creepTracker.get_creep_spread_area(player.pid) - # note that player.max_creep_spread may be a tuple or an int - if player.creep_spread_by_minute: - player.max_creep_spread = max(player.creep_spread_by_minute.items(),key=lambda x:x[1]) - else: - ## 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)) - pass + try: + if len(replay.tracker_events) == 0: + return + for player in replay.players: + if player.play_race[0] == "Z": + self.creepTracker.reduce_cgu_per_minute(player.pid) + player.creep_spread_by_minute = ( + self.creepTracker.get_creep_spread_area(player.pid) + ) + # note that player.max_creep_spread may be a tuple or an int + if player.creep_spread_by_minute: + player.max_creep_spread = max( + player.creep_spread_by_minute.items(), key=lambda x: x[1] + ) + else: + ## Else statement is for players with no creep spread(ie: not Zerg) + player.max_creep_spread = 0 + except Exception as e: + print(f"Whoa! {e}") + pass ## The class used to used to calculate the creep spread -class creep_tracker(): - def __init__(self,replay): - #if the debug option is selected, minimaps will be printed to a file +class creep_tracker: + def __init__(self, replay): + # if the debug option is selected, minimaps will be printed to a file ##and a stringIO containing the minimap image will be saved for - ##every minite in the game and the minimap with creep highlighted + ##every minute in the game and the minimap with creep highlighted ## will be printed out. - self.debug = replay.opt['debug'] + self.debug = replay.opt["debug"] ##This list contains creep spread area for each player self.creep_spread_by_minute = dict() ## this list contains a minimap highlighted with creep spread for each player @@ -103,63 +115,64 @@ def __init__(self,replay): self.creep_spread_image_by_minute = dict() ## This list contains all the active cgus in every time frame self.creep_gen_units = dict() - ## Thist list corresponds to creep_gen_units storing the time of each CGU - self.creep_gen_units_times= dict() + ## This list corresponds to creep_gen_units storing the time of each CGU + self.creep_gen_units_times = dict() ## convert all possible cgu radii into a sets of coordinates centred around the origin, ## in order to use this with the CGUs, the centre point will be ## subtracted with coordinates of cgus created in game - self.unit_name_to_radius={'CreepTumor': 10,"Hatchery":8,"NydusCanal": 5} - self.radius_to_coordinates= dict() + self.unit_name_to_radius = {"CreepTumor": 10, "Hatchery": 8, "NydusCanal": 5} + self.radius_to_coordinates = dict() for x in self.unit_name_to_radius: - self.radius_to_coordinates[self.unit_name_to_radius[x]] =\ - self.radius_to_map_positions(self.unit_name_to_radius[x]) - #Get map information + self.radius_to_coordinates[self.unit_name_to_radius[x]] = ( + self.radius_to_map_positions(self.unit_name_to_radius[x]) + ) + # Get map information replayMap = replay.map # extract image from replay package mapsio = BytesIO(replayMap.minimap) im = PIL_open(mapsio) ##remove black box around minimap -# https://github.com/jonomon/sc2reader/commit/2a793475c0358989e7fda4a75642035a810e2274 -# cropped = im.crop(im.getbbox()) -# cropsize = cropped.size + # https://github.com/jonomon/sc2reader/commit/2a793475c0358989e7fda4a75642035a810e2274 + # cropped = im.crop(im.getbbox()) + # cropsize = cropped.size cropsizeX = replay.map.map_info.camera_right - replay.map.map_info.camera_left cropsizeY = replay.map.map_info.camera_top - replay.map.map_info.camera_bottom - cropsize = (cropsizeX,cropsizeY) + cropsize = (cropsizeX, cropsizeY) self.map_height = 100.0 # resize height to MAPHEIGHT, and compute new width that # would preserve aspect ratio self.map_width = int(cropsize[0] * (float(self.map_height) / cropsize[1])) - self.mapSize =self.map_height * self.map_width + self.mapSize = self.map_height * self.map_width ## the following parameters are only needed if minimaps have to be printed -# minimapSize = ( self.map_width,int(self.map_height) ) -# self.minimap_image = cropped.resize(minimapSize, ANTIALIAS) + # minimapSize = ( self.map_width,int(self.map_height) ) + # self.minimap_image = cropped.resize(minimapSize, ANTIALIAS) - mapOffsetX= replayMap.map_info.camera_left + mapOffsetX = replayMap.map_info.camera_left mapOffsetY = replayMap.map_info.camera_bottom - mapCenter = [mapOffsetX+ cropsize[0]/2.0, mapOffsetY + cropsize[1]/2.0] + mapCenter = [mapOffsetX + cropsize[0] / 2.0, mapOffsetY + cropsize[1] / 2.0] # this is the center of the minimap image, in pixel coordinates - imageCenter = [(self.map_width/2), self.map_height/2] + imageCenter = [(self.map_width / 2), self.map_height / 2] # this is the scaling factor to go from the SC2 coordinate # system to pixel coordinates self.image_scale = float(self.map_height) / cropsize[1] - self.transX =imageCenter[0] + self.image_scale * (mapCenter[0]) + self.transX = imageCenter[0] + self.image_scale * (mapCenter[0]) self.transY = imageCenter[1] + self.image_scale * (mapCenter[1]) - def radius_to_map_positions(self,radius): + def radius_to_map_positions(self, radius): ## this function converts all radius into map coordinates ## centred around the origin that the creep can exist ## the cgu_radius_to_map_position function will simply - ## substract every coordinate with the centre point of the tumour + ## subtract every coordinate with the centre point of the tumour output_coordinates = list() # Sample a square area using the radius - for x in range (-radius,radius): - for y in range (-radius, radius): + for x in range(-radius, radius): + for y in range(-radius, radius): if (x**2 + y**2) <= (radius * radius): - output_coordinates.append((x,y)) + output_coordinates.append((x, y)) return output_coordinates def init_cgu_lists(self, player_id): @@ -169,139 +182,155 @@ def init_cgu_lists(self, player_id): self.creep_gen_units[player_id] = list() self.creep_gen_units_times[player_id] = list() - def add_to_list(self,player_id,unit_id,unit_location,unit_type,event_time): - # This functions adds a new time frame to creep_generating_units_list - # Each time frame contains a list of all CGUs that are alive + def add_to_list(self, player_id, unit_id, unit_location, unit_type, event_time): + # This functions adds a new time frame to creep_generating_units_list + # Each time frame contains a list of all CGUs that are alive length_cgu_list = len(self.creep_gen_units[player_id]) - if length_cgu_list==0: - self.creep_gen_units[player_id].append([(unit_id, unit_location,unit_type)]) + if length_cgu_list == 0: + self.creep_gen_units[player_id].append( + [(unit_id, unit_location, unit_type)] + ) self.creep_gen_units_times[player_id].append(event_time) else: - #if the list is not empty, take the previous time frame, + # if the list is not empty, take the previous time frame, # add the new CGU to it and append it as a new time frame - previous_list = self.creep_gen_units[player_id][length_cgu_list-1][:] - previous_list.append((unit_id, unit_location,unit_type)) + previous_list = self.creep_gen_units[player_id][length_cgu_list - 1][:] + previous_list.append((unit_id, unit_location, unit_type)) self.creep_gen_units[player_id].append(previous_list) self.creep_gen_units_times[player_id].append(event_time) - def remove_from_list(self,unit_id,time_frame): + def remove_from_list(self, unit_id, time_frame): ## This function searches is given a unit ID for every unit who died ## the unit id will be searched in cgu_gen_units for matches ## if there are any, that unit will be removed from active CGUs ## and appended as a new time frame for player_id in self.creep_gen_units: length_cgu_list = len(self.creep_gen_units[player_id]) - if length_cgu_list ==0: - break - cgu_per_player = self.creep_gen_units[player_id] [length_cgu_list-1] - creep_generating_died =filter(lambda x:x[0]==unit_id,cgu_per_player) + if length_cgu_list == 0: + break + cgu_per_player = self.creep_gen_units[player_id][length_cgu_list - 1] + creep_generating_died = filter(lambda x: x[0] == unit_id, cgu_per_player) for creep_generating_died_unit in creep_generating_died: - new_cgu_per_player = list(filter(lambda x:x != creep_generating_died_unit, cgu_per_player )) + new_cgu_per_player = list( + filter(lambda x: x != creep_generating_died_unit, cgu_per_player) + ) self.creep_gen_units[player_id].append(new_cgu_per_player) self.creep_gen_units_times[player_id].append(time_frame) - def cgu_gen_times_to_chunks(self,cgu_time_list): + def cgu_gen_times_to_chunks(self, cgu_time_list): ## this function returns the index and value of every cgu time maximum_cgu_time = max(cgu_time_list) for i in range(0, maximum_cgu_time): - a = list(filter(lambda x_y: x_y[1]//60==i , enumerate(cgu_time_list))) - if len(a)>0: + a = list(filter(lambda x_y: x_y[1] // 60 == i, enumerate(cgu_time_list))) + if len(a) > 0: yield a - def cgu_in_min_to_cgu_units(self,player_id,cgu_in_minutes): - ## this function takes index and value of CGU times and returns - ## the cgu units with the maximum length + def cgu_in_min_to_cgu_units(self, player_id, cgu_in_minutes): + ## this function takes index and value of CGU times and returns + ## the cgu units with the maximum length for cgu_per_minute in cgu_in_minutes: - indexes = map(lambda x:x[0], cgu_per_minute) + indexes = (x[0] for x in cgu_per_minute) cgu_units = list() for index in indexes: cgu_units.append(self.creep_gen_units[player_id][index]) - cgu_max_in_minute = max(cgu_units,key = len) + cgu_max_in_minute = max(cgu_units, key=len) yield cgu_max_in_minute - def reduce_cgu_per_minute(self,player_id): - #the creep_gen_units_lists contains every single time frame - #where a CGU is added, - #To reduce the calculations required, the time frame containing - #the most cgus every minute will be used to represent that minute - cgu_per_minute1, cgu_per_minute2 = tee (self.cgu_gen_times_to_chunks(self.creep_gen_units_times[player_id])) - cgu_unit_max_per_minute = self.cgu_in_min_to_cgu_units(player_id,cgu_per_minute1) - minutes = map(lambda x:int(x[0][1]//60)*60, cgu_per_minute2) - self.creep_gen_units[player_id] = list(cgu_unit_max_per_minute) - self.creep_gen_units_times[player_id] = list(minutes) + def reduce_cgu_per_minute(self, player_id): + # the creep_gen_units_lists contains every single time frame + # where a CGU is added, + # To reduce the calculations required, the time frame containing + # the most cgus every minute will be used to represent that minute + cgu_per_minute1, cgu_per_minute2 = tee( + self.cgu_gen_times_to_chunks(self.creep_gen_units_times[player_id]) + ) + cgu_unit_max_per_minute = self.cgu_in_min_to_cgu_units( + player_id, cgu_per_minute1 + ) + minutes = (int(x[0][1] // 60) * 60 for x in cgu_per_minute2) + self.creep_gen_units[player_id] = list(cgu_unit_max_per_minute) + self.creep_gen_units_times[player_id] = list(minutes) - def get_creep_spread_area(self,player_id): + def get_creep_spread_area(self, player_id): ## iterates through all cgus and and calculate the area - for index,cgu_per_player in enumerate(self.creep_gen_units[player_id]): + for index, cgu_per_player in enumerate(self.creep_gen_units[player_id]): # convert cgu list into centre of circles and radius - cgu_radius = map(lambda x: (x[1], self.unit_name_to_radius[x[2]]),\ - cgu_per_player) + cgu_radius = ( + (x[1], self.unit_name_to_radius[x[2]]) for x in cgu_per_player + ) # convert event coords to minimap coords cgu_radius = self.convert_cgu_radius_event_to_map_coord(cgu_radius) - creep_area_positions = self.cgu_radius_to_map_positions(cgu_radius,self.radius_to_coordinates) + creep_area_positions = self.cgu_radius_to_map_positions( + cgu_radius, self.radius_to_coordinates + ) cgu_event_time = self.creep_gen_units_times[player_id][index] - cgu_event_time_str=str(int(cgu_event_time//60))+":"+str(cgu_event_time%60) + cgu_event_time_str = ( + str(int(cgu_event_time // 60)) + ":" + str(cgu_event_time % 60) + ) if self.debug: - self.print_image(creep_area_positions,player_id,cgu_event_time_str) + self.print_image(creep_area_positions, player_id, cgu_event_time_str) creep_area = len(creep_area_positions) - self.creep_spread_by_minute[player_id][cgu_event_time]=\ - float(creep_area)/self.mapSize*100 + self.creep_spread_by_minute[player_id][cgu_event_time] = ( + float(creep_area) / self.mapSize * 100 + ) return self.creep_spread_by_minute[player_id] - def cgu_radius_to_map_positions(self,cgu_radius,radius_to_coordinates): - ## This function uses the output of radius_to_map_positions + def cgu_radius_to_map_positions(self, cgu_radius, radius_to_coordinates): + ## This function uses the output of radius_to_map_positions total_points_on_map = Set() - if len(cgu_radius)==0: + if len(cgu_radius) == 0: return [] for cgu in cgu_radius: point = cgu[0] radius = cgu[1] ## subtract all radius_to_coordinates with centre of ## cgu radius to change centre of circle - cgu_map_position = map( lambda x:(x[0]+point[0],x[1]+point[1])\ - ,self.radius_to_coordinates[radius]) - total_points_on_map= total_points_on_map | Set(cgu_map_position) + cgu_map_position = ( + (x[0] + point[0], x[1] + point[1]) + for x in self.radius_to_coordinates[radius] + ) + total_points_on_map = total_points_on_map | Set(cgu_map_position) return total_points_on_map - def print_image(self,total_points_on_map,player_id,time_stamp): + def print_image(self, total_points_on_map, player_id, time_stamp): minimap_copy = self.minimap_image.copy() # Convert all creeped points to white for points in total_points_on_map: x = points[0] y = points[1] - x,y = self.check_image_pixel_within_boundary(x,y) - minimap_copy.putpixel((x,y) , (255, 255, 255)) + x, y = self.check_image_pixel_within_boundary(x, y) + minimap_copy.putpixel((x, y), (255, 255, 255)) creeped_image = minimap_copy # write creeped minimap image to a string as a png creeped_imageIO = StringIO() creeped_image.save(creeped_imageIO, "png") - self.creep_spread_image_by_minute[player_id][time_stamp]=creeped_imageIO + self.creep_spread_image_by_minute[player_id][time_stamp] = creeped_imageIO ##debug for print out the images - f = open(str(player_id)+'image'+time_stamp+'.png','w') + f = open(str(player_id) + "image" + time_stamp + ".png", "w") f.write(creeped_imageIO.getvalue()) creeped_imageIO.close() f.close() - def check_image_pixel_within_boundary(self,pointX, pointY): - pointX = 0 if pointX <0 else pointX - pointY=0 if pointY <0 else pointY + def check_image_pixel_within_boundary(self, pointX, pointY): + pointX = 0 if pointX < 0 else pointX + pointY = 0 if pointY < 0 else pointY # put a minus 1 to make sure the pixel is not directly on the edge - pointX = int(self.map_width-1 if pointX >= self.map_width else pointX) - pointY = int(self.map_height-1 if pointY >= self.map_height else pointY) - return pointX,pointY + pointX = int(self.map_width - 1 if pointX >= self.map_width else pointX) + pointY = int(self.map_height - 1 if pointY >= self.map_height else pointY) + return pointX, pointY - def convert_cgu_radius_event_to_map_coord(self,cgu_radius): + def convert_cgu_radius_event_to_map_coord(self, cgu_radius): cgu_radius_new = list() for cgu in cgu_radius: x = cgu[0][0] y = cgu[0][1] - (x,y) = self.convert_event_coord_to_map_coord(x,y) - cgu = ((x,y),cgu[1]) + (x, y) = self.convert_event_coord_to_map_coord(x, y) + cgu = ((x, y), cgu[1]) cgu_radius_new.append(cgu) return cgu_radius_new - def convert_event_coord_to_map_coord(self,x,y): + def convert_event_coord_to_map_coord(self, x, y): imageX = int(self.map_width - self.transX + self.image_scale * x) imageY = int(self.transY - self.image_scale * y) return imageX, imageY diff --git a/sc2reader/engine/plugins/gameheart.py b/sc2reader/engine/plugins/gameheart.py index 08bfc67e..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 @@ -23,7 +20,8 @@ class GameHeartNormalizer(object): * They are all 1v1's. * You can't random in GameHeart """ - name = 'GameHeartNormalizer' + + name = "GameHeartNormalizer" PRIMARY_BUILDINGS = dict(Hatchery="Zerg", Nexus="Protoss", CommandCenter="Terran") @@ -33,19 +31,30 @@ def handleInitGame(self, event, replay): yield PluginExit(self, code=0, details=dict()) return + # Exit plugin if game is LOTV as LOTV games dont use GameHeart + if replay.expansion == "LotV": + yield PluginExit(self, code=0, details=dict()) + return + start_frame = -1 actual_players = {} for event in replay.tracker_events: if start_frame != -1 and event.frame > start_frame + 5: # fuzz it a little break - if event.name == 'UnitBornEvent' and event.control_pid and event.unit_type_name in self.PRIMARY_BUILDINGS: + if ( + event.name == "UnitBornEvent" + and event.control_pid + and event.unit_type_name in self.PRIMARY_BUILDINGS + ): # In normal replays, starting units are born on frame zero. if event.frame == 0: yield PluginExit(self, code=0, details=dict()) return else: start_frame = event.frame - actual_players[event.control_pid] = self.PRIMARY_BUILDINGS[event.unit_type_name] + actual_players[event.control_pid] = self.PRIMARY_BUILDINGS[ + event.unit_type_name + ] self.fix_entities(replay, actual_players) self.fix_events(replay, start_frame) @@ -53,8 +62,12 @@ def handleInitGame(self, event, replay): replay.frames -= start_frame replay.game_length = Length(seconds=replay.frames / 16) replay.real_type = get_real_type(replay.teams) - replay.real_length = Length(seconds=int(replay.game_length.seconds/GAME_SPEED_FACTOR[replay.speed])) - replay.start_time = datetime.utcfromtimestamp(replay.unix_timestamp-replay.real_length.seconds) + replay.real_length = Length( + seconds=int(replay.game_length.seconds / GAME_SPEED_FACTOR[replay.speed]) + ) + replay.start_time = datetime.utcfromtimestamp( + replay.unix_timestamp - replay.real_length.seconds + ) def fix_events(self, replay, start_frame): # Set back the game clock for all events @@ -70,8 +83,8 @@ def fix_entities(self, replay, actual_players): # Change the players that aren't playing into observers for p in [p for p in replay.players if p.pid not in actual_players]: # Fix the slot data to be accurate - p.slot_data['observe'] = 1 - p.slot_data['team_id'] = None + p.slot_data["observe"] = 1 + p.slot_data["team_id"] = None obs = Observer(p.sid, p.slot_data, p.uid, p.init_data, p.pid) # Because these obs start the game as players the client @@ -103,7 +116,7 @@ def fix_entities(self, replay, actual_players): replay.team = dict() replay.teams = list() for index, player in enumerate(replay.players): - team_id = index+1 + team_id = index + 1 team = Team(team_id) replay.team[team_id] = team replay.teams.append(team) @@ -113,5 +126,5 @@ def fix_entities(self, replay, actual_players): player.play_race = player.pick_race team.players = [player] team.result = player.result - if team.result == 'Win': + if team.result == "Win": replay.winner = team diff --git a/sc2reader/engine/plugins/selection.py b/sc2reader/engine/plugins/selection.py index 69aa12a7..4dcc80c2 100644 --- a/sc2reader/engine/plugins/selection.py +++ b/sc2reader/engine/plugins/selection.py @@ -1,29 +1,27 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - - -class SelectionTracker(object): - """ Tracks a player's active selection as an input into other plugins. +class SelectionTracker: + """ + Tracks a player's active selection as an input into other plugins. - In some situations selection tracking isn't perfect. The plugin will - detect these situations and report errors. For a player will a high - level of selection errors, it may be best to ignore the selection - results as they could have been severely compromised. + In some situations selection tracking isn't perfect. The plugin will + detect these situations and report errors. For a player will a high + level of selection errors, it may be best to ignore the selection + results as they could have been severely compromised. - Exposes the following interface, directly integrated into the player: + Exposes the following interface, directly integrated into the player: - for person in replay.entities: - total_errors = person.selection_errors + for person in replay.entities: + total_errors = person.selection_errors - selection = person.selection - control_group_0 = selection[0] - ... - control_group_9 = selection[9] - active_selection = selection[10] + selection = person.selection + control_group_0 = selection[0] + ... + control_group_9 = selection[9] + active_selection = selection[10] - # TODO: list a few error inducing sitations + # TODO: list a few error inducing situations """ - name = 'SelectionTracker' + + name = "SelectionTracker" def handleInitGame(self, event, replay): for person in replay.entities: @@ -34,7 +32,9 @@ def handleInitGame(self, event, replay): def handleSelectionEvent(self, event, replay): selection = event.player.selection[event.control_group] - new_selection, error = self._deselect(selection, event.mask_type, event.mask_data) + new_selection, error = self._deselect( + selection, event.mask_type, event.mask_data + ) new_selection = self._select(new_selection, event.objects) event.player.selection[event.control_group] = new_selection if error: @@ -42,7 +42,9 @@ def handleSelectionEvent(self, event, replay): def handleGetControlGroupEvent(self, event, replay): selection = event.player.selection[event.control_group] - new_selection, error = self._deselect(selection, event.mask_type, event.mask_data) + new_selection, error = self._deselect( + selection, event.mask_type, event.mask_data + ) event.player.selection[10] = new_selection if error: event.player.selection_errors += 1 @@ -52,36 +54,42 @@ def handleSetControlGroupEvent(self, event, replay): def handleAddToControlGroupEvent(self, event, replay): selection = event.player.selection[event.control_group] - new_selection, error = self._deselect(selection, event.mask_type, event.mask_data) + new_selection, error = self._deselect( + selection, event.mask_type, event.mask_data + ) new_selection = self._select(new_selection, event.player.selection[10]) event.player.selection[event.control_group] = new_selection if error: event.player.selection_errors += 1 def _select(self, selection, units): - return sorted(set(selection+units)) + return sorted(set(selection + units)) def _deselect(self, selection, mode, data): - """Returns false if there was a data error when deselecting""" - if mode == 'None': + """ + Returns false if there was a data error when deselecting + """ + if mode == "None": return selection, False selection_size, data_size = len(selection), len(data) - if mode == 'Mask': + if mode == "Mask": # Deselect objects according to deselect mask - sfilter = lambda bit_u: not bit_u[0] - mask = data+[False]*(selection_size-data_size) + def sfilter(bit_u): + return not bit_u[0] + + mask = data + [False] * (selection_size - data_size) new_selection = [u for (bit, u) in filter(sfilter, zip(mask, selection))] error = data_size > selection_size - elif mode == 'OneIndices': + elif mode == "OneIndices": # Deselect objects according to indexes clean_data = list(filter(lambda i: i < selection_size, data)) new_selection = [u for i, u in enumerate(selection) if i < selection_size] error = len(list(filter(lambda i: i >= selection_size, data))) != 0 - elif mode == 'ZeroIndices': + elif mode == "ZeroIndices": # Select objects according to indexes clean_data = list(filter(lambda i: i < selection_size, data)) new_selection = [selection[i] for i in clean_data] diff --git a/sc2reader/engine/plugins/supply.py b/sc2reader/engine/plugins/supply.py index 394a3a64..6935b847 100644 --- a/sc2reader/engine/plugins/supply.py +++ b/sc2reader/engine/plugins/supply.py @@ -1,87 +1,157 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - from collections import defaultdict -class SupplyTracker(object): - def add_to_units_alive(self,event,replay): + +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: + if unit_name in self.unit_name_to_supply: supplyCount = self.unit_name_to_supply[event.unit_type_name][0] buildTime = self.unit_name_to_supply[event.unit_type_name][1] - time_built = event.second - buildTime - time_built= 0 if time_built < 0 else time_built + time_built = event.second - buildTime + 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]]) - replay.players[event.control_pid-1].current_food_used[time_built]= total_supply - print("Second",time_built,replay.players[event.control_pid-1],"SUPPLY",replay.players[event.control_pid-1].current_food_used[time_built]) - + 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 + print( + "Second", + time_built, + replay.players[event.control_pid - 1], + "SUPPLY", + replay.players[event.control_pid - 1].current_food_used[time_built], + ) + elif unit_name in self.supply_gen_unit: - ## see if the unit provides supply + ## see if the unit provides supply supply_gen_count = self.supply_gen_unit[event.unit_type_name][0] build_time = self.supply_gen_unit[event.unit_type_name][1] - time_complete = event.second+ build_time - supply_gen_unit = (supply_gen_count,event.unit_id) + 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]]) - replay.players[event.control_pid-1].current_food_made[time_complete]= total_supply_gen - print("Second",time_complete, replay.players[event.control_pid-1],"Built",replay.players[event.control_pid-1].current_food_made[time_complete]) + 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 + print( + "Second", + time_complete, + replay.players[event.control_pid - 1], + "Built", + 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): + def remove_from_units_alive(self, event, replay): died_unit_id = event.unit_id for player in replay.player: - dead_unit = filter(lambda x:x[1]==died_unit_id,self.units_alive[player]) + 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]]) - - replay.players[player-1].current_food_used[event.second] = total_supply - print("Second", event.second, "Killed", event.unit.name,"SUPPLY",replay.players[player-1].current_food_used[event.second]) - - dead_supply_gen=filter(lambda x:x[1]==died_unit_id, self.supply_gen[player]) + total_supply = sum(x[0] for x in self.units_alive[player]) + + replay.players[player - 1].current_food_used[ + event.second + ] = total_supply + print( + "Second", + event.second, + "Killed", + event.unit.name, + "SUPPLY", + replay.players[player - 1].current_food_used[event.second], + ) + + dead_supply_gen = filter( + lambda x: x[1] == died_unit_id, self.supply_gen[player] + ) 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]]) - replay.players[player-1].current_food_made[event.second] = total_supply_gen - print("Second", event.second, "Killed", event.unit.name,"SUPPLY",replay.players[player-1].current_food_made[event.second]) + 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 + print( + "Second", + event.second, + "Killed", + event.unit.name, + "SUPPLY", + replay.players[player - 1].current_food_made[event.second], + ) def handleInitGame(self, event, replay): - ## This dictionary contains te supply of every unit - self.unit_name_to_supply = { - #Zerg - "Drone":(1,17),"Zergling":(1,25),"Baneling":(0,20),"Queen":(2,50),\ - "Hydralisk":(2,33),"Roach":(2,27),"Infestor":(2,50),"Mutalisk":(2,33),\ - "Corruptor":(2,40),"Utralisk":(6,55),"Broodlord":(2,34),\ - "SwarmHost":(3,40), "Viper":(3,40),\ - #Terran - "SCV":(1,17),"Marine":(1,25),"Marauder":(2,30),"SiegeTank":(2,45),\ - "Reaper":(1,45),"Ghost":(2,40),"Hellion":(2,30),"Thor":(6,60),\ - "Viking":(2,42),"Medivac":(2,42),"Raven":(2,60), "Banshee":(3,60),\ - "Battlecruiser":(6,90), "Hellbat":(2,30),"WidowMine":(2,40),\ - #Protoss - "Probe":(1,17),"Zealot":(2,38),"Stalker":(2,42),"Sentry":(2,42),\ - "Observer":(1,30), "Immortal":(4,55),"WarpPrism":(2,50),\ - "Colossus":(6,75), "Phoenix":(2,35),"VoidRay":(4,60), \ - "HighTemplar":(2,55),"DarkTemplar":(2,55), "Archon":(4,12),\ - "Carrier":(6,120), "Mothership":(6,100),"MothershipCore":(2,30),\ - "Oracle":(3,50),"Tempest":(4,60)} - + ## This dictionary contains the supply of every unit + self.unit_name_to_supply = { + # Zerg + "Drone": (1, 17), + "Zergling": (1, 25), + "Baneling": (0, 20), + "Queen": (2, 50), + "Hydralisk": (2, 33), + "Roach": (2, 27), + "Infestor": (2, 50), + "Mutalisk": (2, 33), + "Corruptor": (2, 40), + "Utralisk": (6, 55), + "Broodlord": (2, 34), + "SwarmHost": (3, 40), + "Viper": (3, 40), + # Terran + "SCV": (1, 17), + "Marine": (1, 25), + "Marauder": (2, 30), + "SiegeTank": (2, 45), + "Reaper": (1, 45), + "Ghost": (2, 40), + "Hellion": (2, 30), + "Thor": (6, 60), + "Viking": (2, 42), + "Medivac": (2, 42), + "Raven": (2, 60), + "Banshee": (3, 60), + "Battlecruiser": (6, 90), + "Hellbat": (2, 30), + "WidowMine": (2, 40), + # Protoss + "Probe": (1, 17), + "Zealot": (2, 38), + "Stalker": (2, 42), + "Sentry": (2, 42), + "Observer": (1, 30), + "Immortal": (4, 55), + "WarpPrism": (2, 50), + "Colossus": (6, 75), + "Phoenix": (2, 35), + "VoidRay": (4, 60), + "HighTemplar": (2, 55), + "DarkTemplar": (2, 55), + "Archon": (4, 12), + "Carrier": (6, 120), + "Mothership": (6, 100), + "MothershipCore": (2, 30), + "Oracle": (3, 50), + "Tempest": (4, 60), + } + self.supply_gen_unit = { - #overlord build time is zero because event for units are made when + # overlord build time is zero because event for units are made when # it is born not when it's created - "Overlord":(8,0),"Hatchery":(2,100), \ - "SupplyDepot":(8,30),"CommandCenter":(11,100),\ - "Pylon":(8,25),"Nexus":(10,100) + "Overlord": (8, 0), + "Hatchery": (2, 100), + "SupplyDepot": (8, 30), + "CommandCenter": (11, 100), + "Pylon": (8, 25), + "Nexus": (10, 100), } - ## This list contains a turple of the units supply and unit ID. + ## This list contains a turple of the units supply and unit ID. ## the purpose of the list is to know which user owns which unit - ## so that when a unit dies, that + ## so that when a unit dies, that self.units_alive = dict() - ## + ## self.supply_gen = dict() for player in replay.players: self.supply_gen[player.pid] = list() @@ -90,20 +160,24 @@ def handleInitGame(self, event, replay): player.current_food_made = defaultdict(int) player.time_supply_capped = int() - def handleUnitInitEvent(self,event,replay): - #print ("Init",event.unit_type_name, event.unit_id) - self.add_to_units_alive(event,replay) + def handleUnitInitEvent(self, event, replay): + # print ("Init",event.unit_type_name, event.unit_id) + self.add_to_units_alive(event, replay) - def handleUnitBornEvent(self,event,replay): - #print ("Born",event.unit_type_name,event.unit_id) - self.add_to_units_alive(event,replay) + def handleUnitBornEvent(self, event, replay): + # print ("Born",event.unit_type_name,event.unit_id) + self.add_to_units_alive(event, replay) - def handleUnitDiedEvent(self,event,replay): + def handleUnitDiedEvent(self, event, replay): if event.unit.name not in self.unit_name_to_supply: return - self.remove_from_units_alive(event,replay) + self.remove_from_units_alive(event, replay) def handleEndGame(self, event, replay): for player in replay.players: - player.current_food_used = sorted(player.current_food_used.iteritems(), key=lambda x: x[0]) - player.current_food_made = sorted(player.current_food_made.iteritems(), key=lambda x:x[0]) + player.current_food_used = sorted( + player.current_food_used.iteritems(), key=lambda x: x[0] + ) + player.current_food_made = sorted( + player.current_food_made.iteritems(), key=lambda x: x[0] + ) diff --git a/sc2reader/engine/utils.py b/sc2reader/engine/utils.py index e3a9a18c..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 @@ -31,7 +28,7 @@ def __getitem__(self, frame): else: # Copy the previous state and use it as our basis here state = self[prev_frame] - if hasattr(state, 'copy'): + if hasattr(state, "copy"): state = state.copy() self[frame] = state @@ -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 dbea286c..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): - name = 'Event' +class Event: + name = "Event" diff --git a/sc2reader/events/game.py b/sc2reader/events/game.py index bac26d94..0da9afa2 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 @@ -13,6 +10,7 @@ class GameEvent(Event): """ This is the base class for all game events. The attributes below are universally available. """ + def __init__(self, frame, pid): #: The id of the player generating the event. This is 16 for global non-player events. #: Prior to Heart of the Swarm this was the player id. Since HotS it is @@ -31,17 +29,21 @@ def __init__(self, frame, pid): self.second = frame >> 4 #: A flag indicating if it is a local or global event. - self.is_local = (pid != 16) + self.is_local = pid != 16 #: Short cut string for event class name self.name = self.__class__.__name__ def _str_prefix(self): - if self.player: - player_name = self.player.name if getattr(self, 'pid', 16) != 16 else "Global" + if getattr(self, "pid", 16) == 16: + player_name = "Global" + elif self.player and not self.player.name: + player_name = f"Player {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 @@ -52,8 +54,9 @@ class GameStartEvent(GameEvent): Recorded when the game starts and the frames start to roll. This is a global non-player event. """ + def __init__(self, frame, pid, data): - super(GameStartEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: ??? self.data = data @@ -63,8 +66,9 @@ class PlayerLeaveEvent(GameEvent): """ Recorded when a player leaves the game. """ + def __init__(self, frame, pid, data): - super(PlayerLeaveEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: ??? self.data = data @@ -75,48 +79,51 @@ class UserOptionsEvent(GameEvent): This event is recorded for each player at the very beginning of the game before the :class:`GameStartEvent`. """ + def __init__(self, frame, pid, data): - super(UserOptionsEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: - self.game_fully_downloaded = data['game_fully_downloaded'] + self.game_fully_downloaded = data["game_fully_downloaded"] #: - self.development_cheats_enabled = data['development_cheats_enabled'] + self.development_cheats_enabled = data["development_cheats_enabled"] #: - self.multiplayer_cheats_enabled = data['multiplayer_cheats_enabled'] + self.multiplayer_cheats_enabled = data["multiplayer_cheats_enabled"] #: - self.sync_checksumming_enabled = data['sync_checksumming_enabled'] + self.sync_checksumming_enabled = data["sync_checksumming_enabled"] #: - self.is_map_to_map_transition = data['is_map_to_map_transition'] + self.is_map_to_map_transition = data["is_map_to_map_transition"] #: - self.use_ai_beacons = data['use_ai_beacons'] + self.use_ai_beacons = data["use_ai_beacons"] #: Are workers sent to auto-mine on game start - self.starting_rally = data['starting_rally'] if 'starting_rally' in data else None + self.starting_rally = ( + data["starting_rally"] if "starting_rally" in data else None + ) #: - self.debug_pause_enabled = data['debug_pause_enabled'] + self.debug_pause_enabled = data["debug_pause_enabled"] #: - self.base_build_num = data['base_build_num'] + self.base_build_num = data["base_build_num"] def create_command_event(frame, pid, data): - ability_type = data['data'][0] - if ability_type == 'None': + ability_type = data["data"][0] + if ability_type == "None": return BasicCommandEvent(frame, pid, data) - elif ability_type == 'TargetUnit': + elif ability_type == "TargetUnit": return TargetUnitCommandEvent(frame, pid, data) - elif ability_type == 'TargetPoint': + elif ability_type == "TargetPoint": return TargetPointCommandEvent(frame, pid, data) - elif ability_type == 'Data': + elif ability_type == "Data": return DataCommandEvent(frame, pid, data) @@ -131,11 +138,12 @@ class CommandEvent(GameEvent): See :class:`TargetPointCommandEvent`, :class:`TargetUnitCommandEvent`, and :class:`DataCommandEvent` for individual details. """ + def __init__(self, frame, pid, data): - super(CommandEvent, self).__init__(frame, pid) + super().__init__(frame, pid) #: Flags on the command??? - self.flags = data['flags'] + self.flags = data["flags"] #: A dictionary of possible ability flags. Flags are: #: @@ -188,16 +196,20 @@ def __init__(self, frame, pid, data): ) #: Flag marking that the command had ability information - self.has_ability = data['ability'] is not None + self.has_ability = data["ability"] is not None #: Link the the ability group - self.ability_link = data['ability']['ability_link'] if self.has_ability else 0 + self.ability_link = data["ability"]["ability_link"] if self.has_ability else 0 #: The index of the ability in the ability group - self.command_index = data['ability']['ability_command_index'] if self.has_ability else 0 + self.command_index = ( + data["ability"]["ability_command_index"] if self.has_ability else 0 + ) #: Additional ability data. - self.ability_data = data['ability']['ability_command_data'] if self.has_ability else 0 + self.ability_data = ( + data["ability"]["ability_command_data"] if self.has_ability else 0 + ) #: Unique identifier for the ability self.ability_id = self.ability_link << 5 | self.command_index @@ -206,16 +218,16 @@ def __init__(self, frame, pid, data): self.ability = None #: A shortcut to the name of the ability being used - self.ability_name = '' + self.ability_name = "" #: The type of ability, one of: None (no target), TargetPoint, TargetUnit, or Data - self.ability_type = data['data'][0] + self.ability_type = data["data"][0] #: The raw data associated with this ability type - self.ability_type_data = data['data'][1] + self.ability_type_data = data["data"][1] #: Other unit id?? - self.other_unit_id = data['other_unit_tag'] + self.other_unit_id = data["other_unit_tag"] #: A reference to the other unit self.other_unit = None @@ -223,17 +235,17 @@ 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(self.target.name, self.target_unit_id) + if self.ability_type == "TargetUnit": + string += f"; Target: {self.target.name} [{self.target_unit_id:0>8X}]" - if self.ability_type in ('TargetPoint', 'TargetUnit'): - string += "; Location: {0}".format(str(self.location)) + if self.ability_type in ("TargetPoint", "TargetUnit"): + string += f"; Location: {str(self.location)}" return string @@ -247,8 +259,9 @@ class BasicCommandEvent(CommandEvent): Note that like all CommandEvents, the event will be recorded regardless of whether or not the command was successful. """ + def __init__(self, frame, pid, data): - super(BasicCommandEvent, self).__init__(frame, pid, data) + super().__init__(frame, pid, data) class TargetPointCommandEvent(CommandEvent): @@ -262,17 +275,18 @@ class TargetPointCommandEvent(CommandEvent): Note that like all CommandEvents, the event will be recorded regardless of whether or not the command was successful. """ + 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 + self.x = self.ability_type_data["point"].get("x", 0) / 4096.0 #: The y coordinate of the target. Available for TargetPoint and TargetUnit type events. - self.y = self.ability_type_data['point'].get('y', 0) / 4096.0 + self.y = self.ability_type_data["point"].get("y", 0) / 4096.0 #: The z coordinate of the target. Available for TargetPoint and TargetUnit type events. - self.z = self.ability_type_data['point'].get('z', 0) + self.z = self.ability_type_data["point"].get("z", 0) #: The location of the target. Available for TargetPoint and TargetUnit type events self.location = (self.x, self.y, self.z) @@ -289,46 +303,48 @@ class TargetUnitCommandEvent(CommandEvent): Note that like all CommandEvents, the event will be recorded regardless of whether or not the command was successful. """ + 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) + self.target_flags = self.ability_type_data.get("flags", None) #: Timer?? Available for TargetUnit type events. - self.target_timer = self.ability_type_data.get('timer', None) + self.target_timer = self.ability_type_data.get("timer", None) #: Unique id of the target unit. Available for TargetUnit type events. #: This id can be 0 when the target unit is shrouded by fog of war. - self.target_unit_id = self.ability_type_data.get('unit_tag', None) + self.target_unit_id = self.ability_type_data.get("unit_tag", None) - #: A reference to the targetted unit. When the :attr:`target_unit_id` is + #: A reference to the targeted unit. When the :attr:`target_unit_id` is #: 0 this target unit is a generic, reused fog of war unit of the :attr:`target_unit_type` #: with an id of zero. It should not be confused with a real unit. self.target_unit = None #: Current integer type id of the target unit. Available for TargetUnit type events. - self.target_unit_type = self.ability_type_data.get('unit_link', None) + self.target_unit_type = self.ability_type_data.get("unit_link", None) #: Integer player id of the controlling player. Available for TargetUnit type events starting in 19595. - #: When the targetted unit is under fog of war this id is zero. - self.control_player_id = self.ability_type_data.get('control_player_id', None) + #: When the targeted unit is under fog of war this id is zero. + self.control_player_id = self.ability_type_data.get("control_player_id", None) #: Integer player id of the player paying upkeep. Available for TargetUnit type events. - self.upkeep_player_id = self.ability_type_data.get('upkeep_player_id', None) + self.upkeep_player_id = self.ability_type_data.get("upkeep_player_id", None) #: 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 + self.x = self.ability_type_data["point"].get("x", 0) / 4096.0 #: The y coordinate of the target. Available for TargetPoint and TargetUnit type events. - self.y = self.ability_type_data['point'].get('y', 0) / 4096.0 + self.y = self.ability_type_data["point"].get("y", 0) / 4096.0 #: The z coordinate of the target. Available for TargetPoint and TargetUnit type events. - self.z = self.ability_type_data['point'].get('z', 0) + self.z = self.ability_type_data["point"].get("z", 0) #: The location of the target. Available for TargetPoint and TargetUnit type events self.location = (self.x, self.y, self.z) + class UpdateTargetPointCommandEvent(TargetPointCommandEvent): """ Extends :class: 'TargetPointCommandEvent' @@ -338,7 +354,9 @@ class UpdateTargetPointCommandEvent(TargetPointCommandEvent): instances of this occurring. """ - name = 'UpdateTargetPointCommandEvent' + + name = "UpdateTargetPointCommandEvent" + class UpdateTargetUnitCommandEvent(TargetUnitCommandEvent): """ @@ -349,11 +367,11 @@ class UpdateTargetUnitCommandEvent(TargetUnitCommandEvent): from TargetUnitCommandEvent, but for flexibility, it will be treated differently. - One example of this event occuring is casting inject on a hatchery while + One example of this event occurring is casting inject on a hatchery while holding shift, and then shift clicking on a second hatchery. """ - name = 'UpdateTargetUnitCommandEvent' + name = "UpdateTargetUnitCommandEvent" class DataCommandEvent(CommandEvent): @@ -366,11 +384,32 @@ class DataCommandEvent(CommandEvent): Note that like all CommandEvents, the event will be recorded regardless of whether or not the command was successful. """ + 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) + self.target_data = self.ability_type_data.get("data", None) + + +@loggable +class CommandManagerStateEvent(GameEvent): + """ + These events indicated that the last :class:`CommandEvent` called has been + called again. For example, if you add three SCVs to an empty queue on a + Command Center, the first add will be generate a :class:`BasicCommandEvent` + and the two subsequent adds will each generate a + :class:`CommandManagerStateEvent`. + """ + + def __init__(self, frame, pid, data): + super().__init__(frame, pid) + + #: Always 1? + self.state = data["state"] + + #: An index identifying how many events of this type have been called + self.sequence = data["sequence"] @loggable @@ -380,42 +419,88 @@ class SelectionEvent(GameEvent): player is updated. Unlike other game events, these events can also be generated by non-player actions like unit deaths or transformations. - Starting in Starcraft 2.0.0, selection events targetting control group + Starting in Starcraft 2.0.0, selection events targeting control group buffers are also generated when control group selections are modified by non-player actions. When a player action updates a control group a :class:`ControlGroupEvent` is generated. """ + 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'] + self.control_group = data["control_group_index"] #: Deprecated, use control_group self.bank = self.control_group #: ??? - self.subgroup_index = data['subgroup_index'] + self.subgroup_index = data["subgroup_index"] #: The type of mask to apply. One of None, Mask, OneIndices, ZeroIndices - self.mask_type = data['remove_mask'][0] + self.mask_type = data["remove_mask"][0] #: The data for the mask - self.mask_data = data['remove_mask'][1] + self.mask_data = data["remove_mask"][1] #: The unit type data for the new units - self.new_unit_types = [(d['unit_link'], d['subgroup_priority'], d['intra_subgroup_priority'], d['count']) for d in data['add_subgroups']] + self.new_unit_types = [ + ( + d["unit_link"], + d["subgroup_priority"], + d["intra_subgroup_priority"], + d["count"], + ) + for d in data["add_subgroups"] + ] #: The unit id data for the new units - self.new_unit_ids = data['add_unit_tags'] + self.new_unit_ids = data["add_unit_tags"] # This stretches out the unit types and priorities to be zipped with ids. - unit_types = chain(*[[utype]*count for (utype, subgroup_priority, intra_subgroup_priority, count) in self.new_unit_types]) - unit_subgroup_priorities = chain(*[[subgroup_priority]*count for (utype, subgroup_priority, intra_subgroup_priority, count) in self.new_unit_types]) - unit_intra_subgroup_priorities = chain(*[[intra_subgroup_priority]*count for (utype, subgroup_priority, intra_subgroup_priority, count) in self.new_unit_types]) + unit_types = chain( + *[ + [utype] * count + for ( + utype, + subgroup_priority, + intra_subgroup_priority, + count, + ) in self.new_unit_types + ] + ) + unit_subgroup_priorities = chain( + *[ + [subgroup_priority] * count + for ( + utype, + subgroup_priority, + intra_subgroup_priority, + count, + ) in self.new_unit_types + ] + ) + unit_intra_subgroup_priorities = chain( + *[ + [intra_subgroup_priority] * count + for ( + utype, + subgroup_priority, + intra_subgroup_priority, + count, + ) in self.new_unit_types + ] + ) #: The combined type and id information for new units - self.new_unit_info = list(zip(self.new_unit_ids, unit_types, unit_subgroup_priorities, unit_intra_subgroup_priorities)) + self.new_unit_info = list( + zip( + self.new_unit_ids, + unit_types, + unit_subgroup_priorities, + unit_intra_subgroup_priorities, + ) + ) #: A list of references to units added by this selection self.new_units = None @@ -425,24 +510,28 @@ def __init__(self, frame, pid, data): def __str__(self): if self.new_units: - return GameEvent.__str__(self)+str([str(u) for u in self.new_units]) + return GameEvent.__str__(self) + str([str(u) for u in self.new_units]) else: - return GameEvent.__str__(self)+str([str(u) for u in self.new_unit_info]) + return GameEvent.__str__(self) + str([str(u) for u in self.new_unit_info]) def create_control_group_event(frame, pid, data): - update_type = data['control_group_update'] - if update_type == 0: + update_type = data["control_group_update"] + if update_type in [0, 4]: + # 0 is the normal set command. + # 4 is used when you steal and set. If required, type 4 will be followed by autogenerated + # selection and control group events that remove the units from their other groups. return SetControlGroupEvent(frame, pid, data) - elif update_type == 1: + elif update_type in [1, 5]: + # 1 is the normal add command. + # 5 is used when you steal and add. If required, type 5 will be followed by autogenerated + # selection and control group events that remove the units from their other groups. return AddToControlGroupEvent(frame, pid, data) elif update_type == 2: return GetControlGroupEvent(frame, pid, data) elif update_type == 3: - # TODO: What could this be?!? - return ControlGroupEvent(frame, pid, data) + return DeleteControlGroupEvent(frame, pid, data) else: - # No idea what this is but we're seeing update_types of 4 and 5 in 3.0 return ControlGroupEvent(frame, pid, data) @@ -457,14 +546,15 @@ class ControlGroupEvent(GameEvent): * :class:`GetControlGroup` - Recorded when a user retrieves a control group (#). * :class:`AddToControlGroup` - Recorded when a user adds to a control group (shift+ctrl+#) - All three events have the same set of data (shown below) but are interpretted differently. + All three events have the same set of data (shown below) but are interpreted differently. See the class entry for details. """ + 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'] + self.control_group = data["control_group_index"] #: Deprecated, use control_group self.bank = self.control_group @@ -473,13 +563,13 @@ def __init__(self, frame, pid, data): self.hotkey = self.control_group #: The type of update being performed, 0 (set),1 (add),2 (get) - self.update_type = data['control_group_update'] + self.update_type = data["control_group_update"] #: The type of mask to apply. One of None, Mask, OneIndices, ZeroIndices - self.mask_type = data['remove_mask'][0] + self.mask_type = data["remove_mask"][0] #: The data for the mask - self.mask_data = data['remove_mask'][1] + self.mask_data = data["remove_mask"][1] class SetControlGroupEvent(ControlGroupEvent): @@ -499,6 +589,15 @@ class AddToControlGroupEvent(SetControlGroupEvent): """ +class DeleteControlGroupEvent(ControlGroupEvent): + """ + Extends :class:`ControlGroupEvent` + + This event deletes the control group (all units are removed). This happens when all + units are stolen from the event group (alt, alt+shift modifiers by default). + """ + + class GetControlGroupEvent(ControlGroupEvent): """ Extends :class:`ControlGroupEvent` @@ -517,29 +616,30 @@ class CameraEvent(GameEvent): It does not matter why the camera changed, this event simply records the current state of the camera after changing. """ + 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 + self.x = (data["target"]["x"] if data["target"] is not None else 0) / 256.0 #: The y coordinate of the center of the camera - self.y = (data['target']['y'] if data['target'] is not None else 0)/256.0 + self.y = (data["target"]["y"] if data["target"] is not None else 0) / 256.0 #: The location of the center of the camera self.location = (self.x, self.y) #: The distance to the camera target ?? - self.distance = data['distance'] + self.distance = data["distance"] #: The current pitch of the camera - self.pitch = data['pitch'] + self.pitch = data["pitch"] #: The current yaw of the camera - self.yaw = data['yaw'] + self.yaw = data["yaw"] def __str__(self): - return self._str_prefix() + "{0} at ({1}, {2})".format(self.name, self.x, self.y) + return self._str_prefix() + f"{self.name} at ({self.x}, {self.y})" @loggable @@ -548,8 +648,9 @@ class ResourceTradeEvent(GameEvent): Generated when a player trades resources with another player. But not when fullfulling resource requests. """ + 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 @@ -558,13 +659,13 @@ def __init__(self, frame, pid, data): self.sender = None #: The id of the player receiving the resources - self.recipient_id = data['recipient_id'] + self.recipient_id = data["recipient_id"] #: A reference to the player receiving the resources self.recipient = None #: An array of resources sent - self.resources = data['resources'] + self.resources = data["resources"] #: Amount minerals sent self.minerals = self.resources[0] if len(self.resources) >= 1 else None @@ -573,24 +674,28 @@ def __init__(self, frame, pid, data): self.vespene = self.resources[1] if len(self.resources) >= 2 else None #: Amount terrazine sent - self.terrazon = self.resources[2] if len(self.resources) >= 3 else None + self.terrazine = self.resources[2] if len(self.resources) >= 3 else None #: Amount custom resource sent 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(self.minerals, self.vespene, self.terrazine, self.custom, self.recipient) + return ( + self._str_prefix() + + f" transfer {self.minerals} minerals, {self.vespene} gas, {self.terrazine} terrazine, and {self.custom_resource} custom to {self.recipient}" + ) class ResourceRequestEvent(GameEvent): """ Generated when a player creates a resource request. """ + 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'] + self.resources = data["resources"] #: Amount minerals sent self.minerals = self.resources[0] if len(self.resources) >= 1 else None @@ -605,40 +710,65 @@ 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() + " requests {0} minerals, {1} gas, {2} terrazine, and {3} custom".format(self.minerals, self.vespene, self.terrazine, self.custom) + return ( + self._str_prefix() + + f" requests {self.minerals} minerals, {self.vespene} gas, {self.terrazine} terrazine, and {self.custom_resource} custom" + ) class ResourceRequestFulfillEvent(GameEvent): """ Generated when a player accepts a resource request. """ + 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'] + self.request_id = data["request_id"] class ResourceRequestCancelEvent(GameEvent): """ Generated when a player cancels their resource request. """ + 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'] + self.request_id = data["request_id"] class HijackReplayGameEvent(GameEvent): """ Generated when players take over from a replay. """ + 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'] + self.method = data["method"] #: Information on the users hijacking the game - self.user_infos = data['user_infos'] + self.user_infos = data["user_infos"] + + +@loggable +class DialogControlEvent(GameEvent): + """ + Generated when a dialog is interacted with. + """ + + def __init__(self, frame, pid, data): + super().__init__(frame, pid) + + #: Identifier for the dialog + self.control_id = data["control_id"] + + #: How dialog was interacted with + self.event_type = data["event_type"] + + #: Data specific to event type such as changes or clicks + self.event_data = data["event_data"] diff --git a/sc2reader/events/message.py b/sc2reader/events/message.py index e9859733..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 @@ -9,8 +6,9 @@ @loggable class MessageEvent(Event): """ - Parent class for all message events. + Parent class for all message events. """ + def __init__(self, frame, pid): #: The user id (or player id for older replays) of the person that generated the event. self.pid = pid @@ -25,8 +23,8 @@ def __init__(self, frame, pid): self.name = self.__class__.__name__ 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) + player_name = self.player.name if getattr(self, "pid", 16) != 16 else "Global" + return f"{Length(seconds=int(self.frame / 16))}\t{player_name:<15} " def __str__(self): return self._str_prefix() + self.name @@ -35,10 +33,11 @@ def __str__(self): @loggable class ChatEvent(MessageEvent): """ - Records in-game chat events. + Records in-game chat events. """ + 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 @@ -46,22 +45,23 @@ def __init__(self, frame, pid, target, text): self.text = text #: Flag marked true of message was to all. - self.to_all = (self.target == 0) + self.to_all = self.target == 0 #: Flag marked true of message was to allies. - self.to_allies = (self.target == 2) + self.to_allies = self.target == 2 #: Flag marked true of message was to observers. - self.to_observers = (self.target == 4) + self.to_observers = self.target == 4 @loggable class ProgressEvent(MessageEvent): """ - Sent during the load screen to update load process for other clients. + Sent during the load screen to update load process for other clients. """ + 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 @@ -70,22 +70,23 @@ def __init__(self, frame, pid, progress): @loggable class PingEvent(MessageEvent): """ - Records pings made by players in game. + Records pings made by players in game. """ + 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 #: Flag marked true of message was to all. - self.to_all = (self.target == 0) + self.to_all = self.target == 0 #: Flag marked true of message was to allies. - self.to_allies = (self.target == 2) + self.to_allies = self.target == 2 #: Flag marked true of message was to observers. - self.to_observers = (self.target == 4) + self.to_observers = self.target == 4 #: The x coordinate of the target location self.x = x diff --git a/sc2reader/events/tracker.py b/sc2reader/events/tracker.py index fe3e6f78..8e0c6772 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 @@ -13,6 +10,7 @@ class TrackerEvent(Event): """ Parent class for all tracker events. """ + def __init__(self, frames): #: The frame of the game this event was applied #: Ignore all but the lowest 32 bits of the frame @@ -28,16 +26,17 @@ 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 class PlayerSetupEvent(TrackerEvent): - """ Sent during game setup to help us organize players better """ + """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] @@ -64,8 +63,9 @@ class PlayerStatsEvent(TrackerEvent): In 1v1 games, the above behavior can cause the losing player to have 2 events generated at the end of the game. One for leaving and one for the end of the game. """ + 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] @@ -101,7 +101,11 @@ def __init__(self, frames, data, build): self.minerals_used_in_progress_technology = clamp(self.stats[7]) #: The total mineral cost of all things in progress - self.minerals_used_in_progress = self.minerals_used_in_progress_army + self.minerals_used_in_progress_economy + self.minerals_used_in_progress_technology + self.minerals_used_in_progress = ( + self.minerals_used_in_progress_army + + self.minerals_used_in_progress_economy + + self.minerals_used_in_progress_technology + ) #: The total vespene cost of army units (buildings?) currently being built/queued self.vespene_used_in_progress_army = clamp(self.stats[8]) @@ -113,10 +117,16 @@ def __init__(self, frames, data, build): self.vespene_used_in_progress_technology = clamp(self.stats[10]) #: The total vespene cost of all things in progress - self.vespene_used_in_progress = self.vespene_used_in_progress_army + self.vespene_used_in_progress_economy + self.vespene_used_in_progress_technology + self.vespene_used_in_progress = ( + self.vespene_used_in_progress_army + + self.vespene_used_in_progress_economy + + self.vespene_used_in_progress_technology + ) #: The total cost of all things in progress - self.resources_used_in_progress = self.minerals_used_in_progress + self.vespene_used_in_progress + self.resources_used_in_progress = ( + self.minerals_used_in_progress + self.vespene_used_in_progress + ) #: The total mineral cost of current army units (buildings?) self.minerals_used_current_army = clamp(self.stats[11]) @@ -128,7 +138,11 @@ def __init__(self, frames, data, build): self.minerals_used_current_technology = clamp(self.stats[13]) #: The total mineral cost of all current things - self.minerals_used_current = self.minerals_used_current_army + self.minerals_used_current_economy + self.minerals_used_current_technology + self.minerals_used_current = ( + self.minerals_used_current_army + + self.minerals_used_current_economy + + self.minerals_used_current_technology + ) #: The total vespene cost of current army units (buildings?) self.vespene_used_current_army = clamp(self.stats[14]) @@ -140,10 +154,16 @@ def __init__(self, frames, data, build): self.vespene_used_current_technology = clamp(self.stats[16]) #: The total vepsene cost of all current things - self.vespene_used_current = self.vespene_used_current_army + self.vespene_used_current_economy + self.vespene_used_current_technology + self.vespene_used_current = ( + self.vespene_used_current_army + + self.vespene_used_current_economy + + self.vespene_used_current_technology + ) #: The total cost of all things current - self.resources_used_current = self.minerals_used_current + self.vespene_used_current + self.resources_used_current = ( + self.minerals_used_current + self.vespene_used_current + ) #: The total mineral cost of all army units (buildings?) lost self.minerals_lost_army = clamp(self.stats[17]) @@ -155,7 +175,11 @@ def __init__(self, frames, data, build): self.minerals_lost_technology = clamp(self.stats[19]) #: The total mineral cost of all lost things - self.minerals_lost = self.minerals_lost_army + self.minerals_lost_economy + self.minerals_lost_technology + self.minerals_lost = ( + self.minerals_lost_army + + self.minerals_lost_economy + + self.minerals_lost_technology + ) #: The total vespene cost of all army units (buildings?) lost self.vespene_lost_army = clamp(self.stats[20]) @@ -167,7 +191,11 @@ def __init__(self, frames, data, build): self.vespene_lost_technology = clamp(self.stats[22]) #: The total vepsene cost of all lost things - self.vespene_lost = self.vespene_lost_army + self.vespene_lost_economy + self.vespene_lost_technology + self.vespene_lost = ( + self.vespene_lost_army + + self.vespene_lost_economy + + self.vespene_lost_technology + ) #: The total resource cost of all lost things self.resources_lost = self.minerals_lost + self.vespene_lost @@ -182,7 +210,11 @@ def __init__(self, frames, data, build): self.minerals_killed_technology = clamp(self.stats[25]) #: The total mineral value of all killed things - self.minerals_killed = self.minerals_killed_army + self.minerals_killed_economy + self.minerals_killed_technology + self.minerals_killed = ( + self.minerals_killed_army + + self.minerals_killed_economy + + self.minerals_killed_technology + ) #: The total vespene value of enemy army units (buildings?) killed self.vespene_killed_army = clamp(self.stats[26]) @@ -194,7 +226,11 @@ def __init__(self, frames, data, build): self.vespene_killed_technology = clamp(self.stats[28]) #: The total vespene cost of all killed things - self.vespene_killed = self.vespene_killed_army + self.vespene_killed_economy + self.vespene_killed_technology + self.vespene_killed = ( + self.vespene_killed_army + + self.vespene_killed_economy + + self.vespene_killed_technology + ) #: The total resource cost of all killed things self.resources_killed = self.minerals_killed + self.vespene_killed @@ -215,10 +251,14 @@ def __init__(self, frames, data, build): self.ff_minerals_lost_army = clamp(self.stats[33]) if build >= 26490 else None #: Minerals of economy value lost to friendly fire - self.ff_minerals_lost_economy = clamp(self.stats[34]) if build >= 26490 else None + self.ff_minerals_lost_economy = ( + clamp(self.stats[34]) if build >= 26490 else None + ) #: Minerals of technology value lost to friendly fire - self.ff_minerals_lost_technology = clamp(self.stats[35]) if build >= 26490 else None + self.ff_minerals_lost_technology = ( + clamp(self.stats[35]) if build >= 26490 else None + ) #: Vespene of army value lost to friendly fire self.ff_vespene_lost_army = clamp(self.stats[36]) if build >= 26490 else None @@ -227,10 +267,12 @@ def __init__(self, frames, data, build): self.ff_vespene_lost_economy = clamp(self.stats[37]) if build >= 26490 else None #: Vespene of technology value lost to friendly fire - self.ff_vespene_lost_technology = clamp(self.stats[38]) if build >= 26490 else None + self.ff_vespene_lost_technology = ( + clamp(self.stats[38]) if build >= 26490 else None + ) 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): @@ -244,8 +286,9 @@ class UnitBornEvent(TrackerEvent): :class:`~sc2reader.event.game.CommandEvent` game events where the command is a train unit command. """ + 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] @@ -260,7 +303,7 @@ def __init__(self, frames, data, build): self.unit = None #: The unit type name of the unit being born - self.unit_type_name = data[2].decode('utf8') + self.unit_type_name = data[2].decode("utf8") #: The id of the player that controls this unit. self.control_pid = data[3] @@ -291,7 +334,10 @@ 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(str(self.unit_upkeeper), self.unit) + return ( + self._str_prefix() + + f"{str(self.unit_upkeeper): >15} - Unit born {self.unit}" + ) class UnitDiedEvent(TrackerEvent): @@ -299,8 +345,9 @@ class UnitDiedEvent(TrackerEvent): Generated when a unit dies or is removed from the game for any reason. Reasons include morphing, merging, and getting killed. """ + 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] @@ -358,10 +405,14 @@ def __init__(self, frames, data, build): self.killing_unit_index = data[5] self.killing_unit_recycle = data[6] if self.killing_unit_index: - self.killing_unit_id = self.killing_unit_index << 18 | self.killing_unit_recycle + self.killing_unit_id = ( + self.killing_unit_index << 18 | self.killing_unit_recycle + ) def __str__(self): - return self._str_prefix() + "{0: >15} - Unit died {1}.".format(str(self.unit.owner), self.unit) + return ( + self._str_prefix() + f"{str(self.unit.owner): >15} - Unit died {self.unit}." + ) class UnitOwnerChangeEvent(TrackerEvent): @@ -369,8 +420,9 @@ class UnitOwnerChangeEvent(TrackerEvent): Generated when either ownership or control of a unit is changed. Neural Parasite is an example of an action that would generate this event. """ + 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] @@ -397,7 +449,7 @@ def __init__(self, frames, data, build): self.unit_controller = None def __str__(self): - return self._str_prefix() + "{0: >15} took {1}".format(str(self.unit_upkeeper), self.unit) + return self._str_prefix() + f"{str(self.unit_upkeeper): >15} took {self.unit}" class UnitTypeChangeEvent(TrackerEvent): @@ -406,8 +458,9 @@ class UnitTypeChangeEvent(TrackerEvent): Lair, Hive) and mode switches (Sieging Tanks, Phasing prisms, Burrowing roaches). There may be some other situations where a unit transformation is a type change and not a new unit. """ + 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] @@ -422,18 +475,22 @@ def __init__(self, frames, data, build): self.unit = None #: The the new unit type name - self.unit_type_name = data[2].decode('utf8') + self.unit_type_name = data[2].decode("utf8") def __str__(self): - return self._str_prefix() + "{0: >15} - Unit {0} type changed to {1}".format(str(self.unit.owner), self.unit, self.unit_type_name) + return ( + self._str_prefix() + + f"{str(self.unit.owner): >15} - Unit {self.unit} type changed to {self.unit_type_name}" + ) class UpgradeCompleteEvent(TrackerEvent): """ Generated when a player completes an upgrade. """ + def __init__(self, frames, data, build): - super(UpgradeCompleteEvent, self).__init__(frames) + super().__init__(frames) #: The player that completed the upgrade self.pid = data[0] @@ -442,13 +499,16 @@ def __init__(self, frames, data, build): self.player = None #: The name of the upgrade - self.upgrade_type_name = data[1].decode('utf8') + self.upgrade_type_name = data[1].decode("utf8") #: The number of times this upgrade as been researched self.count = data[2] def __str__(self): - return self._str_prefix() + "{0: >15} - {1} upgrade completed".format(str(self.player), self.upgrade_type_name) + return ( + self._str_prefix() + + f"{str(self.player): >15} - {self.upgrade_type_name} upgrade completed" + ) class UnitInitEvent(TrackerEvent): @@ -457,8 +517,9 @@ class UnitInitEvent(TrackerEvent): initiated. This applies only to units which are started in game before they are finished. Primary examples being buildings and warp-in units. """ + 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] @@ -473,7 +534,7 @@ def __init__(self, frames, data, build): self.unit = None #: The the new unit type name - self.unit_type_name = data[2].decode('utf8') + self.unit_type_name = data[2].decode("utf8") #: The id of the player that controls this unit. self.control_pid = data[3] @@ -504,7 +565,10 @@ 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(str(self.unit_upkeeper), self.unit) + return ( + self._str_prefix() + + f"{str(self.unit_upkeeper): >15} - Unit initiated {self.unit}" + ) class UnitDoneEvent(TrackerEvent): @@ -512,8 +576,9 @@ class UnitDoneEvent(TrackerEvent): The counter part to the :class:`UnitInitEvent`, generated by the game engine when an initiated unit is completed. E.g. warp-in finished, building finished, morph complete. """ + 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] @@ -528,7 +593,9 @@ def __init__(self, frames, data, build): self.unit = None def __str__(self): - return self._str_prefix() + "{0: >15} - Unit {1} done".format(str(self.unit.owner), self.unit) + return ( + self._str_prefix() + f"{str(self.unit.owner): >15} - Unit {self.unit} done" + ) class UnitPositionsEvent(TrackerEvent): @@ -537,8 +604,9 @@ class UnitPositionsEvent(TrackerEvent): the last interval. If more than 255 units were damaged, then the first 255 are reported and the remaining units are carried into the next interval. """ + 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 caf13b86..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 @@ -27,12 +23,12 @@ class MultipleMatchingFilesError(SC2ReaderError): class ReadError(SC2ReaderError): - def __init__(self, msg, type, location, replay=None, game_events=[], buffer=None): + 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 ad465609..724a51e3 100644 --- a/sc2reader/factories/plugins/replay.py +++ b/sc2reader/factories/plugins/replay.py @@ -1,12 +1,14 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import json from collections import defaultdict from sc2reader import log_utils from sc2reader.utils import Length -from sc2reader.factories.plugins.utils import PlayerSelection, GameState, JSONDateEncoder, plugin +from sc2reader.factories.plugins.utils import ( + PlayerSelection, + GameState, + JSONDateEncoder, + plugin, +) @plugin @@ -23,70 +25,77 @@ def toDict(replay): observers = list() for observer in replay.observers: messages = list() - for message in getattr(observer, 'messages', list()): - messages.append({ - 'time': message.time.seconds, - 'text': message.text, - 'is_public': message.to_all - }) - observers.append({ - 'name': getattr(observer, 'name', None), - 'pid': getattr(observer, 'pid', None), - 'messages': messages, - }) + for message in getattr(observer, "messages", list()): + messages.append( + { + "time": message.time.seconds, + "text": message.text, + "is_public": message.to_all, + } + ) + observers.append( + { + "name": getattr(observer, "name", None), + "pid": getattr(observer, "pid", None), + "messages": messages, + } + ) # Build players into dictionary players = list() for player in replay.players: messages = list() for message in player.messages: - messages.append({ - 'time': message.time.seconds, - 'text': message.text, - 'is_public': message.to_all - }) - players.append({ - 'avg_apm': getattr(player, 'avg_apm', None), - 'color': player.color.__dict__ if hasattr(player, 'color') else None, - 'handicap': getattr(player, 'handicap', None), - 'name': getattr(player, 'name', None), - 'pick_race': getattr(player, 'pick_race', None), - 'pid': getattr(player, 'pid', None), - 'play_race': getattr(player, 'play_race', None), - 'result': getattr(player, 'result', None), - 'type': getattr(player, 'type', None), - 'uid': getattr(player, 'uid', None), - 'url': getattr(player, 'url', None), - 'messages': messages, - }) + messages.append( + { + "time": message.time.seconds, + "text": message.text, + "is_public": message.to_all, + } + ) + players.append( + { + "avg_apm": getattr(player, "avg_apm", None), + "color": player.color.__dict__ if hasattr(player, "color") else None, + "handicap": getattr(player, "handicap", None), + "name": getattr(player, "name", None), + "pick_race": getattr(player, "pick_race", None), + "pid": getattr(player, "pid", None), + "play_race": getattr(player, "play_race", None), + "result": getattr(player, "result", None), + "type": getattr(player, "type", None), + "uid": getattr(player, "uid", None), + "url": getattr(player, "url", None), + "messages": messages, + } + ) # Consolidate replay metadata into dictionary return { - 'region': getattr(replay, 'region', None), - 'map_name': getattr(replay, 'map_name', None), - 'file_time': getattr(replay, 'file_time', None), - 'filehash': getattr(replay, 'filehash', None), - 'unix_timestamp': getattr(replay, 'unix_timestamp', None), - 'date': getattr(replay, 'date', None), - 'utc_date': getattr(replay, 'utc_date', None), - 'speed': getattr(replay, 'speed', None), - 'category': getattr(replay, 'category', None), - 'type': getattr(replay, 'type', None), - 'is_ladder': getattr(replay, 'is_ladder', False), - 'is_private': getattr(replay, 'is_private', False), - 'filename': getattr(replay, 'filename', None), - 'file_time': getattr(replay, 'file_time', None), - 'frames': getattr(replay, 'frames', None), - 'build': getattr(replay, 'build', None), - 'release': getattr(replay, 'release_string', None), - 'game_fps': getattr(replay, 'game_fps', None), - 'game_length': getattr(getattr(replay, 'game_length', None), 'seconds', None), - 'players': players, - 'observers': observers, - 'real_length': getattr(getattr(replay, 'real_length', None), 'seconds', None), - 'real_type': getattr(replay, 'real_type', None), - 'time_zone': getattr(replay, 'time_zone', None), - 'versions': getattr(replay, 'versions', None) + "region": getattr(replay, "region", None), + "map_name": getattr(replay, "map_name", None), + "file_time": getattr(replay, "file_time", None), + "filehash": getattr(replay, "filehash", None), + "unix_timestamp": getattr(replay, "unix_timestamp", None), + "date": getattr(replay, "date", None), + "utc_date": getattr(replay, "utc_date", None), + "speed": getattr(replay, "speed", None), + "category": getattr(replay, "category", None), + "type": getattr(replay, "type", None), + "is_ladder": getattr(replay, "is_ladder", False), + "is_private": getattr(replay, "is_private", False), + "filename": getattr(replay, "filename", None), + "frames": getattr(replay, "frames", None), + "build": getattr(replay, "build", None), + "release": getattr(replay, "release_string", None), + "game_fps": getattr(replay, "game_fps", None), + "game_length": getattr(getattr(replay, "game_length", None), "seconds", None), + "players": players, + "observers": observers, + "real_length": getattr(getattr(replay, "real_length", None), "seconds", None), + "real_type": getattr(replay, "real_type", None), + "time_zone": getattr(replay, "time_zone", None), + "versions": getattr(replay, "versions", None), } @@ -106,23 +115,30 @@ def APMTracker(replay): player.seconds_played = replay.length.seconds for event in player.events: - if event.name == 'SelectionEvent' or 'CommandEvent' in event.name or 'ControlGroup' in event.name: + if ( + event.name == "SelectionEvent" + or "CommandEvent" in event.name + or "ControlGroup" in event.name + ): player.aps[event.second] += 1.4 - player.apm[int(event.second/60)] += 1.4 + player.apm[int(event.second / 60)] += 1.4 - elif event.name == 'PlayerLeaveEvent': + elif event.name == "PlayerLeaveEvent": player.seconds_played = event.second - if len(player.apm) > 0: - player.avg_apm = sum(player.aps.values())/float(player.seconds_played)*60 + if len(player.apm) > 0 and player.seconds_played > 0: + player.avg_apm = ( + sum(player.aps.values()) / float(player.seconds_played) * 60 + ) else: player.avg_apm = 0 return replay + @plugin def SelectionTracker(replay): - debug = replay.opt['debug'] + debug = replay.opt["debug"] logger = log_utils.get_logger(SelectionTracker) for person in replay.entities: @@ -131,37 +147,45 @@ def SelectionTracker(replay): player_selections = GameState(PlayerSelection()) for event in person.events: error = False - if event.name == 'SelectionEvent': + if event.name == "SelectionEvent": selections = player_selections[event.frame] control_group = selections[event.control_group].copy() error = not control_group.deselect(event.mask_type, event.mask_data) control_group.select(event.new_units) selections[event.control_group] = control_group if debug: - logger.info("[{0}] {1} selected {2} units: {3}".format(Length(seconds=event.second), person.name, len(selections[0x0A].objects), selections[0x0A])) + logger.info( + f"[{Length(seconds=event.second)}] {person.name} selected {len(selections[0x0A].objects)} units: {selections[0x0A]}" + ) - elif event.name == 'SetControlGroupEvent': + elif event.name == "SetControlGroupEvent": selections = player_selections[event.frame] selections[event.control_group] = selections[0x0A].copy() if debug: - logger.info("[{0}] {1} set hotkey {2} to current selection".format(Length(seconds=event.second), person.name, event.hotkey)) + logger.info( + f"[{Length(seconds=event.second)}] {person.name} set hotkey {event.hotkey} to current selection" + ) - elif event.name == 'AddToControlGroupEvent': + elif event.name == "AddToControlGroupEvent": selections = player_selections[event.frame] control_group = selections[event.control_group].copy() error = not control_group.deselect(event.mask_type, event.mask_data) control_group.select(selections[0x0A].objects) selections[event.control_group] = control_group if debug: - logger.info("[{0}] {1} added current selection to hotkey {2}".format(Length(seconds=event.second), person.name, event.hotkey)) + logger.info( + f"[{Length(seconds=event.second)}] {person.name} added current selection to hotkey {event.hotkey}" + ) - elif event.name == 'GetControlGroupEvent': + elif event.name == "GetControlGroupEvent": selections = player_selections[event.frame] control_group = selections[event.control_group].copy() error = not control_group.deselect(event.mask_type, event.mask_data) selections[0xA] = control_group if debug: - logger.info("[{0}] {1} retrieved hotkey {2}, {3} units: {4}".format(Length(seconds=event.second), person.name, event.control_group, len(selections[0x0A].objects), selections[0x0A])) + logger.info( + f"[{Length(seconds=event.second)}] {person.name} retrieved hotkey {event.control_group}, {len(selections[0x0A].objects)} units: {selections[0x0A]}" + ) else: continue @@ -172,7 +196,9 @@ def SelectionTracker(replay): if error: person.selection_errors += 1 if debug: - logger.warn("Error detected in deselection mode {0}.".format(event.mask_type)) + logger.warning( + f"Error detected in deselection mode {event.mask_type}." + ) person.selection = player_selections # Not a real lock, so don't change it! diff --git a/sc2reader/factories/plugins/utils.py b/sc2reader/factories/plugins/utils.py index cf3559ea..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 @@ -18,7 +15,9 @@ def call(*args, **kwargs): opt = kwargs.copy() opt.update(options) return func(*args, **opt) + return call + return wrapper @@ -38,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 @@ -56,7 +55,7 @@ def __getitem__(self, frame): else: # Copy the previous state and use it as our basis here state = self[prev_frame] - if hasattr(state, 'copy'): + if hasattr(state, "copy"): state = state.copy() self[frame] = state @@ -67,44 +66,51 @@ 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() def select(self, new_objects): - new_set = set(self.objects+list(new_objects)) + new_set = set(self.objects + list(new_objects)) self.objects = sorted(new_set, key=lambda obj: obj.id) def deselect(self, mode, data): """Returns false if there was a data error when deselecting""" size = len(self.objects) - if mode == 'None': + if mode == "None": return True - elif mode == 'Mask': - """ Deselect objects according to deselect mask """ + elif mode == "Mask": + """Deselect objects according to deselect mask""" mask = data if len(mask) < size: # pad to the right - mask = mask+[False]*(len(self.objects)-len(mask)) - - self.logger.debug("Deselection Mask: {0}".format(mask)) - self.objects = [obj for (slct, obj) in filter(lambda slct_obj: not slct_obj[0], zip(mask, self.objects))] + mask = mask + [False] * (len(self.objects) - len(mask)) + + self.logger.debug(f"Deselection Mask: {mask}") + self.objects = [ + obj + for (slct, obj) in filter( + lambda slct_obj: not slct_obj[0], zip(mask, self.objects) + ) + ] return len(mask) <= size - elif mode == 'OneIndices': - """ Deselect objects according to indexes """ + elif mode == "OneIndices": + """Deselect objects according to indexes""" clean_data = list(filter(lambda i: i < size, data)) - self.objects = [self.objects[i] for i in range(len(self.objects)) if i not in clean_data] + self.objects = [ + self.objects[i] for i in range(len(self.objects)) if i not in clean_data + ] return len(clean_data) == len(data) - elif mode == 'ZeroIndices': - """ Deselect objects according to indexes """ + elif mode == "ZeroIndices": + """Deselect objects according to indexes""" clean_data = list(filter(lambda i: i < size, data)) self.objects = [self.objects[i] for i in clean_data] return len(clean_data) == len(data) @@ -113,7 +119,7 @@ def deselect(self, mode, data): return False def __str__(self): - return ', '.join(str(obj) for obj in self.objects) + return ", ".join(str(obj) for obj in self.objects) def copy(self): return UnitSelection(self.objects[:]) @@ -121,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 36020b2d..40de1c7f 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,8 +24,9 @@ @log_utils.loggable -class SC2Factory(object): - """The SC2Factory class acts as a generic loader interface for all +class SC2Factory: + """ + The SC2Factory class acts as a generic loader interface for all available to sc2reader resources. At current time this includes :class:`~sc2reader.resources.Replay` and :class:`~sc2reader.resources.Map` resources. These resources can be loaded in both singular and plural contexts with: @@ -64,8 +62,8 @@ class SC2Factory(object): _resource_name_map = dict(replay=Replay, map=Map) default_options = { - Resource: {'debug': False}, - Replay: {'load_level': 4, 'load_map': False}, + Resource: {"debug": False}, + Replay: {"load_level": 4, "load_map": False}, } def __init__(self, **options): @@ -81,51 +79,79 @@ def __init__(self, **options): # Primary Interface def load_replay(self, source, options=None, **new_options): - """Loads a single sc2replay file. Accepts file path, url, or file object.""" + """ + Loads a single sc2replay file. Accepts file path, url, or file object. + """ return self.load(Replay, source, options, **new_options) def load_replays(self, sources, options=None, **new_options): - """Loads a collection of sc2replay files, returns a generator.""" - return self.load_all(Replay, sources, options, extension='SC2Replay', **new_options) + """ + Loads a collection of sc2replay files, returns a generator. + """ + return self.load_all( + Replay, sources, options, extension="SC2Replay", **new_options + ) def load_localization(self, source, options=None, **new_options): - """Loads a single s2ml file. Accepts file path, url, or file object.""" + """ + Loads a single s2ml file. Accepts file path, url, or file object. + """ return self.load(Localization, source, options, **new_options) def load_localizations(self, sources, options=None, **new_options): - """Loads a collection of s2ml files, returns a generator.""" - return self.load_all(Localization, sources, options, extension='s2ml', **new_options) + """ + Loads a collection of s2ml files, returns a generator. + """ + return self.load_all( + Localization, sources, options, extension="s2ml", **new_options + ) def load_map(self, source, options=None, **new_options): - """Loads a single s2ma file. Accepts file path, url, or file object.""" + """ + Loads a single s2ma file. Accepts file path, url, or file object. + """ return self.load(Map, source, options, **new_options) def load_maps(self, sources, options=None, **new_options): - """Loads a collection of s2ma files, returns a generator.""" - return self.load_all(Map, sources, options, extension='s2ma', **new_options) + """ + Loads a collection of s2ma files, returns a generator. + """ + return self.load_all(Map, sources, options, extension="s2ma", **new_options) def load_game_summary(self, source, options=None, **new_options): - """Loads a single s2gs file. Accepts file path, url, or file object.""" + """ + Loads a single s2gs file. Accepts file path, url, or file object. + """ return self.load(GameSummary, source, options, **new_options) def load_game_summaries(self, sources, options=None, **new_options): - """Loads a collection of s2gs files, returns a generator.""" - return self.load_all(GameSummary, sources, options, extension='s2gs', **new_options) + """ + Loads a collection of s2gs files, returns a generator. + """ + return self.load_all( + GameSummary, sources, options, extension="s2gs", **new_options + ) def configure(self, cls=None, **options): - """ Configures the factory to use the supplied options. If cls is specified - the options will only be applied when loading that class""" + """ + Configures the factory to use the supplied options. If cls is specified + the options will only be applied when loading that class + """ if isinstance(cls, basestring): cls = self._resource_name_map.get[cls.lower()] cls = cls or Resource self.options[cls].update(options) def reset(self): - "Resets the options to factory defaults" + """ + Resets the options to factory defaults + """ self.options = defaultdict(dict) def register_plugin(self, cls, plugin): - "Registers the given Plugin to be run on classes of the supplied name." + """ + Registers the given Plugin to be run on classes of the supplied name. + """ if isinstance(cls, basestring): cls = self._resource_name_map.get(cls.lower(), Resource) self.plugins.append((cls, plugin)) @@ -144,7 +170,7 @@ def load_all(self, cls, sources, options=None, **new_options): # Internal Functions def _load(self, cls, resource, filename, options): obj = cls(resource, filename=filename, factory=self, **options) - for plugin in options.get('plugins', self._get_plugins(cls)): + for plugin in options.get("plugins", self._get_plugins(cls)): obj = plugin(obj) return obj @@ -164,7 +190,9 @@ def _get_options(self, cls, **new_options): return options def _load_resources(self, resources, options=None, **new_options): - """Collections of resources or a path to a directory""" + """ + Collections of resources or a path to a directory + """ options = options or self._get_options(Resource, **new_options) # Path to a folder, retrieve all relevant files as the collection @@ -180,22 +208,24 @@ def load_remote_resource_contents(self, resource, **options): def load_local_resource_contents(self, location, **options): # Extract the contents so we can close the file - with open(location, 'rb') as resource_file: + with open(location, "rb") as resource_file: return resource_file.read() def _load_resource(self, resource, options=None, **new_options): - """http links, filesystem locations, and file-like objects""" + """ + http links, filesystem locations, and file-like objects + """ options = options or self._get_options(Resource, **new_options) if isinstance(resource, utils.DepotFile): resource = resource.url if isinstance(resource, basestring): - if re.match(r'https?://', resource): + if re.match(r"https?://", resource): contents = self.load_remote_resource_contents(resource, **options) else: - directory = options.get('directory', '') + directory = options.get("directory", "") location = os.path.join(directory, resource) contents = self.load_local_resource_contents(location, **options) @@ -206,44 +236,43 @@ def _load_resource(self, resource, options=None, **new_options): else: # Totally not designed for large files!! # We need a multiread resource, so wrap it in BytesIO - if not hasattr(resource, 'seek'): + if not hasattr(resource, "seek"): resource = BytesIO(resource.read()) - resource_name = getattr(resource, 'name', 'Unknown') + resource_name = getattr(resource, "name", "Unknown") - if options.get('verbose', None): + if options.get("verbose", None): print(resource_name) return (resource, resource_name) class CachedSC2Factory(SC2Factory): - def get_remote_cache_key(self, remote_resource): # Strip the port and use the domain as the bucket # and use the full path as the key parseresult = urlparse(remote_resource) - bucket = re.sub(r':.*', '', parseresult.netloc) - key = parseresult.path.strip('/') + bucket = re.sub(r":.*", "", parseresult.netloc) + key = parseresult.path.strip("/") return (bucket, key) 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(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) return resource def cache_has(self, cache_key): - raise NotImplemented() + raise NotImplementedError() def cache_get(self, cache_key): - raise NotImplemented() + raise NotImplementedError() def cache_set(self, cache_key, value): - raise NotImplemented() + raise NotImplementedError() class FileCachedSC2Factory(CachedSC2Factory): @@ -254,13 +283,18 @@ class FileCachedSC2Factory(CachedSC2Factory): Caches remote depot resources on the file system in the ``cache_dir``. """ + 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)) + raise ValueError( + 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(self.cache_dir)) + raise ValueError( + f"Must have read/write access to {self.cache_dir} for local file caching." + ) def cache_has(self, cache_key): return os.path.exists(self.cache_path(cache_key)) @@ -274,7 +308,7 @@ def cache_set(self, cache_key, value): if not os.path.exists(bucket_dir): os.makedirs(bucket_dir) - with open(cache_path, 'wb') as out: + with open(cache_path, "wb") as out: out.write(value) def cache_path(self, cache_key): @@ -290,8 +324,9 @@ class DictCachedSC2Factory(CachedSC2Factory): Caches remote depot resources in memory. Does not write to the file system. The cache is effectively cleared when the process exits. """ + 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 @@ -322,8 +357,9 @@ class DoubleCachedSC2Factory(DictCachedSC2Factory, FileCachedSC2Factory): Caches remote depot resources to the file system AND holds a subset of them in memory for more efficient access. """ + def __init__(self, cache_dir, cache_max_size=0, **options): - super(DoubleCachedSC2Factory, self).__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) @@ -332,7 +368,9 @@ def load_remote_resource_contents(self, remote_resource, **options): return DictCachedSC2Factory.cache_get(self, cache_key) if not FileCachedSC2Factory.cache_has(self, cache_key): - resource = SC2Factory.load_remote_resource_contents(self, remote_resource, **options) + resource = SC2Factory.load_remote_resource_contents( + self, remote_resource, **options + ) FileCachedSC2Factory.cache_set(self, cache_key, resource) else: resource = FileCachedSC2Factory.cache_get(self, cache_key) diff --git a/sc2reader/log_utils.py b/sc2reader/log_utils.py index 58a442d9..dc20fe92 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: @@ -22,6 +19,7 @@ class NullHandler(logging.Handler): a NullHandler and add it to the top-level logger of the library module or package. """ + def handle(self, record): pass @@ -31,52 +29,53 @@ def emit(self, record): def createLock(self): self.lock = None + LEVEL_MAP = dict( DEBUG=logging.DEBUG, INFO=logging.INFO, - WARN=logging.WARN, + WARN=logging.WARNING, ERROR=logging.ERROR, - CRITICAL=logging.CRITICAL + CRITICAL=logging.CRITICAL, ) def setup(): - logging.getLogger('sc2reader').addHandler(NullHandler()) + logging.getLogger("sc2reader").addHandler(NullHandler()) -def log_to_file(filename, level='WARN', format=None, datefmt=None, **options): +def log_to_file(filename, level="WARN", format=None, datefmt=None, **options): add_log_handler(logging.FileHandler(filename, **options), level, format, datefmt) -def log_to_console(level='WARN', format=None, datefmt=None, **options): +def log_to_console(level="WARN", format=None, datefmt=None, **options): add_log_handler(logging.StreamHandler(**options), level, format, datefmt) -def add_log_handler(handler, level='WARN', format=None, datefmt=None): +def add_log_handler(handler, level="WARN", format=None, datefmt=None): handler.setFormatter(logging.Formatter(format, datefmt)) if isinstance(level, basestring): level = LEVEL_MAP[level] - logger = logging.getLogger('sc2reader') + logger = logging.getLogger("sc2reader") logger.setLevel(level) logger.addHandler(handler) def get_logger(entity): """ - Retrieves loggers from the enties fully scoped name. + Retrieves loggers from the enties fully scoped name. - get_logger(Replay) -> sc2reader.replay.Replay - get_logger(get_logger) -> sc2reader.utils.get_logger + get_logger(Replay) -> sc2reader.replay.Replay + get_logger(get_logger) -> sc2reader.utils.get_logger - :param entity: The entity for which we want a logger. + :param entity: The entity for which we want a logger. """ try: - return logging.getLogger(entity.__module__+'.'+entity.__name__) + 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 eaa2e28b..03632dee 100644 --- a/sc2reader/objects.py +++ b/sc2reader/objects.py @@ -1,28 +1,25 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import hashlib import math from collections import namedtuple from sc2reader import utils, log_utils from sc2reader.decoders import ByteDecoder -from sc2reader.constants import * +from sc2reader.constants import GATEWAY_LOOKUP, LOBBY_PROPERTIES, LOCALIZED_RACES -Location = namedtuple('Location', ['x', 'y']) +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 looped over like a list. - :param interger number: The team number as recorded in the replay + :param integer number: The team number as recorded in the replay """ #: 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 @@ -48,48 +45,54 @@ def lineup(self): A string representation of the team play races like PP or TPZZ. Random pick races are not reflected in this string """ - return ''.join(sorted(p.play_race[0].upper() for p in self.players)) + return "".join(sorted(p.play_race[0].upper() for p in self.players)) @property - def hash(self): - raw_hash = ','.join(sorted(p.url for p in self.players)) + def hash(self): # noqa: F811 + raw_hash = ",".join(sorted(p.url for p in self.players)) return hashlib.sha256(raw_hash).hexdigest() def __str__(self): - return "Team {0}: {1}".format(self.number, ", ".join([str(p) for p in self.players])) + return "Team {}: {}".format( + self.number, ", ".join([str(p) for p in self.players]) + ) def __repr__(self): return str(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: self.name, lookup = LOBBY_PROPERTIES[self.id] - self.value = lookup[value.strip("\x00 ")[::-1]] + try: + self.value = lookup[value.strip("\x00 ")[::-1]] + except KeyError: + 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 """ + def __init__(self, sid, slot_data): #: The entity's unique in-game slot id self.sid = int(sid) @@ -98,53 +101,56 @@ def __init__(self, sid, slot_data): self.slot_data = slot_data #: The player's handicap as set prior to game start, ranges from 50-100 - self.handicap = slot_data['handicap'] + self.handicap = slot_data["handicap"] #: The entity's team number. None for observers self.team_id = None - if slot_data['team_id'] is not None: - self.team_id = slot_data['team_id'] + 1 + if slot_data["team_id"] is not None: + self.team_id = slot_data["team_id"] + 1 #: A flag indicating if the person is a human or computer #: Really just a shortcut for isinstance(entity, User) - self.is_human = slot_data['control'] == 2 + self.is_human = slot_data["control"] == 2 #: A flag indicating the entity's observer status. #: Really just a shortcut for isinstance(entity, Observer). - self.is_observer = slot_data['observe'] != 0 + self.is_observer = slot_data["observe"] != 0 #: A flag marking this entity as a referee (can talk to players) - self.is_referee = slot_data['observe'] == 2 + self.is_referee = slot_data["observe"] == 2 #: - self.hero_name = slot_data['hero'] + self.hero_name = slot_data["hero"] #: - self.hero_skin = slot_data['skin'] + self.hero_skin = slot_data["skin"] #: - self.hero_mount = slot_data['mount'] + self.hero_mount = slot_data["mount"] #: The unique Battle.net account identifier in the form of #: -S2-- - self.toon_handle = slot_data['toon_handle'] + self.toon_handle = slot_data["toon_handle"] toon_handle = self.toon_handle or "0-S2-0-0" parts = toon_handle.split("-") + #: The Battle.net region id the entity is registered to + self.region_id = int(parts[0]) + #: The Battle.net region the entity is registered to - self.region = GATEWAY_LOOKUP[int(parts[0])] + self.region = GATEWAY_LOOKUP[self.region_id] #: The Battle.net subregion the entity is registered to self.subregion = int(parts[2]) - #: The Battle.net acount identifier. Used to construct the + #: The Battle.net account identifier. Used to construct the #: bnet profile url. This value can be zero for games #: played offline when a user was not logged in to battle.net. self.toon_id = int(parts[3]) #: A index to the user that is the leader of the archon team - self.archon_leader_id = slot_data['tandem_leader_user_id'] + self.archon_leader_id = slot_data["tandem_leader_user_id"] #: A list of :class:`Event` objects representing all the game events #: generated by the person over the course of the game @@ -158,12 +164,13 @@ 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 :param dict attribute_data: The attribute data associated with this player """ + def __init__(self, pid, slot_data, detail_data, attribute_data): #: The player's unique in-game player id self.pid = int(pid) @@ -179,9 +186,9 @@ def __init__(self, pid, slot_data, detail_data, attribute_data): #: The player result, one of "Win", "Loss", or None self.result = None - if detail_data['result'] == 1: + if detail_data["result"] == 1: self.result = "Win" - elif detail_data['result'] == 2: + elif detail_data["result"] == 2: self.result = "Loss" #: A reference to the player's :class:`Team` object @@ -189,37 +196,41 @@ def __init__(self, pid, slot_data, detail_data, attribute_data): #: The race the player picked prior to the game starting. #: One of Protoss, Terran, Zerg, Random - self.pick_race = attribute_data.get('Race', 'Unknown') + self.pick_race = attribute_data.get("Race", "Unknown") #: The difficulty setting for the player. Always Medium for human players. #: Very Easy, Easy, Medium, Hard, Harder, Very hard, Elite, Insane, #: Cheater 2 (Resources), Cheater 1 (Vision) - self.difficulty = attribute_data.get('Difficulty', 'Unknown') + self.difficulty = attribute_data.get("Difficulty", "Unknown") #: The race the player played the game with. #: One of Protoss, Terran, Zerg - self.play_race = LOCALIZED_RACES.get(detail_data['race'], detail_data['race']) + self.play_race = LOCALIZED_RACES.get(detail_data["race"], detail_data["race"]) #: The co-op commander the player picked #: Kerrigan, Raynor, etc. - self.commander = slot_data['commander'] + self.commander = slot_data["commander"] if self.commander is not None: - self.commander = self.commander.decode('utf8') + self.commander = self.commander.decode("utf8") #: The level of the co-op commander #: 1-15 or None - self.commander_level = slot_data['commander_level'] + self.commander_level = slot_data["commander_level"] #: The mastery level of the co-op commander #: >0 or None - self.commander_mastery_level = slot_data['commander_mastery_talents'] + self.commander_mastery_level = slot_data["commander_mastery_talents"] + + #: Trophy ID + #: >0 or None + self.trophy_id = slot_data["trophy_id"] #: The mastery talents picked for the co-op commander #: list of longs of length 6, each between 0 and 30 - self.commander_mastery_talents = slot_data['commander_mastery_talents'] + self.commander_mastery_talents = slot_data["commander_mastery_talents"] #: A reference to a :class:`~sc2reader.utils.Color` object representing the player's color - self.color = utils.Color(**detail_data['color']) + self.color = utils.Color(**detail_data["color"]) #: A list of references to the :class:`~sc2reader.data.Unit` objects the player had this game self.units = list() @@ -228,24 +239,30 @@ def __init__(self, pid, slot_data, detail_data, attribute_data): self.killed_units = list() #: The Battle.net region the entity is registered to - self.region = GATEWAY_LOOKUP[detail_data['bnet']['region']] + self.region = GATEWAY_LOOKUP[detail_data["bnet"]["region"]] + + #: The Battle.net region id the entity is registered to + self.region_id = detail_data["bnet"]["region"] #: The Battle.net subregion the entity is registered to - self.subregion = detail_data['bnet']['subregion'] + self.subregion = detail_data["bnet"]["subregion"] - #: The Battle.net acount identifier. Used to construct the + #: The Battle.net account identifier. Used to construct the #: bnet profile url. This value can be zero for games #: played offline when a user was not logged in to battle.net. - self.toon_id = detail_data['bnet']['uid'] + 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 """ + #: The Battle.net profile url template - URL_TEMPLATE = "http://{region}.battle.net/sc2/en/profile/{toon_id}/{subregion}/{name}/" + URL_TEMPLATE = ( + "https://starcraft2.com/en-us/profile/{region_id}/{subregion}/{toon_id}" + ) def __init__(self, uid, init_data): #: The user's unique in-game user id @@ -255,30 +272,44 @@ def __init__(self, uid, init_data): self.init_data = init_data #: The user's Battle.net clan tag at the time of the game - self.clan_tag = init_data['clan_tag'] + self.clan_tag = init_data["clan_tag"] #: The user's Battle.net name at the time of the game - self.name = init_data['name'] + self.name = init_data["name"] #: The user's combined Battle.net race levels - self.combined_race_levels = init_data['combined_race_levels'] + self.combined_race_levels = init_data["combined_race_levels"] #: The highest 1v1 league achieved by the user in the current season with 1 as Bronze and #: 7 as Grandmaster. 8 seems to indicate that there is no current season 1v1 ranking. - self.highest_league = init_data['highest_league'] + self.highest_league = init_data["highest_league"] #: A flag indicating if this person was the one who recorded the game. #: This is deprecated because it doesn't actually work. self.recorder = None + #: The user's mmr at the time of the game + #: Currently, there are three cases observed for a user that does not have a current mmr: + #: 1. The user has no 'scaled_rating' key in their init_data, + #: 2. The user has a None value for their 'scaled_rating' key, or + #: 3. The user has a negative rating, often -36400. + #: For ease of use, this property will return None in both cases. + matchmaking_rating = int(init_data.get("scaled_rating") or 0) + self.mmr = matchmaking_rating if matchmaking_rating > 0 else None + @property def url(self): - """The player's formatted Battle.net profile url""" - return self.URL_TEMPLATE.format(**self.__dict__) # region=self.region, toon_id=self.toon_id, subregion=self.subregion, name=self.name.('utf8')) + """ + The player's formatted Battle.net profile url + """ + return self.URL_TEMPLATE.format( + **self.__dict__ + ) # region=self.region, toon_id=self.toon_id, subregion=self.subregion, name=self.name.('utf8')) class Observer(Entity, User): - """ Extends :class:`Entity` and :class:`User`. + """ + Extends :class:`Entity` and :class:`User`. :param integer sid: The entity's unique slot id. :param dict slot_data: The slot data associated with this entity @@ -286,6 +317,7 @@ class Observer(Entity, User): :param dict init_data: The init data associated with this user :param integer pid: The player's unique player id. """ + def __init__(self, sid, slot_data, uid, init_data, pid): Entity.__init__(self, sid, slot_data) User.__init__(self, uid, init_data) @@ -294,14 +326,15 @@ 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) class Computer(Entity, Player): - """ Extends :class:`Entity` and :class:`Player` + """ + Extends :class:`Entity` and :class:`Player` :param integer sid: The entity's unique slot id. :param dict slot_data: The slot data associated with this entity @@ -309,22 +342,24 @@ class Computer(Entity, Player): :param dict detail_data: The detail data associated with this player :param dict attribute_data: The attribute data associated with this player """ + def __init__(self, sid, slot_data, pid, detail_data, attribute_data): Entity.__init__(self, sid, slot_data) Player.__init__(self, pid, slot_data, detail_data, attribute_data) #: The auto-generated in-game name for this computer player - self.name = detail_data['name'] + 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) class Participant(Entity, User, Player): - """ Extends :class:`Entity`, :class:`User`, and :class:`Player` + """ + Extends :class:`Entity`, :class:`User`, and :class:`Player` :param integer sid: The entity's unique slot id. :param dict slot_data: The slot data associated with this entity @@ -334,19 +369,22 @@ class Participant(Entity, User, Player): :param dict detail_data: The detail data associated with this player :param dict attribute_data: The attribute data associated with this player """ - def __init__(self, sid, slot_data, uid, init_data, pid, detail_data, attribute_data): + + def __init__( + self, sid, slot_data, uid, init_data, pid, detail_data, attribute_data + ): Entity.__init__(self, sid, slot_data) User.__init__(self, uid, init_data) 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) -class PlayerSummary(): +class PlayerSummary: """ Resents a player as loaded from a :class:`~sc2reader.resources.GameSummary` file. @@ -359,10 +397,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 @@ -377,7 +415,7 @@ class PlayerSummary(): subregion = int() #: The player's region, such as us, eu, sea - region = str() + region = "" #: unknown1 unknown1 = int() @@ -400,25 +438,27 @@ def __init__(self, pid): def __str__(self): if not self.is_ai: - return 'User {0}-S2-{1}-{2}'.format(self.region.upper(), self.subregion, self.bnetid) + return f"User {self.region.upper()}-S2-{self.subregion}-{self.bnetid}" else: - return 'AI ({0})'.format(self.play_race) + return f"AI ({self.play_race})" def __repr__(self): return str(self) def get_stats(self): - s = '' + 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() -BuildEntry = namedtuple('BuildEntry', ['supply', 'total_supply', 'time', 'order', 'build_index']) +BuildEntry = namedtuple( + "BuildEntry", ["supply", "total_supply", "time", "order", "build_index"] +) # TODO: Are there libraries with classes like this in them -class Graph(): +class Graph: """ A class to represent a graph on the score screen. Derived from data in the :class:`~sc2reader.resources.GameSummary` file. @@ -443,17 +483,18 @@ def __init__(self, x, y, xy_list=None): self.values = y def as_points(self): - """ Get the graph as a list of (x, y) tuples """ + """Get the graph as a list of (x, y) tuples""" 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. """ + def __init__(self, pid, control, color, race, unknown, start_point, ai, decal): #: The pid of the player self.pid = pid @@ -508,17 +549,18 @@ 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 """ + def __init__(self, contents): # According to http://www.galaxywiki.net/MapInfo_(File_Format) # With a couple small changes for version 0x20+ - data = ByteDecoder(contents, endian='LITTLE') + data = ByteDecoder(contents, endian="LITTLE") magic = data.read_string(4) - if magic != 'MapI': - self.logger.warn("Invalid MapInfo file: {0}".format(magic)) + if magic != "MapI": + self.logger.warning(f"Invalid MapInfo file: {magic}") return #: The map info file format version @@ -537,7 +579,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() @@ -545,17 +587,17 @@ 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() - if self.version >= 0x1f: + if self.version >= 0x1F: self.unknown3 = data.read_cstring() if self.version >= 0x26: self.unknown4 = data.read_cstring() - if self.version >= 0x1f: + if self.version >= 0x1F: self.unknown5 = data.read_uint32() self.unknown6 = data.read_uint32() @@ -579,10 +621,10 @@ def __init__(self, contents): self.camera_top = data.read_uint32() #: The map base height (what is that?). This value is 4096*Base Height in the editor (giving a decimal value). - self.base_height = data.read_uint32()/4096 + self.base_height = data.read_uint32() / 4096 - # Leave early so we dont barf. Turns out ggtracker doesnt need - # any of the map data thats loaded below. + # Leave early so we don't barf. Turns out ggtracker doesn't need + # any of the map data that is loaded below. return #: Load screen type: 0 = default, 1 = custom @@ -592,7 +634,7 @@ def __init__(self, contents): self.load_screen_path = data.read_cstring() #: Unknown string, usually empty - self.unknown7 = data.read_bytes(data.read_uint16()).decode('utf8') + self.unknown7 = data.read_bytes(data.read_uint16()).decode("utf8") #: Load screen image scaling strategy: 0 = normal, 1 = aspect scaling, 2 = stretch the image. self.load_screen_scaling = data.read_uint32() @@ -639,7 +681,7 @@ def __init__(self, contents): if self.version >= 0x19: self.unknown9 = data.read_bytes(8) - if self.version >= 0x1f: + if self.version >= 0x1F: self.unknown10 = data.read_bytes(9) if self.version >= 0x20: @@ -651,16 +693,18 @@ def __init__(self, contents): #: A list of references to :class:`MapInfoPlayer` objects self.players = list() for i in range(self.player_count): - self.players.append(MapInfoPlayer( - pid=data.read_uint8(), - control=data.read_uint32(), - color=data.read_uint32(), - race=data.read_cstring(), - unknown=data.read_uint32(), - start_point=data.read_uint32(), - ai=data.read_uint32(), - decal=data.read_cstring(), - )) + self.players.append( + MapInfoPlayer( + pid=data.read_uint8(), + control=data.read_uint32(), + color=data.read_uint32(), + race=data.read_cstring(), + unknown=data.read_uint32(), + start_point=data.read_uint32(), + ai=data.read_uint32(), + decal=data.read_cstring(), + ) + ) #: A list of the start location point indexes used in Basic Team Settings. #: The editor limits these to only Start Locations and not regular points. @@ -686,7 +730,9 @@ def __init__(self, contents): # } # } #: A bit array of flags mapping out the player alliances - self.alliance_flags = data.read_uint(int(math.ceil(self.alliance_flags_length/8.0))) + self.alliance_flags = data.read_uint( + int(math.ceil(self.alliance_flags_length / 8.0)) + ) #: A list of the advanced start location point indexes used in Advanced Team Settings. #: The editor limits these to only Start Locations and not regular points. @@ -722,10 +768,10 @@ def __init__(self, contents): # } # } #: A bit array of flags mapping out the player enemies. - self.enemy_flags = data.read_uint(int(math.ceil(self.enemy_flags_length/8.0))) + self.enemy_flags = data.read_uint(int(math.ceil(self.enemy_flags_length / 8.0))) if data.length != data.tell(): - self.logger.warn("Not all of the MapInfo file was read!") + self.logger.warning("Not all of the MapInfo file was read!") def __str__(self): return self.map_name diff --git a/sc2reader/readers.py b/sc2reader/readers.py index 54bf3f54..eab6e4c9 100644 --- a/sc2reader/readers.py +++ b/sc2reader/readers.py @@ -1,43 +1,110 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import struct from sc2reader.exceptions import ParseError, ReadError -from sc2reader.objects import * -from sc2reader.events.game import * -from sc2reader.events.message import * -from sc2reader.events.tracker import * +from sc2reader.objects import Attribute +from sc2reader.events.game import ( + CameraEvent, + CommandManagerStateEvent, + HijackReplayGameEvent, + PlayerLeaveEvent, + ResourceTradeEvent, + SelectionEvent, + UpdateTargetPointCommandEvent, + UpdateTargetUnitCommandEvent, + UserOptionsEvent, + DialogControlEvent, + create_command_event, + create_control_group_event, +) +from sc2reader.events.message import ChatEvent, PingEvent, ProgressEvent +from sc2reader.events.tracker import ( + PlayerSetupEvent, + PlayerStatsEvent, + UnitBornEvent, + UnitDiedEvent, + UnitDoneEvent, + UnitInitEvent, + UnitOwnerChangeEvent, + UnitPositionsEvent, + UnitTypeChangeEvent, + UpgradeCompleteEvent, +) from sc2reader.utils import DepotFile from sc2reader.decoders import BitPackedDecoder, ByteDecoder -class InitDataReader(object): +class InitDataReader: def __call__(self, data, replay): data = BitPackedDecoder(data) result = dict( - user_initial_data=[dict( - name=data.read_aligned_string(data.read_uint8()), - clan_tag=data.read_aligned_string(data.read_uint8()) if replay.base_build >= 24764 and data.read_bool() else None, - clan_logo=DepotFile(data.read_aligned_bytes(40)) if replay.base_build >= 27950 and data.read_bool() else None, - highest_league=data.read_uint8() if replay.base_build >= 24764 and data.read_bool() else None, - combined_race_levels=data.read_uint32() if replay.base_build >= 24764 and data.read_bool() else None, - random_seed=data.read_uint32(), - race_preference=data.read_uint8() if data.read_bool() else None, - team_preference=data.read_uint8() if replay.base_build >= 16561 and data.read_bool() else None, - test_map=data.read_bool(), - test_auto=data.read_bool(), - examine=data.read_bool() if replay.base_build >= 21955 else None, - custom_interface=data.read_bool() if replay.base_build >= 24764 else None, - test_type=data.read_uint32() if replay.base_build >= 34784 else None, - observe=data.read_bits(2), - hero=data.read_aligned_string(data.read_bits(9)) if replay.base_build >= 34784 else None, - skin=data.read_aligned_string(data.read_bits(9)) if replay.base_build >= 34784 else None, - mount=data.read_aligned_string(data.read_bits(9)) if replay.base_build >= 34784 else None, - toon_handle=data.read_aligned_string(data.read_bits(7)) if replay.base_build >= 34784 else None, - scaled_rating=data.read_uint32()-2147483648 if replay.base_build >= 54518 and data.read_bool() else None, - ) for i in range(data.read_bits(5))], - + user_initial_data=[ + dict( + name=data.read_aligned_string(data.read_uint8()), + clan_tag=( + data.read_aligned_string(data.read_uint8()) + if replay.base_build >= 24764 and data.read_bool() + else None + ), + clan_logo=( + DepotFile(data.read_aligned_bytes(40)) + if replay.base_build >= 27950 and data.read_bool() + else None + ), + highest_league=( + data.read_uint8() + if replay.base_build >= 24764 and data.read_bool() + else None + ), + combined_race_levels=( + data.read_uint32() + if replay.base_build >= 24764 and data.read_bool() + else None + ), + random_seed=data.read_uint32(), + race_preference=data.read_uint8() if data.read_bool() else None, + team_preference=( + data.read_uint8() + if replay.base_build >= 16561 and data.read_bool() + else None + ), + test_map=data.read_bool(), + test_auto=data.read_bool(), + examine=data.read_bool() if replay.base_build >= 21955 else None, + custom_interface=( + data.read_bool() if replay.base_build >= 24764 else None + ), + test_type=( + data.read_uint32() if replay.base_build >= 34784 else None + ), + observe=data.read_bits(2), + hero=( + data.read_aligned_string(data.read_bits(9)) + if replay.base_build >= 34784 + else None + ), + skin=( + data.read_aligned_string(data.read_bits(9)) + if replay.base_build >= 34784 + else None + ), + mount=( + data.read_aligned_string(data.read_bits(9)) + if replay.base_build >= 34784 + else None + ), + toon_handle=( + data.read_aligned_string(data.read_bits(7)) + if replay.base_build >= 34784 + else None + ), + scaled_rating=( + data.read_uint32() - 2147483648 + if replay.base_build >= 54518 and data.read_bool() + else None + ), + ) + for i in range(data.read_bits(5)) + ], game_description=dict( random_value=data.read_uint32(), game_cache_name=data.read_aligned_string(data.read_bits(10)), @@ -48,163 +115,333 @@ def __call__(self, data, replay): random_races=data.read_bool(), battle_net=data.read_bool(), amm=data.read_bool(), - ranked=data.read_bool() if replay.base_build >= 34784 and replay.base_build < 38215 else None, + ranked=( + data.read_bool() + if replay.base_build >= 34784 and replay.base_build < 38215 + else None + ), competitive=data.read_bool(), practice=data.read_bool() if replay.base_build >= 34784 else None, - cooperative=data.read_bool() if replay.base_build >= 34784 else None, + cooperative=( + data.read_bool() if replay.base_build >= 34784 else None + ), no_victory_or_defeat=data.read_bool(), - hero_duplicates_allowed=data.read_bool() if replay.base_build >= 34784 else None, + hero_duplicates_allowed=( + data.read_bool() if replay.base_build >= 34784 else None + ), fog=data.read_bits(2), observers=data.read_bits(2), user_difficulty=data.read_bits(2), - client_debug_flags=data.read_uint64() if replay.base_build >= 22612 else None, - build_coach_enabled=data.read_bool() if replay.base_build >= 59587 else None, + client_debug_flags=( + data.read_uint64() if replay.base_build >= 22612 else None + ), + build_coach_enabled=( + data.read_bool() if replay.base_build >= 59587 else None + ), ), game_speed=data.read_bits(3), game_type=data.read_bits(3), max_users=data.read_bits(5), max_observers=data.read_bits(5), max_players=data.read_bits(5), - max_teams=data.read_bits(4)+1, - max_colors=data.read_bits(6) if replay.base_build >= 17266 else data.read_bits(5)+1, - max_races=data.read_uint8()+1, - max_controls=data.read_uint8()+(0 if replay.base_build >= 26490 else 1), + max_teams=data.read_bits(4) + 1, + max_colors=( + data.read_bits(6) + if replay.base_build >= 17266 + else data.read_bits(5) + 1 + ), + max_races=data.read_uint8() + 1, + max_controls=data.read_uint8() + + (0 if replay.base_build >= 26490 else 1), map_size_x=data.read_uint8(), map_size_y=data.read_uint8(), map_file_sync_checksum=data.read_uint32(), map_file_name=data.read_aligned_string(data.read_bits(11)), map_author_name=data.read_aligned_string(data.read_uint8()), mod_file_sync_checksum=data.read_uint32(), - slot_descriptions=[dict( - allowed_colors=data.read_bits(data.read_bits(6)), - allowed_races=data.read_bits(data.read_uint8()), - allowedDifficulty=data.read_bits(data.read_bits(6)), - allowedControls=data.read_bits(data.read_uint8()), - allowed_observe_types=data.read_bits(data.read_bits(2)), - allowed_ai_builds=data.read_bits(data.read_bits(8 if replay.base_build >= 38749 else 7)) if replay.base_build >= 23925 else None, - ) for i in range(data.read_bits(5))], + slot_descriptions=[ + dict( + allowed_colors=data.read_bits(data.read_bits(6)), + allowed_races=data.read_bits(data.read_uint8()), + allowedDifficulty=data.read_bits(data.read_bits(6)), + allowedControls=data.read_bits(data.read_uint8()), + allowed_observe_types=data.read_bits(data.read_bits(2)), + allowed_ai_builds=( + data.read_bits( + data.read_bits(8 if replay.base_build >= 38749 else 7) + ) + if replay.base_build >= 23925 + else None + ), + ) + for i in range(data.read_bits(5)) + ], default_difficulty=data.read_bits(6), - default_ai_build=data.read_bits(8 if replay.base_build >= 38749 else 7) if replay.base_build >= 23925 else None, - cache_handles=[DepotFile(data.read_aligned_bytes(40)) for i in range(data.read_bits(6 if replay.base_build >= 21955 else 4))], - has_extension_mod=data.read_bool() if replay.base_build >= 27950 else None, - has_nonBlizzardExtensionMod=data.read_bool() if replay.base_build >= 42932 else None, + default_ai_build=( + data.read_bits(8 if replay.base_build >= 38749 else 7) + if replay.base_build >= 23925 + else None + ), + cache_handles=[ + DepotFile(data.read_aligned_bytes(40)) + for i in range( + data.read_bits(6 if replay.base_build >= 21955 else 4) + ) + ], + has_extension_mod=( + data.read_bool() if replay.base_build >= 27950 else None + ), + has_nonBlizzardExtensionMod=( + data.read_bool() if replay.base_build >= 42932 else None + ), is_blizzardMap=data.read_bool(), is_premade_ffa=data.read_bool(), is_coop_mode=data.read_bool() if replay.base_build >= 23925 else None, - is_realtime_mode=data.read_bool() if replay.base_build >= 54518 else None, + is_realtime_mode=( + data.read_bool() if replay.base_build >= 54518 else None + ), ), - lobby_state=dict( phase=data.read_bits(3), max_users=data.read_bits(5), max_observers=data.read_bits(5), - slots=[dict( - control=data.read_uint8(), - user_id=data.read_bits(4) if data.read_bool() else None, - team_id=data.read_bits(4), - colorPref=data.read_bits(5) if data.read_bool() else None, - race_pref=data.read_uint8() if data.read_bool() else None, - difficulty=data.read_bits(6), - ai_build=data.read_bits(8 if replay.base_build >= 38749 else 7) if replay.base_build >= 23925 else None, - handicap=data.read_bits(7), - observe=data.read_bits(2), - logo_index=data.read_uint32() if replay.base_build >= 32283 else None, - hero=data.read_aligned_string(data.read_bits(9)) if replay.base_build >= 34784 else None, - skin=data.read_aligned_string(data.read_bits(9)) if replay.base_build >= 34784 else None, - mount=data.read_aligned_string(data.read_bits(9)) if replay.base_build >= 34784 else None, - artifacts=[dict( - type_struct=data.read_aligned_string(data.read_bits(9)), - ) for i in range(data.read_bits(4))] if replay.base_build >= 34784 else None, - working_set_slot_id=data.read_uint8() if replay.base_build >= 24764 and data.read_bool() else None, - rewards=[data.read_uint32() for i in range(data.read_bits(17 if replay.base_build >= 34784 else 6 if replay.base_build >= 24764 else 5))], - toon_handle=data.read_aligned_string(data.read_bits(7)) if replay.base_build >= 17266 else None, - licenses=[data.read_uint32() for i in range(data.read_bits(13 if replay.base_build >= 70154 else 9))] if replay.base_build >= 19132 else [], - tandem_leader_user_id=data.read_bits(4) if replay.base_build >= 34784 and data.read_bool() else None, - commander=data.read_aligned_bytes(data.read_bits(9)) if replay.base_build >= 34784 else None, - commander_level=data.read_uint32() if replay.base_build >= 36442 else None, - has_silence_penalty=data.read_bool() if replay.base_build >= 38215 else None, - tandem_id=data.read_bits(4) if replay.base_build >= 39576 and data.read_bool() else None, - commander_mastery_level=data.read_uint32() if replay.base_build >= 42932 else None, - commander_mastery_talents=[data.read_uint32() for i in range(data.read_bits(3))] if replay.base_build >= 42932 else None, - reward_overrides=[[data.read_uint32(), [data.read_uint32() for i in range(data.read_bits(17))]] for j in range(data.read_bits(17))] if replay.base_build >= 47185 else None, - ) for i in range(data.read_bits(5))], + slots=[ + dict( + control=data.read_uint8(), + user_id=data.read_bits(4) if data.read_bool() else None, + team_id=data.read_bits(4), + colorPref=data.read_bits(5) if data.read_bool() else None, + race_pref=data.read_uint8() if data.read_bool() else None, + difficulty=data.read_bits(6), + ai_build=( + data.read_bits(8 if replay.base_build >= 38749 else 7) + if replay.base_build >= 23925 + else None + ), + handicap=data.read_bits( + 32 if replay.base_build >= 80669 else 7 + ), + observe=data.read_bits(2), + logo_index=( + data.read_uint32() if replay.base_build >= 32283 else None + ), + hero=( + data.read_aligned_string(data.read_bits(9)) + if replay.base_build >= 34784 + else None + ), + skin=( + data.read_aligned_string(data.read_bits(9)) + if replay.base_build >= 34784 + else None + ), + mount=( + data.read_aligned_string(data.read_bits(9)) + if replay.base_build >= 34784 + else None + ), + artifacts=( + [ + dict( + type_struct=data.read_aligned_string( + data.read_bits(9) + ) + ) + for i in range(data.read_bits(4)) + ] + if replay.base_build >= 34784 + else None + ), + working_set_slot_id=( + data.read_uint8() + if replay.base_build >= 24764 and data.read_bool() + else None + ), + rewards=[ + data.read_uint32() + for i in range( + data.read_bits( + 17 + if replay.base_build >= 34784 + else 6 if replay.base_build >= 24764 else 5 + ) + ) + ], + toon_handle=( + data.read_aligned_string(data.read_bits(7)) + if replay.base_build >= 17266 + else None + ), + licenses=( + [ + data.read_uint32() + for i in range( + data.read_bits( + 16 + if replay.base_build >= 77379 + else 13 if replay.base_build >= 70154 else 9 + ) + ) + ] + if replay.base_build >= 19132 + else [] + ), + tandem_leader_user_id=( + data.read_bits(4) + if replay.base_build >= 34784 and data.read_bool() + else None + ), + commander=( + data.read_aligned_bytes(data.read_bits(9)) + if replay.base_build >= 34784 + else None + ), + commander_level=( + data.read_uint32() if replay.base_build >= 36442 else None + ), + has_silence_penalty=( + data.read_bool() if replay.base_build >= 38215 else None + ), + tandem_id=( + data.read_bits(4) + if replay.base_build >= 39576 and data.read_bool() + else None + ), + commander_mastery_level=( + data.read_uint32() if replay.base_build >= 42932 else None + ), + commander_mastery_talents=( + [data.read_uint32() for i in range(data.read_bits(3))] + if replay.base_build >= 42932 + else None + ), + trophy_id=( + data.read_uint32() if replay.base_build >= 75689 else None + ), + reward_overrides=( + [ + [ + data.read_uint32(), + [ + data.read_uint32() + for i in range(data.read_bits(17)) + ], + ] + for j in range(data.read_bits(17)) + ] + if replay.base_build >= 47185 + else None + ), + brutal_plus_difficulty=( + data.read_uint32() if replay.base_build >= 77379 else None + ), + retry_mutation_indexes=( + [data.read_uint32() for i in range(data.read_bits(3))] + if replay.base_build >= 77379 + else None + ), + ac_enemy_race=( + data.read_uint32() if replay.base_build >= 77379 else None + ), + ac_enemy_wave_type=( + data.read_uint32() if replay.base_build >= 77379 else None + ), + selected_commander_prestige=( + data.read_uint32() if replay.base_build >= 80871 else None + ), + ) + for i in range(data.read_bits(5)) + ], random_seed=data.read_uint32(), host_user_id=data.read_bits(4) if data.read_bool() else None, is_single_player=data.read_bool(), - picked_map_tag=data.read_uint8() if replay.base_build >= 36442 else None, + picked_map_tag=( + data.read_uint8() if replay.base_build >= 36442 else None + ), game_duration=data.read_uint32(), default_difficulty=data.read_bits(6), - default_ai_build=data.read_bits(8 if replay.base_build >= 38749 else 7) if replay.base_build >= 24764 else None, + default_ai_build=( + data.read_bits(8 if replay.base_build >= 38749 else 7) + if replay.base_build >= 24764 + else None + ), ), ) 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 = ByteDecoder(data, endian="LITTLE") data.read_bytes(5 if replay.base_build >= 17326 else 4) - result = [Attribute( - data.read_uint32(), - data.read_uint32(), - data.read_uint8(), - ''.join(reversed(data.read_string(4))), - ) for i in range(data.read_uint32())] + result = [ + Attribute( + data.read_uint32(), + data.read_uint32(), + data.read_uint8(), + "".join(reversed(data.read_string(4))), + ) + for i in range(data.read_uint32()) + ] if not data.done(): raise ValueError("Not all bytes used up!") return result -class DetailsReader(object): +class DetailsReader: def __call__(self, data, replay): details = BitPackedDecoder(data).read_struct() return dict( - players=[dict( - name=p[0].decode('utf8'), - bnet=dict( - region=p[1][0], - program_id=p[1][1], - subregion=p[1][2], - # name=p[1][3].decode('utf8'), # This is documented but never available - uid=p[1][4], - ), - race=p[2].decode('utf8'), - color=dict( - a=p[3][0], - r=p[3][1], - g=p[3][2], - b=p[3][3], - ), - control=p[4], - team=p[5], - handicap=p[6], - observe=p[7], - result=p[8], - working_set_slot=p[9] if replay.build >= 24764 else None, - hero=p[10] if replay.build >= 34784 and 10 in p else None, # hero appears to be present in Heroes replays but not StarCraft 2 replays - ) for p in details[0]], - map_name=details[1].decode('utf8'), + players=[ + dict( + name=p[0].decode("utf8"), + bnet=dict( + region=p[1][0], + program_id=p[1][1], + subregion=p[1][2], + # name=p[1][3].decode('utf8'), # This is documented but never available + uid=p[1][4], + ), + race=p[2].decode("utf8"), + color=dict(a=p[3][0], r=p[3][1], g=p[3][2], b=p[3][3]), + control=p[4], + team=p[5], + handicap=p[6], + observe=p[7], + result=p[8], + working_set_slot=p[9] if replay.build >= 24764 else None, + hero=( + p[10] if replay.build >= 34784 and 10 in p else None + ), # hero appears to be present in Heroes replays but not StarCraft 2 replays + ) + for p in details[0] + ], + map_name=details[1].decode("utf8"), difficulty=details[2], thumbnail=details[3][0], blizzard_map=details[4], file_time=details[5], utc_adjustment=details[6], description=details[7], - image_file_path=details[8].decode('utf8'), - map_file_name=details[9].decode('utf8'), + image_file_path=details[8].decode("utf8"), + map_file_name=details[9].decode("utf8"), cache_handles=[DepotFile(bytes) for bytes in details[10]], mini_save=details[11], game_speed=details[12], default_difficulty=details[13], - mod_paths=details[14] if (replay.build >= 22612 and replay.versions[1] == 1) else None, + mod_paths=( + details[14] + if (replay.build >= 22612 and replay.versions[1] == 1) + else None + ), campaign_index=details[15] if replay.versions[1] == 2 else None, restartAsTransitionMap=details[16] if replay.build > 26490 else None, ) -class MessageEventsReader(object): +class MessageEventsReader: def __call__(self, data, replay): data = BitPackedDecoder(data) pings = list() @@ -223,12 +460,12 @@ def __call__(self, data, replay): elif flag == 1: # Client ping message recipient = data.read_bits(3 if replay.base_build >= 21955 else 2) - x = data.read_uint32()-2147483648 - y = data.read_uint32()-2147483648 + x = data.read_uint32() - 2147483648 + y = data.read_uint32() - 2147483648 pings.append(PingEvent(frame, pid, recipient, x, y)) elif flag == 2: # Loading progress message - progress = data.read_uint32()-2147483648 + progress = data.read_uint32() - 2147483648 packets.append(ProgressEvent(frame, pid, progress)) elif flag == 3: # Server ping message @@ -243,8 +480,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), @@ -263,7 +499,7 @@ def __init__(self): 28: (SelectionEvent, self.selection_delta_event), 29: (create_control_group_event, self.control_group_update_event), 30: (None, self.selection_sync_check_event), - 31: (None, self.resource_trade_event), + 31: (ResourceTradeEvent, self.resource_trade_event), 32: (None, self.trigger_chat_message_event), 33: (None, self.ai_communicate_event), 34: (None, self.set_absolute_game_speed_event), @@ -284,7 +520,7 @@ def __init__(self): 52: (None, self.trigger_purchase_exit_event), 53: (None, self.trigger_planet_mission_launched_event), 54: (None, self.trigger_planet_panel_canceled_event), - 55: (None, self.trigger_dialog_control_event), + 55: (DialogControlEvent, self.trigger_dialog_control_event), 56: (None, self.trigger_sound_length_sync_event), 57: (None, self.trigger_conversation_skipped_event), 58: (None, self.trigger_mouse_clicked_event), @@ -318,8 +554,14 @@ def __init__(self): 90: (None, self.trigger_custom_dialog_dismissed_event), 91: (None, self.trigger_game_menu_item_selected_event), 92: (None, self.trigger_camera_move_event), - 93: (None, self.trigger_purchase_panel_selected_purchase_item_changed_event), - 94: (None, self.trigger_purchase_panel_selected_purchase_category_changed_event), + 93: ( + None, + self.trigger_purchase_panel_selected_purchase_item_changed_event, + ), + 94: ( + None, + self.trigger_purchase_panel_selected_purchase_category_changed_event, + ), 95: (None, self.trigger_button_pressed_event), 96: (None, self.trigger_game_credits_finished_event), } @@ -330,7 +572,7 @@ def __call__(self, data, replay): # method short cuts, avoid dict lookups EVENT_DISPATCH = self.EVENT_DISPATCH - debug = replay.opt['debug'] + debug = replay.opt["debug"] tell = data.tell read_frames = data.read_frames read_bits = data.read_bits @@ -358,16 +600,37 @@ def __call__(self, data, replay): # Otherwise throw a read error else: - raise ReadError("Event type {0} unknown at position {1}.".format(hex(event_type), hex(event_start)), event_type, event_start, replay, game_events, data) + raise ReadError( + f"Event type {hex(event_type)} unknown at position {hex(event_start)}.", + event_type, + event_start, + replay, + game_events, + data, + ) byte_align() event_start = tell() return game_events except ParseError as e: - raise ReadError("Parse error '{0}' unknown at position {1}.".format(e.msg, hex(event_start)), event_type, event_start, replay, game_events, data) + raise ReadError( + f"Parse error '{e.msg}' unknown at position {hex(event_start)}.", + event_type, + event_start, + replay, + game_events, + data, + ) except EOFError as e: - raise ReadError("EOFError error '{0}' unknown at position {1}.".format(e.msg, hex(event_start)), event_type, event_start, replay, game_events, data) + raise ReadError( + f"EOFError error '{e.msg}' unknown at position {hex(event_start)}.", + event_type, + event_start, + replay, + game_events, + data, + ) # Don't want to do this more than once SINGLE_BIT_MASKS = [0x1 << i for i in range(2**9)] @@ -376,15 +639,15 @@ def read_selection_bitmask(self, data, mask_length): bits_left = mask_length bits = data.read_bits(mask_length) mask = list() - shift_diff = (mask_length+data._bit_shift) % 8 - data._bit_shift + shift_diff = (mask_length + data._bit_shift) % 8 - data._bit_shift if shift_diff > 0: mask = [bits & data._lo_masks[shift_diff]] bits = bits >> shift_diff bits_left -= shift_diff elif shift_diff < 0: - mask = [bits & data._lo_masks[8+shift_diff]] - bits = bits >> (8+shift_diff) - bits_left -= 8+shift_diff + mask = [bits & data._lo_masks[8 + shift_diff]] + bits = bits >> (8 + shift_diff) + bits_left -= 8 + shift_diff # Now shift the rest of the bits off into the mask in byte-sized # chunks in reverse order. No idea why it'd be stored like this. @@ -394,7 +657,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 @@ -402,24 +665,17 @@ def read_selection_bitmask(self, data, mask_length): class GameEventsReader_15405(GameEventsReader_Base): - def unknown_event(self, data): - return dict( - unknown=data.read_bytes(2) - ) + return dict(unknown=data.read_bytes(2)) def finished_loading_sync_event(self, data): return None def bank_file_event(self, data): - return dict( - name=data.read_aligned_string(data.read_bits(7)), - ) + return dict(name=data.read_aligned_string(data.read_bits(7))) def bank_section_event(self, data): - return dict( - name=data.read_aligned_string(data.read_bits(6)), - ) + return dict(name=data.read_aligned_string(data.read_bits(6))) def bank_key_event(self, data): return dict( @@ -473,10 +729,9 @@ def player_leave_event(self, data): def game_cheat_event(self, data): return dict( point=dict( - x=data.read_uint32()-2147483648, - y=data.read_uint32()-2147483648, + x=data.read_uint32() - 2147483648, y=data.read_uint32() - 2147483648 ), - time=data.read_uint32()-2147483648, + time=data.read_uint32() - 2147483648, verb=data.read_aligned_string(data.read_bits(10)), arguments=data.read_aligned_string(data.read_bits(10)), ) @@ -488,23 +743,25 @@ def command_event(self, data): ability_command_index=data.read_uint8(), ability_command_data=data.read_uint8(), ) - target_data = ('TargetUnit', dict( - flags=data.read_uint8(), - timer=data.read_uint8(), - )) + target_data = ( + "TargetUnit", + dict(flags=data.read_uint8(), timer=data.read_uint8()), + ) other_unit_tag = data.read_uint32() - target_data[1].update(dict( - unit_tag=data.read_uint32(), - unit_link=data.read_uint16(), - control_player_id=None, - upkeep_player_id=data.read_bits(4) if data.read_bool() else None, - point=dict( - x=data.read_uint32()-2147483648, - y=data.read_uint32()-2147483648, - z=data.read_uint32()-2147483648, - ), - )) + target_data[1].update( + dict( + unit_tag=data.read_uint32(), + unit_link=data.read_uint16(), + control_player_id=None, + upkeep_player_id=data.read_bits(4) if data.read_bool() else None, + point=dict( + x=data.read_uint32() - 2147483648, + y=data.read_uint32() - 2147483648, + z=data.read_uint32() - 2147483648, + ), + ) + ) return dict( flags=flags, ability=ability, @@ -516,13 +773,16 @@ def selection_delta_event(self, data): return dict( control_group_index=data.read_bits(4), subgroup_index=data.read_uint8(), - remove_mask=('Mask', self.read_selection_bitmask(data, data.read_uint8())), - add_subgroups=[dict( - unit_link=data.read_uint16(), - subgroup_priority=None, - intra_subgroup_priority=data.read_uint8(), - count=data.read_uint8(), - ) for i in range(data.read_uint8())], + remove_mask=("Mask", self.read_selection_bitmask(data, data.read_uint8())), + add_subgroups=[ + dict( + unit_link=data.read_uint16(), + subgroup_priority=None, + intra_subgroup_priority=data.read_uint8(), + count=data.read_uint8(), + ) + for i in range(data.read_uint8()) + ], add_unit_tags=[data.read_uint32() for i in range(data.read_uint8())], ) @@ -530,7 +790,11 @@ def control_group_update_event(self, data): return dict( control_group_index=data.read_bits(4), control_group_update=data.read_bits(2), - remove_mask=('Mask', self.read_selection_bitmask(data, data.read_uint8())) if data.read_bool() else ('None', None), + remove_mask=( + ("Mask", self.read_selection_bitmask(data, data.read_uint8())) + if data.read_bool() + else ("None", None) + ), ) def selection_sync_check_event(self, data): @@ -543,46 +807,42 @@ def selection_sync_check_event(self, data): unit_tags_checksum=data.read_uint32(), subgroup_indices_checksum=data.read_uint32(), subgroups_checksum=data.read_uint32(), - ) + ), ) def resource_trade_event(self, data): return dict( recipient_id=data.read_bits(4), - resources=[data.read_uint32()-2147483648 for i in range(data.read_bits(3))], + resources=[ + data.read_uint32() - 2147483648 for i in range(data.read_bits(3)) + ], ) def trigger_chat_message_event(self, data): - return dict( - message=data.read_aligned_string(data.read_bits(10)), - ) + return dict(message=data.read_aligned_string(data.read_bits(10))) def ai_communicate_event(self, data): return dict( - beacon=data.read_uint8()-128, - ally=data.read_uint8()-128, - flags=data.read_uint8()-128, + beacon=data.read_uint8() - 128, + ally=data.read_uint8() - 128, + flags=data.read_uint8() - 128, build=None, target_unit_tag=data.read_uint32(), target_unit_link=data.read_uint16(), target_upkeep_player_id=data.read_bits(4) if data.read_bool() else None, target_control_player_id=None, target_point=dict( - x=data.read_uint32()-2147483648, - y=data.read_uint32()-2147483648, - z=data.read_uint32()-2147483648, + x=data.read_uint32() - 2147483648, + y=data.read_uint32() - 2147483648, + z=data.read_uint32() - 2147483648, ), ) def set_absolute_game_speed_event(self, data): - return dict( - speed=data.read_bits(3), - ) + return dict(speed=data.read_bits(3)) def add_absolute_game_speed_event(self, data): - return dict( - delta=data.read_uint8()-128, - ) + return dict(delta=data.read_uint8() - 128) def broadcast_cheat_event(self, data): return dict( @@ -591,58 +851,38 @@ def broadcast_cheat_event(self, data): ) def alliance_event(self, data): - return dict( - alliance=data.read_uint32(), - control=data.read_uint32(), - ) + return dict(alliance=data.read_uint32(), control=data.read_uint32()) def unit_click_event(self, data): - return dict( - unit_tag=data.read_uint32(), - ) + return dict(unit_tag=data.read_uint32()) def unit_highlight_event(self, data): - return dict( - unit_tag=data.read_uint32(), - flags=data.read_uint8(), - ) + return dict(unit_tag=data.read_uint32(), flags=data.read_uint8()) def trigger_reply_selected_event(self, data): return dict( - conversation_id=data.read_uint32()-2147483648, - reply_id=data.read_uint32()-2147483648, + conversation_id=data.read_uint32() - 2147483648, + reply_id=data.read_uint32() - 2147483648, ) def trigger_skipped_event(self, data): return None def trigger_sound_length_query_event(self, data): - return dict( - sound_hash=data.read_uint32(), - length=data.read_uint32(), - ) + return dict(sound_hash=data.read_uint32(), length=data.read_uint32()) def trigger_sound_offset_event(self, data): - return dict( - sound=data.read_uint32(), - ) + return dict(sound=data.read_uint32()) def trigger_transmission_offset_event(self, data): - return dict( - transmission_id=data.read_uint32()-2147483648, - ) + return dict(transmission_id=data.read_uint32() - 2147483648) def trigger_transmission_complete_event(self, data): - return dict( - transmission_id=data.read_uint32()-2147483648, - ) + return dict(transmission_id=data.read_uint32() - 2147483648) def camera_update_event(self, data): return dict( - target=dict( - x=data.read_uint16(), - y=data.read_uint16(), - ), + target=dict(x=data.read_uint16(), y=data.read_uint16()), distance=data.read_uint16() if data.read_bool() else None, pitch=data.read_uint16() if data.read_bool() else None, yaw=data.read_uint16() if data.read_bool() else None, @@ -653,31 +893,30 @@ def trigger_abort_mission_event(self, data): return None def trigger_purchase_made_event(self, data): - return dict( - purchase_item_id=data.read_uint32()-2147483648, - ) + return dict(purchase_item_id=data.read_uint32() - 2147483648) def trigger_purchase_exit_event(self, data): return None def trigger_planet_mission_launched_event(self, data): - return dict( - difficulty_level=data.read_uint32()-2147483648, - ) + return dict(difficulty_level=data.read_uint32() - 2147483648) def trigger_planet_panel_canceled_event(self, data): return None def trigger_dialog_control_event(self, data): return dict( - control_id=data.read_uint32()-2147483648, - event_type=data.read_uint32()-2147483648, + control_id=data.read_uint32() - 2147483648, + event_type=data.read_uint32() - 2147483648, event_data={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('Checked', data.read_bool()), - 2: lambda: ('ValueChanged', data.read_uint32()), - 3: lambda: ('SelectionChanged', data.read_uint32()-2147483648), - 4: lambda: ('TextChanged', data.read_aligned_string(data.read_bits(11))), + 0: lambda: ("None", None), + 1: lambda: ("Checked", data.read_bool()), + 2: lambda: ("ValueChanged", data.read_uint32()), + 3: lambda: ("SelectionChanged", data.read_uint32() - 2147483648), + 4: lambda: ( + "TextChanged", + data.read_aligned_string(data.read_bits(11)), + ), }[data.read_bits(3)](), ) @@ -690,22 +929,17 @@ def trigger_sound_length_sync_event(self, data): ) def trigger_conversation_skipped_event(self, data): - return dict( - skip_type=data.read_int(1), - ) + return dict(skip_type=data.read_int(1)) def trigger_mouse_clicked_event(self, data): return dict( button=data.read_uint32(), down=data.read_bool(), - position_ui=dict( - x=data.read_uint32(), - y=data.read_uint32(), - ), + position_ui=dict(x=data.read_uint32(), y=data.read_uint32()), position_world=dict( - x=data.read_uint32()-2147483648, - y=data.read_uint32()-2147483648, - z=data.read_uint32()-2147483648, + x=data.read_uint32() - 2147483648, + y=data.read_uint32() - 2147483648, + z=data.read_uint32() - 2147483648, ), ) @@ -713,25 +947,16 @@ def trigger_planet_panel_replay_event(self, data): return None def trigger_soundtrack_done_event(self, data): - return dict( - soundtrack=data.read_uint32(), - ) + return dict(soundtrack=data.read_uint32()) def trigger_planet_mission_selected_event(self, data): - return dict( - planet_id=data.read_uint32()-2147483648, - ) + return dict(planet_id=data.read_uint32() - 2147483648) def trigger_key_pressed_event(self, data): - return dict( - key=data.read_uint8()-128, - flags=data.read_uint8()-128, - ) + return dict(key=data.read_uint8() - 128, flags=data.read_uint8() - 128) def trigger_movie_function_event(self, data): - return dict( - function_name=data.read_aligned_string(data.read_bits(7)), - ) + return dict(function_name=data.read_aligned_string(data.read_bits(7))) def trigger_planet_panel_birth_complete_event(self, data): return None @@ -741,18 +966,16 @@ def trigger_planet_panel_death_complete_event(self, data): def resource_request_event(self, data): return dict( - resources=[data.read_uint32()-2147483648 for i in range(data.read_bits(3))], + resources=[ + data.read_uint32() - 2147483648 for i in range(data.read_bits(3)) + ] ) def resource_request_fulfill_event(self, data): - return dict( - request_id=data.read_uint32()-2147483648, - ) + return dict(request_id=data.read_uint32() - 2147483648) def resource_request_cancel_event(self, data): - return dict( - request_id=data.read_uint32()-2147483648, - ) + return dict(request_id=data.read_uint32() - 2147483648) def trigger_research_panel_exit_event(self, data): return None @@ -761,14 +984,10 @@ def trigger_research_panel_purchase_event(self, data): return None def trigger_research_panel_selection_changed_event(self, data): - return dict( - item_id=data.read_uint32()-2147483648, - ) + return dict(item_id=data.read_uint32() - 2147483648) def lag_message_event(self, data): - return dict( - player_id=data.read_bits(4), - ) + return dict(player_id=data.read_bits(4)) def trigger_mercenary_panel_exit_event(self, data): return None @@ -777,9 +996,7 @@ def trigger_mercenary_panel_purchase_event(self, data): return None def trigger_mercenary_panel_selection_changed_event(self, data): - return dict( - item_id=data.read_uint32()-2147483648, - ) + return dict(item_id=data.read_uint32() - 2147483648) def trigger_victory_panel_exit_event(self, data): return None @@ -789,24 +1006,18 @@ def trigger_battle_report_panel_exit_event(self, data): def trigger_battle_report_panel_play_mission_event(self, data): return dict( - battle_report_id=data.read_uint32()-2147483648, - difficulty_level=data.read_uint32()-2147483648, + battle_report_id=data.read_uint32() - 2147483648, + difficulty_level=data.read_uint32() - 2147483648, ) def trigger_battle_report_panel_play_scene_event(self, data): - return dict( - battle_report_id=data.read_uint32()-2147483648, - ) + return dict(battle_report_id=data.read_uint32() - 2147483648) def trigger_battle_report_panel_selection_changed_event(self, data): - return dict( - battle_report_id=data.read_uint32()-2147483648, - ) + return dict(battle_report_id=data.read_uint32() - 2147483648) def trigger_victory_panel_play_mission_again_event(self, data): - return dict( - difficulty_level=data.read_uint32()-2147483648, - ) + return dict(difficulty_level=data.read_uint32() - 2147483648) def trigger_movie_started_event(self, data): return None @@ -815,84 +1026,81 @@ def trigger_movie_finished_event(self, data): return None def decrement_game_time_remaining_event(self, data): - return dict( - decrement_ms=data.read_uint32(), - ) + return dict(decrement_ms=data.read_uint32()) def trigger_portrait_loaded_event(self, data): - return dict( - portrait_id=data.read_uint32()-2147483648, - ) + return dict(portrait_id=data.read_uint32() - 2147483648) def trigger_custom_dialog_dismissed_event(self, data): - return dict( - result=data.read_uint32()-2147483648, - ) + return dict(result=data.read_uint32() - 2147483648) def trigger_game_menu_item_selected_event(self, data): - return dict( - game_menu_item_index=data.read_uint32()-2147483648, - ) + return dict(game_menu_item_index=data.read_uint32() - 2147483648) def trigger_camera_move_event(self, data): - return dict( - reason=data.read_uint8()-128, - ) + return dict(reason=data.read_uint8() - 128) def trigger_purchase_panel_selected_purchase_item_changed_event(self, data): - return dict( - item_id=data.read_uint32()-2147483648, - ) + return dict(item_id=data.read_uint32() - 2147483648) def trigger_purchase_panel_selected_purchase_category_changed_event(self, data): - return dict( - category_id=data.read_uint32()-2147483648, - ) + return dict(category_id=data.read_uint32() - 2147483648) def trigger_button_pressed_event(self, data): - return dict( - button=data.read_uint16(), - ) + return dict(button=data.read_uint16()) def trigger_game_credits_finished_event(self, data): return None class GameEventsReader_16561(GameEventsReader_15405): - def command_event(self, data): return dict( flags=data.read_bits(17), - ability=dict( - ability_link=data.read_uint16(), - ability_command_index=data.read_bits(5), - ability_command_data=data.read_uint8() if data.read_bool() else None, - ) if data.read_bool() else None, + ability=( + dict( + ability_link=data.read_uint16(), + ability_command_index=data.read_bits(5), + ability_command_data=( + data.read_uint8() if data.read_bool() else None + ), + ) + if data.read_bool() + else None + ), data={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('TargetPoint', dict( - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_uint32()-2147483648, - ) - )), - 2: lambda: ('TargetUnit', dict( - flags=data.read_uint8(), - timer=data.read_uint8(), - unit_tag=data.read_uint32(), - unit_link=data.read_uint16(), - control_player_id=None, - upkeep_player_id=data.read_bits(4) if data.read_bool() else None, - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_uint32()-2147483648, + 0: lambda: ("None", None), + 1: lambda: ( + "TargetPoint", + dict( + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ) + ), + ), + 2: lambda: ( + "TargetUnit", + dict( + flags=data.read_uint8(), + timer=data.read_uint8(), + unit_tag=data.read_uint32(), + unit_link=data.read_uint16(), + control_player_id=None, + upkeep_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ), ), - )), - 3: lambda: ('Data', dict(data=data.read_uint32())), + ), + 3: lambda: ("Data", dict(data=data.read_uint32())), }[data.read_bits(2)](), - other_unit_tag=data.read_uint32() if data.read_bool() else None + other_unit_tag=data.read_uint32() if data.read_bool() else None, ) def selection_delta_event(self, data): @@ -900,17 +1108,29 @@ def selection_delta_event(self, data): control_group_index=data.read_bits(4), subgroup_index=data.read_uint8(), remove_mask={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('Mask', self.read_selection_bitmask(data, data.read_uint8())), - 2: lambda: ('OneIndices', [data.read_uint8() for i in range(data.read_uint8())]), - 3: lambda: ('ZeroIndices', [data.read_uint8() for i in range(data.read_uint8())]), + 0: lambda: ("None", None), + 1: lambda: ( + "Mask", + self.read_selection_bitmask(data, data.read_uint8()), + ), + 2: lambda: ( + "OneIndices", + [data.read_uint8() for i in range(data.read_uint8())], + ), + 3: lambda: ( + "ZeroIndices", + [data.read_uint8() for i in range(data.read_uint8())], + ), }[data.read_bits(2)](), - add_subgroups=[dict( - unit_link=data.read_uint16(), - subgroup_priority=None, - intra_subgroup_priority=data.read_uint8(), - count=data.read_uint8(), - ) for i in range(data.read_uint8())], + add_subgroups=[ + dict( + unit_link=data.read_uint16(), + subgroup_priority=None, + intra_subgroup_priority=data.read_uint8(), + count=data.read_uint8(), + ) + for i in range(data.read_uint8()) + ], add_unit_tags=[data.read_uint32() for i in range(data.read_uint8())], ) @@ -919,19 +1139,26 @@ def control_group_update_event(self, data): control_group_index=data.read_bits(4), control_group_update=data.read_bits(2), remove_mask={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('Mask', self.read_selection_bitmask(data, data.read_uint8())), - 2: lambda: ('OneIndices', [data.read_uint8() for i in range(data.read_uint8())]), - 3: lambda: ('ZeroIndices', [data.read_uint8() for i in range(data.read_uint8())]), + 0: lambda: ("None", None), + 1: lambda: ( + "Mask", + self.read_selection_bitmask(data, data.read_uint8()), + ), + 2: lambda: ( + "OneIndices", + [data.read_uint8() for i in range(data.read_uint8())], + ), + 3: lambda: ( + "ZeroIndices", + [data.read_uint8() for i in range(data.read_uint8())], + ), }[data.read_bits(2)](), ) def decrement_game_time_remaining_event(self, data): # really this should be set to 19, and a new GameEventsReader_41743 should be introduced that specifies 32 bits. - # but I dont care about ability to read old replays. - return dict( - decrement_ms=data.read_bits(32) - ) + # but I don't care about ability to read old replays. + return dict(decrement_ms=data.read_bits(32)) class GameEventsReader_16605(GameEventsReader_16561): @@ -947,13 +1174,10 @@ 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), - }) + self.EVENT_DISPATCH.update({59: (None, self.trigger_mouse_moved_event)}) def bank_signature_event(self, data): return dict( @@ -965,10 +1189,7 @@ def trigger_mouse_clicked_event(self, data): return dict( button=data.read_uint32(), down=data.read_bool(), - position_ui=dict( - x=data.read_bits(11), - y=data.read_bits(11), - ), + position_ui=dict(x=data.read_bits(11), y=data.read_bits(11)), position_world=dict( x=data.read_bits(20), y=data.read_bits(20), @@ -978,14 +1199,11 @@ def trigger_mouse_clicked_event(self, data): def trigger_mouse_moved_event(self, data): return dict( - position_ui=dict( - x=data.read_bits(11), - y=data.read_bits(11), - ), + position_ui=dict(x=data.read_bits(11), y=data.read_bits(11)), position_world=dict( x=data.read_bits(20), y=data.read_bits(20), - z=data.read_uint32()-2147483648, + z=data.read_uint32() - 2147483648, ), ) @@ -995,40 +1213,53 @@ class GameEventsReader_18092(GameEventsReader_17326): class GameEventsReader_18574(GameEventsReader_18092): - def command_event(self, data): return dict( flags=data.read_bits(18), - ability=dict( - ability_link=data.read_uint16(), - ability_command_index=data.read_bits(5), - ability_command_data=data.read_uint8() if data.read_bool() else None, - ) if data.read_bool() else None, + ability=( + dict( + ability_link=data.read_uint16(), + ability_command_index=data.read_bits(5), + ability_command_data=( + data.read_uint8() if data.read_bool() else None + ), + ) + if data.read_bool() + else None + ), data={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('TargetPoint', dict( - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_uint32()-2147483648, - ) - )), - 2: lambda: ('TargetUnit', dict( - flags=data.read_uint8(), - timer=data.read_uint8(), - unit_tag=data.read_uint32(), - unit_link=data.read_uint16(), - control_player_id=None, - upkeep_player_id=data.read_bits(4) if data.read_bool() else None, - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_uint32()-2147483648, + 0: lambda: ("None", None), + 1: lambda: ( + "TargetPoint", + dict( + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ) + ), + ), + 2: lambda: ( + "TargetUnit", + dict( + flags=data.read_uint8(), + timer=data.read_uint8(), + unit_tag=data.read_uint32(), + unit_link=data.read_uint16(), + control_player_id=None, + upkeep_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ), ), - )), - 3: lambda: ('Data', dict(data=data.read_uint32())), + ), + 3: lambda: ("Data", dict(data=data.read_uint32())), }[data.read_bits(2)](), - other_unit_tag=data.read_uint32() if data.read_bool() else None + other_unit_tag=data.read_uint32() if data.read_bool() else None, ) @@ -1037,56 +1268,71 @@ class GameEventsReader_19132(GameEventsReader_18574): class GameEventsReader_19595(GameEventsReader_19132): - def command_event(self, data): return dict( flags=data.read_bits(18), - ability=dict( - ability_link=data.read_uint16(), - ability_command_index=data.read_bits(5), - ability_command_data=data.read_uint8() if data.read_bool() else None, - ) if data.read_bool() else None, + ability=( + dict( + ability_link=data.read_uint16(), + ability_command_index=data.read_bits(5), + ability_command_data=( + data.read_uint8() if data.read_bool() else None + ), + ) + if data.read_bool() + else None + ), data={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('TargetPoint', dict( - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_uint32()-2147483648, - ) - )), - 2: lambda: ('TargetUnit', dict( - flags=data.read_uint8(), - timer=data.read_uint8(), - unit_tag=data.read_uint32(), - unit_link=data.read_uint16(), - control_player_id=data.read_bits(4) if data.read_bool() else None, - upkeep_player_id=data.read_bits(4) if data.read_bool() else None, - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_uint32()-2147483648, + 0: lambda: ("None", None), + 1: lambda: ( + "TargetPoint", + dict( + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ) ), - )), - 3: lambda: ('Data', dict(data=data.read_uint32())), + ), + 2: lambda: ( + "TargetUnit", + dict( + flags=data.read_uint8(), + timer=data.read_uint8(), + unit_tag=data.read_uint32(), + unit_link=data.read_uint16(), + control_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + upkeep_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ), + ), + ), + 3: lambda: ("Data", dict(data=data.read_uint32())), }[data.read_bits(2)](), - other_unit_tag=data.read_uint32() if data.read_bool() else None + other_unit_tag=data.read_uint32() if data.read_bool() else None, ) def ai_communicate_event(self, data): return dict( - beacon=data.read_uint8()-128, - ally=data.read_uint8()-128, - flags=data.read_uint8()-128, # autocast?? + beacon=data.read_uint8() - 128, + ally=data.read_uint8() - 128, + flags=data.read_uint8() - 128, # autocast?? build=None, target_unit_tag=data.read_uint32(), target_unit_link=data.read_uint16(), target_upkeep_player_id=data.read_bits(4) if data.read_bool() else None, target_control_player_id=data.read_bits(4) if data.read_bool() else None, target_point=dict( - x=data.read_uint32()-2147483648, - y=data.read_uint32()-2147483648, - z=data.read_uint32()-2147483648, + x=data.read_uint32() - 2147483648, + y=data.read_uint32() - 2147483648, + z=data.read_uint32() - 2147483648, ), ) @@ -1096,18 +1342,19 @@ class GameEventsReader_21029(GameEventsReader_19595): class GameEventsReader_22612(GameEventsReader_21029): - def __init__(self): - super(GameEventsReader_22612, self).__init__() + super().__init__() - self.EVENT_DISPATCH.update({ - 36: (None, self.trigger_ping_event), - 60: (None, self.achievement_awarded_event), - 97: (None, self.trigger_cutscene_bookmark_fired_event), - 98: (None, self.trigger_cutscene_end_scene_fired_event), - 99: (None, self.trigger_cutscene_conversation_line_event), - 100: (None, self.trigger_cutscene_conversation_line_missing_event), - }) + self.EVENT_DISPATCH.update( + { + 36: (None, self.trigger_ping_event), + 60: (None, self.achievement_awarded_event), + 97: (None, self.trigger_cutscene_bookmark_fired_event), + 98: (None, self.trigger_cutscene_end_scene_fired_event), + 99: (None, self.trigger_cutscene_conversation_line_event), + 100: (None, self.trigger_cutscene_conversation_line_missing_event), + } + ) def user_options_event(self, data): return dict( @@ -1125,36 +1372,52 @@ def user_options_event(self, data): def command_event(self, data): return dict( flags=data.read_bits(20), - ability=dict( - ability_link=data.read_uint16(), - ability_command_index=data.read_bits(5), - ability_command_data=data.read_uint8() if data.read_bool() else None, - ) if data.read_bool() else None, + ability=( + dict( + ability_link=data.read_uint16(), + ability_command_index=data.read_bits(5), + ability_command_data=( + data.read_uint8() if data.read_bool() else None + ), + ) + if data.read_bool() + else None + ), data={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('TargetPoint', dict( - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_uint32()-2147483648, - ) - )), - 2: lambda: ('TargetUnit', dict( - flags=data.read_uint8(), - timer=data.read_uint8(), - unit_tag=data.read_uint32(), - unit_link=data.read_uint16(), - control_player_id=data.read_bits(4) if data.read_bool() else None, - upkeep_player_id=data.read_bits(4) if data.read_bool() else None, - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_uint32()-2147483648, + 0: lambda: ("None", None), + 1: lambda: ( + "TargetPoint", + dict( + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ) + ), + ), + 2: lambda: ( + "TargetUnit", + dict( + flags=data.read_uint8(), + timer=data.read_uint8(), + unit_tag=data.read_uint32(), + unit_link=data.read_uint16(), + control_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + upkeep_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ), ), - )), - 3: lambda: ('Data', dict(data=data.read_uint32())), + ), + 3: lambda: ("Data", dict(data=data.read_uint32())), }[data.read_bits(2)](), - other_unit_tag=data.read_uint32() if data.read_bool() else None + other_unit_tag=data.read_uint32() if data.read_bool() else None, ) def selection_delta_event(self, data): @@ -1162,17 +1425,29 @@ def selection_delta_event(self, data): control_group_index=data.read_bits(4), subgroup_index=data.read_bits(9), remove_mask={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('Mask', self.read_selection_bitmask(data, data.read_bits(9))), - 2: lambda: ('OneIndices', [data.read_bits(9) for i in range(data.read_bits(9))]), - 3: lambda: ('ZeroIndices', [data.read_bits(9) for i in range(data.read_bits(9))]), + 0: lambda: ("None", None), + 1: lambda: ( + "Mask", + self.read_selection_bitmask(data, data.read_bits(9)), + ), + 2: lambda: ( + "OneIndices", + [data.read_bits(9) for i in range(data.read_bits(9))], + ), + 3: lambda: ( + "ZeroIndices", + [data.read_bits(9) for i in range(data.read_bits(9))], + ), }[data.read_bits(2)](), - add_subgroups=[dict( - unit_link=data.read_uint16(), - subgroup_priority=None, - intra_subgroup_priority=data.read_uint8(), - count=data.read_bits(9), - ) for i in range(data.read_bits(9))], + add_subgroups=[ + dict( + unit_link=data.read_uint16(), + subgroup_priority=None, + intra_subgroup_priority=data.read_uint8(), + count=data.read_bits(9), + ) + for i in range(data.read_bits(9)) + ], add_unit_tags=[data.read_uint32() for i in range(data.read_bits(9))], ) @@ -1181,10 +1456,19 @@ def control_group_update_event(self, data): control_group_index=data.read_bits(4), control_group_update=data.read_bits(2), remove_mask={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('Mask', self.read_selection_bitmask(data, data.read_bits(9))), - 2: lambda: ('OneIndices', [data.read_bits(9) for i in range(data.read_bits(9))]), - 3: lambda: ('ZeroIndices', [data.read_bits(9) for i in range(data.read_bits(9))]), + 0: lambda: ("None", None), + 1: lambda: ( + "Mask", + self.read_selection_bitmask(data, data.read_bits(9)), + ), + 2: lambda: ( + "OneIndices", + [data.read_bits(9) for i in range(data.read_bits(9))], + ), + 3: lambda: ( + "ZeroIndices", + [data.read_bits(9) for i in range(data.read_bits(9))], + ), }[data.read_bits(2)](), ) @@ -1198,31 +1482,30 @@ def selection_sync_check_event(self, data): unit_tags_checksum=data.read_uint32(), subgroup_indices_checksum=data.read_uint32(), subgroups_checksum=data.read_uint32(), - ) + ), ) def ai_communicate_event(self, data): return dict( - beacon=data.read_uint8()-128, - ally=data.read_uint8()-128, - flags=data.read_uint8()-128, - build=data.read_uint8()-128, + beacon=data.read_uint8() - 128, + ally=data.read_uint8() - 128, + flags=data.read_uint8() - 128, + build=data.read_uint8() - 128, target_unit_tag=data.read_uint32(), target_unit_link=data.read_uint16(), target_upkeep_player_id=data.read_uint8(), target_control_player_id=data.read_uint8(), target_point=dict( - x=data.read_uint32()-2147483648, - y=data.read_uint32()-2147483648, - z=data.read_uint32()-2147483648, + x=data.read_uint32() - 2147483648, + y=data.read_uint32() - 2147483648, + z=data.read_uint32() - 2147483648, ), ) def trigger_ping_event(self, data): return dict( point=dict( - x=data.read_uint32()-2147483648, - y=data.read_uint32()-2147483648, + x=data.read_uint32() - 2147483648, y=data.read_uint32() - 2147483648 ), unit_tag=data.read_uint32(), pinged_minimap=data.read_bool(), @@ -1231,42 +1514,36 @@ def trigger_ping_event(self, data): def trigger_transmission_offset_event(self, data): # I'm not actually sure when this second int is introduced.. return dict( - transmission_id=data.read_uint32()-2147483648, - thread=data.read_uint32(), + transmission_id=data.read_uint32() - 2147483648, thread=data.read_uint32() ) def achievement_awarded_event(self, data): - return dict( - achievement_link=data.read_uint16(), - ) + return dict(achievement_link=data.read_uint16()) def trigger_cutscene_bookmark_fired_event(self, data): return dict( - cutscene_id=data.read_uint32()-2147483648, + cutscene_id=data.read_uint32() - 2147483648, bookmark_name=data.read_aligned_string(data.read_bits(7)), ) def trigger_cutscene_end_scene_fired_event(self, data): - return dict( - cutscene_id=data.read_uint32()-2147483648, - ) + return dict(cutscene_id=data.read_uint32() - 2147483648) def trigger_cutscene_conversation_line_event(self, data): return dict( - cutscene_id=data.read_uint32()-2147483648, + cutscene_id=data.read_uint32() - 2147483648, conversation_line=data.read_aligned_string(data.read_bits(7)), alt_conversation_line=data.read_aligned_string(data.read_bits(7)), ) def trigger_cutscene_conversation_line_missing_event(self, data): return dict( - cutscene_id=data.read_uint32()-2147483648, + cutscene_id=data.read_uint32() - 2147483648, conversation_line=data.read_aligned_string(data.read_bits(7)), ) class GameEventsReader_23260(GameEventsReader_22612): - def trigger_sound_length_sync_event(self, data): return dict( sync_info=dict( @@ -1290,7 +1567,6 @@ def user_options_event(self, data): class GameEventsReader_HotSBeta(GameEventsReader_23260): - def user_options_event(self, data): return dict( game_fully_downloaded=data.read_bool(), @@ -1309,26 +1585,39 @@ def selection_delta_event(self, data): control_group_index=data.read_bits(4), subgroup_index=data.read_bits(9), remove_mask={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('Mask', self.read_selection_bitmask(data, data.read_bits(9))), - 2: lambda: ('OneIndices', [data.read_bits(9) for i in range(data.read_bits(9))]), - 3: lambda: ('ZeroIndices', [data.read_bits(9) for i in range(data.read_bits(9))]), + 0: lambda: ("None", None), + 1: lambda: ( + "Mask", + self.read_selection_bitmask(data, data.read_bits(9)), + ), + 2: lambda: ( + "OneIndices", + [data.read_bits(9) for i in range(data.read_bits(9))], + ), + 3: lambda: ( + "ZeroIndices", + [data.read_bits(9) for i in range(data.read_bits(9))], + ), }[data.read_bits(2)](), - add_subgroups=[dict( - unit_link=data.read_uint16(), - subgroup_priority=data.read_uint8(), - intra_subgroup_priority=data.read_uint8(), - count=data.read_bits(9), - ) for i in range(data.read_bits(9))], + add_subgroups=[ + dict( + unit_link=data.read_uint16(), + subgroup_priority=data.read_uint8(), + intra_subgroup_priority=data.read_uint8(), + count=data.read_bits(9), + ) + for i in range(data.read_bits(9)) + ], add_unit_tags=[data.read_uint32() for i in range(data.read_bits(9))], ) def camera_update_event(self, data): return dict( - target=dict( - x=data.read_uint16(), - y=data.read_uint16(), - ) if data.read_bool() else None, + target=( + dict(x=data.read_uint16(), y=data.read_uint16()) + if data.read_bool() + else None + ), distance=data.read_uint16() if data.read_bool() else None, pitch=data.read_uint16() if data.read_bool() else None, yaw=data.read_uint16() if data.read_bool() else None, @@ -1336,40 +1625,44 @@ def camera_update_event(self, data): def trigger_dialog_control_event(self, data): return dict( - control_id=data.read_uint32()-2147483648, - event_type=data.read_uint32()-2147483648, + control_id=data.read_uint32() - 2147483648, + event_type=data.read_uint32() - 2147483648, event_data={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('Checked', data.read_bool()), - 2: lambda: ('ValueChanged', data.read_uint32()), - 3: lambda: ('SelectionChanged', data.read_uint32()-2147483648), - 4: lambda: ('TextChanged', data.read_aligned_string(data.read_bits(11))), - 5: lambda: ('MouseButton', data.read_uint32()) + 0: lambda: ("None", None), + 1: lambda: ("Checked", data.read_bool()), + 2: lambda: ("ValueChanged", data.read_uint32()), + 3: lambda: ("SelectionChanged", data.read_uint32() - 2147483648), + 4: lambda: ( + "TextChanged", + data.read_aligned_string(data.read_bits(11)), + ), + 5: lambda: ("MouseButton", data.read_uint32()), }[data.read_bits(3)](), ) class GameEventsReader_24247(GameEventsReader_HotSBeta): - def __init__(self): - super(GameEventsReader_24247, self).__init__() - - self.EVENT_DISPATCH.update({ - 7: (UserOptionsEvent, self.user_options_event), # Override - 9: (None, self.bank_file_event), # Override - 10: (None, self.bank_section_event), # Override - 11: (None, self.bank_key_event), # Override - 12: (None, self.bank_value_event), # Override - 13: (None, self.bank_signature_event), # New - 14: (None, self.camera_save_event), # New - 21: (None, self.save_game_event), # New - 22: (None, self.save_game_done_event), # Override - 23: (None, self.load_game_done_event), # Override - 43: (HijackReplayGameEvent, self.hijack_replay_game_event), # New - 62: (None, self.trigger_target_mode_update_event), # New - 101: (PlayerLeaveEvent, self.game_user_leave_event), # New - 102: (None, self.game_user_join_event), # New - }) + super().__init__() + + self.EVENT_DISPATCH.update( + { + 7: (UserOptionsEvent, self.user_options_event), # Override + 9: (None, self.bank_file_event), # Override + 10: (None, self.bank_section_event), # Override + 11: (None, self.bank_key_event), # Override + 12: (None, self.bank_value_event), # Override + 13: (None, self.bank_signature_event), # New + 14: (None, self.camera_save_event), # New + 21: (None, self.save_game_event), # New + 22: (None, self.save_game_done_event), # Override + 23: (None, self.load_game_done_event), # Override + 43: (HijackReplayGameEvent, self.hijack_replay_game_event), # New + 62: (None, self.trigger_target_mode_update_event), # New + 101: (PlayerLeaveEvent, self.game_user_leave_event), # New + 102: (None, self.game_user_join_event), # New + } + ) del self.EVENT_DISPATCH[8] del self.EVENT_DISPATCH[25] del self.EVENT_DISPATCH[76] @@ -1377,16 +1670,13 @@ def __init__(self): def bank_signature_event(self, data): return dict( signature=[data.read_uint8() for i in range(data.read_bits(5))], - toon_handle=data.read_aligned_string(data.read_bits(7)) + toon_handle=data.read_aligned_string(data.read_bits(7)), ) def camera_save_event(self, data): return dict( which=data.read_bits(3), - target=dict( - x=data.read_uint16(), - y=data.read_uint16(), - ) + target=dict(x=data.read_uint16(), y=data.read_uint16()), ) def load_game_done_event(self, data): @@ -1394,23 +1684,35 @@ def load_game_done_event(self, data): def hijack_replay_game_event(self, data): return dict( - user_infos=[dict( - game_user_id=data.read_bits(4), - observe=data.read_bits(2), - name=data.read_aligned_string(data.read_uint8()), - toon_handle=data.read_aligned_string(data.read_bits(7)) if data.read_bool() else None, - clan_tag=data.read_aligned_string(data.read_uint8()) if data.read_bool() else None, - clan_logo=None, - ) for i in range(data.read_bits(5))], + user_infos=[ + dict( + game_user_id=data.read_bits(4), + observe=data.read_bits(2), + name=data.read_aligned_string(data.read_uint8()), + toon_handle=( + data.read_aligned_string(data.read_bits(7)) + if data.read_bool() + else None + ), + clan_tag=( + data.read_aligned_string(data.read_uint8()) + if data.read_bool() + else None + ), + clan_logo=None, + ) + for i in range(data.read_bits(5)) + ], method=data.read_bits(1), ) def camera_update_event(self, data): return dict( - target=dict( - x=data.read_uint16(), - y=data.read_uint16(), - ) if data.read_bool() else None, + target=( + dict(x=data.read_uint16(), y=data.read_uint16()) + if data.read_bool() + else None + ), distance=data.read_uint16() if data.read_bool() else None, pitch=data.read_uint16() if data.read_bool() else None, yaw=data.read_uint16() if data.read_bool() else None, @@ -1421,7 +1723,7 @@ def trigger_target_mode_update_event(self, data): return dict( ability_link=data.read_uint16(), ability_command_index=data.read_bits(5), - state=data.read_uint8()-128, + state=data.read_uint8() - 128, ) def game_user_leave_event(self, data): @@ -1431,14 +1733,21 @@ def game_user_join_event(self, data): return dict( observe=data.read_bits(2), name=data.read_aligned_string(data.read_bits(8)), - toon_handle=data.read_aligned_string(data.read_bits(7)) if data.read_bool() else None, - clan_tag=data.read_aligned_string(data.read_uint8()) if data.read_bool() else None, + toon_handle=( + data.read_aligned_string(data.read_bits(7)) + if data.read_bool() + else None + ), + clan_tag=( + data.read_aligned_string(data.read_uint8()) + if data.read_bool() + else None + ), clan_log=None, ) class GameEventsReader_26490(GameEventsReader_24247): - def user_options_event(self, data): return dict( game_fully_downloaded=data.read_bool(), @@ -1456,10 +1765,7 @@ def trigger_mouse_clicked_event(self, data): return dict( button=data.read_uint32(), down=data.read_bool(), - position_ui=dict( - x=data.read_bits(11), - y=data.read_bits(11), - ), + position_ui=dict(x=data.read_bits(11), y=data.read_bits(11)), position_world=dict( x=data.read_bits(20) - 2147483648, y=data.read_bits(20) - 2147483648, @@ -1470,10 +1776,7 @@ def trigger_mouse_clicked_event(self, data): def trigger_mouse_moved_event(self, data): return dict( - position_ui=dict( - x=data.read_bits(11), - y=data.read_bits(11), - ), + position_ui=dict(x=data.read_bits(11), y=data.read_bits(11)), position_world=dict( x=data.read_bits(20), y=data.read_bits(20), @@ -1484,26 +1787,41 @@ def trigger_mouse_moved_event(self, data): class GameEventsReader_27950(GameEventsReader_26490): - def hijack_replay_game_event(self, data): return dict( - user_infos=[dict( - game_user_id=data.read_bits(4), - observe=data.read_bits(2), - name=data.read_aligned_string(data.read_uint8()), - toon_handle=data.read_aligned_string(data.read_bits(7)) if data.read_bool() else None, - clan_tag=data.read_aligned_string(data.read_uint8()) if data.read_bool() else None, - clan_logo=DepotFile(data.read_aligned_bytes(40)) if data.read_bool() else None, - ) for i in range(data.read_bits(5))], + user_infos=[ + dict( + game_user_id=data.read_bits(4), + observe=data.read_bits(2), + name=data.read_aligned_string(data.read_uint8()), + toon_handle=( + data.read_aligned_string(data.read_bits(7)) + if data.read_bool() + else None + ), + clan_tag=( + data.read_aligned_string(data.read_uint8()) + if data.read_bool() + else None + ), + clan_logo=( + DepotFile(data.read_aligned_bytes(40)) + if data.read_bool() + else None + ), + ) + for i in range(data.read_bits(5)) + ], method=data.read_bits(1), ) def camera_update_event(self, data): return dict( - target=dict( - x=data.read_uint16(), - y=data.read_uint16(), - ) if data.read_bool() else None, + target=( + dict(x=data.read_uint16(), y=data.read_uint16()) + if data.read_bool() + else None + ), distance=data.read_uint16() if data.read_bool() else None, pitch=data.read_uint16() if data.read_bool() else None, yaw=data.read_uint16() if data.read_bool() else None, @@ -1514,43 +1832,60 @@ def game_user_join_event(self, data): return dict( observe=data.read_bits(2), name=data.read_aligned_string(data.read_bits(8)), - toon_handle=data.read_aligned_string(data.read_bits(7)) if data.read_bool() else None, - clan_tag=data.read_aligned_string(data.read_uint8()) if data.read_bool() else None, - clan_logo=DepotFile(data.read_aligned_bytes(40)) if data.read_bool() else None, + toon_handle=( + data.read_aligned_string(data.read_bits(7)) + if data.read_bool() + else None + ), + clan_tag=( + data.read_aligned_string(data.read_uint8()) + if data.read_bool() + else None + ), + clan_logo=( + DepotFile(data.read_aligned_bytes(40)) if data.read_bool() else None + ), ) -class GameEventsReader_34784(GameEventsReader_27950): +class GameEventsReader_34784(GameEventsReader_27950): def __init__(self): - super(GameEventsReader_34784, self).__init__() - - self.EVENT_DISPATCH.update({ - 25: (None, self.command_manager_reset_event), # Re-using this old number - 61: (None, self.trigger_hotkey_pressed_event), - 103: (None, self.command_manager_state_event), - 104: (UpdateTargetPointCommandEvent, self.command_update_target_point_event), - 105: (UpdateTargetUnitCommandEvent, self.command_update_target_unit_event), - 106: (None, self.trigger_anim_length_query_by_name_event), - 107: (None, self.trigger_anim_length_query_by_props_event), - 108: (None, self.trigger_anim_offset_event), - 109: (None, self.catalog_modify_event), - 110: (None, self.hero_talent_tree_selected_event), - 111: (None, self.trigger_profiler_logging_finished_event), - 112: (None, self.hero_talent_tree_selection_panel_toggled_event), - }) + super().__init__() + + self.EVENT_DISPATCH.update( + { + 25: ( + None, + self.command_manager_reset_event, + ), # Reusing this old number + 61: (None, self.trigger_hotkey_pressed_event), + 103: (CommandManagerStateEvent, self.command_manager_state_event), + 104: ( + UpdateTargetPointCommandEvent, + self.command_update_target_point_event, + ), + 105: ( + UpdateTargetUnitCommandEvent, + self.command_update_target_unit_event, + ), + 106: (None, self.trigger_anim_length_query_by_name_event), + 107: (None, self.trigger_anim_length_query_by_props_event), + 108: (None, self.trigger_anim_offset_event), + 109: (None, self.catalog_modify_event), + 110: (None, self.hero_talent_tree_selected_event), + 111: (None, self.trigger_profiler_logging_finished_event), + 112: (None, self.hero_talent_tree_selection_panel_toggled_event), + } + ) def hero_talent_tree_selection_panel_toggled_event(self, data): - return dict( - shown=data.read_bool(), - ) + return dict(shown=data.read_bool()) def trigger_profiler_logging_finished_event(self, data): return dict() def hero_talent_tree_selected_event(self, data): - return dict( - index=data.read_uint32() - ) + return dict(index=data.read_uint32()) def catalog_modify_event(self, data): return dict( @@ -1561,15 +1896,10 @@ def catalog_modify_event(self, data): ) def trigger_anim_offset_event(self, data): - return dict( - anim_wait_query_id=data.read_uint16(), - ) + return dict(anim_wait_query_id=data.read_uint16()) def trigger_anim_length_query_by_props_event(self, data): - return dict( - query_id=data.read_uint16(), - length_ms=data.read_uint32(), - ) + return dict(query_id=data.read_uint16(), length_ms=data.read_uint32()) def trigger_anim_length_query_by_name_event(self, data): return dict( @@ -1579,9 +1909,7 @@ def trigger_anim_length_query_by_name_event(self, data): ) def command_manager_reset_event(self, data): - return dict( - sequence=data.read_uint32(), - ) + return dict(sequence=data.read_uint32()) def command_manager_state_event(self, data): return dict( @@ -1593,13 +1921,16 @@ def command_update_target_point_event(self, data): return dict( flags=0, # fill me with previous TargetPointEvent.flags ability=None, # fill me with previous TargetPointEvent.ability - data=('TargetPoint', dict( - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_bits(32) - 2147483648, + data=( + "TargetPoint", + dict( + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_bits(32) - 2147483648, + ) ), - )), + ), sequence=0, # fill me with previous TargetPointEvent.flags other_unit_tag=None, # fill me with previous TargetPointEvent.flags unit_group=None, # fill me with previous TargetPointEvent.flags @@ -1607,44 +1938,11 @@ def command_update_target_point_event(self, data): def command_update_target_unit_event(self, data): return dict( - flags=0, # fill me with previous TargetUnitEvent.flags + flags=0, # fill me with previous TargetUnitEvent.flags ability=None, # fill me with previous TargetUnitEvent.ability - data=('TargetUnit', dict( - flags=data.read_uint16(), - timer=data.read_uint8(), - unit_tag=data.read_uint32(), - unit_link=data.read_uint16(), - control_player_id=data.read_bits(4) if data.read_bool() else None, - upkeep_player_id=data.read_bits(4) if data.read_bool() else None, - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_bits(32) - 2147483648, - ), - )), - sequence=0, # fill me with previous TargetUnitEvent.flags - other_unit_tag=None, # fill me with previous TargetUnitEvent.flags - unit_group=None, # fill me with previous TargetUnitEvent.flags - ) - - def command_event(self, data): - return dict( - flags=data.read_bits(23), - ability=dict( - ability_link=data.read_uint16(), - ability_command_index=data.read_bits(5), - ability_command_data=data.read_uint8() if data.read_bool() else None, - ) if data.read_bool() else None, - data={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('TargetPoint', dict( - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_uint32() - 2147483648, - ) - )), - 2: lambda: ('TargetUnit', dict( + data=( + "TargetUnit", + dict( flags=data.read_uint16(), timer=data.read_uint8(), unit_tag=data.read_uint32(), @@ -1654,12 +1952,62 @@ def command_event(self, data): point=dict( x=data.read_bits(20), y=data.read_bits(20), - z=data.read_uint32() - 2147483648, + z=data.read_bits(32) - 2147483648, + ), + ), + ), + sequence=0, # fill me with previous TargetUnitEvent.flags + other_unit_tag=None, # fill me with previous TargetUnitEvent.flags + unit_group=None, # fill me with previous TargetUnitEvent.flags + ) + + def command_event(self, data): + return dict( + flags=data.read_bits(23), + ability=( + dict( + ability_link=data.read_uint16(), + ability_command_index=data.read_bits(5), + ability_command_data=( + data.read_uint8() if data.read_bool() else None + ), + ) + if data.read_bool() + else None + ), + data={ # Choice + 0: lambda: ("None", None), + 1: lambda: ( + "TargetPoint", + dict( + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ) ), - )), - 3: lambda: ('Data', dict( - data=data.read_uint32() - )), + ), + 2: lambda: ( + "TargetUnit", + dict( + flags=data.read_uint16(), + timer=data.read_uint8(), + unit_tag=data.read_uint32(), + unit_link=data.read_uint16(), + control_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + upkeep_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ), + ), + ), + 3: lambda: ("Data", dict(data=data.read_uint32())), }[data.read_bits(2)](), sequence=data.read_uint32() + 1, other_unit_tag=data.read_uint32() if data.read_bool() else None, @@ -1689,8 +2037,7 @@ def user_options_event(self, data): def trigger_ping_event(self, data): return dict( point=dict( - x=data.read_uint32() - 2147483648, - y=data.read_uint32() - 2147483648, + x=data.read_uint32() - 2147483648, y=data.read_uint32() - 2147483648 ), unit_tag=data.read_uint32(), pinged_minimap=data.read_bool(), @@ -1699,10 +2046,11 @@ def trigger_ping_event(self, data): def camera_update_event(self, data): return dict( - target=dict( - x=data.read_uint16(), - y=data.read_uint16(), - ) if data.read_bool() else None, + target=( + dict(x=data.read_uint16(), y=data.read_uint16()) + if data.read_bool() + else None + ), distance=data.read_uint16() if data.read_bool() else None, pitch=data.read_uint16() if data.read_bool() else None, yaw=data.read_uint16() if data.read_bool() else None, @@ -1711,66 +2059,88 @@ def camera_update_event(self, data): ) def trigger_hotkey_pressed_event(self, data): - return dict( - hotkey=data.read_uint32(), - down=data.read_bool(), - ) + return dict(hotkey=data.read_uint32(), down=data.read_bool()) def game_user_join_event(self, data): return dict( observe=data.read_bits(2), name=data.read_aligned_string(data.read_bits(8)), - toon_handle=data.read_aligned_string(data.read_bits(7)) if data.read_bool() else None, - clan_tag=data.read_aligned_string(data.read_uint8()) if data.read_bool() else None, - clan_logo=DepotFile(data.read_aligned_bytes(40)) if data.read_bool() else None, + toon_handle=( + data.read_aligned_string(data.read_bits(7)) + if data.read_bool() + else None + ), + clan_tag=( + data.read_aligned_string(data.read_uint8()) + if data.read_bool() + else None + ), + clan_logo=( + DepotFile(data.read_aligned_bytes(40)) if data.read_bool() else None + ), hijack=data.read_bool(), hijack_clone_game_user_id=data.read_bits(4) if data.read_bool() else None, ) def game_user_leave_event(self, data): - return dict( - leave_reason=data.read_bits(4) - ) + return dict(leave_reason=data.read_bits(4)) -class GameEventsReader_36442(GameEventsReader_34784): +class GameEventsReader_36442(GameEventsReader_34784): def control_group_update_event(self, data): return dict( control_group_index=data.read_bits(4), control_group_update=data.read_bits(3), remove_mask={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('Mask', self.read_selection_bitmask(data, data.read_bits(9))), - 2: lambda: ('OneIndices', [data.read_bits(9) for i in range(data.read_bits(9))]), - 3: lambda: ('ZeroIndices', [data.read_bits(9) for i in range(data.read_bits(9))]), + 0: lambda: ("None", None), + 1: lambda: ( + "Mask", + self.read_selection_bitmask(data, data.read_bits(9)), + ), + 2: lambda: ( + "OneIndices", + [data.read_bits(9) for i in range(data.read_bits(9))], + ), + 3: lambda: ( + "ZeroIndices", + [data.read_bits(9) for i in range(data.read_bits(9))], + ), }[data.read_bits(2)](), ) -class GameEventsReader_38215(GameEventsReader_36442): +class GameEventsReader_38215(GameEventsReader_36442): def __init__(self): - super(GameEventsReader_38215, self).__init__() + super().__init__() - self.EVENT_DISPATCH.update({ - 76: (None, self.trigger_command_error_event), - 92: (None, self.trigger_mousewheel_event), # 172 in protocol38125.py - }) + self.EVENT_DISPATCH.update( + { + 76: (None, self.trigger_command_error_event), + 92: (None, self.trigger_mousewheel_event), # 172 in protocol38125.py + } + ) def trigger_command_error_event(self, data): return dict( error=data.read_uint32() - 2147483648, - ability=dict( - ability_link=data.read_uint16(), - ability_command_index=data.read_bits(5), - ability_command_data=data.read_uint8() if data.read_bool() else None, - ) if data.read_bool() else None, + ability=( + dict( + ability_link=data.read_uint16(), + ability_command_index=data.read_bits(5), + ability_command_data=( + data.read_uint8() if data.read_bool() else None + ), + ) + if data.read_bool() + else None + ), ) def trigger_mousewheel_event(self, data): # 172 in protocol38125.py return dict( - wheelspin=data.read_uint16()-32768, # 171 in protocol38125.py - flags=data.read_uint8() - 128, # 112 in protocol38125.py + wheelspin=data.read_uint16() - 32768, # 171 in protocol38125.py + flags=data.read_uint8() - 128, # 112 in protocol38125.py ) def command_event(self, data): @@ -1778,36 +2148,50 @@ def command_event(self, data): # with the only change being that flags now has 25 bits instead of 23. return dict( flags=data.read_bits(25), - ability=dict( - ability_link=data.read_uint16(), - ability_command_index=data.read_bits(5), - ability_command_data=data.read_uint8() if data.read_bool() else None, - ) if data.read_bool() else None, + ability=( + dict( + ability_link=data.read_uint16(), + ability_command_index=data.read_bits(5), + ability_command_data=( + data.read_uint8() if data.read_bool() else None + ), + ) + if data.read_bool() + else None + ), data={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('TargetPoint', dict( - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_uint32() - 2147483648, - ) - )), - 2: lambda: ('TargetUnit', dict( - flags=data.read_uint16(), - timer=data.read_uint8(), - unit_tag=data.read_uint32(), - unit_link=data.read_uint16(), - control_player_id=data.read_bits(4) if data.read_bool() else None, - upkeep_player_id=data.read_bits(4) if data.read_bool() else None, - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_uint32() - 2147483648, + 0: lambda: ("None", None), + 1: lambda: ( + "TargetPoint", + dict( + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ) + ), + ), + 2: lambda: ( + "TargetUnit", + dict( + flags=data.read_uint16(), + timer=data.read_uint8(), + unit_tag=data.read_uint32(), + unit_link=data.read_uint16(), + control_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + upkeep_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ), ), - )), - 3: lambda: ('Data', dict( - data=data.read_uint32() - )), + ), + 3: lambda: ("Data", dict(data=data.read_uint32())), }[data.read_bits(2)](), sequence=data.read_uint32() + 1, other_unit_tag=data.read_uint32() if data.read_bool() else None, @@ -1834,86 +2218,98 @@ def user_options_event(self, data): use_ai_beacons=None, ) -class GameEventsReader_38749(GameEventsReader_38215): +class GameEventsReader_38749(GameEventsReader_38215): def trigger_ping_event(self, data): return dict( point=dict( - x=data.read_uint32() - 2147483648, - y=data.read_uint32() - 2147483648, + x=data.read_uint32() - 2147483648, y=data.read_uint32() - 2147483648 ), unit_tag=data.read_uint32(), unit_link=data.read_uint16(), unit_control_player_id=(data.read_bits(4) if data.read_bool() else None), unit_upkeep_player_id=(data.read_bits(4) if data.read_bool() else None), unit_position=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_bits(32) - 2147483648, - ), + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_bits(32) - 2147483648, + ), pinged_minimap=data.read_bool(), option=data.read_uint32() - 2147483648, ) -class GameEventsReader_38996(GameEventsReader_38749): +class GameEventsReader_38996(GameEventsReader_38749): def trigger_ping_event(self, data): return dict( point=dict( - x=data.read_uint32() - 2147483648, - y=data.read_uint32() - 2147483648, + x=data.read_uint32() - 2147483648, y=data.read_uint32() - 2147483648 ), unit_tag=data.read_uint32(), unit_link=data.read_uint16(), unit_control_player_id=(data.read_bits(4) if data.read_bool() else None), unit_upkeep_player_id=(data.read_bits(4) if data.read_bool() else None), unit_position=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_bits(32) - 2147483648, - ), + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_bits(32) - 2147483648, + ), unit_is_under_construction=data.read_bool(), pinged_minimap=data.read_bool(), option=data.read_uint32() - 2147483648, ) -class GameEventsReader_64469(GameEventsReader_38996): +class GameEventsReader_64469(GameEventsReader_38996): # this function is exactly the same as command_event() from GameEventsReader_38996 # with the only change being that flags now has 26 bits instead of 25. def command_event(self, data): return dict( flags=data.read_bits(26), - ability=dict( - ability_link=data.read_uint16(), - ability_command_index=data.read_bits(5), - ability_command_data=data.read_uint8() if data.read_bool() else None, - ) if data.read_bool() else None, + ability=( + dict( + ability_link=data.read_uint16(), + ability_command_index=data.read_bits(5), + ability_command_data=( + data.read_uint8() if data.read_bool() else None + ), + ) + if data.read_bool() + else None + ), data={ # Choice - 0: lambda: ('None', None), - 1: lambda: ('TargetPoint', dict( - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_uint32() - 2147483648, - ) - )), - 2: lambda: ('TargetUnit', dict( - flags=data.read_uint16(), - timer=data.read_uint8(), - unit_tag=data.read_uint32(), - unit_link=data.read_uint16(), - control_player_id=data.read_bits(4) if data.read_bool() else None, - upkeep_player_id=data.read_bits(4) if data.read_bool() else None, - point=dict( - x=data.read_bits(20), - y=data.read_bits(20), - z=data.read_uint32() - 2147483648, + 0: lambda: ("None", None), + 1: lambda: ( + "TargetPoint", + dict( + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ) + ), + ), + 2: lambda: ( + "TargetUnit", + dict( + flags=data.read_uint16(), + timer=data.read_uint8(), + unit_tag=data.read_uint32(), + unit_link=data.read_uint16(), + control_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + upkeep_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ), ), - )), - 3: lambda: ('Data', dict( - data=data.read_uint32() - )), + ), + 3: lambda: ("Data", dict(data=data.read_uint32())), }[data.read_bits(2)](), sequence=data.read_uint32() + 1, other_unit_tag=data.read_uint32() if data.read_bool() else None, @@ -1927,26 +2323,83 @@ 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), - }) + self.EVENT_DISPATCH.update( + {116: (None, self.set_sync_loading), 117: (None, self.set_sync_playing)} + ) def set_sync_loading(self, data): - return dict( - sync_load=data.read_uint32() - ) + return dict(sync_load=data.read_uint32()) def set_sync_playing(self, data): + return dict(sync_load=data.read_uint32()) + + +class GameEventsReader_80669(GameEventsReader_65895): + # this is almost the same as `command_event` from previous build + # the only addition is introduction of extra command flag: + # > https://news.blizzard.com/en-us/starcraft2/23471116/starcraft-ii-4-13-0-ptr-patch-notes + # > New order command flag: Attack Once + # > When issuing an attack order, it is now allowed to issue an “attack once” order with order command flags. + # > const int c_cmdAttackOnce = 26; + # ideally this part of the code should be more generic so it doesn't have to copy-pasted as a whole + # every time there's a tiny change in one of the sub-structs + def command_event(self, data): return dict( - sync_load=data.read_uint32() + flags=data.read_bits(27), + ability=( + dict( + ability_link=data.read_uint16(), + ability_command_index=data.read_bits(5), + ability_command_data=( + data.read_uint8() if data.read_bool() else None + ), + ) + if data.read_bool() + else None + ), + data={ # Choice + 0: lambda: ("None", None), + 1: lambda: ( + "TargetPoint", + dict( + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ) + ), + ), + 2: lambda: ( + "TargetUnit", + dict( + flags=data.read_uint16(), + timer=data.read_uint8(), + unit_tag=data.read_uint32(), + unit_link=data.read_uint16(), + control_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + upkeep_player_id=( + data.read_bits(4) if data.read_bool() else None + ), + point=dict( + x=data.read_bits(20), + y=data.read_bits(20), + z=data.read_uint32() - 2147483648, + ), + ), + ), + 3: lambda: ("Data", dict(data=data.read_uint32())), + }[data.read_bits(2)](), + sequence=data.read_uint32() + 1, + other_unit_tag=data.read_uint32() if data.read_bool() else None, + unit_group=data.read_uint32() if data.read_bool() else None, ) -class TrackerEventsReader(object): - +class TrackerEventsReader: def __init__(self): self.EVENT_DISPATCH = { 0: PlayerStatsEvent, diff --git a/sc2reader/resources.py b/sc2reader/resources.py index 8d165670..388f1765 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 @@ -16,32 +13,40 @@ from sc2reader import exceptions from sc2reader.data import datapacks from sc2reader.exceptions import SC2ReaderLocalizationError, CorruptTrackerFileError -from sc2reader.objects import Participant, Observer, Computer, Team, PlayerSummary, Graph, BuildEntry, MapInfo +from sc2reader.objects import ( + Participant, + Observer, + Computer, + Team, + PlayerSummary, + Graph, + BuildEntry, + MapInfo, +) 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 self.logger = log_utils.get_logger(self.__class__) - self.filename = filename or getattr(file_object, 'name', 'Unavailable') + self.filename = filename or getattr(file_object, "name", "Unavailable") - if hasattr(file_object, 'seek'): + if hasattr(file_object, "seek"): file_object.seek(0) self.filehash = hashlib.sha256(file_object.read()).hexdigest() file_object.seek(0) class Replay(Resource): - #: A nested dictionary of player => { attr_name : attr_value } for #: known attributes. Player 16 represents the global context and #: contains attributes like game speed. 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() @@ -53,27 +58,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 choosen at game creation: 1v1, 2v2, 3v3, 4v4, FFA - game_type = str() + #: The game type chosen at game creation: 1v1, 2v2, 3v3, 4v4, FFA + 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() @@ -82,10 +87,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 @@ -121,7 +126,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() @@ -178,10 +183,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 @@ -192,8 +197,16 @@ class Replay(Resource): #: Lists info for each user that is resuming from replay. resume_user_info = None - def __init__(self, replay_file, filename=None, load_level=4, engine=sc2reader.engine, do_tracker_events=True, **options): - super(Replay, self).__init__(replay_file, filename, **options) + def __init__( + self, + replay_file, + filename=None, + load_level=4, + engine=sc2reader.engine, + do_tracker_events=True, + **options, + ): + super().__init__(replay_file, filename, **options) self.datapack = None self.raw_data = dict() @@ -254,35 +267,45 @@ def __init__(self, replay_file, filename=None, load_level=4, engine=sc2reader.en except Exception as e: raise exceptions.MPQError("Unable to construct the MPQArchive", e) - header_content = self.archive.header['user_data_header']['content'] + header_content = self.archive.header["user_data_header"]["content"] header_data = BitPackedDecoder(header_content).read_struct() self.versions = list(header_data[1].values()) 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 + if 34784 <= self.build: # lotv replay, adjust time fps = self.game_fps * 1.4 - self.length = self.game_length = self.real_length = utils.Length(seconds=int(self.frames/fps)) + self.length = self.game_length = self.real_length = utils.Length( + seconds=int(self.frames / fps) + ) # Load basic details if requested + # .backup files are read in case the main files are missing or removed if load_level >= 1: self.load_level = 1 - for data_file in ['replay.initData', 'replay.details', 'replay.attributes.events']: + files = [ + "replay.initData.backup", + "replay.details.backup", + "replay.attributes.events", + "replay.initData", + "replay.details", + ] + for data_file in files: self._read_data(data_file, self._get_reader(data_file)) - self.load_details() + self.load_all_details() self.datapack = self._get_datapack() # Can only be effective if map data has been loaded - if options.get('load_map', False): + if options.get("load_map", False): self.load_map() # Load players if requested if load_level >= 2: self.load_level = 2 - for data_file in ['replay.message.events']: + for data_file in ["replay.message.events"]: self._read_data(data_file, self._get_reader(data_file)) self.load_message_events() self.load_players() @@ -290,104 +313,151 @@ def __init__(self, replay_file, filename=None, load_level=4, engine=sc2reader.en # Load tracker events if requested if load_level >= 3 and do_tracker_events: self.load_level = 3 - for data_file in ['replay.tracker.events']: + for data_file in ["replay.tracker.events"]: self._read_data(data_file, self._get_reader(data_file)) self.load_tracker_events() # Load events if requested if load_level >= 4: self.load_level = 4 - for data_file in ['replay.game.events']: + for data_file in ["replay.game.events"]: self._read_data(data_file, self._get_reader(data_file)) self.load_game_events() # Run this replay through the engine as indicated if engine: - resume_events = [ev for ev in self.game_events if ev.name == 'HijackReplayGameEvent'] - if self.base_build <= 26490 and self.tracker_events and len(resume_events) > 0: + resume_events = [ + ev for ev in self.game_events if ev.name == "HijackReplayGameEvent" + ] + if ( + self.base_build <= 26490 + and self.tracker_events + and len(resume_events) > 0 + ): raise CorruptTrackerFileError( - "Cannot run engine on resumed games with tracker events. Run again with the " + - "do_tracker_events=False option to generate context without tracker events.") + "Cannot run engine on resumed games with tracker events. Run again with the " + + "do_tracker_events=False option to generate context without tracker events." + ) engine.run(self) - def load_details(self): - if 'replay.initData' in self.raw_data: - initData = self.raw_data['replay.initData'] - options = initData['game_description']['game_options'] - self.amm = options['amm'] - self.ranked = options['ranked'] - self.competitive = options['competitive'] - self.practice = options['practice'] - self.cooperative = options['cooperative'] - self.battle_net = options['battle_net'] - self.hero_duplicates_allowed = options['hero_duplicates_allowed'] - - if 'replay.attributes.events' in self.raw_data: + def load_init_data(self): + if "replay.initData" in self.raw_data: + initData = self.raw_data["replay.initData"] + elif "replay.initData.backup" in self.raw_data: + initData = self.raw_data["replay.initData.backup"] + else: + return + + options = initData["game_description"]["game_options"] + self.amm = options["amm"] + self.ranked = options["ranked"] + self.competitive = options["competitive"] + self.practice = options["practice"] + self.cooperative = options["cooperative"] + self.battle_net = options["battle_net"] + self.hero_duplicates_allowed = options["hero_duplicates_allowed"] + + def load_attribute_events(self): + if "replay.attributes.events" in self.raw_data: # Organize the attribute data to be useful self.attributes = defaultdict(dict) - attributesEvents = self.raw_data['replay.attributes.events'] + attributesEvents = self.raw_data["replay.attributes.events"] for attr in attributesEvents: self.attributes[attr.player][attr.name] = attr.value # Populate replay with attributes - self.speed = self.attributes[16]['Game Speed'] - self.category = self.attributes[16]['Game Mode'] - self.type = self.game_type = self.attributes[16]['Teams'] - self.is_ladder = (self.category == "Ladder") - self.is_private = (self.category == "Private") - - if 'replay.details' in self.raw_data: - details = self.raw_data['replay.details'] - - self.map_name = details['map_name'] - - self.region = details['cache_handles'][0].server.lower() - self.map_hash = details['cache_handles'][-1].hash - self.map_file = details['cache_handles'][-1] - - # Expand this special case mapping - if self.region == 'sg': - self.region = 'sea' - - dependency_hashes = [d.hash for d in details['cache_handles']] - if hashlib.sha256('Standard Data: Void.SC2Mod'.encode('utf8')).hexdigest() in dependency_hashes: - self.expansion = 'LotV' - elif hashlib.sha256('Standard Data: Swarm.SC2Mod'.encode('utf8')).hexdigest() in dependency_hashes: - self.expansion = 'HotS' - elif hashlib.sha256('Standard Data: Liberty.SC2Mod'.encode('utf8')).hexdigest() in dependency_hashes: - self.expansion = 'WoL' - else: - self.expansion = '' - - self.windows_timestamp = details['file_time'] - self.unix_timestamp = utils.windows_to_unix(self.windows_timestamp) - self.end_time = datetime.utcfromtimestamp(self.unix_timestamp) - - # The utc_adjustment is either the adjusted windows timestamp OR - # the value required to get the adjusted timestamp. We know the upper - # limit for any adjustment number so use that to distinguish between - # the two cases. - if details['utc_adjustment'] < 10**7*60*60*24: - self.time_zone = details['utc_adjustment']/(10**7*60*60) - else: - self.time_zone = (details['utc_adjustment']-details['file_time'])/(10**7*60*60) + self.speed = self.attributes[16].get("Game Speed", 1.0) + self.category = self.attributes[16].get("Game Mode", "") + self.type = self.game_type = self.attributes[16].get("Teams", "") + self.is_ladder = self.category == "Ladder" + self.is_private = self.category == "Private" + + def load_details(self): + if "replay.details" in self.raw_data: + details = self.raw_data["replay.details"] + elif "replay.details.backup" in self.raw_data: + details = self.raw_data["replay.details.backup"] + else: + return - self.game_length = self.length - self.real_length = utils.Length(seconds=int(self.length.seconds/GAME_SPEED_FACTOR[self.expansion][self.speed])) - self.start_time = datetime.utcfromtimestamp(self.unix_timestamp-self.real_length.seconds) - self.date = self.end_time # backwards compatibility + self.map_name = details["map_name"] + self.region = details["cache_handles"][0].server.lower() + self.map_hash = details["cache_handles"][-1].hash + self.map_file = details["cache_handles"][-1] + + # Expand this special case mapping + if self.region == "sg": + self.region = "sea" + + dependency_hashes = [d.hash for d in details["cache_handles"]] + if ( + hashlib.sha256(b"Standard Data: Void.SC2Mod").hexdigest() + in dependency_hashes + ): + self.expansion = "LotV" + elif ( + hashlib.sha256(b"Standard Data: Swarm.SC2Mod").hexdigest() + in dependency_hashes + ): + self.expansion = "HotS" + elif ( + hashlib.sha256(b"Standard Data: Liberty.SC2Mod").hexdigest() + in dependency_hashes + ): + self.expansion = "WoL" + else: + self.expansion = "" + + self.windows_timestamp = details["file_time"] + self.unix_timestamp = utils.windows_to_unix(self.windows_timestamp) + self.end_time = datetime.utcfromtimestamp(self.unix_timestamp) + + # The utc_adjustment is either the adjusted windows timestamp OR + # the value required to get the adjusted timestamp. We know the upper + # limit for any adjustment number so use that to distinguish between + # the two cases. + if details["utc_adjustment"] < 10**7 * 60 * 60 * 24: + self.time_zone = details["utc_adjustment"] / (10**7 * 60 * 60) + else: + self.time_zone = (details["utc_adjustment"] - details["file_time"]) / ( + 10**7 * 60 * 60 + ) + + self.game_length = self.length + self.real_length = utils.Length( + seconds=self.length.seconds + // GAME_SPEED_FACTOR[self.expansion].get(self.speed, 1.0) + ) + self.start_time = datetime.utcfromtimestamp( + self.unix_timestamp - self.real_length.seconds + ) + self.date = self.end_time # backwards compatibility + + def load_all_details(self): + self.load_init_data() + self.load_attribute_events() + self.load_details() def load_map(self): self.map = self.factory.load_map(self.map_file, **self.opt) def load_players(self): # If we don't at least have details and attributes_events we can go no further - if 'replay.details' not in self.raw_data: + # We can use the backup detail files if the main files have been removed + if "replay.details" in self.raw_data: + details = self.raw_data["replay.details"] + elif "replay.details.backup" in self.raw_data: + details = self.raw_data["replay.details.backup"] + else: return - if 'replay.attributes.events' not in self.raw_data: + if "replay.attributes.events" not in self.raw_data: return - if 'replay.initData' not in self.raw_data: + if "replay.initData" in self.raw_data: + initData = self.raw_data["replay.initData"] + elif "replay.initData.backup" in self.raw_data: + initData = self.raw_data["replay.initData.backup"] + else: return self.clients = list() @@ -397,36 +467,60 @@ def load_players(self): # information. detail_id marks the current index into this data. detail_id = 0 player_id = 1 - details = self.raw_data['replay.details'] - initData = self.raw_data['replay.initData'] # Assume that the first X map slots starting at 1 are player slots # so that we can assign player ids without the map self.entities = list() - for slot_id, slot_data in enumerate(initData['lobby_state']['slots']): - user_id = slot_data['user_id'] - - if slot_data['control'] == 2: - if slot_data['observe'] == 0: - self.entities.append(Participant(slot_id, slot_data, user_id, initData['user_initial_data'][user_id], player_id, details['players'][detail_id], self.attributes.get(player_id, dict()))) + for slot_id, slot_data in enumerate(initData["lobby_state"]["slots"]): + user_id = slot_data["user_id"] + + if slot_data["control"] == 2: + if slot_data["observe"] == 0: + self.entities.append( + Participant( + slot_id, + slot_data, + user_id, + initData["user_initial_data"][user_id], + player_id, + details["players"][detail_id], + self.attributes.get(player_id, dict()), + ) + ) detail_id += 1 player_id += 1 else: - self.entities.append(Observer(slot_id, slot_data, user_id, initData['user_initial_data'][user_id], player_id)) + self.entities.append( + Observer( + slot_id, + slot_data, + user_id, + initData["user_initial_data"][user_id], + player_id, + ) + ) player_id += 1 - elif slot_data['control'] == 3 and detail_id < len(details['players']): + elif slot_data["control"] == 3 and detail_id < len(details["players"]): # detail_id check needed for coop - self.entities.append(Computer(slot_id, slot_data, player_id, details['players'][detail_id], self.attributes.get(player_id, dict()))) + self.entities.append( + Computer( + slot_id, + slot_data, + player_id, + details["players"][detail_id], + self.attributes.get(player_id, dict()), + ) + ) detail_id += 1 player_id += 1 def get_team(team_id): if team_id is not None and team_id not in self.team: - team = Team(team_id) - self.team[team_id] = team - self.teams.append(team) + team = Team(team_id) + self.team[team_id] = team + self.teams.append(team) return self.team[team_id] # Set up all our cross reference data structures @@ -452,14 +546,16 @@ 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': + if team.result == "Win": self.winner = team else: - self.logger.warn("Conflicting results for Team {0}: {1}".format(team.number, results)) - team.result = 'Unknown' + self.logger.warning( + f"Conflicting results for Team {team.number}: {results}" + ) + team.result = "Unknown" self.teams.sort(key=lambda t: t.number) @@ -482,9 +578,9 @@ def get_team(team_id): # Pretty sure this just never worked, forget about it for now self.recorder = None - entity_names = sorted(map(lambda p: p.name, self.entities)) - hash_input = self.region+":"+','.join(entity_names) - self.people_hash = hashlib.sha256(hash_input.encode('utf8')).hexdigest() + entity_names = sorted((p.name for p in self.entities)) + hash_input = self.region + ":" + ",".join(entity_names) + self.people_hash = hashlib.sha256(hash_input.encode("utf8")).hexdigest() # The presence of observers and/or computer players makes this not actually ladder # This became an issue in HotS where Training, vs AI, Unranked, and Ranked @@ -493,35 +589,39 @@ def get_team(team_id): self.is_ladder = False def load_message_events(self): - if 'replay.message.events' not in self.raw_data: + if "replay.message.events" not in self.raw_data: return - self.messages = self.raw_data['replay.message.events']['messages'] - self.pings = self.raw_data['replay.message.events']['pings'] - self.packets = self.raw_data['replay.message.events']['packets'] + self.messages = self.raw_data["replay.message.events"]["messages"] + self.pings = self.raw_data["replay.message.events"]["pings"] + self.packets = self.raw_data["replay.message.events"]["packets"] - self.message_events = self.messages+self.pings+self.packets + self.message_events = self.messages + self.pings + self.packets self.events = sorted(self.events + self.message_events, key=lambda e: e.frame) def load_game_events(self): # Copy the events over # TODO: the events need to be fixed both on the reader and processor side - if 'replay.game.events' not in self.raw_data: + if "replay.game.events" not in self.raw_data: return - self.game_events = self.raw_data['replay.game.events'] - self.events = sorted(self.events+self.game_events, key=lambda e: e.frame) + self.game_events = self.raw_data["replay.game.events"] + self.events = sorted(self.events + self.game_events, key=lambda e: e.frame) # hideous hack for HotS 2.0.0.23925, see https://github.com/GraylinKim/sc2reader/issues/87 - if self.base_build == 23925 and self.events and self.events[-1].frame > self.frames: + if ( + self.base_build == 23925 + and self.events + and self.events[-1].frame > self.frames + ): self.frames = self.events[-1].frame - self.length = utils.Length(seconds=int(self.frames/self.game_fps)) + self.length = utils.Length(seconds=int(self.frames / self.game_fps)) def load_tracker_events(self): - if 'replay.tracker.events' not in self.raw_data: + if "replay.tracker.events" not in self.raw_data: return - self.tracker_events = self.raw_data['replay.tracker.events'] + self.tracker_events = self.raw_data["replay.tracker.events"] self.events = sorted(self.tracker_events + self.events, key=lambda e: e.frame) def register_reader(self, data_file, reader, filterfunc=lambda r: True): @@ -566,53 +666,216 @@ def register_datapack(self, datapack, filterfunc=lambda r: True): # Override points def register_default_readers(self): """Registers factory default readers.""" - self.register_reader('replay.details', readers.DetailsReader(), lambda r: True) - self.register_reader('replay.initData', readers.InitDataReader(), lambda r: True) - self.register_reader('replay.tracker.events', readers.TrackerEventsReader(), lambda r: True) - self.register_reader('replay.message.events', readers.MessageEventsReader(), lambda r: True) - self.register_reader('replay.attributes.events', readers.AttributesEventsReader(), lambda r: True) - - self.register_reader('replay.game.events', readers.GameEventsReader_15405(), lambda r: 15405 <= r.base_build < 16561) - self.register_reader('replay.game.events', readers.GameEventsReader_16561(), lambda r: 16561 <= r.base_build < 17326) - self.register_reader('replay.game.events', readers.GameEventsReader_17326(), lambda r: 17326 <= r.base_build < 18574) - self.register_reader('replay.game.events', readers.GameEventsReader_18574(), lambda r: 18574 <= r.base_build < 19595) - self.register_reader('replay.game.events', readers.GameEventsReader_19595(), lambda r: 19595 <= r.base_build < 22612) - self.register_reader('replay.game.events', readers.GameEventsReader_22612(), lambda r: 22612 <= r.base_build < 23260) - self.register_reader('replay.game.events', readers.GameEventsReader_23260(), lambda r: 23260 <= r.base_build < 24247) - self.register_reader('replay.game.events', readers.GameEventsReader_24247(), lambda r: 24247 <= r.base_build < 26490) - self.register_reader('replay.game.events', readers.GameEventsReader_26490(), lambda r: 26490 <= r.base_build < 27950) - self.register_reader('replay.game.events', readers.GameEventsReader_27950(), lambda r: 27950 <= r.base_build < 34784) - self.register_reader('replay.game.events', readers.GameEventsReader_34784(), lambda r: 34784 <= r.base_build < 36442) - self.register_reader('replay.game.events', readers.GameEventsReader_36442(), lambda r: 36442 <= r.base_build < 38215) - self.register_reader('replay.game.events', readers.GameEventsReader_38215(), lambda r: 38215 <= r.base_build < 38749) - self.register_reader('replay.game.events', readers.GameEventsReader_38749(), lambda r: 38749 <= r.base_build < 38996) - self.register_reader('replay.game.events', readers.GameEventsReader_38996(), lambda r: 38996 <= r.base_build < 64469) - self.register_reader('replay.game.events', readers.GameEventsReader_64469(), lambda r: 64469 <= r.base_build < 65895) - self.register_reader('replay.game.events', readers.GameEventsReader_65895(), lambda r: 65895 <= r.base_build) - self.register_reader('replay.game.events', readers.GameEventsReader_HotSBeta(), lambda r: r.versions[1] == 2 and r.build < 24247) + self.register_reader("replay.details", readers.DetailsReader(), lambda r: True) + self.register_reader( + "replay.initData", readers.InitDataReader(), lambda r: True + ) + self.register_reader( + "replay.details.backup", readers.DetailsReader(), lambda r: True + ) + self.register_reader( + "replay.initData.backup", readers.InitDataReader(), lambda r: True + ) + self.register_reader( + "replay.tracker.events", readers.TrackerEventsReader(), lambda r: True + ) + self.register_reader( + "replay.message.events", readers.MessageEventsReader(), lambda r: True + ) + self.register_reader( + "replay.attributes.events", readers.AttributesEventsReader(), lambda r: True + ) + + self.register_reader( + "replay.game.events", + readers.GameEventsReader_15405(), + lambda r: 15405 <= r.base_build < 16561, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_16561(), + lambda r: 16561 <= r.base_build < 17326, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_17326(), + lambda r: 17326 <= r.base_build < 18574, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_18574(), + lambda r: 18574 <= r.base_build < 19595, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_19595(), + lambda r: 19595 <= r.base_build < 22612, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_22612(), + lambda r: 22612 <= r.base_build < 23260, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_23260(), + lambda r: 23260 <= r.base_build < 24247, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_24247(), + lambda r: 24247 <= r.base_build < 26490, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_26490(), + lambda r: 26490 <= r.base_build < 27950, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_27950(), + lambda r: 27950 <= r.base_build < 34784, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_34784(), + lambda r: 34784 <= r.base_build < 36442, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_36442(), + lambda r: 36442 <= r.base_build < 38215, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_38215(), + lambda r: 38215 <= r.base_build < 38749, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_38749(), + lambda r: 38749 <= r.base_build < 38996, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_38996(), + lambda r: 38996 <= r.base_build < 64469, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_64469(), + lambda r: 64469 <= r.base_build < 65895, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_65895(), + lambda r: 65895 <= r.base_build < 80669, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_80669(), + lambda r: 80669 <= r.base_build, + ) + self.register_reader( + "replay.game.events", + readers.GameEventsReader_HotSBeta(), + lambda r: r.versions[1] == 2 and r.build < 24247, + ) def register_default_datapacks(self): """Registers factory default datapacks.""" - self.register_datapack(datapacks['WoL']['16117'], lambda r: r.expansion == 'WoL' and 16117 <= r.build < 17326) - self.register_datapack(datapacks['WoL']['17326'], lambda r: r.expansion == 'WoL' and 17326 <= r.build < 18092) - self.register_datapack(datapacks['WoL']['18092'], lambda r: r.expansion == 'WoL' and 18092 <= r.build < 19458) - self.register_datapack(datapacks['WoL']['19458'], lambda r: r.expansion == 'WoL' and 19458 <= r.build < 22612) - self.register_datapack(datapacks['WoL']['22612'], lambda r: r.expansion == 'WoL' and 22612 <= r.build < 24944) - self.register_datapack(datapacks['WoL']['24944'], lambda r: r.expansion == 'WoL' and 24944 <= r.build) - self.register_datapack(datapacks['HotS']['base'], lambda r: r.expansion == 'HotS' and r.build < 23925) - self.register_datapack(datapacks['HotS']['23925'], lambda r: r.expansion == 'HotS' and 23925 <= r.build < 24247) - self.register_datapack(datapacks['HotS']['24247'], lambda r: r.expansion == 'HotS' and 24247 <= r.build < 24764) - self.register_datapack(datapacks['HotS']['24764'], lambda r: r.expansion == 'HotS' and 24764 <= r.build < 38215) - self.register_datapack(datapacks['HotS']['38215'], lambda r: r.expansion == 'HotS' and 38215 <= r.build) - self.register_datapack(datapacks['LotV']['base'], lambda r: r.expansion == 'LotV' and 34784 <= r.build) - self.register_datapack(datapacks['LotV']['44401'], lambda r: r.expansion == 'LotV' and 44401 <= r.build < 47185) - self.register_datapack(datapacks['LotV']['47185'], lambda r: r.expansion == 'LotV' and 47185 <= r.build < 48258) - self.register_datapack(datapacks['LotV']['48258'], lambda r: r.expansion == 'LotV' and 48258 <= r.build < 53644) - self.register_datapack(datapacks['LotV']['53644'], lambda r: r.expansion == 'LotV' and 53644 <= r.build < 54724) - self.register_datapack(datapacks['LotV']['54724'], lambda r: r.expansion == 'LotV' and 54724 <= r.build < 59587) - self.register_datapack(datapacks['LotV']['59587'], lambda r: r.expansion == 'LotV' and 59587 <= r.build < 70154) - self.register_datapack(datapacks['LotV']['70154'], lambda r: r.expansion == 'LotV' and 70154 <= r.build) - + self.register_datapack( + datapacks["WoL"]["16117"], + lambda r: r.expansion == "WoL" and 16117 <= r.build < 17326, + ) + self.register_datapack( + datapacks["WoL"]["17326"], + lambda r: r.expansion == "WoL" and 17326 <= r.build < 18092, + ) + self.register_datapack( + datapacks["WoL"]["18092"], + lambda r: r.expansion == "WoL" and 18092 <= r.build < 19458, + ) + self.register_datapack( + datapacks["WoL"]["19458"], + lambda r: r.expansion == "WoL" and 19458 <= r.build < 22612, + ) + self.register_datapack( + datapacks["WoL"]["22612"], + lambda r: r.expansion == "WoL" and 22612 <= r.build < 24944, + ) + self.register_datapack( + datapacks["WoL"]["24944"], + lambda r: r.expansion == "WoL" and 24944 <= r.build, + ) + self.register_datapack( + datapacks["HotS"]["base"], + lambda r: r.expansion == "HotS" and r.build < 23925, + ) + self.register_datapack( + datapacks["HotS"]["23925"], + lambda r: r.expansion == "HotS" and 23925 <= r.build < 24247, + ) + self.register_datapack( + datapacks["HotS"]["24247"], + lambda r: r.expansion == "HotS" and 24247 <= r.build < 24764, + ) + self.register_datapack( + datapacks["HotS"]["24764"], + lambda r: r.expansion == "HotS" and 24764 <= r.build < 38215, + ) + self.register_datapack( + datapacks["HotS"]["38215"], + lambda r: r.expansion == "HotS" and 38215 <= r.build, + ) + self.register_datapack( + datapacks["LotV"]["base"], + lambda r: r.expansion == "LotV" and 34784 <= r.build, + ) + self.register_datapack( + datapacks["LotV"]["44401"], + lambda r: r.expansion == "LotV" and 44401 <= r.build < 47185, + ) + self.register_datapack( + datapacks["LotV"]["47185"], + lambda r: r.expansion == "LotV" and 47185 <= r.build < 48258, + ) + self.register_datapack( + datapacks["LotV"]["48258"], + lambda r: r.expansion == "LotV" and 48258 <= r.build < 53644, + ) + self.register_datapack( + datapacks["LotV"]["53644"], + lambda r: r.expansion == "LotV" and 53644 <= r.build < 54724, + ) + self.register_datapack( + datapacks["LotV"]["54724"], + lambda r: r.expansion == "LotV" and 54724 <= r.build < 59587, + ) + self.register_datapack( + datapacks["LotV"]["59587"], + lambda r: r.expansion == "LotV" and 59587 <= r.build < 70154, + ) + self.register_datapack( + datapacks["LotV"]["70154"], + lambda r: r.expansion == "LotV" and 70154 <= r.build < 76114, + ) + self.register_datapack( + datapacks["LotV"]["76114"], + lambda r: r.expansion == "LotV" and 76114 <= r.build < 77379, + ) + self.register_datapack( + datapacks["LotV"]["77379"], + lambda r: r.expansion == "LotV" and 77379 <= r.build < 80949, + ) + self.register_datapack( + datapacks["LotV"]["80949"], + lambda r: r.expansion == "LotV" and 80949 <= r.build < 89634, + ) + self.register_datapack( + datapacks["LotV"]["89720"], + lambda r: r.expansion == "LotV" and 89634 <= r.build, + ) # Internal Methods def _get_reader(self, data_file): @@ -620,7 +883,9 @@ def _get_reader(self, data_file): if callback(self): return reader else: - raise ValueError("Valid {0} reader could not found for build {1}".format(data_file, self.build)) + raise ValueError( + f"Valid {data_file} reader could not found for build {self.build}" + ) def _get_datapack(self): for callback, datapack in self.registered_datapacks: @@ -633,33 +898,34 @@ def _read_data(self, data_file, reader): data = utils.extract_data_file(data_file, self.archive) if data: self.raw_data[data_file] = reader(data, self) - elif self.opt['debug'] and data_file not in ['replay.message.events', 'replay.tracker.events']: - raise ValueError("{0} not found in archive".format(data_file)) + elif self.opt["debug"] and data_file not in [ + "replay.message.events", + "replay.tracker.events", + ]: + raise ValueError(f"{data_file} not found in archive") def __getstate__(self): state = self.__dict__.copy() - del state['registered_readers'] - del state['registered_datapacks'] + del state["registered_readers"] + del state["registered_datapacks"] return state class Map(Resource): - url_template = 'http://{0}.depot.battle.net:1119/{1}.s2ma' - 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 @@ -674,76 +940,83 @@ def __init__(self, map_file, filename=None, region=None, map_hash=None, **option self.archive = mpyq.MPQArchive(map_file) #: A byte string representing the minimap in tga format. - self.minimap = self.archive.read_file('Minimap.tga') + self.minimap = self.archive.read_file("Minimap.tga") # This will only populate the fields for maps with enUS localizations. # Clearly this isn't a great solution but we can't be throwing exceptions # 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') + game_strings_file = self.archive.read_file( + r"enUS.SC2Data\LocalizedData\GameStrings.txt" + ) if game_strings_file: - for line in game_strings_file.decode('utf8').split('\r\n'): + for line in game_strings_file.decode("utf8").split("\r\n"): if len(line) == 0: continue - key, value = line.split('=', 1) - if key == 'DocInfo/Name': + key, value = line.split("=", 1) + if key == "DocInfo/Name": self.name = value - elif key == 'DocInfo/Author': + elif key == "DocInfo/Author": self.author = value - elif key == 'DocInfo/DescLong': + elif key == "DocInfo/DescLong": self.description = value - elif key == 'DocInfo/Website': + elif key == "DocInfo/Website": self.website = value #: A reference to the map's :class:`~sc2reader.objects.MapInfo` object self.map_info = None - map_info_file = self.archive.read_file('MapInfo') + map_info_file = self.archive.read_file("MapInfo") if map_info_file: self.map_info = MapInfo(map_info_file) - doc_info_file = self.archive.read_file('DocumentInfo') + doc_info_file = self.archive.read_file("DocumentInfo") if doc_info_file: - doc_info = ElementTree.fromstring(doc_info_file.decode('utf8')) + doc_info = ElementTree.fromstring(doc_info_file.decode("utf8")) - icon_path_node = doc_info.find('Icon/Value') + icon_path_node = doc_info.find("Icon/Value") #: (Optional) The path to the icon for the map, relative to the archive root self.icon_path = icon_path_node.text if icon_path_node is not None else None #: (Optional) The icon image for the map in tga format - self.icon = self.archive.read_file(self.icon_path) if self.icon_path is not None else None + self.icon = ( + self.archive.read_file(self.icon_path) + if self.icon_path is not None + else None + ) #: A list of module names this map depends on self.dependencies = list() - for dependency_node in doc_info.findall('Dependencies/Value'): + for dependency_node in doc_info.findall("Dependencies/Value"): self.dependencies.append(dependency_node.text) @classmethod def get_url(cls, region, map_hash): """Builds a download URL for the map from its components.""" if region and map_hash: - # it seems like sea maps are stored on us depots. - region = 'us' if region == 'sea' else region - return cls.url_template.format(region, map_hash) + return utils.get_resource_url(region, hash, "s2ma") else: return None class Localization(Resource, dict): - def __init__(self, s2ml_file, **options): Resource.__init__(self, s2ml_file, **options) xml = ElementTree.parse(s2ml_file) - for entry in xml.findall('e'): - self[int(entry.attrib['id'])] = entry.text + for entry in xml.findall("e"): + self[int(entry.attrib["id"])] = entry.text class GameSummary(Resource): - - url_template = 'http://{0}.depot.battle.net:1119/{1}.s2gs' + """ + Data extracted from the post-game Game Summary with units killed, + etc. This code does not work as reliably for Co-op games, which + have a completely different format for the report, which means + that the data is not necessarily in the places we expect. + """ #: Game speed - game_speed = str() + game_speed = "" #: Game length (real-time) real_length = int() @@ -769,8 +1042,8 @@ class GameSummary(Resource): #: Map localization urls localization_urls = dict() - def __init__(self, summary_file, filename=None, lang='enUS', **options): - super(GameSummary, self).__init__(summary_file, filename, lang=lang, **options) + def __init__(self, summary_file, filename=None, lang="enUS", **options): + super().__init__(summary_file, filename, lang=lang, **options) #: A dict of team# -> teams self.team = dict() @@ -797,8 +1070,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:])) @@ -810,32 +1083,42 @@ def __init__(self, summary_file, filename=None, lang='enUS', **options): self.parts.append(buffer.read_struct()) self.load_translations() - dependencies = [sheet[1] for sheet in self.lang_sheets['enUS']] - if 'Swarm (Mod)' in dependencies: - self.expansion = 'HotS' - elif 'Liberty (Mod)' in dependencies: - self.expansion = 'WoL' + dependencies = [sheet[1] for sheet in self.lang_sheets["enUS"]] + if "Swarm (Mod)" in dependencies: + self.expansion = "HotS" + elif "Liberty (Mod)" in dependencies: + self.expansion = "WoL" else: - self.expansion = '' + self.expansion = "" self.end_time = datetime.utcfromtimestamp(self.parts[0][8]) - self.game_speed = LOBBY_PROPERTIES[0xBB8][1][self.parts[0][0][1].decode('utf8')] + self.game_speed = LOBBY_PROPERTIES[0xBB8][1][self.parts[0][0][1].decode("utf8")] self.game_length = utils.Length(seconds=self.parts[0][7]) - self.real_length = utils.Length(seconds=int(self.parts[0][7]/GAME_SPEED_FACTOR[self.expansion][self.game_speed])) - self.start_time = datetime.utcfromtimestamp(self.parts[0][8] - self.real_length.seconds) + self.real_length = utils.Length( + seconds=int( + self.parts[0][7] / GAME_SPEED_FACTOR[self.expansion][self.game_speed] + ) + ) + self.start_time = datetime.utcfromtimestamp( + self.parts[0][8] - self.real_length.seconds + ) self.load_map_info() self.load_settings() self.load_player_stats() self.load_players() - self.game_type = self.settings['Teams'].replace(" ", "") + # the game type is probably co-op because it uses a different + # game summary format than other games + self.game_type = self.settings.get("Teams", "Unknown").replace(" ", "") self.real_type = utils.get_real_type(self.teams) # The s2gs file also keeps reference to a series of s2mv files # Some of these appear to be encoded bytes and others appear to be # the preview images that authors may bundle with their maps. - self.s2mv_urls = [str(utils.DepotFile(file_hash)) for file_hash in self.parts[0][6][7]] + self.s2mv_urls = [ + str(utils.DepotFile(file_hash)) for file_hash in self.parts[0][6][7] + ] def load_translations(self): # This section of the file seems to map numerical ids to their @@ -866,8 +1149,8 @@ def load_translations(self): self.id_map[uid] = (sheet, entry) for value in item[1]: - sheet = value[1][0][1] - entry = value[1][0][2] + sheet = value[1][0][1] if value[1][0] else None + entry = value[1][0][2] if value[1][0] else None self.id_map[(uid, value[0])] = (sheet, entry) # Each localization is a pairing of a language id, e.g. enUS @@ -876,11 +1159,11 @@ def load_translations(self): # # Sometimes these byte strings are all NULLed out and need to be ignored. for localization in self.parts[0][6][8]: - language = localization[0].decode('utf8') + language = localization[0].decode("utf8") files = list() for file_hash in localization[1]: - if file_hash[:4].decode('utf8') != '\x00\x00\x00\x00': + if file_hash[:4].decode("utf8") != "\x00\x00\x00\x00": files.append(utils.DepotFile(file_hash)) self.localization_urls[language] = files @@ -896,7 +1179,7 @@ def load_translations(self): self.lang_sheets = dict() self.translations = dict() for lang, files in self.localization_urls.items(): - if lang != self.opt['lang']: + if lang != self.opt["lang"]: continue sheets = list() @@ -905,11 +1188,13 @@ def load_translations(self): translation = dict() for uid, (sheet, item) in self.id_map.items(): - if sheet < len(sheets) and item in sheets[sheet]: + if sheet is not None and sheet < len(sheets) and item in sheets[sheet]: translation[uid] = sheets[sheet][item] - elif self.opt['debug']: + elif self.opt["debug"]: msg = "No {0} translation for sheet {1}, item {2}" - raise SC2ReaderLocalizationError(msg.format(self.opt['lang'], sheet, item)) + raise SC2ReaderLocalizationError( + msg.format(self.opt["lang"], sheet, item) + ) else: translation[uid] = "Unknown" @@ -917,17 +1202,21 @@ def load_translations(self): self.translations[lang] = translation def load_map_info(self): - map_strings = self.lang_sheets[self.opt['lang']][-1] + map_strings = self.lang_sheets[self.opt["lang"]][-1] self.map_name = map_strings[1] self.map_description = map_strings[2] self.map_tileset = map_strings[3] def load_settings(self): - Property = namedtuple('Property', ['id', 'values', 'requirements', 'defaults', 'is_lobby']) + Property = namedtuple( + "Property", ["id", "values", "requirements", "defaults", "is_lobby"] + ) properties = dict() for p in self.parts[0][5]: - properties[p[0][1]] = Property(p[0][1], p[1], p[3], p[8], isinstance(p[8], dict)) + properties[p[0][1]] = Property( + p[0][1], p[1], p[3], p[8], isinstance(p[8], dict) + ) settings = dict() for setting in self.parts[0][6][6]: @@ -957,7 +1246,7 @@ def use_property(prop, player=None): # Lobby properties can require on player properties. # How does this work? I assume that one player satisfying the - # property requirments is sufficient + # property requirements is sufficient if requirement.is_lobby: values = [setting] else: @@ -965,7 +1254,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: @@ -976,7 +1265,7 @@ def use_property(prop, player=None): activated[(prop.id, player)] = use return use - translation = self.translations[self.opt['lang']] + translation = self.translations[self.opt["lang"]] for uid, prop in properties.items(): name = translation.get(uid, "Unknown") if prop.is_lobby: @@ -990,9 +1279,9 @@ def use_property(prop, player=None): self.player_settings[index][name] = translation[(uid, value)] def load_player_stats(self): - translation = self.translations[self.opt['lang']] + 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 @@ -1011,7 +1300,12 @@ def load_player_stats(self): if not value: continue - if stat_name in ('Army Value', 'Resource Collection Rate', 'Upgrade Spending', 'Workers Active'): + if stat_name in ( + "Army Value", + "Resource Collection Rate", + "Upgrade Spending", + "Workers Active", + ): # Each point entry for the graph is laid out as follows # # {0:Value, 1:0, 2:Time} @@ -1030,15 +1324,17 @@ def load_player_stats(self): # up to the first 64 successful actions in the game. for pindex, commands in enumerate(item[1]): for command in commands: - self.build_orders[pindex].append(BuildEntry( - supply=command[0], - total_supply=command[1] & 0xff, - time=int((command[2] >> 8) / 16), - order=stat_name, - build_index=command[1] >> 16 - )) + self.build_orders[pindex].append( + BuildEntry( + supply=command[0], + total_supply=command[1] & 0xFF, + time=int((command[2] >> 8) / 16), + order=stat_name, + build_index=command[1] >> 16, + ) + ) elif stat_id != 83886080: # We know this one is always bad. - self.logger.warn("Untranslatable key = {0}".format(stat_id)) + self.logger.warning(f"Untranslatable key = {stat_id}") # Once we've compiled all the build commands we need to make # sure they are properly sorted for presentation. @@ -1062,7 +1358,7 @@ def load_players(self): player.unknown2 = struct[0][1][1] # Either a referee or a spectator, nothing else to do - if settings.get('Participant Role', '') != 'Participant': + if settings.get("Participant Role", "") != "Participant": self.observers.append(player) continue @@ -1072,7 +1368,7 @@ def load_players(self): if player.is_winner: self.winners.append(player.pid) - team_id = int(settings['Team'].split(' ')[1]) + team_id = int(settings["Team"].split(" ")[1]) if team_id not in self.team: self.team[team_id] = Team(team_id) self.teams.append(self.team[team_id]) @@ -1081,49 +1377,51 @@ def load_players(self): self.team[team_id].players.append(player) # We can just copy these settings right over - player.color = utils.Color(name=settings.get('Color', None)) - player.pick_race = settings.get('Race', None) - player.handicap = settings.get('Handicap', None) + player.color = utils.Color(name=settings.get("Color", None)) + player.pick_race = settings.get("Race", None) + player.handicap = settings.get("Handicap", None) # Overview Tab - player.resource_score = stats.get('Resources', None) - player.structure_score = stats.get('Structures', None) - player.unit_score = stats.get('Units', None) - player.overview_score = stats.get('Overview', None) + player.resource_score = stats.get("Resources", None) + player.structure_score = stats.get("Structures", None) + player.unit_score = stats.get("Units", None) + player.overview_score = stats.get("Overview", None) # Units Tab - player.units_killed = stats.get('Killed Unit Count', None) - player.structures_built = stats.get('Structures Built', None) - player.units_trained = stats.get('Units Trained', None) - player.structures_razed = stats.get('Structures Razed Count', None) + player.units_killed = stats.get("Killed Unit Count", None) + player.structures_built = stats.get("Structures Built", None) + player.units_trained = stats.get("Units Trained", None) + player.structures_razed = stats.get("Structures Razed Count", None) # Graphs Tab # Keep income_graph for backwards compatibility - player.army_graph = stats.get('Army Value') - player.resource_collection_graph = stats.get('Resource Collection Rate', None) + player.army_graph = stats.get("Army Value") + player.resource_collection_graph = stats.get( + "Resource Collection Rate", None + ) player.income_graph = player.resource_collection_graph # HotS Stats - player.upgrade_spending_graph = stats.get('Upgrade Spending', None) - player.workers_active_graph = stats.get('Workers Active', None) - player.enemies_destroyed = stats.get('Enemies Destroyed:', None) - player.time_supply_capped = stats.get('Time Supply Capped', None) - player.idle_production_time = stats.get('Idle Production Time', None) - player.resources_spent = stats.get('Resources Spent:', None) - player.apm = stats.get('APM', None) + player.upgrade_spending_graph = stats.get("Upgrade Spending", None) + player.workers_active_graph = stats.get("Workers Active", None) + player.enemies_destroyed = stats.get("Enemies Destroyed:", None) + player.time_supply_capped = stats.get("Time Supply Capped", None) + player.idle_production_time = stats.get("Idle Production Time", None) + player.resources_spent = stats.get("Resources Spent:", None) + player.apm = stats.get("APM", None) # Economic Breakdown Tab if isinstance(player.income_graph, Graph): values = player.income_graph.values - player.resource_collection_rate = int(sum(values)/len(values)) + player.resource_collection_rate = int(sum(values) / len(values)) else: # In old s2gs files the field with this name was actually a number not a graph player.resource_collection_rate = player.income_graph player.resource_collection_graph = None player.income_graph = None - player.avg_unspent_resources = stats.get('Average Unspent Resources', None) - player.workers_created = stats.get('Workers Created', None) + player.avg_unspent_resources = stats.get("Average Unspent Resources", None) + player.workers_created = stats.get("Workers Created", None) # Build Orders Tab player.build_order = self.build_orders.get(index, None) @@ -1132,30 +1430,32 @@ def load_players(self): self.player[player.pid] = player def __str__(self): - return "{0} - {1} {2}".format(self.start_time, self.game_length, 'v'.join(''.join(p.play_race[0] for p in team.players) for team in self.teams)) + return "{} - {} {}".format( + self.start_time, + self.game_length, + "v".join( + "".join(p.play_race[0] for p in team.players) for team in self.teams + ), + ) class MapHeader(Resource): """**Experimental**""" - base_url_template = 'http://{0}.depot.battle.net:1119/{1}.{2}' - url_template = 'http://{0}.depot.battle.net:1119/{1}.s2mh' - image_url_template = 'http://{0}.depot.battle.net:1119/{1}.s2mv' - #: 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() @@ -1164,27 +1464,33 @@ 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 self.name = self.data[0][1] # Blizzard - self.blizzard = (self.data[0][11] == 'BLIZ') + self.blizzard = self.data[0][11] == "BLIZ" # Parse image hash parsed_hash = utils.parse_hash(self.data[0][1]) - self.image_hash = parsed_hash['hash'] - self.image_url = self.image_url_template.format(parsed_hash['server'], parsed_hash['hash']) + self.image_hash = parsed_hash["hash"] + self.image_url = utils.get_resource_url( + parsed_hash["server"], parsed_hash["hash"], "s2mv" + ) # Parse map hash parsed_hash = utils.parse_hash(self.data[0][2]) - self.map_hash = parsed_hash['hash'] - self.map_url = self.base_url_template.format(parsed_hash['server'], parsed_hash['hash'], parsed_hash['type']) + self.map_hash = parsed_hash["hash"] + self.map_url = utils.get_resource_url( + parsed_hash["server"], parsed_hash["hash"], parsed_hash["type"] + ) # Parse localization hashes l18n_struct = self.data[0][4][8] - for l in l18n_struct: - parsed_hash = utils.parse_hash(l[1][0]) - self.localization_urls[l[0]] = self.base_url_template.format(parsed_hash['server'], parsed_hash['hash'], parsed_hash['type']) + for h in l18n_struct: + parsed_hash = utils.parse_hash(h[1][0]) + self.localization_urls[h[0]] = utils.get_resource_url( + parsed_hash["server"], parsed_hash["hash"], parsed_hash["type"] + ) 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 da0160e9..6e2ca4d1 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 @@ -39,7 +37,7 @@ import sc2reader try: - raw_input # Python 2 + raw_input # Python 2 except NameError: raw_input = input # Python 3 @@ -49,51 +47,68 @@ def main(): global decisions - parser = argparse.ArgumentParser(description="Recursively parses replay files, inteded for debugging parse issues.") - parser.add_argument('folders', metavar='folder', type=str, nargs='+', help="Path to a folder") + parser = argparse.ArgumentParser( + description="Recursively parses replay files, intended for debugging parse issues." + ) + parser.add_argument( + "folders", metavar="folder", type=str, nargs="+", help="Path to a folder" + ) args = parser.parse_args() scripts_dir = os.path.dirname(os.path.abspath(__file__)) - data_path = os.path.normpath(os.path.join(scripts_dir, '..', 'data', 'attributes.json')) + data_path = os.path.normpath( + os.path.join(scripts_dir, "..", "data", "attributes.json") + ) 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.')) + attributes = data.get("attributes", attributes) + decisions = pickle.loads(data.get("decisions", "(dp0\n.")) for folder in args.folders: - for path in sc2reader.utils.get_files(folder, extension='s2gs'): + for path in sc2reader.utils.get_files(folder, extension="s2gs"): try: summary = sc2reader.load_game_summary(path) for prop in summary.parts[0][5]: group_key = prop[0][1] - group_name = summary.translations['enUS'][group_key] + group_name = summary.translations["enUS"][group_key] attribute_values = dict() if str(group_key) in attributes: attribute_name, attribute_values = attributes[str(group_key)] if attribute_name != group_name: - group_name = get_choice(group_key, attribute_name, group_name) + group_name = get_choice( + group_key, attribute_name, group_name + ) for value in prop[1]: - value_key = value[0].strip("\x00 ").replace(' v ', 'v') - value_name = summary.lang_sheets['enUS'][value[1][0][1]][value[1][0][2]] + value_key = value[0].strip("\x00 ").replace(" v ", "v") + value_name = summary.lang_sheets["enUS"][value[1][0][1]][ + value[1][0][2] + ] if str(value_key) in attribute_values: attribute_value_name = attribute_values[str(value_key)] if value_name != attribute_value_name: - value_name = get_choice((group_key, value_key), attribute_value_name, value_name) + value_name = get_choice( + (group_key, value_key), + attribute_value_name, + value_name, + ) attribute_values[str(value_key)] = value_name - attributes["{0:0>4}".format(group_key)] = (group_name, attribute_values) + attributes[f"{group_key:0>4}"] = ( + group_name, + attribute_values, + ) except Exception as e: if isinstance(e, KeyboardInterrupt): raise else: traceback.print_exc() - with open(data_path, 'w') as data_file: + with open(data_path, "w") as data_file: data = dict(attributes=attributes, decisions=pickle.dumps(decisions)) json.dump(data, data_file, indent=2, sort_keys=True) @@ -104,20 +119,20 @@ 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("Naming conflict on {0}: {1} != {2}".format(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(" (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)) + if answer not in ("o", "n"): + print(f"Invalid choice `{answer}`") else: break - decisions[key] = {'o': old_value, 'n': new_value}[answer] + decisions[key] = {"o": old_value, "n": new_value}[answer] print("") return decisions[key] -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/sc2reader/scripts/sc2json.py b/sc2reader/scripts/sc2json.py index bd42178f..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 @@ -8,16 +6,41 @@ def main(): import argparse + parser = argparse.ArgumentParser(description="Prints replay data to a json string.") - parser.add_argument('--indent', '-i', type=int, default=None, help="The per-line indent to use when printing a human readable json string") - parser.add_argument('--encoding', '-e', type=str, default='UTF-8', help="The character encoding use..") - parser.add_argument('path', metavar='path', type=str, nargs=1, help="Path to the replay to serialize.") + parser.add_argument( + "--indent", + "-i", + type=int, + default=None, + help="The per-line indent to use when printing a human readable json string", + ) + parser.add_argument( + "--encoding", + "-e", + type=str, + default="UTF-8", + help="The character encoding use..", + ) + parser.add_argument( + "path", + metavar="path", + type=str, + nargs=1, + help="Path to the replay to serialize.", + ) args = parser.parse_args() factory = sc2reader.factories.SC2Factory() - factory.register_plugin("Replay", toJSON(encoding=args.encoding, indent=args.indent)) + try: + factory.register_plugin( + "Replay", toJSON(encoding=args.encoding, indent=args.indent) + ) # legacy Python + except TypeError: + factory.register_plugin("Replay", toJSON(indent=args.indent)) replay_json = factory.load_replay(args.path[0]) print(replay_json) -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/sc2reader/scripts/sc2parse.py b/sc2reader/scripts/sc2parse.py index 571b0c05..4b517908 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,26 +15,37 @@ 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 import traceback -sc2reader.log_utils.log_to_console('INFO') +sc2reader.log_utils.log_to_console("INFO") def main(): - parser = argparse.ArgumentParser(description="Recursively parses replay files, inteded for debugging parse issues.") - parser.add_argument('--one_each', help="Attempt to parse only one Ladder replay for each release_string", action="store_true") - parser.add_argument('--ladder_only', help="If a non-ladder game fails, ignore it", action="store_true") - parser.add_argument('folders', metavar='folder', type=str, nargs='+', help="Path to a folder") + parser = argparse.ArgumentParser( + description="Recursively parses replay files, intended for debugging parse issues." + ) + parser.add_argument( + "--one_each", + help="Attempt to parse only one Ladder replay for each release_string", + action="store_true", + ) + parser.add_argument( + "--ladder_only", + help="If a non-ladder game fails, ignore it", + action="store_true", + ) + parser.add_argument( + "folders", metavar="folder", type=str, nargs="+", help="Path to a folder" + ) args = parser.parse_args() releases_parsed = set() for folder in args.folders: - print("dealing with {0}".format(folder)) - for path in sc2reader.utils.get_files(folder, extension='SC2Replay'): + 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 already_did = rs in releases_parsed @@ -45,19 +55,47 @@ 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([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([event.player.pid for event in replay.events if 'CommandEvent' in event.name]) + 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 = { + 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(pids=human_pids, event_pids=event_pids)) - print(' with {path}: {build} - {real_type} on {map_name} - Played {start_time}'.format(path=path, **replay.__dict__)) + print( + f"Event Pid problem! pids={human_pids} but event pids={event_pids}" + ) + print( + " with {path}: {build} - {real_type} on {map_name} - Played {start_time}".format( + path=path, **replay.__dict__ + ) + ) elif player_pids != ability_pids: - print('Ability Pid problem! pids={pids} but event pids={event_pids}'.format(pids=player_pids, event_pids=ability_pids)) - print(' with {path}: {build} - {real_type} on {map_name} - Played {start_time}'.format(path=path, **replay.__dict__)) + print( + f"Ability Pid problem! pids={player_pids} but event pids={ability_pids}" + ) + print( + " with {path}: {build} - {real_type} on {map_name} - Played {start_time}".format( + path=path, **replay.__dict__ + ) + ) else: - print('No problems with {path}: {build} - {real_type} on {map_name} - Played {start_time}'.format(path=path, **replay.__dict__)) - print('Units were: {units}'.format(units=set([obj.name for obj in replay.objects.values()]))) + print( + "No problems with {path}: {build} - {real_type} on {map_name} - Played {start_time}".format( + path=path, **replay.__dict__ + ) + ) + print( + f"Units were: {({obj.name for obj in replay.objects.values()})}" + ) except sc2reader.exceptions.ReadError as e: if args.ladder_only and not e.replay.is_ladder: @@ -65,35 +103,47 @@ def main(): print("") print(path) - print('{build} - {real_type} on {map_name} - Played {start_time}'.format(**e.replay.__dict__)) - print('[ERROR] {}', e) + print( + "{build} - {real_type} on {map_name} - Played {start_time}".format( + **e.replay.__dict__ + ) + ) + print("[ERROR] {}", e) for event in e.game_events[-5:]: - print('{0}'.format(event)) - print(e.buffer.read_range(e.location, e.location + 50).encode('hex')) + print(f"{event}") + print(e.buffer.read_range(e.location, e.location + 50).encode("hex")) print except Exception as e: print("") print(path) try: replay = sc2reader.load_replay(path, debug=True, load_level=2) - print('{build} - {real_type} on {map_name} - Played {start_time}'.format(**replay.__dict__)) - print('[ERROR] {0}'.format(e)) + print( + "{build} - {real_type} on {map_name} - Played {start_time}".format( + **replay.__dict__ + ) + ) + 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: replay = sc2reader.load_replay(path, debug=True, load_level=0) - print('Total failure parsing {release_string}'.format(**replay.__dict__)) - print('[ERROR] {0}'.format(e)) - print('[ERROR] {0}'.format(e2)) + print( + "Total failure parsing {release_string}".format( + **replay.__dict__ + ) + ) + print(f"[ERROR] {e}") + print(f"[ERROR] {e2}") traceback.print_exc() print -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/sc2reader/scripts/sc2printer.py b/sc2reader/scripts/sc2printer.py index c780d16e..76241a05 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 @@ -11,50 +9,52 @@ def printReplay(filepath, arguments): - """ Prints summary information about SC2 replay file """ + """Prints summary information about SC2 replay file""" try: 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.number, team.players[0].name, team.players[0].pick_race[0])) + print( + f" Team {team.number}\t{team.players[0].name} ({team.players[0].pick_race[0]})" + ) for player in team.players[1:]: - print(" \t{0} ({1})".format(player.name, player.pick_race[0])) + print(f" \t{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: raise return prev = e.game_events[-1] - print("\nVersion {0} replay:\n\t{1}".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("\t\t" + prev.bytes.encode('hex')) + print(f"\nVersion {e.replay.release_string} replay:\n\t{e.replay.filepath}") + 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("\t\t" + e.buffer.read_range(e.location, e.location + 30).encode("hex")) + 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 @@ -63,71 +63,113 @@ 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(msg.format(order.time / 60, order.time % 60, order.order, order.supply, order.total_supply)) + print( + msg.format( + order.time / 60, + order.time % 60, + order.order, + order.supply, + order.total_supply, + ) + ) print("") def main(): parser = argparse.ArgumentParser( description="""Prints basic information from Starcraft II replay and - game summary files or directories.""") - parser.add_argument('--recursive', action="store_true", default=True, - help="Recursively read through directories of Starcraft II files [default on]") - - required = parser.add_argument_group('Required Arguments') - required.add_argument('paths', metavar='filename', type=str, nargs='+', - help="Paths to one or more Starcraft II files or directories") - - shared_args = parser.add_argument_group('Shared Arguments') - shared_args.add_argument('--date', action="store_true", default=True, - help="print game date [default on]") - shared_args.add_argument('--length', action="store_true", default=False, - help="print game duration mm:ss in game time (not real time) [default off]") - shared_args.add_argument('--map', action="store_true", default=True, - help="print map name [default on]") - shared_args.add_argument('--teams', action="store_true", default=True, - help="print teams, their players, and the race matchup [default on]") - shared_args.add_argument('--observers', action="store_true", default=True, - help="print observers") - - replay_args = parser.add_argument_group('Replay Options') - replay_args.add_argument('--messages', action="store_true", default=False, - help="print(in-game player chat messages [default off]") - replay_args.add_argument('--version', action="store_true", default=True, - help="print(the release string as seen in game [default on]") - - s2gs_args = parser.add_argument_group('Game Summary Options') - s2gs_args.add_argument('--builds', action="store_true", default=False, - help="print(player build orders (first 64 items) [default off]") + game summary files or directories.""" + ) + parser.add_argument( + "--recursive", + action="store_true", + default=True, + help="Recursively read through directories of Starcraft II files [default on]", + ) + + required = parser.add_argument_group("Required Arguments") + required.add_argument( + "paths", + metavar="filename", + type=str, + nargs="+", + help="Paths to one or more Starcraft II files or directories", + ) + + shared_args = parser.add_argument_group("Shared Arguments") + shared_args.add_argument( + "--date", action="store_true", default=True, help="print game date [default on]" + ) + shared_args.add_argument( + "--length", + action="store_true", + default=False, + help="print game duration mm:ss in game time (not real time) [default off]", + ) + shared_args.add_argument( + "--map", action="store_true", default=True, help="print map name [default on]" + ) + shared_args.add_argument( + "--teams", + action="store_true", + default=True, + help="print teams, their players, and the race matchup [default on]", + ) + shared_args.add_argument( + "--observers", action="store_true", default=True, help="print observers" + ) + + replay_args = parser.add_argument_group("Replay Options") + replay_args.add_argument( + "--messages", + action="store_true", + default=False, + help="print(in-game player chat messages [default off]", + ) + replay_args.add_argument( + "--version", + action="store_true", + default=True, + help="print(the release string as seen in game [default on]", + ) + + s2gs_args = parser.add_argument_group("Game Summary Options") + s2gs_args.add_argument( + "--builds", + action="store_true", + default=False, + help="print(player build orders (first 64 items) [default off]", + ) arguments = parser.parse_args() for path in arguments.paths: depth = -1 if arguments.recursive else 0 for filepath in utils.get_files(path, depth=depth): name, ext = os.path.splitext(filepath) - if ext.lower() == '.sc2replay': - print("\n--------------------------------------\n{0}\n".format(filepath)) + if ext.lower() == ".sc2replay": + print(f"\n--------------------------------------\n{filepath}\n") printReplay(filepath, arguments) - elif ext.lower() == '.s2gs': - print("\n--------------------------------------\n{0}\n".format(filepath)) + elif ext.lower() == ".s2gs": + print(f"\n--------------------------------------\n{filepath}\n") printGameSummary(filepath, arguments) -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/sc2reader/scripts/sc2replayer.py b/sc2reader/scripts/sc2replayer.py index 7a72c7ed..c3c8ee17 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) @@ -30,16 +28,24 @@ def getch(): except ImportError as e: try: - # Opps, we might be on windows, try this one + # Oops, we might be on windows, try this one from msvcrt import getch except ImportError as e: # We can't make getch happen, just dump events to the screen - getch = lambda: True + def getch(): + return True import argparse import sc2reader -from sc2reader.events import * +from sc2reader.events import ( + CameraEvent, + CommandEvent, + ControlGroupEvent, + GameStartEvent, + PlayerLeaveEvent, + SelectionEvent, +) def main(): @@ -49,22 +55,42 @@ def main(): key to advance through the events in sequential order.""" ) - parser.add_argument('FILE', type=str, help="The file you would like to replay") - parser.add_argument('--player', default=0, type=int, help="The number of the player you would like to watch. Defaults to 0 (All).") - parser.add_argument('--bytes', default=False, action="store_true", help="Displays the byte code of the event in hex after each event.") - parser.add_argument('--hotkeys', default=False, action="store_true", help="Shows the hotkey events in the event stream.") - parser.add_argument('--cameras', default=False, action="store_true", help="Shows the camera events in the event stream.") + parser.add_argument("FILE", type=str, help="The file you would like to replay") + parser.add_argument( + "--player", + default=0, + type=int, + help="The number of the player you would like to watch. Defaults to 0 (All).", + ) + parser.add_argument( + "--bytes", + default=False, + action="store_true", + help="Displays the byte code of the event in hex after each event.", + ) + parser.add_argument( + "--hotkeys", + default=False, + action="store_true", + help="Shows the hotkey events in the event stream.", + ) + parser.add_argument( + "--cameras", + default=False, + action="store_true", + help="Shows the camera events in the event stream.", + ) args = parser.parse_args() for filename in sc2reader.utils.get_files(args.FILE): replay = sc2reader.load_replay(filename, debug=True) - print("Release {0}".format(replay.release_string)) - print("{0} on {1} at {2}".format(replay.type, replay.map_name, replay.start_time)) + print(f"Release {replay.release_string}") + print(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' @@ -76,18 +102,19 @@ def main(): # Allow specification of events to `show` # Loop through the events for event in events: - - if isinstance(event, CommandEvent) or \ - isinstance(event, SelectionEvent) or \ - isinstance(event, PlayerLeaveEvent) or \ - isinstance(event, GameStartEvent) or \ - (args.hotkeys and isinstance(event, HotkeyEvent)) or \ - (args.cameras and isinstance(event, CameraEvent)): + if ( + isinstance(event, CommandEvent) + or isinstance(event, SelectionEvent) + or isinstance(event, PlayerLeaveEvent) + or isinstance(event, GameStartEvent) + or (args.hotkeys and isinstance(event, ControlGroupEvent)) + or (args.cameras and isinstance(event, CameraEvent)) + ): print(event) getch() if args.bytes: - print("\t"+event.bytes.encode('hex')) + print("\t" + event.bytes.encode("hex")) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/sc2reader/scripts/utils.py b/sc2reader/scripts/utils.py deleted file mode 100644 index 3eb05188..00000000 --- a/sc2reader/scripts/utils.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - -import argparse -import re -import textwrap - - -class Formatter(argparse.RawTextHelpFormatter): - """FlexiFormatter which respects new line formatting and wraps the rest - - Example: - >>> parser = argparse.ArgumentParser(formatter_class=FlexiFormatter) - >>> parser.add_argument('a',help='''\ - ... This argument's help text will have this first long line\ - ... wrapped to fit the target window size so that your text\ - ... remains flexible. - ... - ... 1. This option list - ... 2. is still persisted - ... 3. and the option strings get wrapped like this\ - ... with an indent for readability. - ... - ... You must use backslashes at the end of lines to indicate that\ - ... you want the text to wrap instead of preserving the newline. - ... ''') - - Only the name of this class is considered a public API. All the methods - provided by the class are considered an implementation detail. - """ - - @classmethod - def new(cls, **options): - return lambda prog: Formatter(prog, **options) - - def _split_lines(self, text, width): - lines = list() - main_indent = len(re.match(r'( *)', text).group(1)) - # Wrap each line individually to allow for partial formatting - for line in text.splitlines(): - - # Get this line's indent and figure out what indent to use - # if the line wraps. Account for lists of small variety. - indent = len(re.match(r'( *)', line).group(1)) - list_match = re.match(r'( *)(([*-+>]+|\w+\)|\w+\.) +)', line) - if(list_match): - sub_indent = indent + len(list_match.group(2)) - else: - sub_indent = indent - - # Textwrap will do all the hard work for us - line = self._whitespace_matcher.sub(' ', line).strip() - new_lines = textwrap.wrap( - text=line, - width=width, - initial_indent=' '*(indent-main_indent), - subsequent_indent=' '*(sub_indent-main_indent), - ) - - # Blank lines get eaten by textwrap, put it back with [' '] - lines.extend(new_lines or [' ']) - - return lines diff --git a/sc2reader/utils.py b/sc2reader/utils.py index 2ee3d382..660f07bd 100644 --- a/sc2reader/utils.py +++ b/sc2reader/utils.py @@ -1,17 +1,14 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals, division - import binascii -import os import json +import os from datetime import timedelta, datetime -from sc2reader.log_utils import loggable -from sc2reader.exceptions import MPQError from sc2reader.constants import COLOR_CODES, COLOR_CODES_INV +from sc2reader.exceptions import MPQError +from sc2reader.log_utils import loggable -class DepotFile(object): +class DepotFile: """ :param bytes: The raw bytes representing the depot file @@ -19,27 +16,20 @@ class DepotFile(object): and assembles them into a URL so that the dependency can be fetched. """ - #: The url template for all DepotFiles - url_template = 'http://{0}.depot.battle.net:1119/{1}.{2}' - def __init__(self, bytes): #: The server the file is hosted on - self.server = bytes[4:8].decode('utf-8').strip('\x00 ') - - # There is no SEA depot, use US instead - if self.server == 'SEA': - self.server = 'US' + self.server = bytes[4:8].decode("utf-8").strip("\x00 ").lower() #: The unique content based hash of the file - self.hash = binascii.b2a_hex(bytes[8:]).decode('utf8') + self.hash = binascii.b2a_hex(bytes[8:]).decode("utf8") #: The extension of the file on the server - self.type = bytes[0:4].decode('utf8') + self.type = bytes[0:4].decode("utf8") @property def url(self): - """ Returns url of the depot file. """ - return self.url_template.format(self.server, self.hash, self.type) + """Returns url of the depot file.""" + return get_resource_url(self.server, self.hash, self.type) def __hash__(self): return hash(self.url) @@ -52,11 +42,11 @@ def windows_to_unix(windows_time): # This windows timestamp measures the number of 100 nanosecond periods since # January 1st, 1601. First we subtract the number of nanosecond periods from # 1601-1970, then we divide by 10^7 to bring it back to seconds. - return int((windows_time - 116444735995904000) / 10 ** 7) + return int((windows_time - 116444735995904000) / 10**7) @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:: @@ -71,11 +61,12 @@ class Color(object): Only standard Starcraft colors are supported. ValueErrors will be thrown on invalid names or hex values. """ + def __init__(self, name=None, r=0, g=0, b=0, a=255): if name: if name not in COLOR_CODES_INV: - self.logger.warn("Invalid color name: " + name) - hexstr = COLOR_CODES_INV.get(name, '000000') + self.logger.warning(f"Invalid color name: {name}") + hexstr = COLOR_CODES_INV.get(name, "000000") self.r = int(hexstr[0:2], 16) self.g = int(hexstr[2:4], 16) self.b = int(hexstr[4:6], 16) @@ -87,18 +78,22 @@ def __init__(self, name=None, r=0, g=0, b=0, a=255): self.b = b self.a = a if self.hex not in COLOR_CODES: - self.logger.warn("Invalid color hex value: " + self.hex) + self.logger.warning(f"Invalid color hex value: {self.hex}") self.name = COLOR_CODES.get(self.hex, self.hex) @property def rgba(self): - """ Returns a tuple containing the color's (r,g,b,a) """ + """ + Returns a tuple containing the color's (r,g,b,a) + """ return (self.r, self.g, self.b, self.a) @property def hex(self): - """The hexadecimal representation of the color""" - return "{0.r:02X}{0.g:02X}{0.b:02X}".format(self) + """ + The hexadecimal representation of the color + """ + return f"{self.r:02X}{self.g:02X}{self.b:02X}" def __str__(self): return self.name @@ -114,7 +109,6 @@ def get_real_type(teams): def extract_data_file(data_file, archive): - def recovery_attempt(): try: return archive.read_file(data_file) @@ -148,10 +142,12 @@ 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(path, exclude=list(), depth=-1, followlinks=False, extension=None, **extras): +def get_files( + path, exclude=list(), depth=-1, followlinks=False, extension=None, **extras +): """ Retrieves files from the given path with configurable behavior. @@ -163,13 +159,18 @@ def get_files(path, exclude=list(), depth=-1, followlinks=False, extension=None, """ # 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: - type_check = lambda path: os.path.splitext(path)[1][1:].lower() == extension.lower() + + def type_check(path): + return os.path.splitext(path)[1][1:].lower() == extension.lower() + else: - type_check = lambda n: True + + def type_check(n): + return True # os.walk can't handle file paths, only directories if os.path.isfile(path): @@ -192,31 +193,51 @@ def get_files(path, exclude=list(), depth=-1, followlinks=False, extension=None, depth -= 1 +def get_resource_url(region, hash, type): + url_template = "{}://{}-s2-depot.{}/{}.{}" + scheme = "https" + domain = "classic.blizzard.com" + + if region == "sea": + region = "us" + elif region == "cn": + scheme = "http" + domain = "battlenet.com.cn" + return url_template.format(scheme, region, domain, hash, type) + + class Length(timedelta): - """ Extends the builtin timedelta class. See python docs for more info on - what capabilities this gives you. + """ + Extends the builtin timedelta class. See python docs for more info on + what capabilities this gives you. """ @property def hours(self): - """ The number of hours in represented. """ + """ + The number of hours in represented. + """ return self.seconds // 3600 @property def mins(self): - """ The number of minutes in excess of the hours. """ + """ + The number of minutes in excess of the hours. + """ return self.seconds // 60 % 60 @property def secs(self): - """ The number of seconds in excess of the minutes. """ + """ + The number of seconds in excess of the minutes. + """ return self.seconds % 60 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): @@ -237,68 +258,75 @@ def toDict(replay): observers = list() for observer in replay.observers: messages = list() - for message in getattr(observer, 'messages', list()): - messages.append({ - 'time': message.time.seconds, - 'text': message.text, - 'is_public': message.to_all - }) - observers.append({ - 'name': getattr(observer, 'name', None), - 'pid': getattr(observer, 'pid', None), - 'messages': messages, - }) + for message in getattr(observer, "messages", list()): + messages.append( + { + "time": message.time.seconds, + "text": message.text, + "is_public": message.to_all, + } + ) + observers.append( + { + "name": getattr(observer, "name", None), + "pid": getattr(observer, "pid", None), + "messages": messages, + } + ) # Build players into dictionary players = list() for player in replay.players: messages = list() for message in player.messages: - messages.append({ - 'time': message.time.seconds, - 'text': message.text, - 'is_public': message.to_all - }) - players.append({ - 'avg_apm': getattr(player, 'avg_apm', None), - 'color': player.color.__dict__ if hasattr(player, 'color') else None, - 'handicap': getattr(player, 'handicap', None), - 'name': getattr(player, 'name', None), - 'pick_race': getattr(player, 'pick_race', None), - 'pid': getattr(player, 'pid', None), - 'play_race': getattr(player, 'play_race', None), - 'result': getattr(player, 'result', None), - 'type': getattr(player, 'type', None), - 'uid': getattr(player, 'uid', None), - 'url': getattr(player, 'url', None), - 'messages': messages, - }) + messages.append( + { + "time": message.time.seconds, + "text": message.text, + "is_public": message.to_all, + } + ) + players.append( + { + "avg_apm": getattr(player, "avg_apm", None), + "color": player.color.__dict__ if hasattr(player, "color") else None, + "handicap": getattr(player, "handicap", None), + "name": getattr(player, "name", None), + "pick_race": getattr(player, "pick_race", None), + "pid": getattr(player, "pid", None), + "play_race": getattr(player, "play_race", None), + "result": getattr(player, "result", None), + "type": getattr(player, "type", None), + "uid": getattr(player, "uid", None), + "url": getattr(player, "url", None), + "messages": messages, + } + ) # Consolidate replay metadata into dictionary return { - 'region': getattr(replay, 'region', None), - 'map_name': getattr(replay, 'map_name', None), - 'file_time': getattr(replay, 'file_time', None), - 'filehash': getattr(replay, 'filehash', None), - 'unix_timestamp': getattr(replay, 'unix_timestamp', None), - 'date': getattr(replay, 'date', None), - 'utc_date': getattr(replay, 'utc_date', None), - 'speed': getattr(replay, 'speed', None), - 'category': getattr(replay, 'category', None), - 'type': getattr(replay, 'type', None), - 'is_ladder': getattr(replay, 'is_ladder', False), - 'is_private': getattr(replay, 'is_private', False), - 'filename': getattr(replay, 'filename', None), - 'file_time': getattr(replay, 'file_time', None), - 'frames': getattr(replay, 'frames', None), - 'build': getattr(replay, 'build', None), - 'release': getattr(replay, 'release_string', None), - 'game_fps': getattr(replay, 'game_fps', None), - 'game_length': getattr(getattr(replay, 'game_length', None), 'seconds', None), - 'players': players, - 'observers': observers, - 'real_length': getattr(getattr(replay, 'real_length', None), 'seconds', None), - 'real_type': getattr(replay, 'real_type', None), - 'time_zone': getattr(replay, 'time_zone', None), - 'versions': getattr(replay, 'versions', None) + "region": getattr(replay, "region", None), + "map_name": getattr(replay, "map_name", None), + "file_time": getattr(replay, "file_time", None), + "filehash": getattr(replay, "filehash", None), + "unix_timestamp": getattr(replay, "unix_timestamp", None), + "date": getattr(replay, "date", None), + "utc_date": getattr(replay, "utc_date", None), + "speed": getattr(replay, "speed", None), + "category": getattr(replay, "category", None), + "type": getattr(replay, "type", None), + "is_ladder": getattr(replay, "is_ladder", False), + "is_private": getattr(replay, "is_private", False), + "filename": getattr(replay, "filename", None), + "frames": getattr(replay, "frames", None), + "build": getattr(replay, "build", None), + "release": getattr(replay, "release_string", None), + "game_fps": getattr(replay, "game_fps", None), + "game_length": getattr(getattr(replay, "game_length", None), "seconds", None), + "players": players, + "observers": observers, + "real_length": getattr(getattr(replay, "real_length", None), "seconds", None), + "real_type": getattr(replay, "real_type", None), + "time_zone": getattr(replay, "time_zone", None), + "versions": getattr(replay, "versions", None), } diff --git a/setup.py b/setup.py deleted file mode 100644 index c06d6fce..00000000 --- a/setup.py +++ /dev/null @@ -1,54 +0,0 @@ -import sys -import setuptools - -setuptools.setup( - license="MIT", - name="sc2reader", - version='1.3.0', - keywords=["starcraft 2", "sc2", "replay", "parser"], - description="Utility for parsing Starcraft II replay files", - long_description=open("README.rst").read()+"\n\n"+open("CHANGELOG.rst").read(), - - author="Kevin Leung", - author_email="kkleung89@gmail.com", - url="https://github.com/ggtracker/sc2reader", - - platforms=["any"], - - classifiers=[ - "Development Status :: 5 - Production/Stable", - "Environment :: Console", - "Intended Audience :: Developers", - "License :: OSI Approved :: MIT License", - "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 :: Implementation :: PyPy", - "Programming Language :: Python :: Implementation :: CPython", - "Topic :: Games/Entertainment", - "Topic :: Games/Entertainment :: Real Time Strategy", - "Topic :: Software Development", - "Topic :: Software Development :: Libraries", - "Topic :: Utilities", - ], - - entry_points={ - 'console_scripts': [ - 'sc2printer = sc2reader.scripts.sc2printer:main', - 'sc2replayer = sc2reader.scripts.sc2replayer:main', - 'sc2parse = sc2reader.scripts.sc2parse:main', - 'sc2attributes = sc2reader.scripts.sc2attributes:main', - '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'], - packages=setuptools.find_packages(), - include_package_data=True, - zip_safe=True -) diff --git a/test_replays/4.1.2.60604/1.SC2Replay b/test_replays/4.1.2.60604/1.SC2Replay new file mode 100644 index 00000000..54693ca7 Binary files /dev/null and b/test_replays/4.1.2.60604/1.SC2Replay differ diff --git a/test_replays/4.10.0.75689/trophy_id_13.SC2Replay b/test_replays/4.10.0.75689/trophy_id_13.SC2Replay new file mode 100644 index 00000000..050e6307 Binary files /dev/null and b/test_replays/4.10.0.75689/trophy_id_13.SC2Replay differ diff --git a/test_replays/4.11.0.77379/Oblivion Express.SC2Replay b/test_replays/4.11.0.77379/Oblivion Express.SC2Replay new file mode 100644 index 00000000..c1646f4d Binary files /dev/null and b/test_replays/4.11.0.77379/Oblivion Express.SC2Replay differ diff --git a/test_replays/5.0.0.80949/2020-07-28 - (T)Ocrucius VS (Z)Rairden.SC2Replay b/test_replays/5.0.0.80949/2020-07-28 - (T)Ocrucius VS (Z)Rairden.SC2Replay new file mode 100644 index 00000000..a2fbc3ee Binary files /dev/null and b/test_replays/5.0.0.80949/2020-07-28 - (T)Ocrucius VS (Z)Rairden.SC2Replay differ diff --git a/test_replays/test_all.py b/test_replays/test_replays.py similarity index 54% rename from test_replays/test_all.py rename to test_replays/test_replays.py index b779e7cf..4ea53c20 100644 --- a/test_replays/test_all.py +++ b/test_replays/test_replays.py @@ -1,12 +1,10 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals - import datetime import json from xml.dom import minidom # Newer unittest features aren't built in for python 2.6 import sys + if sys.version_info[:2] < (2, 7): import unittest2 as unittest else: @@ -19,11 +17,13 @@ import sc2reader from sc2reader.exceptions import CorruptTrackerFileError +from sc2reader.events.game import GameEvent +from sc2reader.objects import Player sc2reader.log_utils.log_to_console("INFO") -class TestReplays(unittest.TestCase): +class TestReplays(unittest.TestCase): def test_teams(self): replay = sc2reader.load_replay("test_replays/1.2.2.17811/13.SC2Replay") self.assertNotEqual(replay.player[1].team.number, replay.player[2].team.number) @@ -76,8 +76,8 @@ def test_standard_1v1(self): self.assertEqual(emperor.result, "Win") self.assertEqual(boom.result, "Loss") - self.assertEqual(emperor.url, "http://eu.battle.net/sc2/en/profile/520049/1/Emperor/") - self.assertEqual(boom.url, "http://eu.battle.net/sc2/en/profile/1694745/1/Boom/") + self.assertEqual(emperor.url, "https://starcraft2.com/en-us/profile/2/1/520049") + self.assertEqual(boom.url, "https://starcraft2.com/en-us/profile/2/1/1694745") self.assertEqual(len(replay.messages), 12) self.assertEqual(replay.messages[0].text, "hf") @@ -142,16 +142,25 @@ def test_random_player(self): self.assertEqual(gogeta.play_race, "Terran") replay = sc2reader.load_replay("test_replays/1.2.2.17811/6.SC2Replay") - permafrost = next(player for player in replay.players if player.name == "Permafrost") + permafrost = next( + player for player in replay.players if player.name == "Permafrost" + ) self.assertEqual(permafrost.pick_race, "Random") self.assertEqual(permafrost.play_race, "Protoss") def test_us_realm(self): replay = sc2reader.load_replay("test_replays/1.2.2.17811/5.SC2Replay") - shadesofgray = [player for player in replay.players if player.name == "ShadesofGray"][0] + shadesofgray = [ + player for player in replay.players if player.name == "ShadesofGray" + ][0] reddawn = [player for player in replay.players if player.name == "reddawn"][0] - self.assertEqual(shadesofgray.url, "http://us.battle.net/sc2/en/profile/2358439/1/ShadesofGray/") - self.assertEqual(reddawn.url, "http://us.battle.net/sc2/en/profile/2198663/1/reddawn/") + self.assertEqual( + shadesofgray.url, + "https://starcraft2.com/en-us/profile/1/1/2358439", + ) + self.assertEqual( + reddawn.url, "https://starcraft2.com/en-us/profile/1/1/2198663" + ) def test_kr_realm_and_tampered_messages(self): """ @@ -161,9 +170,11 @@ def test_kr_realm_and_tampered_messages(self): replay = sc2reader.load_replay("test_replays/1.1.3.16939/11.SC2Replay") self.assertEqual(replay.expansion, "WoL") first = [player for player in replay.players if player.name == "명지대학교"][0] - second = [player for player in replay.players if player.name == "티에스엘사기수"][0] - self.assertEqual(first.url, "http://kr.battle.net/sc2/en/profile/258945/1/명지대학교/") - self.assertEqual(second.url, "http://kr.battle.net/sc2/en/profile/102472/1/티에스엘사기수/") + second = [ + player for player in replay.players if player.name == "티에스엘사기수" + ][0] + self.assertEqual(first.url, "https://starcraft2.com/en-us/profile/3/1/258945") + self.assertEqual(second.url, "https://starcraft2.com/en-us/profile/3/1/102472") self.assertEqual(replay.messages[0].text, "sc2.replays.net") self.assertEqual(replay.messages[5].text, "sc2.replays.net") @@ -198,56 +209,91 @@ def test_hots_pids(self): "test_replays/2.0.3.24764/Antiga Shipyard (3).SC2Replay", "test_replays/2.0.0.24247/molten.SC2Replay", "test_replays/2.0.0.23925/Akilon Wastes.SC2Replay", - ]: - + ]: 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([event.player.pid for event in replay.events if "CommandEvent" in event.name]) + 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): - replay = sc2reader.load_replay("test_replays/1.5.4.24540/ggtracker_1471849.SC2Replay") + replay = sc2reader.load_replay( + "test_replays/1.5.4.24540/ggtracker_1471849.SC2Replay" + ) self.assertEqual(replay.expansion, "WoL") - ability_pids = set([event.player.pid for event in replay.events if "CommandEvent" in event.name]) - player_pids = set([player.pid for player in replay.players]) + ability_pids = { + 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) 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([ event.player.pid for event in replay.events if "TargetUnitCommandEvent" in event.name and event.ability.name == "SpawnLarva"]) + 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): - replay = sc2reader.load_replay("test_replays/2.0.0.24247/Cloud Kingdom LE (13).SC2Replay") + replay = sc2reader.load_replay( + "test_replays/2.0.0.24247/Cloud Kingdom LE (13).SC2Replay" + ) self.assertEqual(replay.expansion, "HotS") - replay = sc2reader.load_replay("test_replays/2.0.0.24247/Korhal City (19).SC2Replay") + replay = sc2reader.load_replay( + "test_replays/2.0.0.24247/Korhal City (19).SC2Replay" + ) self.assertEqual(replay.expansion, "HotS") def test_oracle_parsing(self): - replay = sc2reader.load_replay("test_replays/2.0.3.24764/ggtracker_1571740.SC2Replay") + replay = sc2reader.load_replay( + "test_replays/2.0.3.24764/ggtracker_1571740.SC2Replay" + ) self.assertEqual(replay.expansion, "HotS") oracles = [unit for unit in replay.objects.values() if unit.name == "Oracle"] self.assertEqual(len(oracles), 2) def test_resume_from_replay(self): - replay = sc2reader.load_replay("test_replays/2.0.3.24764/resume_from_replay.SC2Replay") + replay = sc2reader.load_replay( + "test_replays/2.0.3.24764/resume_from_replay.SC2Replay" + ) self.assertTrue(replay.resume_from_replay) self.assertEqual(replay.resume_method, 0) def test_clan_players(self): - replay = sc2reader.load_replay("test_replays/2.0.4.24944/Lunar Colony V.SC2Replay") + replay = sc2reader.load_replay( + "test_replays/2.0.4.24944/Lunar Colony V.SC2Replay" + ) self.assertEqual(replay.expansion, "WoL") self.assertEqual(len(replay.people), 4) def test_WoL_204(self): - replay = sc2reader.load_replay("test_replays/2.0.4.24944/ggtracker_1789768.SC2Replay") + replay = sc2reader.load_replay( + "test_replays/2.0.4.24944/ggtracker_1789768.SC2Replay" + ) self.assertEqual(replay.expansion, "WoL") self.assertEqual(len(replay.people), 2) def test_send_resources(self): - replay = sc2reader.load_replay("test_replays/2.0.4.24944/Backwater Complex (15).SC2Replay") + replay = sc2reader.load_replay( + "test_replays/2.0.4.24944/Backwater Complex (15).SC2Replay" + ) + trade_events = [ + event for event in replay.events if event.name == "ResourceTradeEvent" + ] + self.assertEqual(len(trade_events), 5) + self.assertEqual(trade_events[0].sender.name, "Guardian") + self.assertEqual(trade_events[0].recipient.name, "Sturmkind") + self.assertEqual(trade_events[0].recipient_id, 2) + self.assertEqual(trade_events[0].minerals, 0) + self.assertEqual(trade_events[0].vespene, 750) def test_cn_replays(self): replay = sc2reader.load_replay("test_replays/2.0.5.25092/cn1.SC2Replay") @@ -255,21 +301,27 @@ def test_cn_replays(self): self.assertEqual(replay.expansion, "WoL") def test_unit_types(self): - """ sc2reader#136 regression test """ - replay = sc2reader.load_replay('test_replays/2.0.8.25604/issue136.SC2Replay') - hellion_times = [u.started_at for u in replay.players[0].units if u.name == 'Hellion'] - hellbat_times = [u.started_at for u in replay.players[0].units if u.name == 'BattleHellion'] + """sc2reader#136 regression test""" + replay = sc2reader.load_replay("test_replays/2.0.8.25604/issue136.SC2Replay") + hellion_times = [ + u.started_at for u in replay.players[0].units if u.name == "Hellion" + ] + hellbat_times = [ + u.started_at for u in replay.players[0].units if u.name == "BattleHellion" + ] self.assertEqual(hellion_times, [5180, 5183]) self.assertEqual(hellbat_times, [6736, 6741, 7215, 7220, 12004, 12038]) @unittest.expectedFailure def test_outmatched_pids(self): - replay = sc2reader.load_replay('test_replays/2.0.8.25604/issue131_arid_wastes.SC2Replay') + replay = sc2reader.load_replay( + "test_replays/2.0.8.25604/issue131_arid_wastes.SC2Replay" + ) self.assertEqual(replay.players[0].pid, 1) self.assertEqual(replay.players[1].pid, 3) self.assertEqual(replay.players[2].pid, 4) - replay = sc2reader.load_replay('test_replays/2.0.8.25604/issue135.SC2Replay') + replay = sc2reader.load_replay("test_replays/2.0.8.25604/issue135.SC2Replay") self.assertEqual(replay.players[0].pid, 1) self.assertEqual(replay.players[1].pid, 2) self.assertEqual(replay.players[2].pid, 4) @@ -282,9 +334,11 @@ def test_outmatched_pids(self): @unittest.expectedFailure def test_map_info(self): - replay = sc2reader.load_replay("test_replays/1.5.3.23260/ggtracker_109233.SC2Replay", load_map=True) - self.assertEqual(replay.map.map_info.tile_set, 'Avernus') - self.assertEqual(replay.map.map_info.fog_type, 'Dark') + replay = sc2reader.load_replay( + "test_replays/1.5.3.23260/ggtracker_109233.SC2Replay", load_map=True + ) + self.assertEqual(replay.map.map_info.tile_set, "Avernus") + self.assertEqual(replay.map.map_info.fog_type, "Dark") self.assertEqual(replay.map.map_info.width, 176) self.assertEqual(replay.map.map_info.height, 160) self.assertEqual(replay.map.map_info.camera_top, 134) @@ -299,20 +353,22 @@ def test_engine_plugins(self): replay = sc2reader.load_replay( "test_replays/2.0.5.25092/cn1.SC2Replay", - engine=sc2reader.engine.GameEngine(plugins=[ - ContextLoader(), - APMTracker(), - SelectionTracker(), - ]) + engine=sc2reader.engine.GameEngine( + plugins=[ContextLoader(), APMTracker(), SelectionTracker()] + ), ) - code, details = replay.plugins['ContextLoader'] + code, details = replay.plugins["ContextLoader"] self.assertEqual(code, 0) self.assertEqual(details, dict()) @unittest.expectedFailure def test_factory_plugins(self): - from sc2reader.factories.plugins.replay import APMTracker, SelectionTracker, toJSON + from sc2reader.factories.plugins.replay import ( + APMTracker, + SelectionTracker, + toJSON, + ) factory = sc2reader.factories.SC2Factory() factory.register_plugin("Replay", APMTracker()) @@ -334,197 +390,230 @@ def test_factory_plugins(self): def test_gameheartnormalizer_plugin(self): from sc2reader.engine.plugins import GameHeartNormalizer + sc2reader.engine.register_plugin(GameHeartNormalizer()) # 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([ event.player.pid for event in replay.events if "TargetUnitCommandEvent" in event.name and event.ability.name == "SpawnLarva"]) + 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") self.assertEqual(replay.events[0].frame, 0) self.assertEqual(replay.game_length.seconds, 636) self.assertEqual(len(replay.observers), 5) - self.assertEqual(replay.players[0].name, 'SjoWBBII') - self.assertEqual(replay.players[0].play_race, 'Terran') - self.assertEqual(replay.players[1].name, 'Stardust') - self.assertEqual(replay.players[1].play_race, 'Protoss') + self.assertEqual(replay.players[0].name, "SjoWBBII") + self.assertEqual(replay.players[0].play_race, "Terran") + self.assertEqual(replay.players[1].name, "Stardust") + self.assertEqual(replay.players[1].play_race, "Protoss") self.assertEqual(len(replay.teams), 2) - self.assertEqual(replay.teams[0].players[0].name, 'SjoWBBII') - self.assertEqual(replay.teams[1].players[0].name, 'Stardust') + self.assertEqual(replay.teams[0].players[0].name, "SjoWBBII") + self.assertEqual(replay.teams[1].players[0].name, "Stardust") self.assertEqual(replay.winner, replay.teams[1]) replay = sc2reader.load_replay("test_replays/gameheart/gh_sameteam.SC2Replay") self.assertEqual(replay.events[0].frame, 0) self.assertEqual(replay.game_length.seconds, 424) self.assertEqual(len(replay.observers), 5) - self.assertEqual(replay.players[0].name, 'EGJDRC') - self.assertEqual(replay.players[0].play_race, 'Zerg') - self.assertEqual(replay.players[1].name, 'LiquidTaeJa') - self.assertEqual(replay.players[1].play_race, 'Terran') + self.assertEqual(replay.players[0].name, "EGJDRC") + self.assertEqual(replay.players[0].play_race, "Zerg") + self.assertEqual(replay.players[1].name, "LiquidTaeJa") + self.assertEqual(replay.players[1].play_race, "Terran") self.assertEqual(len(replay.teams), 2) - self.assertEqual(replay.teams[0].players[0].name, 'EGJDRC') - self.assertEqual(replay.teams[1].players[0].name, 'LiquidTaeJa') + self.assertEqual(replay.teams[0].players[0].name, "EGJDRC") + self.assertEqual(replay.teams[1].players[0].name, "LiquidTaeJa") self.assertEqual(replay.winner, replay.teams[0]) def test_replay_event_order(self): replay = sc2reader.load_replay("test_replays/event_order.SC2Replay") def test_creepTracker(self): - from sc2reader.engine.plugins import CreepTracker - - for replayfilename in [ - "test_replays/2.0.8.25605/ggtracker_3621322.SC2Replay", - "test_replays/2.0.8.25605/ggtracker_3621402.SC2Replay", - "test_replays/2.0.8.25605/ggtracker_3663861.SC2Replay", - "test_replays/2.0.8.25605/ggtracker_3695400.SC2Replay", - "test_replays/3.1.2/6494799.SC2Replay", - ]: - factory = sc2reader.factories.SC2Factory() - pluginEngine=sc2reader.engine.GameEngine(plugins=[ - CreepTracker() - ]) - replay =factory.load_replay(replayfilename,engine=pluginEngine,load_map= True,load_level=4) + from sc2reader.engine.plugins import CreepTracker - for player_id in replay.player: - if replay.player[player_id].play_race == "Zerg": - assert replay.player[player_id].max_creep_spread[1] >0 - assert replay.player[player_id].creep_spread_by_minute[0] >0 -# print("MCS", replay.player[player_id].max_creep_spread) -# print("CSBM", replay.player[player_id].creep_spread_by_minute) - - - replay =factory.load_replay("test_replays/2.0.8.25605/ggtracker_3621402.SC2Replay",load_map= True,engine=pluginEngine,load_level=4) - assert replay.player[2].max_creep_spread == (840,24.83) - assert replay.player[2].creep_spread_by_minute[420] == 9.4 - assert replay.player[2].creep_spread_by_minute[780] == 22.42 + for replayfilename in [ + "test_replays/2.0.8.25605/ggtracker_3621322.SC2Replay", + "test_replays/2.0.8.25605/ggtracker_3621402.SC2Replay", + "test_replays/2.0.8.25605/ggtracker_3663861.SC2Replay", + "test_replays/2.0.8.25605/ggtracker_3695400.SC2Replay", + "test_replays/3.1.2/6494799.SC2Replay", + ]: + factory = sc2reader.factories.SC2Factory() + pluginEngine = sc2reader.engine.GameEngine(plugins=[CreepTracker()]) + replay = factory.load_replay( + replayfilename, engine=pluginEngine, load_map=True, load_level=4 + ) + + for player_id in replay.player: + if replay.player[player_id].play_race == "Zerg": + assert replay.player[player_id].max_creep_spread[1] > 0 + assert replay.player[player_id].creep_spread_by_minute[0] > 0 + # print("MCS", replay.player[player_id].max_creep_spread) + # print("CSBM", replay.player[player_id].creep_spread_by_minute) + + replay = factory.load_replay( + "test_replays/2.0.8.25605/ggtracker_3621402.SC2Replay", + load_map=True, + engine=pluginEngine, + load_level=4, + ) + assert replay.player[2].max_creep_spread == (840, 24.83) + assert replay.player[2].creep_spread_by_minute[420] == 9.4 + assert replay.player[2].creep_spread_by_minute[780] == 22.42 def test_bad_unit_ids(self): with self.assertRaises(CorruptTrackerFileError): - replay = sc2reader.load_replay("test_replays/2.0.11.26825/bad_unit_ids_1.SC2Replay", load_level=4) + replay = sc2reader.load_replay( + "test_replays/2.0.11.26825/bad_unit_ids_1.SC2Replay", load_level=4 + ) with self.assertRaises(CorruptTrackerFileError): - replay = sc2reader.load_replay("test_replays/2.0.9.26147/bad_unit_ids_2.SC2Replay", load_level=4) + replay = sc2reader.load_replay( + "test_replays/2.0.9.26147/bad_unit_ids_2.SC2Replay", load_level=4 + ) def test_daedalus_point(self): - replay = sc2reader.load_replay("test_replays/2.0.11.26825/DaedalusPoint.SC2Replay") + replay = sc2reader.load_replay( + "test_replays/2.0.11.26825/DaedalusPoint.SC2Replay" + ) def test_reloaded(self): - replay = sc2reader.load_replay("test_replays/2.1.3.28667/Habitation Station LE (54).SC2Replay") + replay = sc2reader.load_replay( + "test_replays/2.1.3.28667/Habitation Station LE (54).SC2Replay" + ) def test_214(self): - replay = sc2reader.load_replay("test_replays/2.1.4/Catallena LE.SC2Replay", load_level=4) + replay = sc2reader.load_replay( + "test_replays/2.1.4/Catallena LE.SC2Replay", load_level=4 + ) def test_lotv1(self): - replay = sc2reader.load_replay("test_replays/lotv/lotv1.SC2Replay") - self.assertEqual(replay.expansion, "LotV") - replay = sc2reader.load_replay("test_replays/lotv/lotv2.SC2Replay") - self.assertEqual(replay.expansion, "LotV") - + replay = sc2reader.load_replay("test_replays/lotv/lotv1.SC2Replay") + self.assertEqual(replay.expansion, "LotV") + replay = sc2reader.load_replay("test_replays/lotv/lotv2.SC2Replay") + self.assertEqual(replay.expansion, "LotV") def test_lotv_creepTracker(self): - from sc2reader.engine.plugins import CreepTracker - - for replayfilename in [ - "test_replays/lotv/lotv1.SC2Replay", - ]: - factory = sc2reader.factories.SC2Factory() - pluginEngine=sc2reader.engine.GameEngine(plugins=[ - CreepTracker() - ]) - replay =factory.load_replay(replayfilename,engine=pluginEngine,load_map= True) - - for player_id in replay.player: - if replay.player[player_id].play_race == "Zerg": - assert replay.player[player_id].max_creep_spread != 0 - assert replay.player[player_id].creep_spread_by_minute + from sc2reader.engine.plugins import CreepTracker + + for replayfilename in ["test_replays/4.0.0.59587/1.SC2Replay"]: + factory = sc2reader.factories.SC2Factory() + pluginEngine = sc2reader.engine.GameEngine(plugins=[CreepTracker()]) + replay = factory.load_replay( + replayfilename, engine=pluginEngine, load_map=True + ) + + is_at_least_one_zerg_in_game = False + for player_id in replay.player: + if replay.player[player_id].play_race == "Zerg": + is_at_least_one_zerg_in_game = True + assert replay.player[player_id].max_creep_spread != 0 + assert replay.player[player_id].creep_spread_by_minute + assert is_at_least_one_zerg_in_game def test_lotv_map(self): - # This test currently fails in decoders.py with 'TypeError: ord() expected a character, but string of length 0 found' - for replayfilename in [ - "test_replays/lotv/lotv1.SC2Replay", - ]: - factory = sc2reader.factories.SC2Factory() - replay =factory.load_replay(replayfilename,load_level=1,load_map= True) + for replayfilename in ["test_replays/4.0.0.59587/1.SC2Replay"]: + factory = sc2reader.factories.SC2Factory() + replay = factory.load_replay(replayfilename, load_level=1, load_map=True) def test_30(self): - replay = sc2reader.load_replay("test_replays/3.0.0.38215/first.SC2Replay") - replay = sc2reader.load_replay("test_replays/3.0.0.38215/second.SC2Replay") - replay = sc2reader.load_replay("test_replays/3.0.0.38215/third.SC2Replay") + replay = sc2reader.load_replay("test_replays/3.0.0.38215/first.SC2Replay") + replay = sc2reader.load_replay("test_replays/3.0.0.38215/second.SC2Replay") + replay = sc2reader.load_replay("test_replays/3.0.0.38215/third.SC2Replay") 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)) + for i in range(1, 5): + 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", - ]: - factory = sc2reader.factories.SC2Factory() - replay =factory.load_replay(replayfilename,load_level=1,load_map= True) + for replayfilename in ["test_replays/3.0.0.38215/third.SC2Replay"]: + factory = sc2reader.factories.SC2Factory() + replay = factory.load_replay(replayfilename, load_level=1, load_map=True) def test_30_apms(self): - from sc2reader.factories.plugins.replay import APMTracker, SelectionTracker, toJSON + from sc2reader.factories.plugins.replay import ( + APMTracker, + SelectionTracker, + toJSON, + ) factory = sc2reader.factories.SC2Factory() factory.register_plugin("Replay", APMTracker()) replay = factory.load_replay("test_replays/3.0.0.38215/fourth.SC2Replay") for player in replay.players: - if player.name == 'Owl': + if player.name == "Owl": print(player.name, player.avg_apm) self.assertTrue(player.avg_apm > 110) def test_38749(self): replay = sc2reader.load_replay("test_replays/3.0.0.38749/1.SC2Replay") - self.assertEqual(replay.expansion, 'HotS') + self.assertEqual(replay.expansion, "HotS") replay = sc2reader.load_replay("test_replays/3.0.0.38749/2.SC2Replay") - self.assertEqual(replay.expansion, 'HotS') + self.assertEqual(replay.expansion, "HotS") def test_38996(self): replay = sc2reader.load_replay("test_replays/3.0.0.38996/1.SC2Replay") - self.assertEqual(replay.expansion, 'LotV') + self.assertEqual(replay.expansion, "LotV") replay = sc2reader.load_replay("test_replays/3.0.0.38996/2.SC2Replay") - self.assertEqual(replay.expansion, 'LotV') + self.assertEqual(replay.expansion, "LotV") def test_funny_minerals(self): replay = sc2reader.load_replay("test_replays/3.1.0/centralprotocol.SC2Replay") replay.load_map() - xmldoc = minidom.parseString(replay.map.archive.read_file('Objects')) - itemlist = xmldoc.getElementsByTagName('ObjectUnit') - mineralPosStrs = [ou.attributes['Position'].value for ou in itemlist 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])) + xmldoc = minidom.parseString(replay.map.archive.read_file("Objects")) + itemlist = xmldoc.getElementsByTagName("ObjectUnit") + mineralPosStrs = [ + ou.attributes["Position"].value + for ou in itemlist + if "MineralField" in ou.attributes["UnitType"].value + ] + mineralFieldNames = list( + { + ou.attributes["UnitType"].value + for ou in itemlist + if "MineralField" in ou.attributes["UnitType"].value + } + ) # print(mineralFieldNames) self.assertTrue(len(mineralPosStrs) > 0) def test_dusk(self): replay = sc2reader.load_replay("test_replays/3.1.0/dusktowers.SC2Replay") - self.assertEqual(replay.expansion, 'LotV') + self.assertEqual(replay.expansion, "LotV") def test_32(self): replay = sc2reader.load_replay("test_replays/3.2.0/1.SC2Replay") self.assertTrue(replay is not None) def test_33(self): - for replaynum in range(1,4): - replay = sc2reader.load_replay("test_replays/3.3.0/{}.SC2Replay".format(replaynum)) + for replaynum in range(1, 4): + 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): replay = sc2reader.load_replay("test_replays/3.3.0/ggissue48.SC2Replay") + def efilter(e): return hasattr(e, "ability") and e.ability_name == "CalldownMULE" + self.assertEqual(len(list(filter(efilter, replay.events))), 29) def test_33_shift_click_spawn_larva(self): replay = sc2reader.load_replay("test_replays/3.3.0/ggissue49.SC2Replay") + def efilter(e): return hasattr(e, "ability") and e.ability_name == "SpawnLarva" + self.assertEqual(len(list(filter(efilter, replay.events))), 23) def test_34(self): replay = sc2reader.load_replay("test_replays/3.4.0/issueYY.SC2Replay") - self.assertEqual(replay.expansion, 'LotV') + self.assertEqual(replay.expansion, "LotV") def test_lotv_time(self): replay = sc2reader.load_replay("test_replays/lotv/lotv1.SC2Replay") @@ -536,56 +625,44 @@ def test_37(self): replay = sc2reader.load_replay("test_replays/3.7.0/2.SC2Replay") def test_312(self): - for replayfilename in [ - "test_replays/3.12/Honorgrounds.SC2Replay", - ]: - factory = sc2reader.factories.SC2Factory() - replay =factory.load_replay(replayfilename,load_level=0) - replay =factory.load_replay(replayfilename,load_level=1) + for replayfilename in ["test_replays/3.12/Honorgrounds.SC2Replay"]: + factory = sc2reader.factories.SC2Factory() + replay = factory.load_replay(replayfilename, load_level=0) + replay = factory.load_replay(replayfilename, load_level=1) def test_316(self): - for replayfilename in [ - "test_replays/3.16/AbyssalReef.SC2Replay", - ]: - factory = sc2reader.factories.SC2Factory() - replay =factory.load_replay(replayfilename) + for replayfilename in ["test_replays/3.16/AbyssalReef.SC2Replay"]: + factory = sc2reader.factories.SC2Factory() + replay = factory.load_replay(replayfilename) def test_54518(self): - for replayfilename in [ - "test_replays/3.14.0.54518/1.SC2Replay", - "test_replays/3.14.0.54518/2.SC2Replay", - "test_replays/3.14.0.54518/3.SC2Replay", + for replayfilename in [ + "test_replays/3.14.0.54518/1.SC2Replay", + "test_replays/3.14.0.54518/2.SC2Replay", + "test_replays/3.14.0.54518/3.SC2Replay", ]: - factory = sc2reader.factories.SC2Factory() - replay =factory.load_replay(replayfilename) + factory = sc2reader.factories.SC2Factory() + replay = factory.load_replay(replayfilename) def test_59587(self): - for replayfilename in [ - "test_replays/4.0.0.59587/1.SC2Replay", - ]: - factory = sc2reader.factories.SC2Factory() - replay = factory.load_replay(replayfilename) + for replayfilename in ["test_replays/4.0.0.59587/1.SC2Replay"]: + factory = sc2reader.factories.SC2Factory() + replay = factory.load_replay(replayfilename) def test_64469(self): - for replayfilename in [ - "test_replays/4.3.0.64469/1.SC2Replay", - ]: - factory = sc2reader.factories.SC2Factory() - replay = factory.load_replay(replayfilename) + for replayfilename in ["test_replays/4.3.0.64469/1.SC2Replay"]: + factory = sc2reader.factories.SC2Factory() + replay = factory.load_replay(replayfilename) def test_coop(self): - for replayfilename in [ - "test_replays/coop/CoA.SC2Replay", - ]: - factory = sc2reader.factories.SC2Factory() - replay = factory.load_replay(replayfilename) + for replayfilename in ["test_replays/coop/CoA.SC2Replay"]: + factory = sc2reader.factories.SC2Factory() + replay = factory.load_replay(replayfilename) def test_65895(self): - for replayfilename in [ - "test_replays/4.4.0.65895/1.SC2Replay", - ]: - factory = sc2reader.factories.SC2Factory() - replay = factory.load_replay(replayfilename) + for replayfilename in ["test_replays/4.4.0.65895/1.SC2Replay"]: + factory = sc2reader.factories.SC2Factory() + replay = factory.load_replay(replayfilename) def test_event_print(self): replay = sc2reader.load_replay("test_replays/lotv/lotv1.SC2Replay") @@ -597,40 +674,99 @@ def test_event_print(self): capturedOutput.close() def test_70154(self): - for replayfilename in [ - "test_replays/4.7.0.70154/1.SC2Replay", - ]: + for replayfilename in ["test_replays/4.7.0.70154/1.SC2Replay"]: + factory = sc2reader.factories.SC2Factory() + replay = factory.load_replay(replayfilename) + + def test_75689(self): + for replayfilename in ["test_replays/4.10.0.75689/trophy_id_13.SC2Replay"]: + factory = sc2reader.factories.SC2Factory() + replay = factory.load_replay(replayfilename) + self.assertEqual(replay.players[0].trophy_id, 13) + + def test_77379(self): + replay = sc2reader.load_replay( + "test_replays/4.11.0.77379/Oblivion Express.SC2Replay" + ) + self.assertEqual(replay.players[0].commander, "Mengsk") + self.assertEqual(replay.players[1].commander, "Stetmann") + + def test_80949(self): + replay = sc2reader.load_replay( + "test_replays/5.0.0.80949/2020-07-28 - (T)Ocrucius VS (Z)Rairden.SC2Replay" + ) + + def test_anonymous_replay(self): + replayfilename = "test_replays/4.1.2.60604/1.SC2Replay" factory = sc2reader.factories.SC2Factory() replay = factory.load_replay(replayfilename) + def test_game_event_string(self): + time = "00.01" + # Global + player = MockPlayer() + player.name = "TestPlayer" + player.play_race = "TestRace" + event = GameEvent(16, 16) + event.player = player + self.assertEqual("{}\t{:<15} ".format(time, "Global"), event._str_prefix()) + + # Player with name + player = MockPlayer() + player.name = "TestPlayer" + player.play_race = "TestRace" + event = GameEvent(16, 1) + event.player = player + self.assertEqual(f"{time}\t{player.name:<15} ", event._str_prefix()) + + # No Player + player = MockPlayer() + event = GameEvent(16, 1) + self.assertEqual("{}\t{:<15} ".format(time, "no name"), event._str_prefix()) + + # Player without name + player = MockPlayer() + player.play_race = "TestRace" + player.pid = 1 + event = GameEvent(16, 1) + event.player = player + self.assertEqual( + f"{time}\tPlayer {player.pid} - ({player.play_race}) ", + event._str_prefix(), + ) + class TestGameEngine(unittest.TestCase): - class TestEvent(object): - name='TestEvent' + class TestEvent: + name = "TestEvent" + def __init__(self, value): self.value = value + def __str__(self): return self.value - class TestPlugin1(object): - name = 'TestPlugin1' + class TestPlugin1: + name = "TestPlugin1" def handleInitGame(self, event, replay): - yield TestGameEngine.TestEvent('b') - yield TestGameEngine.TestEvent('c') + yield TestGameEngine.TestEvent("b") + yield TestGameEngine.TestEvent("c") def handleTestEvent(self, event, replay): - print("morestuff") - if event.value == 'd': - yield sc2reader.engine.PluginExit(self, code=1, details=dict(msg="Fail!")) + if event.value == "d": + yield sc2reader.engine.PluginExit( + self, code=1, details=dict(msg="Fail!") + ) else: - yield TestGameEngine.TestEvent('d') + yield TestGameEngine.TestEvent("d") def handleEndGame(self, event, replay): - yield TestGameEngine.TestEvent('g') + yield TestGameEngine.TestEvent("g") + + class TestPlugin2: + name = "TestPlugin2" - class TestPlugin2(object): - name = 'TestPlugin2' def handleInitGame(self, event, replay): replay.engine_events = list() @@ -638,12 +774,12 @@ def handleTestEvent(self, event, replay): replay.engine_events.append(event) def handlePluginExit(self, event, replay): - yield TestGameEngine.TestEvent('e') + yield TestGameEngine.TestEvent("e") def handleEndGame(self, event, replay): - yield TestGameEngine.TestEvent('f') + yield TestGameEngine.TestEvent("f") - class MockReplay(object): + class MockReplay: def __init__(self, events): self.events = events @@ -651,13 +787,20 @@ def test_plugin1(self): engine = sc2reader.engine.GameEngine() engine.register_plugin(self.TestPlugin1()) engine.register_plugin(self.TestPlugin2()) - replay = self.MockReplay([self.TestEvent('a')]) + replay = self.MockReplay([self.TestEvent("a")]) engine.run(replay) - self.assertEqual(''.join(str(e) for e in replay.engine_events), 'bdecaf') - self.assertEqual(replay.plugin_failures, ['TestPlugin1']) - self.assertEqual(replay.plugin_result['TestPlugin1'], (1, dict(msg="Fail!"))) - self.assertEqual(replay.plugin_result['TestPlugin2'], (0, dict())) + self.assertEqual("".join(str(e) for e in replay.engine_events), "bdecaf") + self.assertEqual(replay.plugin_failures, ["TestPlugin1"]) + self.assertEqual(replay.plugin_result["TestPlugin1"], (1, dict(msg="Fail!"))) + self.assertEqual(replay.plugin_result["TestPlugin2"], (0, dict())) + + +class MockPlayer: + def __init__(self): + self.name = None + self.play_race = None + self.pid = None -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/test_s2gs/lotv.s2gs b/test_s2gs/lotv.s2gs new file mode 100644 index 00000000..13242594 Binary files /dev/null and b/test_s2gs/lotv.s2gs differ diff --git a/test_s2gs/test_all.py b/test_s2gs/test_all.py index 1a5e576c..75a1daa9 100644 --- a/test_s2gs/test_all.py +++ b/test_s2gs/test_all.py @@ -1,30 +1,31 @@ -# -*- coding: UTF-8 -*- - # Newer unittest features aren't built in for python 2.6 import sys + if sys.version_info[:2] < (2, 7): import unittest2 as unittest else: import unittest import sc2reader + sc2reader.log_utils.log_to_console("INFO") class TestSummaries(unittest.TestCase): - def test_a_WoL_s2gs(self): summary = sc2reader.load_game_summary("test_s2gs/s2gs1.s2gs") self.assertEqual(summary.players[0].resource_collection_rate, 1276) - self.assertEqual(summary.players[0].build_order[0].order, 'Probe') - self.assertEqual(summary.expansion, 'WoL') + self.assertEqual(summary.players[0].build_order[0].order, "Probe") + self.assertEqual(summary.expansion, "WoL") + + def test_a_LotV_s2gs(self): + summary = sc2reader.load_game_summary("test_s2gs/lotv.s2gs") + self.assertEqual(summary.players[0].resource_collection_rate, 1619) + self.assertEqual(summary.players[0].build_order[0].order, "Probe") + self.assertEqual(summary.expansion, "HotS") - def test_a_HotS_s2gs(self): - summary = sc2reader.load_game_summary("test_s2gs/hots1.s2gs") - self.assertEqual(summary.players[0].resource_collection_rate, 1599) - self.assertEqual(summary.players[0].build_order[0].order, 'SCV') - self.assertEqual(summary.expansion, 'HotS') +""" def test_another_HotS_s2gs(self): summary = sc2reader.load_game_summary("test_s2gs/hots2.s2gs") self.assertEqual(summary.players[0].enemies_destroyed, 14575) @@ -35,6 +36,7 @@ def test_another_HotS_s2gs(self): self.assertEqual(summary.players[0].workers_active_graph.as_points()[8][1], 25) self.assertEqual(summary.players[0].upgrade_spending_graph.as_points()[8][1], 300) self.assertEqual(summary.expansion, 'HotS') +""" -if __name__ == '__main__': +if __name__ == "__main__": unittest.main()