### Install Spawningtool from GitHub Source: https://github.com/stoicloofah/spawningtool/wiki/How-to-use-this-library-in-your-projects Install Spawningtool directly from its GitHub repository for the latest, potentially less stable, version. This is an editable installation. ```bash pip install -e git+git://github.com/StoicLoofah/spawningtool.git#egg=spawningtool ``` -------------------------------- ### Install Spawningtool from PyPi Source: https://github.com/stoicloofah/spawningtool/wiki/How-to-use-this-library-in-your-projects Use this command to install the latest stable version of Spawningtool from the Python Package Index. ```bash pip install spawningtool ``` -------------------------------- ### Build Replay Model in Python Project Source: https://github.com/stoicloofah/spawningtool/wiki/How-to-use-this-library-in-your-projects Example of how to integrate Spawningtool into your Python project to build a replay model. This requires copying the spawningtool folder into your project. ```python import spawningtool from spawningtool.parser import GameTimeline class SpawningReplayModel(): def loadRequestedReplay(self, filePath): result_replay = spawningtool.parser.parse_replay(filePath) return result_replay ``` -------------------------------- ### Batch Analysis: Win Rate by Supply Ratio (TvZ Matchup) Source: https://context7.com/stoicloofah/spawningtool/llms.txt Calculate win rates for specific matchups, like Terran vs. Zerg, using supply ratio. This example defines a TvZ condition function and utilizes caching. ```python from spawningtool.analyzer import ( count_win_rate_by_supply_difference, count_win_rate_by_supply_ratio, RACE_BY_LETTER ) # Create a text file with paths to replays # replays.txt: # replays/game1.SC2Replay # replays/game2.SC2Replay # replays/game3.SC2Replay # Analyze TvZ matchup def tvz_condition(replay, player_1, player_2): return player_1['race'] == 'Terran' and player_2['race'] == 'Zerg' with open('replays.txt', 'r') as replay_list: results = count_win_rate_by_supply_ratio( replay_list, condition=tvz_condition, cache_dir='./cache' ) ``` -------------------------------- ### Parsed Data Structure Reference Example Source: https://context7.com/stoicloofah/spawningtool/llms.txt This snippet shows how to import the necessary modules and call the parse_replay function to obtain the parsed data structure, which can then be further inspected. ```python import spawningtool.parser import json result = spawningtool.parser.parse_replay('replays/game.SC2Replay') ``` -------------------------------- ### Include Map Details Source: https://context7.com/stoicloofah/spawningtool/llms.txt Extract spatial information such as map dimensions and player starting positions in clock notation. ```python import spawningtool.parser # Parse with map details enabled result = spawningtool.parser.parse_replay( 'replays/game.SC2Replay', include_map_details=True ) # Access map dimensions if result.get('include_map_details'): print(f"Map dimensions: {result['map_details']['width']}x{result['map_details']['height']}") # Access player starting positions (clock notation) for player_id, player in result['players'].items(): print(f"{player['name']} started at {player['clock_position']}:00") # Build order events include clock positions for event in player['buildOrder'][:5]: if event['clock_position']: print(f" {event['name']} built at {event['clock_position']}:00") ``` -------------------------------- ### Command Line: Show Abilities Used Source: https://context7.com/stoicloofah/spawningtool/llms.txt Use this option to see a breakdown of all abilities used by players in the replay. ```bash python -m spawningtool replays/game.SC2Replay --abilities ``` -------------------------------- ### Run Spawning Tool via Command Line Source: https://context7.com/stoicloofah/spawningtool/llms.txt Execute Spawning Tool directly from the terminal to quickly view build orders and game data. The basic usage command shows all available information for a given replay file. ```bash python -m spawningtool replays/game.SC2Replay ``` -------------------------------- ### Command Line: Use Caching for Faster Analysis Source: https://context7.com/stoicloofah/spawningtool/llms.txt Enable caching to speed up repeated analysis of the same replay by specifying a cache directory. ```bash python -m spawningtool replays/game.SC2Replay --cache-dir ./cache ``` -------------------------------- ### Execute Spawningtool from Command Line Source: https://github.com/stoicloofah/spawningtool/wiki/How-to-use-this-library-in-your-projects Run Spawningtool directly from your terminal to parse a replay file. Replace PATH/TO/REPLAY with the actual file path. ```bash python -m spawningtool PATH/TO/REPLAY ``` -------------------------------- ### Command Line: Show Build Orders (No Workers) Source: https://context7.com/stoicloofah/spawningtool/llms.txt Use this command to display only build orders, excluding worker units, from a replay file. ```bash python -m spawningtool replays/game.SC2Replay --build ``` -------------------------------- ### Command Line: Include Map Position Details Source: https://context7.com/stoicloofah/spawningtool/llms.txt Add map position information to the output with the --map-details flag. ```bash python -m spawningtool replays/game.SC2Replay --map-details ``` -------------------------------- ### Python API: Basic Game Parsing Source: https://context7.com/stoicloofah/spawningtool/llms.txt Instantiate the GameParser class to access parsed replay data. This allows for custom processing and access to intermediate data. ```python from spawningtool.parser import GameParser # Create parser instance parser = GameParser('replays/game.SC2Replay') # Get parsed data with all options result = parser.get_parsed_data( cutoff_time='10:00', cache_dir='./cache', include_map_details=True ) # Access the underlying sc2reader replay object parser.load_replay() replay = parser.replay print(f"Replay version: {replay.build}") print(f"Map hash: {replay.map_hash}") # Access players through sc2reader for player in replay.players: print(f"Player: {player.name}") print(f" APM: {player.avg_apm}") print(f" Commander: {player.commander}" ) # For Co-op games ``` -------------------------------- ### Enable Replay Caching Source: https://context7.com/stoicloofah/spawningtool/llms.txt Store parsed results in a directory to improve performance on subsequent reads of the same file. ```python import spawningtool.parser import os # Create cache directory cache_dir = './replay_cache' os.makedirs(cache_dir, exist_ok=True) # First call parses and caches the result result1 = spawningtool.parser.parse_replay( 'replays/game.SC2Replay', cache_dir=cache_dir ) print("First parse complete") # Second call retrieves from cache (much faster) result2 = spawningtool.parser.parse_replay( 'replays/game.SC2Replay', cache_dir=cache_dir ) print("Retrieved from cache") # Results are identical assert result1['map'] == result2['map'] assert len(result1['players']) == len(result2['players']) ``` -------------------------------- ### Build Order Object Properties Source: https://github.com/stoicloofah/spawningtool/wiki/Diving-into-the-Data Details of a specific unit or structure added to the player's build order. ```javascript buildOrder: clock_position: null frame: 18 is_worker: true name: "Probe" supply: 6 time: "0:01" ``` -------------------------------- ### Batch Analysis: Win Rate by Supply Difference Source: https://context7.com/stoicloofah/spawningtool/llms.txt Analyze win rates across multiple replays based on supply difference. Requires a text file listing replay paths. The condition lambda filters for specific matchups and min/max analysis times. ```python from spawningtool.analyzer import ( count_win_rate_by_supply_difference, count_win_rate_by_supply_ratio, RACE_BY_LETTER ) # Create a text file with paths to replays # replays.txt: # replays/game1.SC2Replay # replays/game2.SC2Replay # replays/game3.SC2Replay # Analyze win rate by supply difference with open('replays.txt', 'r') as replay_list: results = count_win_rate_by_supply_difference( replay_list, condition=lambda r, p1, p2: p1['race'] == 'Terran' and p2['race'] == 'Zerg', min_time=300, # Start at 5 minutes (in seconds) max_time=600 # End at 10 minutes ) # Results format: [[supply_diff, wins, total_games], ...] for diff, wins, games in results: if int(games) > 0: win_rate = int(wins) / int(games) * 100 print(f"Supply diff {diff:+3s}: {win_rate:5.1f}% ({wins}/{games})") ``` -------------------------------- ### Access Protoss Build Order Events Source: https://context7.com/stoicloofah/spawningtool/llms.txt Iterate through player build order events to extract details like timing, supply, and Chronoboost status. Requires the 'spawningtool.parser' module. ```python import spawningtool.parser result = spawningtool.parser.parse_replay('replays/protoss_game.SC2Replay') for player_id, player in result['players'].items(): if player['race'] == 'Protoss': print(f"Build Order for {player['name']}:") for event in player['buildOrder']: # Event structure: # { # 'frame': 1234, # Game frame number # 'time': '1:23', # Human-readable game time # 'name': 'Stalker', # Unit/building/upgrade name # 'supply': 32, # Supply count when started # 'is_worker': False, # True for Probe/SCV/Drone # 'clock_position': 3, # Map position (if enabled) # 'is_chronoboosted': True # Chronoboost was active # } chrono = " (Chronoboosted)" if event['is_chronoboosted'] else "" print(f" {event['supply']:3d} {event['time']:>6s} {event['name']}{chrono}") ``` -------------------------------- ### Command Line: Include Workers in Build Order Output Source: https://context7.com/stoicloofah/spawningtool/llms.txt To include worker units in the build order output, use the --workers flag. ```bash python -m spawningtool replays/game.SC2Replay --build --workers ``` -------------------------------- ### Abilities Object Properties Source: https://github.com/stoicloofah/spawningtool/wiki/Diving-into-the-Data Details about an ability used by a player during the game. ```javascript abilities: frame: 1489 name: "ChronoBoost" time: "1:33" ``` -------------------------------- ### Command Line: Stop at Specific Game Time Source: https://context7.com/stoicloofah/spawningtool/llms.txt Limit the analysis to a specific point in the game using the --cutoff-time flag. The time format is MM:SS. ```bash python -m spawningtool replays/game.SC2Replay --cutoff-time 5:00 ``` -------------------------------- ### Pretty Print JSON Output Source: https://context7.com/stoicloofah/spawningtool/llms.txt This Python code snippet demonstrates how to pretty-print a dictionary, such as the parsed replay data, into a human-readable JSON format using the `json` library. ```python import json # Assuming 'result' is the dictionary obtained from Spawning Tool # For example: result = { 'buildOrderExtracted': True, 'message': '', 'build': 89720, 'players': { '1': { 'name': 'Oliveira', 'race': 'Terran', 'is_winner': True, 'buildOrder': [["14 Supply", 0], ["15 Barracks", 15]] } } } print(json.dumps(result, indent=2, default=str)) ``` -------------------------------- ### Command Line: Show Units Lost Source: https://context7.com/stoicloofah/spawningtool/llms.txt This command displays a list of units that were lost during the game. ```bash python -m spawningtool replays/game.SC2Replay --units-lost ``` -------------------------------- ### Parse Replay within Python Script Source: https://github.com/stoicloofah/spawningtool/wiki/How-to-use-this-library-in-your-projects Import and use the Spawningtool parser directly within your Python code to process replay files. ```python import spawningtool.parser spawningtool.parser.parse_replay('PATH/TO/REPLAY') ``` -------------------------------- ### Parse a StarCraft 2 Replay Source: https://context7.com/stoicloofah/spawningtool/llms.txt The primary entry point for extracting game data, including player information and build orders, from a replay file. ```python import spawningtool.parser # Basic usage - parse a replay file result = spawningtool.parser.parse_replay('replays/game.SC2Replay') # Access game metadata print(f"Map: {result['map']}") print(f"Game Type: {result['game_type']}") print(f"Expansion: {result['expansion']}") print(f"Duration (frames): {result['frames']}") # Access player data for player_id, player in result['players'].items(): print(f"\nPlayer: {player['name']} ({player['race']})") print(f"Result: {player['result']}") print(f"League: {player['league']}") # Print build order print("Build Order:") for event in player['buildOrder']: if not event['is_worker']: # Skip worker production print(f" {event['supply']} {event['time']} {event['name']}") ``` -------------------------------- ### Parse Replay Data Structure Source: https://context7.com/stoicloofah/spawningtool/llms.txt This dictionary represents the parsed data from a StarCraft 2 replay file, including game details, player information, and build order specifics. It's the primary output of the Spawning Tool's parsing function. ```python parsed_data = { 'buildOrderExtracted': True, # bool: Successfully extracted build orders 'message': '', # str: Error or info message 'build': 89720, # int: Game client build number 'baseBuild': 89720, # int: Base protocol build 'category': 'Ladder', # str: Game category (Ladder, Private, etc.) 'expansion': 'LotV', # str: HotS, LotV 'unix_timestamp': 1676225347, # int: When game was played 'frames': 13704, # int: Total game frames 'frames_per_second': 22.4, # float: Game speed (22.4 for LotV) 'game_type': '1v1', # str: 1v1, 2v2, etc. 'region': 'eu', # str: Server region 'map': '[ESL] Gresvan', # str: Map name 'map_hash': 'abc123...', # str: Unique map identifier 'cooperative': False, # bool: Is this a Co-op game 'include_map_details': False, # bool: Map details requested 'map_details': { # dict: Only if include_map_details=True 'height': 200, 'width': 200 }, 'players': { '1': { # dict: Keyed by player ID 'name': 'Oliveira', # str: Player name 'pick_race': 'Terran', # str: Selected race (may be Random) 'race': 'Terran', # str: Actual race played 'league': 6, # int: League (0-7, Grandmaster=6) 'level': 150, # int: Race level 'is_winner': True, # bool: Won the game 'result': 'Win', # str: Win, Loss, Tie 'is_human': True, # bool: Human player 'handicap': 100, # int: Handicap percentage 'color': 'B4141E', # str: Player color hex 'uid': 10400125, # int: Battle.net ID 'region': 'eu', # str: Player region 'team': 1, # int: Team number 'clock_position': 2, # int: Start position (1-12 o'clock) 'commander': None, # str: Co-op commander name 'supply': [[0, 12], ...], # list: [frame, supply] pairs 'buildOrder': [...], # list: Build order events 'unitsLost': [...], # list: Units lost events 'abilities': [...] # list: Abilities used events } } } ``` -------------------------------- ### Access Abilities Used Events Source: https://context7.com/stoicloofah/spawningtool/llms.txt Track and count the usage of various in-game abilities like Chronoboost, Scanner Sweep, and Spawn Larva. The event structure includes game frame, time, and ability name. ```python import spawningtool.parser result = spawningtool.parser.parse_replay('replays/game.SC2Replay') for player_id, player in result['players'].items(): print(f"\nAbilities used by {player['name']}:") # Count abilities by type ability_count = {} for event in player['abilities']: # Event structure: # { # 'frame': 1500, # Game frame # 'time': '1:07', # Human-readable time # 'name': 'ChronoBoost' # Ability name # } name = event['name'] ability_count[name] = ability_count.get(name, 0) + 1 for ability, count in sorted(ability_count.items(), key=lambda x: -x[1]): print(f" {ability}: {count}") ``` -------------------------------- ### Root JSON Object Properties Source: https://github.com/stoicloofah/spawningtool/wiki/Diving-into-the-Data This object contains general details about the StarCraft 2 game session. ```javascript baseBuild: 28667 build: 30508 buildOrderExtracted: true category: "Private" expansion: "HotS" frames: 19150 game_type: "1v1" include_map_details: false map: "Frost LE" map_hash: "bb12240d1748afb6b728a7c6ebd716f4ce5bf3cb49bbb8062c33e3b4938c617d" message: "" players: Object unix_timestamp: 1404604126 ``` -------------------------------- ### Parse Replay with Cutoff Time Source: https://context7.com/stoicloofah/spawningtool/llms.txt Limit the processing of replay events to a specific game time, useful for analyzing early-game strategies. ```python import spawningtool.parser # Parse only the first 5 minutes of the game result = spawningtool.parser.parse_replay( 'replays/game.SC2Replay', cutoff_time='5:00' ) # Only events before 5:00 game time are included for player_id, player in result['players'].items(): print(f"Player: {player['name']}") print(f"Build order (first 5 minutes):") for event in player['buildOrder']: print(f" {event['time']} - {event['name']}") ``` -------------------------------- ### Replay Data Structure Source: https://context7.com/stoicloofah/spawningtool/llms.txt The structure of the dictionary returned after parsing a StarCraft 2 replay file. ```APIDOC ## Replay Data Structure ### Description This object represents the parsed data extracted from a StarCraft 2 replay file, containing game metadata, player information, and build order events. ### Response - **buildOrderExtracted** (bool) - Successfully extracted build orders - **message** (str) - Error or info message - **build** (int) - Game client build number - **baseBuild** (int) - Base protocol build - **category** (str) - Game category (Ladder, Private, etc.) - **expansion** (str) - Game expansion (HotS, LotV) - **unix_timestamp** (int) - When game was played - **frames** (int) - Total game frames - **frames_per_second** (float) - Game speed - **game_type** (str) - Game type (e.g., 1v1) - **region** (str) - Server region - **map** (str) - Map name - **map_hash** (str) - Unique map identifier - **cooperative** (bool) - Is this a Co-op game - **players** (dict) - Player data keyed by player ID ### Response Example { "buildOrderExtracted": true, "build": 89720, "category": "Ladder", "players": { "1": { "name": "Oliveira", "race": "Terran", "is_winner": true } } } ``` -------------------------------- ### Supply Array Format Source: https://github.com/stoicloofah/spawningtool/wiki/Diving-into-the-Data Represents player supply over time. Each element is a [FRAME, SUPPLY] pair. ```javascript 0: 1 1: 6 ``` -------------------------------- ### Access Supply Progression Over Time Source: https://context7.com/stoicloofah/spawningtool/llms.txt Analyze player supply throughout the game by accessing a list of [frame, supply] pairs. This snippet demonstrates how to convert frame numbers to human-readable time. ```python import spawningtool.parser result = spawningtool.parser.parse_replay('replays/game.SC2Replay') # Game runs at 22.4 frames per second in LotV FRAMES_PER_SECOND = 22.4 for player_id, player in result['players'].items(): print(f"\n{player['name']}'s supply progression:") # Supply is stored as [frame, supply] pairs for frame, supply in player['supply'][:10]: # First 10 entries seconds = frame / FRAMES_PER_SECOND minutes = int(seconds // 60) secs = int(seconds % 60) print(f" {minutes}:{secs:02d} - {supply} supply") ``` -------------------------------- ### Python API: Error Handling for Replay Parsing Source: https://context7.com/stoicloofah/spawningtool/llms.txt Implement robust error handling for replay parsing using specific exception classes like CutoffTimeError, ReplayFormatError, and ReadError. The safe_parse function provides a convenient wrapper. ```python from spawningtool.parser import parse_replay from spawningtool.exception import CutoffTimeError, ReplayFormatError, ReadError try: result = parse_replay('replays/game.SC2Replay', cutoff_time='invalid') except CutoffTimeError as e: print(f"Invalid cutoff time format: {e}") # Output: Invalid cutoff time format: You must enter a valid cutoff time! eg: 10:05 try: result = parse_replay('replays/old_wol_game.SC2Replay') except ReplayFormatError as e: print(f"Replay format error: {e}") # May contain partial data in e.parsed_data if hasattr(e, 'parsed_data'): print(f"Map: {e.parsed_data.get('map', 'Unknown')}") try: result = parse_replay('replays/corrupted.SC2Replay') except ReadError as e: print(f"Could not read replay: {e}") # Safe parsing function def safe_parse(filepath): try: return parse_replay(filepath) except (CutoffTimeError, ReplayFormatError, ReadError) as e: print(f"Failed to parse {filepath}: {e}") return None ``` -------------------------------- ### parse_replay Source: https://context7.com/stoicloofah/spawningtool/llms.txt The primary function for parsing StarCraft 2 replay files, returning a comprehensive dictionary of game data. ```APIDOC ## parse_replay ### Description Parses a StarCraft 2 replay file and returns a dictionary containing game metadata, player information, build orders, and unit events. ### Parameters #### Path Parameters - **filename** (str/file-like) - Required - The path to the .SC2Replay file or a file-like object. #### Query Parameters - **cutoff_time** (str) - Optional - Stop processing events after a specified game time (e.g., '5:00'). - **cache_dir** (str) - Optional - Directory path to store and retrieve cached results using MD5 hashing. - **include_map_details** (bool) - Optional - Include map dimensions and clock position information for units and events. ### Response #### Success Response (dict) - **map** (str) - Name of the map. - **game_type** (str) - Type of game (e.g., 1v1). - **expansion** (str) - Game expansion (e.g., LotV). - **frames** (int) - Total duration of the game in frames. - **players** (dict) - Dictionary of player data keyed by player_id, containing name, race, result, league, and buildOrder. ``` -------------------------------- ### Player Object Properties Source: https://github.com/stoicloofah/spawningtool/wiki/Diving-into-the-Data Details for an individual player in the game. This object is part of the root 'players' object. ```javascript clock_position: null color: "B4141E" handicap: 100 is_human: true is_winner: true league: 8 level: 33 name: "AxAlicia" pick_race: "Protoss" race: "Protoss" region: "us" result: "Win" supply: Array[122] team: 1 uid: 4174681 unitsLost: Array[121] ``` -------------------------------- ### Units Lost Object Properties Source: https://github.com/stoicloofah/spawningtool/wiki/Diving-into-the-Data Information about a unit lost by a player, including when it was lost and by which player. ```javascript unitsLost: clock_position: null frame: 14226 killer: 2 <-- the id for the player who killed the unit unfortunately we don't know what unit did the killing name: "HighTemplar" time: "14:49" ``` -------------------------------- ### Access Units Lost Events Source: https://context7.com/stoicloofah/spawningtool/llms.txt Retrieve information about units lost during a game, including when they were lost, their type, and the player who destroyed them. This snippet groups lost units by type and counts them. ```python import spawningtool.parser result = spawningtool.parser.parse_replay('replays/game.SC2Replay') for player_id, player in result['players'].items(): print(f"\nUnits lost by {player['name']}:") # Group units lost by type units_lost_count = {} for event in player['unitsLost']: # Event structure: # { # 'frame': 5000, # Game frame # 'time': '5:12', # Human-readable time # 'name': 'Marine', # Unit type # 'killer': 2, # Player ID of killer # 'clock_position': 6 # Map position (if enabled) # } name = event['name'] units_lost_count[name] = units_lost_count.get(name, 0) + 1 for unit, count in sorted(units_lost_count.items(), key=lambda x: -x[1]): print(f" {unit}: {count}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.