sc2nachos.protocol

Talking to a running game client.

 1"""Talking to a running game client."""
 2
 3from sc2nachos.protocol._client import Client
 4from sc2nachos.protocol._errors import (
 5    ConnectionClosedError,
 6    ConnectionTimeoutError,
 7    GameEndedError,
 8    GameNotStartedError,
 9    ProtocolError,
10)
11from sc2nachos.protocol._permissive_playback_transport import PermissivePlaybackTransport
12from sc2nachos.protocol._ports import GamePorts, PortPair
13from sc2nachos.protocol._recording import Exchange, PlaybackTransport, Recording, RecordingTransport
14from sc2nachos.protocol._status import Status
15from sc2nachos.protocol._transport import Transport
16from sc2nachos.protocol._websocket import WebSocketTransport
17
18__all__ = [
19    "Client",
20    "ConnectionClosedError",
21    "ConnectionTimeoutError",
22    "Exchange",
23    "GameEndedError",
24    "GameNotStartedError",
25    "GamePorts",
26    "PermissivePlaybackTransport",
27    "PortPair",
28    "ProtocolError",
29    "Recording",
30    "RecordingTransport",
31    "PlaybackTransport",
32    "Status",
33    "Transport",
34    "WebSocketTransport",
35]
class Client:
 69class Client:
 70    """A game client, addressed over a transport.
 71
 72    Every method is one request and blocks until the game answers. The protocol carries one request at a time and
 73    matches an answer only to the last question, so nothing can overlap.
 74
 75    One connection can play game after game. What the client keeps of a game, its own player id and how the game
 76    ended, lasts from the join until the game is left or the next one is set up.
 77
 78    Nothing is interpreted here beyond what the protocol demands: the responses are the game's own messages, and
 79    turning them into a data model belongs above.
 80    """
 81
 82    def __init__(self, transport: Transport) -> None:
 83        """Talk to the game over `transport`. Nothing is sent until a request is made."""
 84        self._transport = transport
 85        self._status: Status | None = None
 86        self._player_id: int | None = None
 87        self._fog_disabled = False
 88        self._results: dict[int, Result] = {}
 89
 90    @property
 91    def status(self) -> Status | None:
 92        """The status the game reported in its last answer, or `None` before it has answered at all."""
 93        return self._status
 94
 95    @property
 96    def in_game(self) -> bool:
 97        """Whether a game is running, rather than loading, ended or not yet started. A replay being played back is
 98        one."""
 99        return self._status in (Status.IN_GAME, Status.IN_REPLAY)
