sc2nachos.run
Playing a game on a client this library starts, or on one a ladder started, playing a replay back, and finding StarCraft II on this machine and starting it.
1"""Playing a game on a client this library starts, or on one a ladder started, playing a replay back, and finding 2StarCraft II on this machine and starting it.""" 3 4from sc2nachos.run._game_process import GameLaunchError, GameProcess, free_port 5from sc2nachos.run._installation import ( 6 MINIMUM_BASE_BUILD, 7 GameVersionError, 8 Installation, 9 InstallationNotFoundError, 10 UnsupportedPlatformError, 11) 12from sc2nachos.run._map_file import MapFile, MapNotFoundError 13from sc2nachos.run._replay import ReplayPlayback, open_replay, open_replay_recording, run_replay 14from sc2nachos.run._runners import run_from_command_line, run_ladder, run_local, run_recording 15 16__all__ = [ 17 "MINIMUM_BASE_BUILD", 18 "GameLaunchError", 19 "GameProcess", 20 "GameVersionError", 21 "Installation", 22 "InstallationNotFoundError", 23 "MapFile", 24 "MapNotFoundError", 25 "ReplayPlayback", 26 "UnsupportedPlatformError", 27 "free_port", 28 "open_replay", 29 "open_replay_recording", 30 "run_from_command_line", 31 "run_ladder", 32 "run_local", 33 "run_recording", 34 "run_replay", 35]
20class GameLaunchError(NachOSError, OSError): 21 """The client did not start, or died before it began listening."""
The client did not start, or died before it began listening.
64class GameProcess: 65 """A StarCraft II client started by this library, and the temporary directory it was given. 66 67 Use it as a context manager, or call `terminate` when the game is over. A process still running at interpreter 68 exit is terminated. 69 """ 70 71 def __init__(self, process: "subprocess.Popen[bytes]", *, url: str, temp_directory: Path) -> None: 72 """Adopt a running client at `url`, and own `temp_directory` until it is terminated.""" 73 self._process = process 74 self._url = url 75 self._temp_directory = temp_directory 76 atexit.register(self.terminate) 77 78 @classmethod 79 def launch( 80 cls, 81 installation: Installation | None = None, 82 *, 83 host: str = "127.0.0.1", 84 port: int | None = None, 85 base_build: int | None = None, 86 fullscreen: bool = False, 87 window: tuple[int, int] = (1024, 768), 88 window_position: tuple[int, int] | None = None, 89 ) -> Self: 90 """Start a client and return it once it is listening.""" 91 installation = installation or Installation.find() 92 # Resolved before anything is created, so a build that does not exist leaves nothing to clean up. 93 executable = installation.executable(base_build=base_build) 94 port = port or free_port() 95 temp_directory = Path(tempfile.mkdtemp(prefix="sc2nachos-")) 96 command = launch_command( 97 executable, 98 data_directory=installation.base, 99 temp_directory=temp_directory, 100 host=host, 101 port=port, 102 fullscreen=fullscreen, 103 window=window, 104 window_position=window_position, 105 ) 106 logger.info("Starting StarCraft II on port {}", port) 107 try: 108 process = subprocess.Popen(command, cwd=installation.working_directory, stderr=subprocess.DEVNULL) 109 except OSError as error: 110 shutil.rmtree(temp_directory, ignore_errors=True) 111 raise GameLaunchError(f"could not start {command[0]}: {error}") from error 112 113 game = cls(process, url=f"ws://{host}:{port}/sc2api", temp_directory=temp_directory) 114 try: 115 game.wait_until_listening(host=host, port=port) 116 except BaseException: 117 game.terminate() 118 raise 119 return game 120 121 @property 122 def url(self) -> str: 123 """The websocket address the client is listening on.""" 124 return self._url 125 126 @property 127 def is_running(self) -> bool: 128 """Whether the client is still alive.""" 129 return self._process.poll() is None 130 131 def wait_until_listening(self, *, host: str, port: int, timeout: float = 180) -> None: 132 """Block until the client accepts connections. 133 134 Raises `GameLaunchError` if the client exits first or is not listening within `timeout` seconds. 135 """ 136 deadline = time.monotonic() + timeout 137 while time.monotonic() < deadline: 138 if not self.is_running: 139 raise GameLaunchError(f"StarCraft II exited with code {self._process.returncode} before listening") 140 try: 141 with socket.create_connection((host, port), timeout=1): 142 logger.info("StarCraft II is listening on {}", self._url) 143 return 144 except OSError: 145 time.sleep(0.2) 146 raise GameLaunchError(f"StarCraft II did not listen on port {port} within {timeout:.0f} seconds") 147 148 def terminate(self, *, timeout: float = 5) -> None: 149 """Stop the client and remove its temporary directory. Doing this twice is not an error.""" 150 atexit.unregister(self.terminate) 151 if self._process.poll() is None: 152 self._process.terminate() 153 try: 154 self._process.wait(timeout=timeout) 155 except subprocess.TimeoutExpired: 156 logger.warning("StarCraft II ignored the request to stop; killing it") 157 self._process.kill() 158 self._process.wait() 159 shutil.rmtree(self._temp_directory, ignore_errors=True) 160 161 def __enter__(self) -> Self: 162 return self 163 164 def __exit__( 165 self, 166 exception_type: type[BaseException] | None, 167 exception: BaseException | None, 168 traceback: TracebackType | None, 169 ) -> None: 170 self.terminate()
A StarCraft II client started by this library, and the temporary directory it was given.
Use it as a context manager, or call terminate when the game is over. A process still running at interpreter
exit is terminated.
71 def __init__(self, process: "subprocess.Popen[bytes]", *, url: str, temp_directory: Path) -> None: 72 """Adopt a running client at `url`, and own `temp_directory` until it is terminated.""" 73 self._process = process 74 self._url = url 75 self._temp_directory = temp_directory 76 atexit.register(self.terminate)
Adopt a running client at url, and own temp_directory until it is terminated.
78 @classmethod 79 def launch( 80 cls, 81 installation: Installation | None = None, 82 *, 83 host: str = "127.0.0.1", 84 port: int | None = None, 85 base_build: int | None = None, 86 fullscreen: bool = False, 87 window: tuple[int, int] = (1024, 768), 88 window_position: tuple[int, int] | None = None, 89 ) -> Self: 90 """Start a client and return it once it is listening.""" 91 installation = installation or Installation.find() 92 # Resolved before anything is created, so a build that does not exist leaves nothing to clean up. 93 executable = installation.executable(base_build=base_build) 94 port = port or free_port() 95 temp_directory = Path(tempfile.mkdtemp(prefix="sc2nachos-")) 96 command = launch_command( 97 executable, 98 data_directory=installation.base, 99 temp_directory=temp_directory, 100 host=host, 101 port=port, 102 fullscreen=fullscreen, 103 window=window, 104 window_position=window_position, 105 ) 106 logger.info("Starting StarCraft II on port {}", port) 107 try: 108 process = subprocess.Popen(command, cwd=installation.working_directory, stderr=subprocess.DEVNULL) 109 except OSError as error: 110 shutil.rmtree(temp_directory, ignore_errors=True) 111 raise GameLaunchError(f"could not start {command[0]}: {error}") from error 112 113 game = cls(process, url=f"ws://{host}:{port}/sc2api", temp_directory=temp_directory) 114 try: 115 game.wait_until_listening(host=host, port=port) 116 except BaseException: 117 game.terminate() 118 raise 119 return game
Start a client and return it once it is listening.
121 @property 122 def url(self) -> str: 123 """The websocket address the client is listening on.""" 124 return self._url
The websocket address the client is listening on.
126 @property 127 def is_running(self) -> bool: 128 """Whether the client is still alive.""" 129 return self._process.poll() is None
Whether the client is still alive.
131 def wait_until_listening(self, *, host: str, port: int, timeout: float = 180) -> None: 132 """Block until the client accepts connections. 133 134 Raises `GameLaunchError` if the client exits first or is not listening within `timeout` seconds. 135 """ 136 deadline = time.monotonic() + timeout 137 while time.monotonic() < deadline: 138 if not self.is_running: 139 raise GameLaunchError(f"StarCraft II exited with code {self._process.returncode} before listening") 140 try: 141 with socket.create_connection((host, port), timeout=1): 142 logger.info("StarCraft II is listening on {}", self._url) 143 return 144 except OSError: 145 time.sleep(0.2) 146 raise GameLaunchError(f"StarCraft II did not listen on port {port} within {timeout:.0f} seconds")
Block until the client accepts connections.
Raises GameLaunchError if the client exits first or is not listening within timeout seconds.
148 def terminate(self, *, timeout: float = 5) -> None: 149 """Stop the client and remove its temporary directory. Doing this twice is not an error.""" 150 atexit.unregister(self.terminate) 151 if self._process.poll() is None: 152 self._process.terminate() 153 try: 154 self._process.wait(timeout=timeout) 155 except subprocess.TimeoutExpired: 156 logger.warning("StarCraft II ignored the request to stop; killing it") 157 self._process.kill() 158 self._process.wait() 159 shutil.rmtree(self._temp_directory, ignore_errors=True)
Stop the client and remove its temporary directory. Doing this twice is not an error.
30class GameVersionError(NachOSError, LookupError): 31 """The installation holds no version this library can drive."""
The installation holds no version this library can drive.
74@dataclass(frozen=True, slots=True) 75class Installation: 76 """A StarCraft II installation directory, and the things inside it this library needs. 77 78 `system` decides the layout and defaults to the one this process runs on. Wine and WSL are not supported: 79 run the native client for the platform you are on. 80 """ 81 82 base: Path 83 system: str = field(default_factory=platform.system) 84 85 def __post_init__(self) -> None: 86 _settings(self.system) 87 88 @classmethod 89 def find(cls, *, system: str | None = None) -> Self: 90 """Locate the installation: `SC2PATH`, then the launcher's own record of it, then the platform default.""" 91 system = system or platform.system() 92 settings = _settings(system) 93 # An empty SC2PATH is no path at all, and `Path("")` would be the working directory. 94 candidates = (os.environ.get("SC2PATH") or None, cls._from_execute_info(settings), settings.default_base) 95 for candidate in candidates: 96 if candidate is None: 97 continue 98 base = Path(candidate).expanduser() 99 if base.is_dir(): 100 logger.info("Found StarCraft II at {}", base) 101 return cls(base, system) 102 raise InstallationNotFoundError( 103 f"no StarCraft II installation at {settings.default_base}; set SC2PATH to where it is" 104 ) 105 106 def executable(self, *, base_build: int | None = None) -> Path: 107 """The client binary, for `base_build` or for the newest build installed.""" 108 base_build = self.build_to_launch(base_build=base_build) 109 return self.base / _VERSIONS / f"{_BASE_PREFIX}{base_build}" / _settings(self.system).executable 110 111 def build_to_launch(self, *, base_build: int | None = None) -> int: 112 """`base_build`, or the newest build installed. Raises `GameVersionError` for a build not installed or older 113 than the raw interface.""" 114 builds = self.builds() 115 if not builds: 116 raise GameVersionError(f"{self.base / _VERSIONS} holds no {_BASE_PREFIX}<build> directory") 117 if base_build is None: 118 base_build = max(builds) 119 elif base_build not in builds: 120 raise GameVersionError(f"build {base_build} is not installed; {self.base} has {sorted(builds)}") 121 if base_build < MINIMUM_BASE_BUILD: 122 raise GameVersionError( 123 f"build {base_build} predates the raw interface; {MINIMUM_BASE_BUILD} or newer is required" 124 ) 125 return base_build 126 127 def builds(self) -> frozenset[int]: 128 """Every base build installed, by number.""" 129 versions = self.base / _VERSIONS 130 if not versions.is_dir(): 131 return frozenset() 132 return frozenset( 133 int(entry.name[len(_BASE_PREFIX) :]) 134 for entry in versions.iterdir() 135 if entry.is_dir() and re.fullmatch(rf"{_BASE_PREFIX}\d+", entry.name) 136 ) 137 138 @property 139 def working_directory(self) -> Path | None: 140 """The directory the client must be started from, on a platform that demands one.""" 141 directory = _settings(self.system).working_directory 142 return None if directory is None else self.base / directory 143 144 @property 145 def maps(self) -> Path: 146 """The map directory. Blizzard's installers disagree about its capitalization.""" 147 lowercase = self.base / "maps" 148 return lowercase if lowercase.is_dir() else self.base / "Maps" 149 150 @staticmethod 151 def _from_execute_info(settings: _Platform) -> str | None: 152 """The install path the launcher last recorded, where a non-default install shows up.""" 153 if settings.execute_info is None: 154 return None 155 record = Path.home().expanduser() / settings.execute_info 156 if not record.is_file(): 157 return None 158 found = re.search(r" = (.*)Versions", record.read_text(encoding="utf-8", errors="replace")) 159 if found is None: 160 return None 161 # The capture ends at the separator before `Versions`, and only the host's own separator counts as one. 162 return found.group(1).rstrip("\\/")
A StarCraft II installation directory, and the things inside it this library needs.
system decides the layout and defaults to the one this process runs on. Wine and WSL are not supported:
run the native client for the platform you are on.
88 @classmethod 89 def find(cls, *, system: str | None = None) -> Self: 90 """Locate the installation: `SC2PATH`, then the launcher's own record of it, then the platform default.""" 91 system = system or platform.system() 92 settings = _settings(system) 93 # An empty SC2PATH is no path at all, and `Path("")` would be the working directory. 94 candidates = (os.environ.get("SC2PATH") or None, cls._from_execute_info(settings), settings.default_base) 95 for candidate in candidates: 96 if candidate is None: 97 continue 98 base = Path(candidate).expanduser() 99 if base.is_dir(): 100 logger.info("Found StarCraft II at {}", base) 101 return cls(base, system) 102 raise InstallationNotFoundError( 103 f"no StarCraft II installation at {settings.default_base}; set SC2PATH to where it is" 104 )
Locate the installation: SC2PATH, then the launcher's own record of it, then the platform default.
106 def executable(self, *, base_build: int | None = None) -> Path: 107 """The client binary, for `base_build` or for the newest build installed.""" 108 base_build = self.build_to_launch(base_build=base_build) 109 return self.base / _VERSIONS / f"{_BASE_PREFIX}{base_build}" / _settings(self.system).executable
The client binary, for base_build or for the newest build installed.
111 def build_to_launch(self, *, base_build: int | None = None) -> int: 112 """`base_build`, or the newest build installed. Raises `GameVersionError` for a build not installed or older 113 than the raw interface.""" 114 builds = self.builds() 115 if not builds: 116 raise GameVersionError(f"{self.base / _VERSIONS} holds no {_BASE_PREFIX}<build> directory") 117 if base_build is None: 118 base_build = max(builds) 119 elif base_build not in builds: 120 raise GameVersionError(f"build {base_build} is not installed; {self.base} has {sorted(builds)}") 121 if base_build < MINIMUM_BASE_BUILD: 122 raise GameVersionError( 123 f"build {base_build} predates the raw interface; {MINIMUM_BASE_BUILD} or newer is required" 124 ) 125 return base_build
base_build, or the newest build installed. Raises GameVersionError for a build not installed or older
than the raw interface.
127 def builds(self) -> frozenset[int]: 128 """Every base build installed, by number.""" 129 versions = self.base / _VERSIONS 130 if not versions.is_dir(): 131 return frozenset() 132 return frozenset( 133 int(entry.name[len(_BASE_PREFIX) :]) 134 for entry in versions.iterdir() 135 if entry.is_dir() and re.fullmatch(rf"{_BASE_PREFIX}\d+", entry.name) 136 )
Every base build installed, by number.
138 @property 139 def working_directory(self) -> Path | None: 140 """The directory the client must be started from, on a platform that demands one.""" 141 directory = _settings(self.system).working_directory 142 return None if directory is None else self.base / directory
The directory the client must be started from, on a platform that demands one.
144 @property 145 def maps(self) -> Path: 146 """The map directory. Blizzard's installers disagree about its capitalization.""" 147 lowercase = self.base / "maps" 148 return lowercase if lowercase.is_dir() else self.base / "Maps"
The map directory. Blizzard's installers disagree about its capitalization.
26class InstallationNotFoundError(NachOSError, FileNotFoundError): 27 """StarCraft II is not installed where this platform keeps it, and `SC2PATH` does not say otherwise."""
StarCraft II is not installed where this platform keeps it, and SC2PATH does not say otherwise.
21@dataclass(frozen=True, slots=True) 22class MapFile: 23 """A map file the game can load. 24 25 Construct one directly to play a map that lives outside the installation. 26 """ 27 28 path: Path 29 30 @property 31 def name(self) -> str: 32 """The file name without its extension, which is the name the map is known by.""" 33 return self.path.stem 34 35 @classmethod 36 def find(cls, name: str, *, installation: Installation | None = None) -> Self: 37 """The map called `name`, anywhere under the installation's map directory, linked directories included. 38 39 The extension `.SC2Map` is optional, and the name and extension match exactly, case included, on every 40 platform. Map packs install alongside the maps they replace, so a name can match more than once: the shallowest 41 match wins, ties alphabetically. 42 """ 43 installation = installation or Installation.find() 44 wanted = name.removesuffix(_SUFFIX) 45 matches = sorted( 46 (path for path in cls._paths(installation) if path.stem == wanted), 47 key=lambda path: (len(path.parts), path), 48 ) 49 if not matches: 50 raise MapNotFoundError( 51 f"{installation.maps} holds no map called {wanted}; it has {cls._names(installation)}" 52 ) 53 if len(matches) > 1: 54 logger.debug("{} maps are called {}; playing {}", len(matches), wanted, matches[0]) 55 return cls(matches[0]) 56 57 @staticmethod 58 def _names(installation: Installation) -> list[str]: 59 return sorted({path.stem for path in MapFile._paths(installation)}) 60 61 @staticmethod 62 def _paths(installation: Installation) -> Iterator[Path]: 63 maps = installation.maps 64 for directory, subdirectories, files in maps.walk(follow_symlinks=True): 65 # A linked directory that leads back into one the walk is inside is not entered, or the walk would go 66 # round it. 67 inside = {path.resolve() for path in (directory, *directory.parents) if path.is_relative_to(maps)} 68 subdirectories[:] = [name for name in subdirectories if (directory / name).resolve() not in inside] 69 yield from (directory / name for name in files if name.endswith(_SUFFIX))
A map file the game can load.
Construct one directly to play a map that lives outside the installation.
30 @property 31 def name(self) -> str: 32 """The file name without its extension, which is the name the map is known by.""" 33 return self.path.stem
The file name without its extension, which is the name the map is known by.
35 @classmethod 36 def find(cls, name: str, *, installation: Installation | None = None) -> Self: 37 """The map called `name`, anywhere under the installation's map directory, linked directories included. 38 39 The extension `.SC2Map` is optional, and the name and extension match exactly, case included, on every 40 platform. Map packs install alongside the maps they replace, so a name can match more than once: the shallowest 41 match wins, ties alphabetically. 42 """ 43 installation = installation or Installation.find() 44 wanted = name.removesuffix(_SUFFIX) 45 matches = sorted( 46 (path for path in cls._paths(installation) if path.stem == wanted), 47 key=lambda path: (len(path.parts), path), 48 ) 49 if not matches: 50 raise MapNotFoundError( 51 f"{installation.maps} holds no map called {wanted}; it has {cls._names(installation)}" 52 ) 53 if len(matches) > 1: 54 logger.debug("{} maps are called {}; playing {}", len(matches), wanted, matches[0]) 55 return cls(matches[0])
The map called name, anywhere under the installation's map directory, linked directories included.
The extension .SC2Map is optional, and the name and extension match exactly, case included, on every
platform. Map packs install alongside the maps they replace, so a name can match more than once: the shallowest
match wins, ties alphabetically.
17class MapNotFoundError(NachOSError, LookupError): 18 """The installation holds no map by the name asked for."""
The installation holds no map by the name asked for.
65@final 66@dataclass(frozen=True, slots=True) 67class ReplayPlayback: 68 """A replay being played back, on a game client or from a recording, for its observations to be read straight from 69 the protocol.""" 70 71 client: Client 72 """The connection, in the replay at its start, before its first observation. It answers what the game answers in a 73 game, observations, steps, the game's info and data among them, as the player played for saw the game, and refuses 74 every action and debug command (in game).""" 75 info: sc2api_pb2.ResponseReplayInfo 76 """What the game read from the replay: its map, its length, the build it was played on and its players."""
A replay being played back, on a game client or from a recording, for its observations to be read straight from the protocol.
The connection, in the replay at its start, before its first observation. It answers what the game answers in a game, observations, steps, the game's info and data among them, as the player played for saw the game, and refuses every action and debug command (in game).
22class UnsupportedPlatformError(NachOSError, ValueError): 23 """StarCraft II does not run on the platform asked for."""
StarCraft II does not run on the platform asked for.
24def free_port() -> int: 25 """A port nothing is listening on, for the client to take.""" 26 with socket.socket() as probe: 27 probe.bind(("127.0.0.1", 0)) 28 port = probe.getsockname()[1] 29 return int(port)
A port nothing is listening on, for the client to take.
79@contextmanager 80def open_replay( 81 replay: Path | str, 82 *, 83 player_id: int, 84 disable_fog: bool = False, 85 record_to: Path | str | None = None, 86 installation: Installation | None = None, 87 window: tuple[int, int] = (1024, 768), 88) -> Iterator[ReplayPlayback]: 89 """Start a game client, play back the replay in the file `replay` on it as the player `player_id` saw it, and give 90 the playback, for its observations to be read straight from the protocol. `run_replay` plays one for an api. 91 92 Raises `ValueError` for a `player_id` that is not one of the replay's players, as 0 is not. The replay is played 93 on its own build, which must be installed, or `GameVersionError` is raised: the newest build installed reads which 94 it is, and a second client is started when that is not the one. The game opens the replay's map by the path the 95 replay names, which an AI Arena replay gives as a bare file name the game does not find (in game); so unless the 96 path is an absolute path to a file here, the map it names under the installation's maps goes with the replay, or 97 else the map of its name there. The game reports the raw interface, with cloaked units, burrowed units' shadows 98 and the placeholders of structures ordered shown, on the whole map. `disable_fog` lists every unit, as 99 `Client.start_replay` says. 100 101 `record_to` is a file to record the whole conversation into, the replay's info included, which 102 `open_replay_recording` and `run_recording` play back; it is complete once the playback ends. However the 103 playback ends, the client leaves the replay and is stopped, and its temporary directory removed. Each playback 104 starts a client of its own, so two can be open at once, one for each player. 105 """ 106 check_output_files(record_to, None) 107 replay_data = Path(replay).read_bytes() 108 installation = installation or Installation.find() 109 newest_build = installation.build_to_launch() 110 with ExitStack() as running: 111 game = running.enter_context(GameProcess.launch(installation, base_build=newest_build, window=window)) 112 with closing(Client(WebSocketTransport.connect(game.url))) as info_client: 113 info_on_the_newest_build = info_client.replay_info(replay_data) 114 _check_replay_player(info_on_the_newest_build, player_id) 115 if info_on_the_newest_build.base_build != newest_build: 116 replay_build = installation.build_to_launch(base_build=info_on_the_newest_build.base_build) 117 game.terminate() 118 game = running.enter_context(GameProcess.launch(installation, base_build=replay_build, window=window)) 119 map_data = _map_bytes_the_game_needs(info_on_the_newest_build.local_map_path, installation) 120 with closing(connect_client(game.url, record_to)) as client: 121 try: 122 # Asked again on the connection recorded, so that a recording holds it. 123 info = client.replay_info(replay_data) 124 client.start_replay(replay_data, player_id=player_id, disable_fog=disable_fog, map_data=map_data) 125 yield ReplayPlayback(client, info) 126 finally: 127 client.leave_game() 128 client.quit()
Start a game client, play back the replay in the file replay on it as the player player_id saw it, and give
the playback, for its observations to be read straight from the protocol. run_replay plays one for an api.
Raises ValueError for a player_id that is not one of the replay's players, as 0 is not. The replay is played
on its own build, which must be installed, or GameVersionError is raised: the newest build installed reads which
it is, and a second client is started when that is not the one. The game opens the replay's map by the path the
replay names, which an AI Arena replay gives as a bare file name the game does not find (in game); so unless the
path is an absolute path to a file here, the map it names under the installation's maps goes with the replay, or
else the map of its name there. The game reports the raw interface, with cloaked units, burrowed units' shadows
and the placeholders of structures ordered shown, on the whole map. disable_fog lists every unit, as
Client.start_replay says.
record_to is a file to record the whole conversation into, the replay's info included, which
open_replay_recording and run_recording play back; it is complete once the playback ends. However the
playback ends, the client leaves the replay and is stopped, and its temporary directory removed. Each playback
starts a client of its own, so two can be open at once, one for each player.
131@contextmanager 132def open_replay_recording(recording: Recording | Path | str) -> Iterator[ReplayPlayback]: 133 """Play back `recording`, a recording of a replay played back that `open_replay` or `run_replay` made, with no game 134 client, and give the playback, as `open_replay` gives it. It answers what was asked when it was recorded, in the 135 same order, and raises `ProtocolError` when asked for a request of another kind, as `PlaybackTransport` does. 136 137 Raises `ValueError` for a recording of a game played rather than a replay played back, and for one of a replay 138 made before NachOS recorded a replay's info, which plays back once recorded again. 139 """ 140 if not isinstance(recording, Recording): 141 recording = Recording(Path(recording)) 142 start_replay_request = _start_of_recorded_replay(recording) 143 with closing(Client(PlaybackTransport(recording))) as client: 144 # A recording answers each kind of request in turn without reading it, so the setup is repeated without its 145 # details. 146 info = client.replay_info(start_replay_request.replay_data) 147 client.start_replay( 148 start_replay_request.replay_data, 149 player_id=start_replay_request.observed_player_id, 150 disable_fog=start_replay_request.disable_fog, 151 map_data=start_replay_request.map_data if start_replay_request.HasField("map_data") else None, 152 ) 153 yield ReplayPlayback(client, info)
Play back recording, a recording of a replay played back that open_replay or run_replay made, with no game
client, and give the playback, as open_replay gives it. It answers what was asked when it was recorded, in the
same order, and raises ProtocolError when asked for a request of another kind, as PlaybackTransport does.
Raises ValueError for a recording of a game played rather than a replay played back, and for one of a replay
made before NachOS recorded a replay's info, which plays back once recorded again.
191def run_from_command_line( 192 api: Api[object], 193 argv: Sequence[str] | None = None, 194 *, 195 race: Race, 196 name: str | None = None, 197 steps_per_turn: int = 1, 198) -> Result: 199 """Play one game for `api` as the command line asks, a ladder's or a local one against the built-in computer, 200 playing `race` under `name`, a turn every `steps_per_turn` steps, and write how it went. 201 202 With `--GamePort` it joins the game a ladder has set up, as `run_ladder` does, with the ladder's `--LadderServer` 203 (127.0.0.1 if not given), `--StartPort` and `--OpponentId`, which `Enemy.ladder_id` reads. It takes the ladder's 204 `--ComputerOpponent`, `--ComputerRace` and `--ComputerDifficulty` and uses none of them. A connection the ladder 205 closes before the game ends is logged as a warning, and the game's result is `Result.UNDECIDED`. 206 207 Without it, it plays a local game against the built-in computer, as NachOS's match workflow, 208 `.github/workflows/match.yml`, asks: `--ComputerRace`, `--ComputerDifficulty` and `--ComputerBuild` as member names 209 of `Race`, `Difficulty` and `AIBuild` (`ZERG`, `VERY_EASY`, `RANDOM`; by default `RANDOM`, `VERY_HARD` and 210 `RANDOM`), `--Map`, by default one at random from the installation's, and `--TimeLimit` in game seconds. A value 211 that names no member stops the run, as an argument argparse refuses does. 212 213 In either, `--RealTime` plays the game in real time, `--ReplayFile` is a file to save its replay to, `--RecordFile` 214 one to record the whole conversation with the game into, as `record_to` does, for `run_recording` to play back, and 215 `--ResultFile` one to write the JSON the match workflow reads: the result, the map, as its file's name in a local 216 game and as its display name in a ladder game, and the game time, each of those two `null` if the ladder closed the 217 connection before the game began, and `opponent_actual_race`, the race the opponent played as `Enemy.race` reads at 218 the end, `null` if it was never known. An argument of the other kind of game is logged as ignored, and one NachOS 219 does not read is left for the bot, listed in the log. `argv` defaults to `sys.argv[1:]`. 220 221 Raises `RuntimeError` before anything else if `api` has played its game. 222 """ 223 api._check_has_not_played() 224 command_line_arguments = _CommandLineArguments(argv) 225 command_line_arguments.log_arguments_not_used() 226 if command_line_arguments.is_ladder_game: 227 result, map_name = _play_ladder_game( 228 api, command_line_arguments, race=race, name=name, steps_per_turn=steps_per_turn 229 ) 230 else: 231 result, map_name = _play_local_game( 232 api, command_line_arguments, race=race, name=name, steps_per_turn=steps_per_turn 233 ) 234 if command_line_arguments.result_file is not None: 235 outcome = { 236 "result": result.name, 237 "map": map_name, 238 "game_time": _game_time(api), 239 "opponent_actual_race": _enemy_race_name(api), 240 } 241 command_line_arguments.result_file.write_text(json.dumps(outcome), encoding="utf-8") 242 return result
Play one game for api as the command line asks, a ladder's or a local one against the built-in computer,
playing race under name, a turn every steps_per_turn steps, and write how it went.
With --GamePort it joins the game a ladder has set up, as run_ladder does, with the ladder's --LadderServer
(127.0.0.1 if not given), --StartPort and --OpponentId, which Enemy.ladder_id reads. It takes the ladder's
--ComputerOpponent, --ComputerRace and --ComputerDifficulty and uses none of them. A connection the ladder
closes before the game ends is logged as a warning, and the game's result is Result.UNDECIDED.
Without it, it plays a local game against the built-in computer, as NachOS's match workflow,
.github/workflows/match.yml, asks: --ComputerRace, --ComputerDifficulty and --ComputerBuild as member names
of Race, Difficulty and AIBuild (ZERG, VERY_EASY, RANDOM; by default RANDOM, VERY_HARD and
RANDOM), --Map, by default one at random from the installation's, and --TimeLimit in game seconds. A value
that names no member stops the run, as an argument argparse refuses does.
In either, --RealTime plays the game in real time, --ReplayFile is a file to save its replay to, --RecordFile
one to record the whole conversation with the game into, as record_to does, for run_recording to play back, and
--ResultFile one to write the JSON the match workflow reads: the result, the map, as its file's name in a local
game and as its display name in a ladder game, and the game time, each of those two null if the ladder closed the
connection before the game began, and opponent_actual_race, the race the opponent played as Enemy.race reads at
the end, null if it was never known. An argument of the other kind of game is logged as ignored, and one NachOS
does not read is left for the bot, listed in the log. argv defaults to sys.argv[1:].
Raises RuntimeError before anything else if api has played its game.
92def run_ladder( 93 api: Api[object], 94 *, 95 race: Race, 96 name: str | None = None, 97 host: str, 98 port: int, 99 start_port: int | None = None, 100 enemy_ladder_id: str | None = None, 101 steps_per_turn: int = 1, 102 realtime: bool = False, 103 record_to: Path | str | None = None, 104 save_replay_to: Path | str | None = None, 105) -> Result: 106 """Join the game a ladder has set up for `api`, playing `race` under `name`, and play it out. 107 108 The ladder starts the client, creates the match, and passes the bot the client's address, `start_port` and the 109 opponent's `enemy_ladder_id` on the command line. A game against the built-in computer has no `start_port`. 110 `realtime` must match the ladder's `--RealTime` flag, as `Api.play` says. There is no time limit: a bot can only 111 end a game early by leaving it, which concedes. `record_to` and `save_replay_to` are as for `run_local`. Raises 112 `RuntimeError` before anything else if `api` has played its game. 113 """ 114 api._check_has_not_played() 115 check_output_files(record_to, save_replay_to) 116 with closing(connect_client(f"ws://{host}:{port}/sc2api", record_to)) as client: 117 try: 118 ports = GamePorts.from_start_port(start_port) if start_port is not None else None 119 client.join_game(race, name=name, ports=ports) 120 return api.play( 121 client, 122 steps_per_turn=steps_per_turn, 123 realtime=realtime, 124 enemy_ladder_id=enemy_ladder_id, 125 save_replay_to=save_replay_to, 126 ) 127 finally: 128 # The client is the ladder's, so it is left running. 129 client.leave_game()
Join the game a ladder has set up for api, playing race under name, and play it out.
The ladder starts the client, creates the match, and passes the bot the client's address, start_port and the
opponent's enemy_ladder_id on the command line. A game against the built-in computer has no start_port.
realtime must match the ladder's --RealTime flag, as Api.play says. There is no time limit: a bot can only
end a game early by leaving it, which concedes. record_to and save_replay_to are as for run_local. Raises
RuntimeError before anything else if api has played its game.
34def run_local( 35 map_file: MapFile | str, 36 api: Api[object], 37 opponent: Computer | None = None, 38 *, 39 race: Race, 40 name: str | None = None, 41 steps_per_turn: int = 1, 42 realtime: bool = False, 43 time_limit: GameTime | None = None, 44 random_seed: int | None = None, 45 record_to: Path | str | None = None, 46 save_replay_to: Path | str | None = None, 47 installation: Installation | None = None, 48 window: tuple[int, int] = (1024, 768), 49) -> Result: 50 """Start a game client, create a match on `map_file` for `api` against `opponent`, and play it out. 51 52 `map_file` is a file or the name of one under the installation. The api takes the first slot, playing `race` under 53 `name`, and without an `opponent` it plays the map alone, which on a melee map, such as the ladder's, ends at once 54 in a victory (in game). `realtime` creates the game in real time and plays it so. 55 `record_to` is a file to record the whole conversation into, and `save_replay_to` one to save the game's replay to, 56 as `Api.play` says. Each must be in a folder that exists, or `FileNotFoundError` is raised before the game starts, 57 and `IsADirectoryError` if it names a folder; so is `TypeError` for a `time_limit` that is not a `GameTime`. However 58 the game ends, the client is stopped and its temporary directory removed. The newest build installed is played, with 59 a warning if it is not the one the tech tree was swept on. Raises `RuntimeError` before anything else if `api` has 60 played its game. 61 """ 62 api._check_has_not_played() 63 check_output_files(record_to, save_replay_to) 64 check_time_limit(time_limit) 65 installation = installation or Installation.find() 66 if isinstance(map_file, str): 67 map_file = MapFile.find(map_file, installation=installation) 68 # A participant tells the game a client will fill the slot; who fills it is settled at the join. 69 players: list[PlayerSetup] = [Participant()] if opponent is None else [Participant(), opponent] 70 base_build = installation.build_to_launch() 71 TECH_TREE.warn_if_not_swept_on(base_build) 72 73 with ( 74 GameProcess.launch(installation, base_build=base_build, window=window) as game, 75 closing(connect_client(game.url, record_to)) as client, 76 ): 77 try: 78 client.create_game(map_file.path, players, realtime=realtime, random_seed=random_seed) 79 client.join_game(race, name=name) 80 return api.play( 81 client, 82 steps_per_turn=steps_per_turn, 83 realtime=realtime, 84 time_limit=time_limit, 85 save_replay_to=save_replay_to, 86 ) 87 finally: 88 client.leave_game() 89 client.quit()
Start a game client, create a match on map_file for api against opponent, and play it out.
map_file is a file or the name of one under the installation. The api takes the first slot, playing race under
name, and without an opponent it plays the map alone, which on a melee map, such as the ladder's, ends at once
in a victory (in game). realtime creates the game in real time and plays it so.
record_to is a file to record the whole conversation into, and save_replay_to one to save the game's replay to,
as Api.play says. Each must be in a folder that exists, or FileNotFoundError is raised before the game starts,
and IsADirectoryError if it names a folder; so is TypeError for a time_limit that is not a GameTime. However
the game ends, the client is stopped and its temporary directory removed. The newest build installed is played, with
a warning if it is not the one the tech tree was swept on. Raises RuntimeError before anything else if api has
played its game.
132def run_recording( 133 recording: Recording | Path | str, 134 api: Api[object], 135 *, 136 permissive: bool = False, 137 time_limit: GameTime | None = None, 138 enemy_ladder_id: str | None = None, 139 save_replay_to: Path | str | None = None, 140) -> Result: 141 """Play `api` through the game recorded in `recording`, with no game client, a turn at each recorded observation, 142 and return how it ended for the player recorded, or `TIE` at `time_limit`. `enemy_ladder_id` and `save_replay_to` 143 are as for `Api.play`. 144 145 By default the bot must ask what was asked when the game was recorded, and gets the game's own answers, as a 146 `PlaybackTransport` gives them: a request of another kind raises `ProtocolError`. The game is created if the 147 recording created it, and played in real time if it was, as `Recording.created_its_game` and `played_in_real_time` 148 say. `time_limit`, `enemy_ladder_id` and `save_replay_to` must be what the game was played with: a game its time 149 limit ended raises at its end without it, and so does one the bot left after saving its replay without 150 `save_replay_to`, which then holds the replay recorded. 151 152 With `permissive`, any bot plays the recording through, though nothing it does changes what comes next: what it 153 asks of its own accord is answered as `PermissivePlaybackTransport` makes it up. It returns `UNDECIDED` if the 154 recording stops before the game's end, as one made with a time limit does, and `DEFEAT` if the bot leaves first, 155 and saves no replay, logging a save asked for as failed. A request the recording cannot answer raises 156 `ProtocolError`. 157 158 A replay played back by `run_replay` or `open_replay` is played back again as `open_replay_recording` plays it, as 159 the player it was played for and with the fog as it was, by default only: `permissive` raises `ValueError` for 160 one. 161 162 Raises `RuntimeError` before anything else if `api` has played its game. 163 """ 164 api._check_has_not_played() 165 check_time_limit(time_limit) 166 if not isinstance(recording, Recording): 167 recording = Recording(Path(recording)) 168 if recording.start_replay_request is not None: 169 if permissive: 170 raise ValueError(f"{recording.path} is a replay played back, which plays back only as it was recorded") 171 with open_replay_recording(recording) as playback: 172 return api.play( 173 playback.client, time_limit=time_limit, enemy_ladder_id=enemy_ladder_id, save_replay_to=save_replay_to 174 ) 175 transport: Transport = PermissivePlaybackTransport(recording) if permissive else PlaybackTransport(recording) 176 with closing(Client(transport)) as client: 177 # A recording answers each kind of request in turn without reading it, so the setup is repeated without its 178 # details. A permissive one makes up a create and every step. 179 if permissive or recording.created_its_game: 180 client.create_game("recorded", [Participant(), Computer()]) 181 client.join_game(Race.RANDOM) 182 return api.play( 183 client, 184 realtime=not permissive and recording.played_in_real_time, 185 time_limit=time_limit, 186 enemy_ladder_id=enemy_ladder_id, 187 save_replay_to=save_replay_to, 188 )
Play api through the game recorded in recording, with no game client, a turn at each recorded observation,
and return how it ended for the player recorded, or TIE at time_limit. enemy_ladder_id and save_replay_to
are as for Api.play.
By default the bot must ask what was asked when the game was recorded, and gets the game's own answers, as a
PlaybackTransport gives them: a request of another kind raises ProtocolError. The game is created if the
recording created it, and played in real time if it was, as Recording.created_its_game and played_in_real_time
say. time_limit, enemy_ladder_id and save_replay_to must be what the game was played with: a game its time
limit ended raises at its end without it, and so does one the bot left after saving its replay without
save_replay_to, which then holds the replay recorded.
With permissive, any bot plays the recording through, though nothing it does changes what comes next: what it
asks of its own accord is answered as PermissivePlaybackTransport makes it up. It returns UNDECIDED if the
recording stops before the game's end, as one made with a time limit does, and DEFEAT if the bot leaves first,
and saves no replay, logging a save asked for as failed. A request the recording cannot answer raises
ProtocolError.
A replay played back by run_replay or open_replay is played back again as open_replay_recording plays it, as
the player it was played for and with the fog as it was, by default only: permissive raises ValueError for
one.
Raises RuntimeError before anything else if api has played its game.
25def run_replay( 26 replay: Path | str, 27 api: Api[object], 28 *, 29 player_id: int, 30 disable_fog: bool = False, 31 steps_per_turn: int = 1, 32 time_limit: GameTime | None = None, 33 record_to: Path | str | None = None, 34 installation: Installation | None = None, 35 window: tuple[int, int] = (1024, 768), 36) -> Result: 37 """Start a game client, play back the replay in the file `replay` for `api` as the player `player_id` saw it, a 38 turn every `steps_per_turn` steps, and return how it ended for that player. 39 40 The api sees what that player saw when the game was played (in game): `api.player` is that player, `api.units.own` 41 its units, and each action it took comes as an `OwnActionEvent`. With `disable_fog`, it sees that too, and 42 `api.all_units` holds every unit besides. The game takes no actions or debug commands in a replay, so a turn that 43 orders, chats, draws or moves the camera raises `ProtocolError` once its handlers have run (in game). Leaving the 44 replay, or reaching `time_limit`, stops it `Result.UNDECIDED`. 45 46 The replay is played back as `open_replay` plays it, on its own build and with its map, and refused where that 47 says. `record_to` is a file to record the whole conversation into, as for `run_local`, which `run_recording` plays 48 back. However the replay ends, the client is stopped and its temporary directory removed. Raises `RuntimeError` 49 before anything else if `api` has played its game. 50 """ 51 api._check_has_not_played() 52 check_time_limit(time_limit) 53 with open_replay( 54 replay, 55 player_id=player_id, 56 disable_fog=disable_fog, 57 record_to=record_to, 58 installation=installation, 59 window=window, 60 ) as playback: 61 TECH_TREE.warn_if_not_swept_on(playback.info.base_build) 62 return api.play(playback.client, steps_per_turn=steps_per_turn, time_limit=time_limit)
Start a game client, play back the replay in the file replay for api as the player player_id saw it, a
turn every steps_per_turn steps, and return how it ended for that player.
The api sees what that player saw when the game was played (in game): api.player is that player, api.units.own
its units, and each action it took comes as an OwnActionEvent. With disable_fog, it sees that too, and
api.all_units holds every unit besides. The game takes no actions or debug commands in a replay, so a turn that
orders, chats, draws or moves the camera raises ProtocolError once its handlers have run (in game). Leaving the
replay, or reaching time_limit, stops it Result.UNDECIDED.
The replay is played back as open_replay plays it, on its own build and with its map, and refused where that
says. record_to is a file to record the whole conversation into, as for run_local, which run_recording plays
back. However the replay ends, the client is stopped and its temporary directory removed. Raises RuntimeError
before anything else if api has played its game.