100
101    @property
102    def in_replay(self) -> bool:
103        """Whether a replay is being played back, rather than a game played, or nothing running."""
104        return self._status is Status.IN_REPLAY
105
106    @property
107    def fog_disabled(self) -> bool:
108        """Whether the replay being played back was started with the fog off, as `start_replay` says."""
109        return self._fog_disabled
110
111    @property
112    def player_id(self) -> int | None:
113        """This client's player id, once it has joined a game."""
114        return self._player_id
115
116    @property
117    def result(self) -> Result | None:
118        """How the game ended for this client's own player, or `None` until it ends."""
119        if self._player_id is None:
120            return None
121        return self._results.get(self._player_id)
122
123    @property
124    def results(self) -> Mapping[int, Result]:
125        """How the game ended, by player id. Empty until it ends."""
126        return self._results
127
128    def ping(self) -> sc2api_pb2.ResponsePing:
129        """Ask the game for its version. This also proves the connection works."""
130        response = self._send(sc2api_pb2.Request(ping=sc2api_pb2.RequestPing()), "ping")
131        return response.ping
132
133    def create_game(
134        self,
135        map_path: Path | str,
136        players: Sequence[PlayerSetup],
137        *,
138        realtime: bool = False,
139        disable_fog: bool = False,
140        random_seed: int | None = None,
141    ) -> None:
142        """Set up a match on `map_path` for `players`. Each participant then joins it.
143
144        Only the client that creates the game sends this; on a ladder the game already exists. At least one player
145        must be a participant. The game seats only as many players as the map has slots and silently drops the rest.
146        """
147        self._forget_game()
148        request = sc2api_pb2.RequestCreateGame(
149            local_map=sc2api_pb2.LocalMap(map_path=str(map_path)),
150            player_setup=[_player_setup(player) for player in players],
151            realtime=realtime,
152            disable_fog=disable_fog,
153        )
154        if random_seed is not None:
155            request.random_seed = random_seed
156
157        response = self._send(sc2api_pb2.Request(create_game=request), "create_game")
158        created = response.create_game
159        # An unset error field reads as the first error the proto declares, so check that it is set first.
160        if created.HasField("error"):
161            reason = sc2api_pb2.ResponseCreateGame.Error.Name(created.error)
162            detail = created.error_details or "no detail given"
163            raise ProtocolError(f"the game refused to create the match as {reason}: {detail}")
164        logger.info("Created a game on {} for {} players", map_path, len(players))
165
166    def join_game(
167        self,
168        race: Race,
169        *,
170        name: str | None = None,
171        ports: GamePorts | None = None,
172        raw_affects_selection: bool = False,
173    ) -> int:
174        """Join the waiting game as `race` and return the player id the game assigns.
175
176        NachOS plays on the raw interface; the rendered interfaces are never requested.
177        """
178        self._forget_game()
179        request = sc2api_pb2.RequestJoinGame(
180            race=race.value, options=_raw_interface(raw_affects_selection=raw_affects_selection)
181        )
182        if name is not None:
183            request.player_name = name
184        if ports is not None:
185            request.server_ports.game_port = ports.server.game
186            request.server_ports.base_port = ports.server.base
187            for pair in ports.players:
188                request.client_ports.add(game_port=pair.game, base_port=pair.base)
189
190        response = self._send(sc2api_pb2.Request(join_game=request), "join_game")
191        joined = response.join_game
192        # An unset error field reads as the first error the proto declares, so check that it is set first.
193        if joined.HasField("error"):
194            reason = sc2api_pb2.ResponseJoinGame.Error.Name(joined.error)
195            detail = joined.error_details or "no detail given"
196            raise ProtocolError(f"the game refused the join as {reason}: {detail}")
197        self._player_id = joined.player_id
198        logger.info("Joined the game as player {} playing {}", joined.player_id, race)
199        return joined.player_id
200
201    def replay_info(self, replay: bytes) -> sc2api_pb2.ResponseReplayInfo:
202        """What the game reads from `replay`, the bytes of a `.SC2Replay` file: its map, its length, the build it was
203        played on and its players. Raises `ProtocolError` if the game cannot read it."""
204        request = sc2api_pb2.RequestReplayInfo(replay_data=replay)
205        info = self._send(sc2api_pb2.Request(replay_info=request), "replay_info").replay_info
206        # An unset error field reads as the first error the proto declares, so check that it is set first.
207        if info.HasField("error"):
208            reason = sc2api_pb2.ResponseReplayInfo.Error.Name(info.error)
209            detail = info.error_details or "no detail given"
210            raise ProtocolError(f"the game could not read the replay, as {reason}: {detail}")
211        return info
212
213    def start_replay(
214        self, replay: bytes, *, player_id: int, disable_fog: bool = False, map_data: bytes | None = None
215    ) -> None:
216        """Play back `replay`, the bytes of a `.SC2Replay` file, as the player `player_id` saw it, which then stands
217        for the player id a join assigns. With `disable_fog`, the game also lists every unit that player did not see,
218        out of its sight in full but for orders, and one undetected in its sight with its health and the like at 0 (in
219        game). `map_data` is the bytes of the replay's map, for one the game cannot open by the path the replay names.
220
221        The game then answers observations, steps, queries and the rest as in a game, and as that player saw the game
222        when it was played, but refuses every action and debug command (in game). It is played stepped, never in real
223        time.
224        """
225        self._forget_game()
226        request = sc2api_pb2.RequestStartReplay(
227            replay_data=replay,
228            observed_player_id=player_id,
229            options=_raw_interface(raw_affects_selection=False),
230            disable_fog=disable_fog,
231            realtime=False,
232        )
233        if map_data is not None:
234            request.map_data = map_data
235        started = self._send(sc2api_pb2.Request(start_replay=request), "start_replay").start_replay
236        # An unset error field reads as the first error the proto declares, so check that it is set first.
237        if started.HasField("error"):
238            reason = sc2api_pb2.ResponseStartReplay.Error.Name(started.error)
239            detail = started.error_details or "no detail given"
240            raise ProtocolError(f"the game refused to play the replay back, as {reason}: {detail}")
241        self._player_id = player_id
242        self._fog_disabled = disable_fog
243        logger.info("Playing a replay back as player {}{}", player_id, " with the fog off" if disable_fog else "")
244
245    def game_info(self) -> sc2api_pb2.ResponseGameInfo:
246        """The map: its size, terrain, start locations and players."""
247        response = self._send(sc2api_pb2.Request(game_info=sc2api_pb2.RequestGameInfo()), "game_info")
248        return response.game_info
249
250    def game_data(
251        self,
252        *,
253        abilities: bool = True,
254        unit_types: bool = True,
255        upgrades: bool = True,
256        buffs: bool = True,
257        effects: bool = True,
258    ) -> sc2api_pb2.ResponseData:
259        """The tables behind the ids: costs, ranges, requirements and names.
260
261        Unit weapons, armor and movement speed include the upgrades this player holds at the time of asking.
262        """
263        request = sc2api_pb2.RequestData(
264            ability_id=abilities,
265            unit_type_id=unit_types,
266            upgrade_id=upgrades,
267            buff_id=buffs,
268            effect_id=effects,
269        )
270        response = self._send(sc2api_pb2.Request(data=request), "data")
271        return response.data
272
273    def observation(self, *, game_loop: int | None = None) -> sc2api_pb2.ResponseObservation:
274        """What this player can see now, or once the game reaches `game_loop`.
275
276        When the game is over, each player's result is stored in `results`, and kept until the next game, though later
277        observations report none.
278        """
279        observation = self._observe(game_loop)
280        if not observation.player_result:
281            if self.in_game or self._results:
282                return observation
283            # The game reports itself ended one step before it says who won, so ask once more.
284            observation = self._observe(None)
285        # An unset result reads as the first the proto declares, a victory, so only the set ones count.
286        results = {
287            entry.player_id: Result(entry.result) for entry in observation.player_result if entry.HasField("result")
288        }
289        if results:
290            self._results = results
291            logger.info("The game ended: {}", results)
292        return observation
293
294    def step(self, count: int) -> sc2api_pb2.ResponseStep:
295        """Let the game run `count` game loops. Only a stepped game needs this; a realtime one runs on its own."""
296        response = self._send(sc2api_pb2.Request(step=sc2api_pb2.RequestStep(count=count)), "step")
297        return response.step
298
299    def act(self, actions: Sequence[sc2api_pb2.Action]) -> sc2api_pb2.ResponseAction:
300        """Send `actions` and return the game's result for each, in the order they were given."""
301        response = self._send(sc2api_pb2.Request(action=sc2api_pb2.RequestAction(actions=actions)), "action")
302        return response.action
303
304    def debug(self, commands: Sequence[debug_pb2.DebugCommand]) -> None:
305        """Send debug `commands`, which the game answers with nothing to read, from a client that joined the game as
306        from the one that created it (in game).
307
308        A drawing lasts until the next debug request, so one that should stay on screen goes with every request.
309        """
310        self._send(sc2api_pb2.Request(debug=sc2api_pb2.RequestDebug(debug=commands)))
311
312    def query(self, request: query_pb2.RequestQuery) -> query_pb2.ResponseQuery:
313        """Ask the game `request`'s questions, and return its answers, each list in the order asked."""
314        return self._send(sc2api_pb2.Request(query=request), "query").query
315
316    def save_replay(self) -> bytes:
317        """The replay of the game so far, as the bytes of a `.SC2Replay` file."""
318        response = self._send(sc2api_pb2.Request(save_replay=sc2api_pb2.RequestSaveReplay()), "save_replay")
319        return response.save_replay.data
320
321    def leave_game(self) -> None:
322        """Leave the game, conceding it if it has not already ended, and return the client to `launched`.
323
324        Leaving when there is no game, or no connection left, is not an error.
325        """
326        with suppress(GameNotStartedError, GameEndedError, ConnectionClosedError):
327            self._send(sc2api_pb2.Request(leave_game=sc2api_pb2.RequestLeaveGame()))
328        self._forget_game()
329
330    def quit(self) -> None:
331        """Ask the game client to exit. A connection already gone is not an error here."""
332        with suppress(ConnectionClosedError):
333            self._send(sc2api_pb2.Request(quit=sc2api_pb2.RequestQuit()))
334
335    def close(self) -> None:
336        """Release the transport."""
337        self._transport.close()
338
339    def _forget_game(self) -> None:
340        """Drop what the client kept of the last game, so none of it carries over to the next."""
341        self._player_id = None
342        self._fog_disabled = False
343        self._results = {}
344
345    def _observe(self, game_loop: int | None) -> sc2api_pb2.ResponseObservation:
346        request = sc2api_pb2.RequestObservation()
347        if game_loop is not None:
348            request.game_loop = game_loop
349        response = self._send(sc2api_pb2.Request(observation=request), "observation")
350        return response.observation
351
352    def _send(self, request: sc2api_pb2.Request, answer: _Answer | None = None) -> sc2api_pb2.Response:
353        """Send `request` and return the response, checking that it holds `answer` and that the game did not refuse
354        it. What the game says beside the answer asked for is a warning, which is logged."""
355        response = self._transport.request(request)
356        # An unset status field reads as `launched`, the first value the proto declares, so check that it is set.
357        if response.HasField("status"):
358            status = Status(response.status)
359            if status is not self._status:
360                logger.info("The game client is now {}", status)
361                self._status = status
362        if response.error:
363            errors = list(response.error)
364            if _GAME_OVER_ERRORS.intersection(errors):
365                raise GameEndedError(f"the game is over: {'; '.join(errors)}")
366            if _NOT_STARTED_ERRORS.intersection(errors):
367                raise GameNotStartedError(f"no game has started: {'; '.join(errors)}")
368            # With the answer there, the proto calls these warnings; without it, the reason there is none.
369            if answer is None or not response.HasField(answer):
370                raise ProtocolError(f"the game refused the request: {'; '.join(errors)}")
371            logger.warning("The game answered {} with warnings: {}", answer, "; ".join(errors))
372        if answer is not None and not response.HasField(answer):
373            asked = response.WhichOneof("response") or "nothing"
374            raise ProtocolError(f"the game was asked for {answer} and answered {asked}")
375        return response

A game client, addressed over a transport.

Every method is one request and blocks until the game answers. The protocol carries one request at a time and matches an answer only to the last question, so nothing can overlap.

One connection can play game after game. What the client keeps of a game, its own player id and how the game ended, lasts from the join until the game is left or the next one is set up.

Nothing is interpreted here beyond what the protocol demands: the responses are the game's own messages, and turning them into a data model belongs above.

Client(transport: Transport)
82    def __init__(self, transport: Transport) -> None:
83        """Talk to the game over `transport`. Nothing is sent until a request is made."""
84        self._transport = transport
85        self._status: Status | None = None
86        self._player_id: int | None = None
87        self._fog_disabled = False
88        self._results: dict[int, Result] = {}

Talk to the game over transport. Nothing is sent until a request is made.

status: Status | None
90    @property
91    def status(self) -> Status | None:
92        """The status the game reported in its last answer, or `None` before it has answered at all."""
93        return self._status

The status the game reported in its last answer, or None before it has answered at all.

in_game: bool
95    @property
96    def in_game(self) -> bool:
97        """Whether a game is running, rather than loading, ended or not yet started. A replay being played back is
98        one."""
99        return self._status in (Status.IN_GAME, Status.IN_REPLAY)

Whether a game is running, rather than loading, ended or not yet started. A replay being played back is one.

in_replay: bool
101    @property
102    def in_replay(self) -> bool:
103        """Whether a replay is being played back, rather than a game played, or nothing running."""
104        return self._status is Status.IN_REPLAY

Whether a replay is being played back, rather than a game played, or nothing running.

fog_disabled: bool
106    @property
107    def fog_disabled(self) -> bool:
108        """Whether the replay being played back was started with the fog off, as `start_replay` says."""
109        return self._fog_disabled

Whether the replay being played back was started with the fog off, as start_replay says.

player_id: int | None
111    @property
112    def player_id(self) -> int | None:
113        """This client's player id, once it has joined a game."""
114        return self._player_id

This client's player id, once it has joined a game.

result: sc2nachos.Result | None
116    @property
117    def result(self) -> Result | None:
118        """How the game ended for this client's own player, or `None` until it ends."""
119        if self._player_id is None:
120            return None
121        return self._results.get(self._player_id)

How the game ended for this client's own player, or None until it ends.

results: Mapping[int, sc2nachos.Result]
123    @property
124    def results(self) -> Mapping[int, Result]:
125        """How the game ended, by player id. Empty until it ends."""
126        return self._results

How the game ended, by player id. Empty until it ends.

def ping(self) -> s2clientprotocol.sc2api_pb2.ResponsePing:
128    def ping(self) -> sc2api_pb2.ResponsePing:
129        """Ask the game for its version. This also proves the connection works."""
130        response = self._send(sc2api_pb2.Request(ping=sc2api_pb2.RequestPing()), "ping")
131        return response.ping

Ask the game for its version. This also proves the connection works.

def create_game( self, map_path: pathlib.Path | str, players: Sequence[PlayerSetup], *, realtime: bool = False, disable_fog: bool = False, random_seed: int | None = None) -> None:
133    def create_game(
134        self,
135        map_path: Path | str,
136        players: Sequence[PlayerSetup],
137        *,
138        realtime: bool = False,
139        disable_fog: bool = False,
140        random_seed: int | None = None,
141    ) -> None:
142        """Set up a match on `map_path` for `players`. Each participant then joins it.
143
144        Only the client that creates the game sends this; on a ladder the game already exists. At least one player
145        must be a participant. The game seats only as many players as the map has slots and silently drops the rest.
146        """
147        self._forget_game()
148        request = sc2api_pb2.RequestCreateGame(
149            local_map=sc2api_pb2.LocalMap(map_path=str(map_path)),
150            player_setup=[_player_setup(player) for player in players],
151            realtime=realtime,
152            disable_fog=disable_fog,
153        )
154        if random_seed is not None:
155            request.random_seed = random_seed
156
157        response = self._send(sc2api_pb2.Request(create_game=request), "create_game")
158        created = response.create_game
159        # An unset error field reads as the first error the proto declares, so check that it is set first.
160        if created.HasField("error"):
161            reason = sc2api_pb2.ResponseCreateGame.Error.Name(created.error)
162            detail = created.error_details or "no detail given"
163            raise ProtocolError(f"the game refused to create the match as {reason}: {detail}")
164        logger.info("Created a game on {} for {} players", map_path, len(players))

Set up a match on map_path for players. Each participant then joins it.

Only the client that creates the game sends this; on a ladder the game already exists. At least one player must be a participant. The game seats only as many players as the map has slots and silently drops the rest.

def join_game( self, race: sc2nachos.Race, *, name: str | None = None, ports: GamePorts | None = None, raw_affects_selection: bool = False) -> int:
166    def join_game(
167        self,
168        race: Race,
169        *,
170        name: str | None = None,
171        ports: GamePorts | None = None,
172        raw_affects_selection: bool = False,
173    ) -> int:
174        """Join the waiting game as `race` and return the player id the game assigns.
175
176        NachOS plays on the raw interface; the rendered interfaces are never requested.
177        """
178        self._forget_game()
179        request = sc2api_pb2.RequestJoinGame(
180            race=race.value, options=_raw_interface(raw_affects_selection=raw_affects_selection)
181        )
182        if name is not None:
183            request.player_name = name
184        if ports is not None:
185            request.server_ports.game_port = ports.server.game
186            request.server_ports.base_port = ports.server.base
187            for pair in ports.players:
188                request.client_ports.add(game_port=pair.game, base_port=pair.base)
189
190        response = self._send(sc2api_pb2.Request(join_game=request), "join_game")
191        joined = response.join_game
192        # An unset error field reads as the first error the proto declares, so check that it is set first.
193        if joined.HasField("error"):
194            reason = sc2api_pb2.ResponseJoinGame.Error.Name(joined.error)
195            detail = joined.error_details or "no detail given"
196            raise ProtocolError(f"the game refused the join as {reason}: {detail}")
197        self._player_id = joined.player_id
198        logger.info("Joined the game as player {} playing {}", joined.player_id, race)
199        return joined.player_id

Join the waiting game as race and return the player id the game assigns.

NachOS plays on the raw interface; the rendered interfaces are never requested.

def replay_info(self, replay: bytes) -> s2clientprotocol.sc2api_pb2.ResponseReplayInfo:
201    def replay_info(self, replay: bytes) -> sc2api_pb2.ResponseReplayInfo:
202        """What the game reads from `replay`, the bytes of a `.SC2Replay` file: its map, its length, the build it was
203        played on and its players. Raises `ProtocolError` if the game cannot read it."""
204        request = sc2api_pb2.RequestReplayInfo(replay_data=replay)
205        info = self._send(sc2api_pb2.Request(replay_info=request), "replay_info").replay_info
206        # An unset error field reads as the first error the proto declares, so check that it is set first.
207        if info.HasField("error"):
208            reason = sc2api_pb2.ResponseReplayInfo.Error.Name(info.error)
209            detail = info.error_details or "no detail given"
210            raise ProtocolError(f"the game could not read the replay, as {reason}: {detail}")
211        return info

What the game reads from replay, the bytes of a .SC2Replay file: its map, its length, the build it was played on and its players. Raises ProtocolError if the game cannot read it.

def start_replay( self, replay: bytes, *, player_id: int, disable_fog: bool = False, map_data: bytes | None = None) -> None:
213    def start_replay(
214        self, replay: bytes, *, player_id: int, disable_fog: bool = False, map_data: bytes | None = None
215    ) -> None:
216        """Play back `replay`, the bytes of a `.SC2Replay` file, as the player `player_id` saw it, which then stands
217        for the player id a join assigns. With `disable_fog`, the game also lists every unit that player did not see,
218        out of its sight in full but for orders, and one undetected in its sight with its health and the like at 0 (in
219        game). `map_data` is the bytes of the replay's map, for one the game cannot open by the path the replay names.
220
221        The game then answers observations, steps, queries and the rest as in a game, and as that player saw the game
222        when it was played, but refuses every action and debug command (in game). It is played stepped, never in real
223        time.
224        """
225        self._forget_game()
226        request = sc2api_pb2.RequestStartReplay(
227            replay_data=replay,
228            observed_player_id=player_id,
229            options=_raw_interface(raw_affects_selection=False),
230            disable_fog=disable_fog,
231            realtime=False,
232        )
233        if map_data is not None:
234            request.map_data = map_data
235        started = self._send(sc2api_pb2.Request(start_replay=request), "start_replay").start_replay
236        # An unset error field reads as the first error the proto declares, so check that it is set first.
237        if started.HasField("error"):
238            reason = sc2api_pb2.ResponseStartReplay.Error.Name(started.error)
239            detail = started.error_details or "no detail given"
240            raise ProtocolError(f"the game refused to play the replay back, as {reason}: {detail}")
241        self._player_id = player_id
242        self._fog_disabled = disable_fog
243        logger.info("Playing a replay back as player {}{}", player_id, " with the fog off" if disable_fog else "")

Play back replay, the bytes of a .SC2Replay file, as the player player_id saw it, which then stands for the player id a join assigns. With disable_fog, the game also lists every unit that player did not see, out of its sight in full but for orders, and one undetected in its sight with its health and the like at 0 (in game). map_data is the bytes of the replay's map, for one the game cannot open by the path the replay names.

The game then answers observations, steps, queries and the rest as in a game, and as that player saw the game when it was played, but refuses every action and debug command (in game). It is played stepped, never in real time.

def game_info(self) -> s2clientprotocol.sc2api_pb2.ResponseGameInfo:
245    def game_info(self) -> sc2api_pb2.ResponseGameInfo:
246        """The map: its size, terrain, start locations and players."""
247        response = self._send(sc2api_pb2.Request(game_info=sc2api_pb2.RequestGameInfo()), "game_info")
248        return response.game_info

The map: its size, terrain, start locations and players.

def game_data( self, *, abilities: bool = True, unit_types: bool = True, upgrades: bool = True, buffs: bool = True, effects: bool = True) -> s2clientprotocol.sc2api_pb2.ResponseData:
250    def game_data(
251        self,
252        *,
253        abilities: bool = True,
254        unit_types: bool = True,
255        upgrades: bool = True,
256        buffs: bool = True,
257        effects: bool = True,
258    ) -> sc2api_pb2.ResponseData:
259        """The tables behind the ids: costs, ranges, requirements and names.
260
261        Unit weapons, armor and movement speed include the upgrades this player holds at the time of asking.
262        """
263        request = sc2api_pb2.RequestData(
264            ability_id=abilities,
265            unit_type_id=unit_types,
266            upgrade_id=upgrades,
267            buff_id=buffs,
268            effect_id=effects,
269        )
270        response = self._send(sc2api_pb2.Request(data=request), "data")
271        return response.data

The tables behind the ids: costs, ranges, requirements and names.

Unit weapons, armor and movement speed include the upgrades this player holds at the time of asking.

def observation( self, *, game_loop: int | None = None) -> s2clientprotocol.sc2api_pb2.ResponseObservation:
273    def observation(self, *, game_loop: int | None = None) -> sc2api_pb2.ResponseObservation:
274        """What this player can see now, or once the game reaches `game_loop`.
275
276        When the game is over, each player's result is stored in `results`, and kept until the next game, though later
277        observations report none.
278        """
279        observation = self._observe(game_loop)
280        if not observation.player_result:
281            if self.in_game or self._results:
282                return observation
283            # The game reports itself ended one step before it says who won, so ask once more.
284            observation = self._observe(None)
285        # An unset result reads as the first the proto declares, a victory, so only the set ones count.
286        results = {
287            entry.player_id: Result(entry.result) for entry in observation.player_result if entry.HasField("result")
288        }
289        if results:
290            self._results = results
291            logger.info("The game ended: {}", results)
292        return observation

What this player can see now, or once the game reaches game_loop.

When the game is over, each player's result is stored in results, and kept until the next game, though later observations report none.

def step(self, count: int) -> s2clientprotocol.sc2api_pb2.ResponseStep:
294    def step(self, count: int) -> sc2api_pb2.ResponseStep:
295        """Let the game run `count` game loops. Only a stepped game needs this; a realtime one runs on its own."""
296        response = self._send(sc2api_pb2.Request(step=sc2api_pb2.RequestStep(count=count)), "step")
297        return response.step

Let the game run count game loops. Only a stepped game needs this; a realtime one runs on its own.

def act( self, actions: Sequence[s2clientprotocol.sc2api_pb2.Action]) -> s2clientprotocol.sc2api_pb2.ResponseAction:
299    def act(self, actions: Sequence[sc2api_pb2.Action]) -> sc2api_pb2.ResponseAction:
300        """Send `actions` and return the game's result for each, in the order they were given."""
301        response = self._send(sc2api_pb2.Request(action=sc2api_pb2.RequestAction(actions=actions)), "action")
302        return response.action

Send actions and return the game's result for each, in the order they were given.

def debug( self, commands: Sequence[s2clientprotocol.debug_pb2.DebugCommand]) -> None:
304    def debug(self, commands: Sequence[debug_pb2.DebugCommand]) -> None:
305        """Send debug `commands`, which the game answers with nothing to read, from a client that joined the game as
306        from the one that created it (in game).
307
308        A drawing lasts until the next debug request, so one that should stay on screen goes with every request.
309        """
310        self._send(sc2api_pb2.Request(debug=sc2api_pb2.RequestDebug(debug=commands)))

Send debug commands, which the game answers with nothing to read, from a client that joined the game as from the one that created it (in game).

A drawing lasts until the next debug request, so one that should stay on screen goes with every request.

def query( self, request: s2clientprotocol.query_pb2.RequestQuery) -> s2clientprotocol.query_pb2.ResponseQuery:
312    def query(self, request: query_pb2.RequestQuery) -> query_pb2.ResponseQuery:
313        """Ask the game `request`'s questions, and return its answers, each list in the order asked."""
314        return self._send(sc2api_pb2.Request(query=request), "query").query

Ask the game request's questions, and return its answers, each list in the order asked.

def save_replay(self) -> bytes:
316    def save_replay(self) -> bytes:
317        """The replay of the game so far, as the bytes of a `.SC2Replay` file."""
318        response = self._send(sc2api_pb2.Request(save_replay=sc2api_pb2.RequestSaveReplay()), "save_replay")
319        return response.save_replay.data

The replay of the game so far, as the bytes of a .SC2Replay file.

def leave_game(self) -> None:
321    def leave_game(self) -> None:
322        """Leave the game, conceding it if it has not already ended, and return the client to `launched`.
323
324        Leaving when there is no game, or no connection left, is not an error.
325        """
326        with suppress(GameNotStartedError, GameEndedError, ConnectionClosedError):
327            self._send(sc2api_pb2.Request(leave_game=sc2api_pb2.RequestLeaveGame()))
328        self._forget_game()

Leave the game, conceding it if it has not already ended, and return the client to launched.

Leaving when there is no game, or no connection left, is not an error.

def quit(self) -> None:
330    def quit(self) -> None:
331        """Ask the game client to exit. A connection already gone is not an error here."""
332        with suppress(ConnectionClosedError):
333            self._send(sc2api_pb2.Request(quit=sc2api_pb2.RequestQuit()))

Ask the game client to exit. A connection already gone is not an error here.

def close(self) -> None:
335    def close(self) -> None:
336        """Release the transport."""
337        self._transport.close()

Release the transport.

class ConnectionClosedError(sc2nachos.protocol.ProtocolError, builtins.ConnectionError):
20class ConnectionClosedError(ProtocolError, ConnectionError):
21    """The connection to the game is gone, so the request could not be answered."""

The connection to the game is gone, so the request could not be answered.

class ConnectionTimeoutError(sc2nachos.protocol.ProtocolError, builtins.TimeoutError):
24class ConnectionTimeoutError(ProtocolError, TimeoutError):
25    """The game did not answer within the transport's timeout."""

The game did not answer within the transport's timeout.

@dataclass(frozen=True, slots=True)
class Exchange:
27@dataclass(frozen=True, slots=True)
28class Exchange:
29    """One request to the game, and its answer."""
30
31    request: sc2api_pb2.Request
32    response: sc2api_pb2.Response

One request to the game, and its answer.

Exchange( request: s2clientprotocol.sc2api_pb2.Request, response: s2clientprotocol.sc2api_pb2.Response)
request: s2clientprotocol.sc2api_pb2.Request
response: s2clientprotocol.sc2api_pb2.Response
class GameEndedError(sc2nachos.protocol.ProtocolError):
12class GameEndedError(ProtocolError):
13    """The request needs a game in progress, and this one is over."""

The request needs a game in progress, and this one is over.

class GameNotStartedError(sc2nachos.protocol.ProtocolError):
16class GameNotStartedError(ProtocolError):
17    """The request needs a game in progress, and none has been started."""

The request needs a game in progress, and none has been started.

@dataclass(frozen=True, slots=True)
class GamePorts:
19@dataclass(frozen=True, slots=True)
20class GamePorts:
21    """The ports every participant in a multiplayer game must agree on: one pair for the host, and one for each
22    guest."""
23
24    server: PortPair
25    players: tuple[PortPair, ...]
26
27    @classmethod
28    def from_start_port(cls, start_port: int) -> Self:
29        """The ladder's layout from `start_port` N: the server on N+2 and N+3, and the one guest on N+4 and N+5."""
30        return cls(
31            server=PortPair(start_port + 2, start_port + 3),
32            players=(PortPair(start_port + 4, start_port + 5),),
33        )

The ports every participant in a multiplayer game must agree on: one pair for the host, and one for each guest.

GamePorts( server: PortPair, players: tuple[PortPair, ...])
server: PortPair
players: tuple[PortPair, ...]
@classmethod
def from_start_port(cls, start_port: int) -> Self:
27    @classmethod
28    def from_start_port(cls, start_port: int) -> Self:
29        """The ladder's layout from `start_port` N: the server on N+2 and N+3, and the one guest on N+4 and N+5."""
30        return cls(
31            server=PortPair(start_port + 2, start_port + 3),
32            players=(PortPair(start_port + 4, start_port + 5),),
33        )

The ladder's layout from start_port N: the server on N+2 and N+3, and the one guest on N+4 and N+5.

class PermissivePlaybackTransport:
 23class PermissivePlaybackTransport:
 24    """A `Transport` that plays a recording back for a bot other than the one recorded, which can play it through,
 25    though nothing it does changes what comes next. A `PlaybackTransport` answers only what the recording was asked.
 26
 27    A step, and what the bot asks of its own accord, is answered as made up here, under the status of the last recorded
 28    answer, and the recording's own answers to such requests are passed over:
 29    - a step, an empty answer;
 30    - an action, every one of its actions `Success`;
 31    - a debug request, an empty answer;
 32    - a query, each pathing distance as the straight line between its ends, from a unit's tag at its position in the
 33      last recorded observation, or 0, which the game answers for no path, for a tag that observation does not hold;
 34    - a request to save the replay, refused.
 35
 36    The rest plays as recorded, a recorded game info or ping passed over while something else is asked, and is made up
 37    where the recording does not answer it next:
 38    - creating a game it did not create, with the status `init_game`;
 39    - a game info, as the last one it answered;
 40    - an observation once only leaving the game, quitting or nothing is left, as its last observation again with the
 41      status `ended`, which ends a game recorded without its result;
 42    - leaving the game, with the status `launched`.
 43
 44    Only the kind of a recorded request is checked, not its contents. A query for abilities or placements, and any other
 45    request the recording does not answer next, raises `ProtocolError`.
 46    """
 47
 48    def __init__(self, recording: Recording) -> None:
 49        """Answer from `recording`, starting at its first exchange."""
 50        self._exchanges = iter(recording)
 51        self._next_exchange: Exchange | None = None
 52        self._last_status: sc2api_pb2.Status.ValueType | None = None
 53        self._last_game_info: sc2api_pb2.Response | None = None
 54        self._last_observation: sc2api_pb2.ResponseObservation | None = None
 55        self._positions_by_tag: dict[int, common_pb2.Point] | None = None
 56        self._closed = False
 57
 58    def request(self, request: sc2api_pb2.Request) -> sc2api_pb2.Response:
 59        """The next recorded answer, if the recording was asked the same kind of question, or one made up as the class
 60        says."""
 61        if self._closed:
 62            raise ConnectionClosedError("the recording is closed")
 63        asked_kind = request.WhichOneof("request") or "nothing"
 64        if asked_kind in _BOT_REQUESTS:
 65            return self._made_up_answer(request, asked_kind)
 66        exchange = self._peek_past_unrecorded(asked_kind)
 67        recorded_kind = "nothing" if exchange is None else exchange.request.WhichOneof("request") or "nothing"
 68        if exchange is not None and recorded_kind == asked_kind:
 69            self._next_exchange = None
 70            return self._remember(exchange.response)
 71        if (response := self._unrecorded_answer(asked_kind, recorded_kind)) is not None:
 72            return response
 73        if exchange is None:
 74            raise ProtocolError(f"the recording has no answer left, and was asked for {asked_kind}")
 75        raise ProtocolError(f"the recording answers {recorded_kind} next, and was asked for {asked_kind}")
 76
 77    def close(self) -> None:
 78        """Stop answering and release the file. A request after this raises, as it would on a closed socket."""
 79        self._closed = True
 80        self._exchanges.close()
 81
 82    def _peek_past_unrecorded(self, asked_kind: str) -> Exchange | None:
 83        """The next exchange, unread, past the answers to a bot's own requests and past a game info or a ping while
 84        something else is asked, the last game info kept; `None` once there is none."""
 85        while True:
 86            if self._next_exchange is None:
 87                self._next_exchange = next(self._exchanges, None)
 88            exchange = self._next_exchange
 89            if exchange is None:
 90                return None
 91            recorded_kind = exchange.request.WhichOneof("request")
 92            if recorded_kind not in _BOT_REQUESTS and (
 93                recorded_kind not in _PASSED_OVER_UNLESS_ASKED or recorded_kind == asked_kind
 94            ):
 95                return exchange
 96            self._next_exchange = None
 97            self._remember(exchange.response)
 98
 99    def _remember(self, response: sc2api_pb2.Response) -> sc2api_pb2.Response:
100        """Keep what a made-up answer reads from `response`, a recorded answer, and return it."""
101        if response.HasField("status"):
102            self._last_status = response.status
103        if response.HasField("game_info"):
104            self._last_game_info = response
105        elif response.HasField("observation"):
106            self._last_observation = response.observation
107            self._positions_by_tag = None
108        return response
109
110    def _made_up_answer(self, request: sc2api_pb2.Request, asked_kind: str) -> sc2api_pb2.Response:
111        """An answer to `request`, a step or a bot's own `asked_kind`, as the class says."""
112        response = sc2api_pb2.Response()
113        if self._last_status is not None:
114            response.status = self._last_status
115        if asked_kind == "step":
116            response.step.SetInParent()
117        elif asked_kind == "action":
118            response.action.result.extend([error_pb2.Success] * len(request.action.actions))
119        elif asked_kind == "debug":
120            response.debug.SetInParent()
121        elif asked_kind == "query":
122            response.query.CopyFrom(self._straight_line_distances(request.query))
123        elif asked_kind == "save_replay":
124            response.error.append("a recording holds no replay to save")
125        else:
126            raise ValueError(f"no answer to {asked_kind} is made up")
127        return response
128
129    def _unrecorded_answer(self, asked_kind: str, recorded_kind: str) -> sc2api_pb2.Response | None:
130        """An answer to `asked_kind`, which the recording does not answer next but `recorded_kind`, as the class says,
131        or `None` if none is made up for it."""
132        if asked_kind == "create_game":
133            return sc2api_pb2.Response(create_game=sc2api_pb2.ResponseCreateGame(), status=sc2api_pb2.init_game)
134        if asked_kind == "game_info":
135            return self._last_game_info
136        if asked_kind == "observation" and recorded_kind in _AFTER_THE_GAME and self._last_observation is not None:
137            return self._remember(sc2api_pb2.Response(observation=self._last_observation, status=sc2api_pb2.ended))
138        if asked_kind == "leave_game":
139            return sc2api_pb2.Response(leave_game=sc2api_pb2.ResponseLeaveGame(), status=sc2api_pb2.launched)
140        return None
141
142    def _straight_line_distances(self, query: query_pb2.RequestQuery) -> query_pb2.ResponseQuery:
143        """The answer to `query`, each pathing distance the straight line between its ends."""
144        if query.abilities or query.placements:
145            raise ProtocolError("a recording answers a query only for pathing distances, not abilities or placements")
146        query_answer = query_pb2.ResponseQuery()
147        for pathing in query.pathing:
148            start_point = (
149                pathing.start_pos if pathing.WhichOneof("start") == "start_pos" else self._position_of(pathing.unit_tag)
150            )
151            straight_distance = (
152                0.0
153                if start_point is None
154                else math.hypot(pathing.end_pos.x - start_point.x, pathing.end_pos.y - start_point.y)
155            )
156            query_answer.pathing.add(distance=straight_distance)
157        return query_answer
158
159    def _position_of(self, tag: int) -> common_pb2.Point | None:
160        """Where the last recorded observation had the unit of `tag`, or `None` if it did not report it."""
161        if self._positions_by_tag is None:
162            units = () if self._last_observation is None else self._last_observation.observation.raw_data.units
163            self._positions_by_tag = {unit.tag: unit.pos for unit in units}
164        return self._positions_by_tag.get(tag)

A Transport that plays a recording back for a bot other than the one recorded, which can play it through, though nothing it does changes what comes next. A PlaybackTransport answers only what the recording was asked.

A step, and what the bot asks of its own accord, is answered as made up here, under the status of the last recorded answer, and the recording's own answers to such requests are passed over:

  • a step, an empty answer;
  • an action, every one of its actions Success;
  • a debug request, an empty answer;
  • a query, each pathing distance as the straight line between its ends, from a unit's tag at its position in the last recorded observation, or 0, which the game answers for no path, for a tag that observation does not hold;
  • a request to save the replay, refused.

The rest plays as recorded, a recorded game info or ping passed over while something else is asked, and is made up where the recording does not answer it next:

  • creating a game it did not create, with the status init_game;
  • a game info, as the last one it answered;
  • an observation once only leaving the game, quitting or nothing is left, as its last observation again with the status ended, which ends a game recorded without its result;
  • leaving the game, with the status launched.

Only the kind of a recorded request is checked, not its contents. A query for abilities or placements, and any other request the recording does not answer next, raises ProtocolError.

PermissivePlaybackTransport(recording: Recording)
48    def __init__(self, recording: Recording) -> None:
49        """Answer from `recording`, starting at its first exchange."""
50        self._exchanges = iter(recording)
51        self._next_exchange: Exchange | None = None
52        self._last_status: sc2api_pb2.Status.ValueType | None = None
53        self._last_game_info: sc2api_pb2.Response | None = None
54        self._last_observation: sc2api_pb2.ResponseObservation | None = None
55        self._positions_by_tag: dict[int, common_pb2.Point] | None = None
56        self._closed = False

Answer from recording, starting at its first exchange.

def request( self, request: s2clientprotocol.sc2api_pb2.Request) -> s2clientprotocol.sc2api_pb2.Response:
58    def request(self, request: sc2api_pb2.Request) -> sc2api_pb2.Response:
59        """The next recorded answer, if the recording was asked the same kind of question, or one made up as the class
60        says."""
61        if self._closed:
62            raise ConnectionClosedError("the recording is closed")
63        asked_kind = request.WhichOneof("request") or "nothing"
64        if asked_kind in _BOT_REQUESTS:
65            return self._made_up_answer(request, asked_kind)
66        exchange = self._peek_past_unrecorded(asked_kind)
67        recorded_kind = "nothing" if exchange is None else exchange.request.WhichOneof("request") or "nothing"
68        if exchange is not None and recorded_kind == asked_kind:
69            self._next_exchange = None
70            return self._remember(exchange.response)
71        if (response := self._unrecorded_answer(asked_kind, recorded_kind)) is not None:
72            return response
73        if exchange is None:
74            raise ProtocolError(f"the recording has no answer left, and was asked for {asked_kind}")
75        raise ProtocolError(f"the recording answers {recorded_kind} next, and was asked for {asked_kind}")

The next recorded answer, if the recording was asked the same kind of question, or one made up as the class says.

def close(self) -> None:
77    def close(self) -> None:
78        """Stop answering and release the file. A request after this raises, as it would on a closed socket."""
79        self._closed = True
80        self._exchanges.close()

Stop answering and release the file. A request after this raises, as it would on a closed socket.

@dataclass(frozen=True, slots=True)
class PortPair:
 8@dataclass(frozen=True, slots=True)
 9class PortPair:
10    """The pair of ports the game needs for one connection.
11
12    Every participant in a match must send the same ports in the same order, or the join fails.
13    """
14
15    game: int
16    base: int

The pair of ports the game needs for one connection.

Every participant in a match must send the same ports in the same order, or the join fails.

PortPair(game: int, base: int)
game: int
base: int
class ProtocolError(sc2nachos._shared.errors.NachOSError):
7class ProtocolError(NachOSError):
8    """Talking to a game failed: it refused a request or answered something other than what was asked, the
9    connection to it failed, or a recording of one could not be read or played back."""

Talking to a game failed: it refused a request or answered something other than what was asked, the connection to it failed, or a recording of one could not be read or played back.

@dataclass(frozen=True, slots=True)
class Recording:
 35@dataclass(frozen=True, slots=True)
 36class Recording:
 37    """A whole game's exchanges, on disk.
 38
 39    Iterating re-reads the file, so a game is never held in memory whole, and a recording can be read again.
 40    """
 41
 42    path: Path
 43
 44    def __iter__(self) -> Generator[Exchange, None, None]:
 45        """Every exchange, in the order the game answered."""
 46        with lzma.open(self.path, "rb") as stream:
 47            try:
 48                if stream.read(len(_HEADER)) != _HEADER:
 49                    raise ProtocolError(f"{self.path} is not a recording this version of NachOS can read")
 50                while (request := _read(stream, sc2api_pb2.Request)) is not None:
 51                    response = _read(stream, sc2api_pb2.Response)
 52                    if response is None:
 53                        raise ProtocolError(f"{self.path} ends on a request the game never answered")
 54                    yield Exchange(request, response)
 55            except EOFError as cut:
 56                raise ProtocolError(
 57                    f"{self.path} stops partway, as it does when its run dies before closing it"
 58                ) from cut
 59            except lzma.LZMAError as error:
 60                raise ProtocolError(f"{self.path} is not a recording, or is a damaged one: {error}") from error
 61
 62    @property
 63    def created_its_game(self) -> bool:
 64        """Whether the client recorded created its game, as a local game's does, rather than only joining it, as a
 65        ladder game's does: whether it asked to create one before it joined. It reads the start of the file."""
 66        with closing(iter(self)) as exchanges:
 67            for exchange in exchanges:
 68                asked_kind = exchange.request.WhichOneof("request")
 69                if asked_kind in ("create_game", "join_game"):
 70                    return asked_kind == "create_game"
 71        return False
 72
 73    @property
 74    def start_replay_request(self) -> sc2api_pb2.RequestStartReplay | None:
 75        """The request that started the replay the client recorded played back, as `run_replay` records one, or `None`
 76        if it played a game, creating or joining it first. It reads the start of the file."""
 77        with closing(iter(self)) as exchanges:
 78            for exchange in exchanges:
 79                asked_kind = exchange.request.WhichOneof("request")
 80                if asked_kind == "start_replay":
 81                    return exchange.request.start_replay
 82                if asked_kind in ("create_game", "join_game"):
 83                    return None
 84        return None
 85
 86    @property
 87    def played_in_real_time(self) -> bool:
 88        """Whether the game recorded was played in real time: as its create asked, and for a game only joined, if it
 89        asked for no step before its second observation. It reads the start of the file."""
 90        observations_seen = 0
 91        with closing(iter(self)) as exchanges:
 92            for exchange in exchanges:
 93                asked_kind = exchange.request.WhichOneof("request")
 94                if asked_kind == "create_game":
 95                    return exchange.request.create_game.realtime
 96                if asked_kind == "step":
 97                    return False
 98                if asked_kind == "observation":
 99                    observations_seen += 1
100                    if observations_seen == 2:
101                        return True
102        return False

A whole game's exchanges, on disk.

Iterating re-reads the file, so a game is never held in memory whole, and a recording can be read again.

Recording(path: pathlib.Path)
path: pathlib.Path
created_its_game: bool
62    @property
63    def created_its_game(self) -> bool:
64        """Whether the client recorded created its game, as a local game's does, rather than only joining it, as a
65        ladder game's does: whether it asked to create one before it joined. It reads the start of the file."""
66        with closing(iter(self)) as exchanges:
67            for exchange in exchanges:
68                asked_kind = exchange.request.WhichOneof("request")
69                if asked_kind in ("create_game", "join_game"):
70                    return asked_kind == "create_game"
71        return False

Whether the client recorded created its game, as a local game's does, rather than only joining it, as a ladder game's does: whether it asked to create one before it joined. It reads the start of the file.

start_replay_request: s2clientprotocol.sc2api_pb2.RequestStartReplay | None
73    @property
74    def start_replay_request(self) -> sc2api_pb2.RequestStartReplay | None:
75        """The request that started the replay the client recorded played back, as `run_replay` records one, or `None`
76        if it played a game, creating or joining it first. It reads the start of the file."""
77        with closing(iter(self)) as exchanges:
78            for exchange in exchanges:
79                asked_kind = exchange.request.WhichOneof("request")
80                if asked_kind == "start_replay":
81                    return exchange.request.start_replay
82                if asked_kind in ("create_game", "join_game"):
83                    return None
84        return None

The request that started the replay the client recorded played back, as run_replay records one, or None if it played a game, creating or joining it first. It reads the start of the file.

played_in_real_time: bool
 86    @property
 87    def played_in_real_time(self) -> bool:
 88        """Whether the game recorded was played in real time: as its create asked, and for a game only joined, if it
 89        asked for no step before its second observation. It reads the start of the file."""
 90        observations_seen = 0
 91        with closing(iter(self)) as exchanges:
 92            for exchange in exchanges:
 93                asked_kind = exchange.request.WhichOneof("request")
 94                if asked_kind == "create_game":
 95                    return exchange.request.create_game.realtime
 96                if asked_kind == "step":
 97                    return False
 98                if asked_kind == "observation":
 99                    observations_seen += 1
100                    if observations_seen == 2:
101                        return True
102        return False

Whether the game recorded was played in real time: as its create asked, and for a game only joined, if it asked for no step before its second observation. It reads the start of the file.

class RecordingTransport:
105class RecordingTransport:
106    """A `Transport` that writes every exchange to disk on its way through to another transport.
107
108    The file is complete only once the transport is closed. A run that dies first leaves what the compressor had
109    already written, which misses the last stretch of the game, or all of a short one.
110    """
111
112    def __init__(self, transport: Transport, path: Path | str) -> None:
113        """Forward to `transport`, recording into `path`. An existing file at `path` is overwritten."""
114        path = Path(path)
115        self._transport = transport
116        self._recording = Recording(path)
117        self._exchanges = 0
118        # The file stays open for the whole game and is closed with the transport.
119        self._stream = lzma.open(path, "wb", preset=_COMPRESSION_PRESET)  # noqa: SIM115
120        self._stream.write(_HEADER)
121
122    @property
123    def recording(self) -> Recording:
124        """The file being written, readable once the transport is closed."""
125        return self._recording
126
127    def request(self, request: sc2api_pb2.Request) -> sc2api_pb2.Response:
128        """Forward `request`, record it with its answer, and return the answer."""
129        response = self._transport.request(request)
130        _write(self._stream, request)
131        _write(self._stream, response)
132        self._exchanges += 1
133        return response
134
135    def close(self) -> None:
136        """Close the underlying transport, then finish the file. Closing twice is not an error."""
137        try:
138            self._transport.close()
139        finally:
140            if not self._stream.closed:
141                self._stream.close()
142                size = self._recording.path.stat().st_size
143                logger.info(
144                    "Recorded {} exchanges to {} ({:.1f} MB)", self._exchanges, self._recording.path, size / 1e6
145                )

A Transport that writes every exchange to disk on its way through to another transport.

The file is complete only once the transport is closed. A run that dies first leaves what the compressor had already written, which misses the last stretch of the game, or all of a short one.

RecordingTransport( transport: Transport, path: pathlib.Path | str)
112    def __init__(self, transport: Transport, path: Path | str) -> None:
113        """Forward to `transport`, recording into `path`. An existing file at `path` is overwritten."""
114        path = Path(path)
115        self._transport = transport
116        self._recording = Recording(path)
117        self._exchanges = 0
118        # The file stays open for the whole game and is closed with the transport.
119        self._stream = lzma.open(path, "wb", preset=_COMPRESSION_PRESET)  # noqa: SIM115
120        self._stream.write(_HEADER)

Forward to transport, recording into path. An existing file at path is overwritten.

recording: Recording
122    @property
123    def recording(self) -> Recording:
124        """The file being written, readable once the transport is closed."""
125        return self._recording

The file being written, readable once the transport is closed.

def request( self, request: s2clientprotocol.sc2api_pb2.Request) -> s2clientprotocol.sc2api_pb2.Response:
127    def request(self, request: sc2api_pb2.Request) -> sc2api_pb2.Response:
128        """Forward `request`, record it with its answer, and return the answer."""
129        response = self._transport.request(request)
130        _write(self._stream, request)
131        _write(self._stream, response)
132        self._exchanges += 1
133        return response

Forward request, record it with its answer, and return the answer.

def close(self) -> None:
135    def close(self) -> None:
136        """Close the underlying transport, then finish the file. Closing twice is not an error."""
137        try:
138            self._transport.close()
139        finally:
140            if not self._stream.closed:
141                self._stream.close()
142                size = self._recording.path.stat().st_size
143                logger.info(
144                    "Recorded {} exchanges to {} ({:.1f} MB)", self._exchanges, self._recording.path, size / 1e6
145                )

Close the underlying transport, then finish the file. Closing twice is not an error.

class PlaybackTransport:
148class PlaybackTransport:
149    """A `Transport` that plays a recording back, so everything above the seam runs without a game.
150
151    Answers come back in the order they were recorded. Only the kind of request is checked, not its contents, so a
152    caller may ask about a different game loop than the recording did, but not for a different thing.
153    """
154
155    def __init__(self, recording: Recording) -> None:
156        """Answer from `recording`, starting at its first exchange."""
157        self._exchanges = iter(recording)
158        self._closed = False
159
160    def request(self, request: sc2api_pb2.Request) -> sc2api_pb2.Response:
161        """The next recorded answer, if the recording was asked the same kind of question."""
162        if self._closed:
163            raise ConnectionClosedError("the recording is closed")
164        asked = request.WhichOneof("request") or "nothing"
165        exchange = next(self._exchanges, None)
166        if exchange is None:
167            raise ProtocolError(f"the recording has no answer left, and was asked for {asked}")
168        recorded = exchange.request.WhichOneof("request") or "nothing"
169        if asked != recorded:
170            raise ProtocolError(f"the recording answers {recorded} next, and was asked for {asked}")
171        return exchange.response
172
173    def close(self) -> None:
174        """Stop answering and release the file. A request after this raises, as it would on a closed socket."""
175        self._closed = True
176        self._exchanges.close()

A Transport that plays a recording back, so everything above the seam runs without a game.

Answers come back in the order they were recorded. Only the kind of request is checked, not its contents, so a caller may ask about a different game loop than the recording did, but not for a different thing.

PlaybackTransport(recording: Recording)
155    def __init__(self, recording: Recording) -> None:
156        """Answer from `recording`, starting at its first exchange."""
157        self._exchanges = iter(recording)
158        self._closed = False

Answer from recording, starting at its first exchange.

def request( self, request: s2clientprotocol.sc2api_pb2.Request) -> s2clientprotocol.sc2api_pb2.Response:
160    def request(self, request: sc2api_pb2.Request) -> sc2api_pb2.Response:
161        """The next recorded answer, if the recording was asked the same kind of question."""
162        if self._closed:
163            raise ConnectionClosedError("the recording is closed")
164        asked = request.WhichOneof("request") or "nothing"
165        exchange = next(self._exchanges, None)
166        if exchange is None:
167            raise ProtocolError(f"the recording has no answer left, and was asked for {asked}")
168        recorded = exchange.request.WhichOneof("request") or "nothing"
169        if asked != recorded:
170            raise ProtocolError(f"the recording answers {recorded} next, and was asked for {asked}")
171        return exchange.response

The next recorded answer, if the recording was asked the same kind of question.

def close(self) -> None:
173    def close(self) -> None:
174        """Stop answering and release the file. A request after this raises, as it would on a closed socket."""
175        self._closed = True
176        self._exchanges.close()

Stop answering and release the file. A request after this raises, as it would on a closed socket.

class Status(sc2nachos._shared.readable_int_enum.ReadableIntEnum):
 9class Status(ReadableIntEnum):
10    """The game client's own status, from launching to quitting.
11
12    Every response carries one, so it is read rather than tracked.
13    """
14
15    LAUNCHED = sc2api_pb2.Status.launched
16    INIT_GAME = sc2api_pb2.Status.init_game
17    IN_GAME = sc2api_pb2.Status.in_game
18    IN_REPLAY = sc2api_pb2.Status.in_replay
19    ENDED = sc2api_pb2.Status.ended
20    QUIT = sc2api_pb2.Status.quit
21    UNKNOWN = sc2api_pb2.Status.unknown

The game client's own status, from launching to quitting.

Every response carries one, so it is read rather than tracked.

LAUNCHED = <Status.LAUNCHED: 1>
INIT_GAME = <Status.INIT_GAME: 2>
IN_GAME = <Status.IN_GAME: 3>
IN_REPLAY = <Status.IN_REPLAY: 4>
ENDED = <Status.ENDED: 5>
QUIT = <Status.QUIT: 6>
UNKNOWN = <Status.UNKNOWN: 99>
class Transport(typing.Protocol):
 9class Transport(Protocol):
10    """Carries one request to a game client and brings back its response.
11
12    Serialization lives below this seam and protobuf messages above it, so a recorded game and a live one drive
13    the same code. The game answers one request at a time, so a request blocks until it is answered.
14    """
15
16    def request(self, request: sc2api_pb2.Request) -> sc2api_pb2.Response:
17        """Send `request`, wait for the game's answer, and return it."""
18        ...
19
20    def close(self) -> None:
21        """Release the transport. A request after this raises `ConnectionClosedError`."""
22        ...

Carries one request to a game client and brings back its response.

Serialization lives below this seam and protobuf messages above it, so a recorded game and a live one drive the same code. The game answers one request at a time, so a request blocks until it is answered.

Transport(*args, **kwargs)
1739def _no_init_or_replace_init(self, *args, **kwargs):
1740    cls = type(self)
1741
1742    if cls._is_protocol:
1743        raise TypeError('Protocols cannot be instantiated')
1744
1745    # Already using a custom `__init__`. No need to calculate correct
1746    # `__init__` to call. This can lead to RecursionError. See bpo-45121.
1747    if cls.__init__ is not _no_init_or_replace_init:
1748        return
1749
1750    # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
1751    # The first instantiation of the subclass will call `_no_init_or_replace_init` which
1752    # searches for a proper new `__init__` in the MRO. The new `__init__`
1753    # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent
1754    # instantiation of the protocol subclass will thus use the new
1755    # `__init__` and no longer call `_no_init_or_replace_init`.
1756    for base in cls.__mro__:
1757        init = base.__dict__.get('__init__', _no_init_or_replace_init)
1758        if init is not _no_init_or_replace_init:
1759            cls.__init__ = init
1760            break
1761    else:
1762        # should not happen
1763        cls.__init__ = object.__init__
1764
1765    cls.__init__(self, *args, **kwargs)
def request( self, request: s2clientprotocol.sc2api_pb2.Request) -> s2clientprotocol.sc2api_pb2.Response:
16    def request(self, request: sc2api_pb2.Request) -> sc2api_pb2.Response:
17        """Send `request`, wait for the game's answer, and return it."""
18        ...

Send request, wait for the game's answer, and return it.

def close(self) -> None:
20    def close(self) -> None:
21        """Release the transport. A request after this raises `ConnectionClosedError`."""
22        ...

Release the transport. A request after this raises ConnectionClosedError.

class WebSocketTransport:
21class WebSocketTransport:
22    """A `Transport` over the websocket of a game client that is already running."""
23
24    def __init__(self, websocket: WebSocket) -> None:
25        """Wrap an open websocket. Closing the transport closes the websocket."""
26        self._websocket = websocket
27
28    @classmethod
29    def connect(cls, url: str, *, timeout: float | None = None) -> Self:
30        """Open a websocket to the game client listening at `url`.
31
32        `timeout` bounds every wait on the socket. It defaults to none: loading a map takes as long as it takes,
33        and a bot has nothing to do in the meantime.
34        """
35        try:
36            websocket = create_connection(url, timeout=timeout)
37        except WebSocketConnectionClosedException as error:
38            raise ConnectionClosedError(
39                f"the game at {url} dropped the connection as it opened, as it does while another connection holds it"
40            ) from error
41        except WebSocketTimeoutException as error:
42            raise ConnectionTimeoutError(f"the game at {url} did not answer in time") from error
43        except WebSocketException as error:
44            raise ProtocolError(f"the websocket to {url} failed to open: {error}") from error
45        # The websocket library passes the socket's own failures through as they are.
46        except TimeoutError as error:
47            raise ConnectionTimeoutError(f"the game at {url} did not answer in time") from error
48        except ConnectionError as error:
49            raise ConnectionClosedError(f"nothing at {url} took the connection: {error}") from error
50        except OSError as error:
51            raise ProtocolError(f"the websocket to {url} failed to open: {error}") from error
52        logger.info("Connected to the game at {}", url)
53        return cls(websocket)
54
55    def request(self, request: sc2api_pb2.Request) -> sc2api_pb2.Response:
56        """Send `request`, wait for the game's answer, and return it.
57
58        A request that fails once sent closes the connection, so every later request raises `ConnectionClosedError`.
59        """
60        payload = request.SerializeToString()
61        try:
62            return self._exchange(payload)
63        except BaseException:
64            # Without waiting for the game's close frame; a failure to close must not hide why the request failed.
65            with suppress(WebSocketException, OSError):
66                self._websocket.close(timeout=0)
67            raise
68
69    def _exchange(self, payload: bytes) -> sc2api_pb2.Response:
70        """Send `payload`, and read and parse the game's answer."""
71        try:
72            self._websocket.send_binary(payload)
73            answer = self._websocket.recv()
74        except WebSocketConnectionClosedException as error:
75            raise ConnectionClosedError("the connection to the game closed mid-request") from error
76        except WebSocketTimeoutException as error:
77            raise ConnectionTimeoutError("the game did not answer in time, so the connection is closed") from error
78        except WebSocketException as error:
79            raise ProtocolError(f"the websocket failed: {error}") from error
80        except ConnectionError as error:
81            # A game that dies resets the socket, which the websocket library passes through as a bare OSError.
82            raise ConnectionClosedError(f"the connection to the game was lost: {error}") from error
83        if answer == "":
84            # What the websocket library returns for a close frame: the game or a proxy closed the connection.
85            raise ConnectionClosedError("the game closed the connection")
86        if not isinstance(answer, bytes):
87            raise ProtocolError(f"the game sent text where the protocol is binary: {answer!r}")
88        response = sc2api_pb2.Response()
89        try:
90            response.ParseFromString(answer)
91        except DecodeError as error:
92            raise ProtocolError("the game sent an answer that does not parse") from error
93        return response
94
95    def close(self) -> None:
96        """Close the websocket."""
97        self._websocket.close()

A Transport over the websocket of a game client that is already running.

WebSocketTransport(websocket: websocket._core.WebSocket)
24    def __init__(self, websocket: WebSocket) -> None:
25        """Wrap an open websocket. Closing the transport closes the websocket."""
26        self._websocket = websocket

Wrap an open websocket. Closing the transport closes the websocket.

@classmethod
def connect(cls, url: str, *, timeout: float | None = None) -> Self:
28    @classmethod
29    def connect(cls, url: str, *, timeout: float | None = None) -> Self:
30        """Open a websocket to the game client listening at `url`.
31
32        `timeout` bounds every wait on the socket. It defaults to none: loading a map takes as long as it takes,
33        and a bot has nothing to do in the meantime.
34        """
35        try:
36            websocket = create_connection(url, timeout=timeout)
37        except WebSocketConnectionClosedException as error:
38            raise ConnectionClosedError(
39                f"the game at {url} dropped the connection as it opened, as it does while another connection holds it"
40            ) from error
41        except WebSocketTimeoutException as error:
42            raise ConnectionTimeoutError(f"the game at {url} did not answer in time") from error
43        except WebSocketException as error:
44            raise ProtocolError(f"the websocket to {url} failed to open: {error}") from error
45        # The websocket library passes the socket's own failures through as they are.
46        except TimeoutError as error:
47            raise ConnectionTimeoutError(f"the game at {url} did not answer in time") from error
48        except ConnectionError as error:
49            raise ConnectionClosedError(f"nothing at {url} took the connection: {error}") from error
50        except OSError as error:
51            raise ProtocolError(f"the websocket to {url} failed to open: {error}") from error
52        logger.info("Connected to the game at {}", url)
53        return cls(websocket)

Open a websocket to the game client listening at url.

timeout bounds every wait on the socket. It defaults to none: loading a map takes as long as it takes, and a bot has nothing to do in the meantime.

def request( self, request: s2clientprotocol.sc2api_pb2.Request) -> s2clientprotocol.sc2api_pb2.Response:
55    def request(self, request: sc2api_pb2.Request) -> sc2api_pb2.Response:
56        """Send `request`, wait for the game's answer, and return it.
57
58        A request that fails once sent closes the connection, so every later request raises `ConnectionClosedError`.
59        """
60        payload = request.SerializeToString()
61        try:
62            return self._exchange(payload)
63        except BaseException:
64            # Without waiting for the game's close frame; a failure to close must not hide why the request failed.
65            with suppress(WebSocketException, OSError):
66                self._websocket.close(timeout=0)
67            raise

Send request, wait for the game's answer, and return it.

A request that fails once sent closes the connection, so every later request raises ConnectionClosedError.

def close(self) -> None:
95    def close(self) -> None:
96        """Close the websocket."""
97        self._websocket.close()

Close the websocket.