sc2nachos.api
Everything a bot talks to.
62class Api[E]: 63 """Everything a bot talks to. It is built before there is a game. 64 65 Construct one where the rest of your bot can reach it, module scope included, and pass it to `run_local` or 66 `run_ladder` for its game. An api plays one game: a program that plays several makes an api for each. Never 67 subclass it: your own helpers belong in your own modules, as ordinary functions. 68 69 Time is counted in steps: one step is one game loop, and 22.4 make a second. A moment or a length of game time is a 70 `GameTime`, but for the two counts of steps, `step` and `steps_per_turn`. The bot takes a turn every 71 `steps_per_turn` steps, which the game is played with. Each turn hands its handlers a `TurnStartEvent`, then 72 the events its observation reports, in the order `docs/events.md` gives, then a `TurnEvent`. 73 74 Anything of the game raises `NotPlayingError` until the game starts. After it ends, the api keeps answering from 75 it. 76 77 `E` is the type of `extensions`: an `Api()` is an `Api[None]`, and one made with `extensions=Extensions` an 78 `Api[Extensions]`. A function that takes any api takes an `Api[object]`. 79 """ 80 81 @overload 82 def __init__( 83 self: "Api[None]", 84 *, 85 extensions: None = None, 86 time_handlers: bool = ..., 87 ) -> None: ... 88 89 @overload 90 def __init__( 91 self, 92 *, 93 extensions: Callable[["Api[E]"], E], 94 time_handlers: bool = ..., 95 ) -> None: ... 96 97 def __init__( 98 self, 99 *, 100 extensions: Callable[[Any], object] | None = None, 101 time_handlers: bool = False, 102 ) -> None: 103 """Build the bot's extensions with `extensions` once the game starts, as `Api.extensions` says, and time every 104 handler call, read as `handler_timings`, if `time_handlers`. This connects to nothing. 105 106 `extensions` builds what `Api.extensions` reads, the bot's own object holding its extensions, from this api: 107 its class, whose constructor takes the api and builds each extension. 108 """ 109 self._extensions_builder = extensions 110 self._extensions: object = _NOT_BUILT 111 self._events = _EventBus(time_handlers=time_handlers) 112 # Everything that comes with the game, from the moment it starts. 113 self._game: _Game | None = None 114 115 # A type checker refuses a parameterized event subscribed to bare: `None` is not callable. 116 @overload 117 def on[T: ParameterizedEvent]( # pyright: ignore[reportOverlappingOverload] 118 self, 119 event_type: type[T], 120 /, 121 *, 122 priority: EventPriority = ..., 123 min_interval: GameTime | None = ..., 124 at_time: GameTime | None = ..., 125 once: bool = ..., 126 catch_exceptions: bool = ..., 127 ) -> None: ... 128 129 @overload 130 def on[T: Event]( 131 self, 132 event_type: type[T] | EventFilter[T], 133 /, 134 *, 135 priority: EventPriority = ..., 136 min_interval: GameTime | None = ..., 137 at_time: GameTime | None = ..., 138 once: bool = ..., 139 catch_exceptions: bool = ..., 140 ) -> EventSubscriber[T]: ... 141 142 def on(self, event_type: type[Event] | EventFilter[Any], /, **options: Any) -> Any: 143 """Subscribe the decorated function to `event_type`, or mark the decorated method for `subscribe`. This works 144 before any game, so handlers can subscribe as their modules are imported. 145 146 `event_type` is an event type, whose events and its subclasses' the handler is handed, or a filter from `only` 147 or `of`. `where` on the `EventSubscriber` it returns narrows further. A type that has `of` is subscribed to only 148 through it, and a type checker refuses it bare. A handler of `Event` is handed every event, which makes NachOS 149 produce every type of event it otherwise would not, including comparing every unit with the observation 150 before; a parameterized event comes only with the parameters other handlers asked for. 151 152 A method is marked, and subscribed for each instance passed to `subscribe`: a function defined in a class body 153 that takes at least two positional arguments without defaults, the instance and the event, or wraps one through 154 `functools.wraps`. Any other function is subscribed at once, wherever it is defined, a static method taking the 155 event alone included, and so is a method already bound to its instance. Either stays subscribed until it is 156 passed to `unsubscribe`, held strongly, so it runs whether or not anything else keeps it alive. 157 158 `priority` orders the handler among the event's handlers, highest first and then in subscription order; and 159 among a turn's: every handler of one priority is handed each event of the turn it selects, in the turn's order, 160 before any handler of the next. `EventPriority.BEFORE` and `EventPriority.AFTER` are for the handlers 161 subscribed while NachOS builds the extensions, and those take no other, as `Api.extensions` says: either misuse 162 raises `ValueError`. The handler runs on every event unless held back: `min_interval` waits until that long has 163 passed since it last ran, `at_time` runs it once, on the first event at or after that time, and `once` on the 164 first event. `min_interval` with either of the others, or not above zero, raises `ValueError`, and either of the 165 two not a `GameTime`, `TypeError`. These count only the events selected, those emitted before the game included. 166 An exception it raises ends the game, unless `catch_exceptions`, which logs it and goes on. 167 168 The handler must take an event of `event_type`, which a type checker checks. One decorated for several event 169 types takes an `Event`. 170 """ 171 return self._events.on(event_type, **options) 172 173 def subscribe(self, instance: object) -> None: 174 """Subscribe every method of `instance` marked with `on`, until `instance` is passed to `unsubscribe`. 175 176 An unmarked override leaves the method it overrides unsubscribed. Raises `ValueError` if `instance` has no 177 marked method, or one of them is subscribed for it already, a method subscribed bound through `on` aside; and 178 `TypeError` if a marked function is under a `classmethod` or a `staticmethod`. 179 """ 180 self._events.subscribe(instance) 181 182 def unsubscribe(self, target: object) -> None: 183 """Unsubscribe `target`: a function, a bound method, or every method of an instance. 184 185 Raises `ValueError` if nothing of it is subscribed. 186 """ 187 self._events.unsubscribe(target) 188 189 def emit(self, event: Event) -> None: 190 """Hand `event` to every handler of its type or a base type that selects it and is due to run. All have returned 191 when this returns. A handler may itself emit an event. 192 193 An event made without a time is handed out as a copy with the current time, and the one passed in keeps none, 194 so it can be emitted again. Raises `ValueError` for one when no game is being played. 195 """ 196 self._events.emit(event) 197 198 @property 199 def handler_timings(self) -> Mapping[type[Event], Mapping[str, HandlerTiming]]: 200 """How long each handler has taken, by event type and handler name, on events emitted before the game too. 201 202 A handler is named by its module and qualified name, so every instance of a class counts under one name. Raises 203 `RuntimeError` unless the api was made with `time_handlers=True`. 204 """ 205 return self._events.timings 206 207 @property 208 def extensions(self) -> E: 209 """The bot's own object holding its extensions, built by what the api was given as `extensions`, or `None` for 210 an api made without. 211 212 NachOS builds it once, with this api, after reading the game's map, tables and first observation and before 213 `GameStartEvent`, so `api.map`, `api.units` and the rest answer while it is built. Every handler subscribed 214 meanwhile runs at `EventPriority.BEFORE`, before every handler of the bot's of its event and of the turn's 215 events handed out with it, or at `EventPriority.AFTER`, after every one, in the order they subscribed; one 216 subscribed at another priority raises `ValueError`. So what an extension works out before the bot is up to date 217 when the bot's handlers read it, an order a bot's handler gives a unit an extension ordered before it goes out 218 last and stands, and an extension working after the bot sees every order the bot gave in the turn. A handler an 219 extension subscribes later is subscribed as the bot's are. 220 221 Raises `NotPlayingError` before the game starts, and `RuntimeError` while the extensions are being built, or 222 once building them raised. 223 """ 224 extensions = self._extensions 225 if extensions is _NOT_BUILT: 226 self._current_game() 227 raise RuntimeError( 228 "the extensions are not built: an extension is handed the others it needs in its constructor" 229 ) 230 # Built by what `extensions` was, typed as building an `E`; `cast` would cost a call on every read. 231 built: E = extensions # pyright: ignore[reportAssignmentType] 232 return built 233 234 def _current_game(self) -> _Game: 235 """The game being played, or the one that was.""" 236 if self._game is None: 237 raise NotPlayingError("no game has been joined") 238 return self._game 239 240 def _check_has_not_played(self) -> None: 241 """Raise `RuntimeError` if this api has started its game.""" 242 if self._game is not None: 243 raise RuntimeError("this api has played its game; make a new Api to play another") 244 245 @property 246 def client(self) -> Client: 247 """The client the game is played on.""" 248 return self._current_game().client 249 250 @property 251 def map(self) -> GameMap: 252 """The map the game is played on.""" 253 return self._current_game().game_map 254 255 @property 256 def expansions(self) -> tuple[Expansion, ...]: 257 """Every place on the map to build a townhall, as the game began, by pathing distance from this player's start, 258 nearest first: its own start, then its natural. Those no path reaches come last, sorted by increasing 259 straight-line distance from this player's start. Each start location is a `StartLocation`, this player's 260 `player.start_location` and the enemy's `enemy.start_location`.""" 261 return self._current_game().expansions 262 263 @property 264 def data(self) -> GameData: 265 """The game's data tables, as they were before any upgrade.""" 266 return self._current_game().game_data 267 268 @property 269 def step(self) -> int: 270 """The step of the last observation.""" 271 return self._current_game().step 272 273 @property 274 def time(self) -> GameTime: 275 """The time of the last observation: `step` as a `GameTime`.""" 276 return self._current_game().time 277 278 @property 279 def result(self) -> Result | None: 280 """How the game ended for this player, or `None` while it is being played.""" 281 return self._current_game().result 282 283 @property 284 def orders(self) -> OrderBook: 285 """This player's orders for the turn. 286 287 Orders are sent in one request after the turn's last handler returns. A turn that orders nothing sends nothing. 288 """ 289 return self._current_game().orders 290 291 @property 292 def units(self) -> Units[Unit[Any]]: 293 """Every unit in the last observation, including remembered structures out of sight and hidden units. In a 294 replay played back with the fog off, those the observation would have listed with the fog on.""" 295 return self._current_game().tracker.unit_tracker.present 296 297 @property 298 def all_units(self) -> Units[Unit[Any]]: 299 """Every unit of a replay played back with the fog off, as the game lists it then: those of `units`, under the 300 same ids, and those this player did not see. Each reads as visible, in full, but one undetected in this 301 player's sight, whose health and the like the game reports as 0 (in game): it reads as last reported in full. 302 303 Raises `FogOnError` in a game, and in a replay played back with the fog on. 304 """ 305 if (whole_game_tracker := self._current_game().whole_game_tracker) is None: 306 raise FogOnError("the fog is on, so the game reports only what this player sees") 307 return whole_game_tracker.unit_tracker.present 308 309 @property 310 def known_units(self) -> Units[Unit[Any]]: 311 """Every unit not known to be dead: those in the last observation first, then those it left out.""" 312 return self._current_game().tracker.unit_tracker.known 313 314 @property 315 def score(self) -> Score: 316 """The score the game keeps for this player.""" 317 return self._current_game().state.score 318 319 @property 320 def resources(self) -> Resources: 321 """The minerals and vespene this player has to spend.""" 322 return self._current_game().state.resources 323 324 @property 325 def supply(self) -> Supply: 326 """The supply this player's units take and its structures and units provide.""" 327 return self._current_game().state.supply 328 329 @property 330 def ui_unit_counts(self) -> UiUnitCounts: 331 """The game interface's counts of this player's idle workers, army units and warp gates.""" 332 return self._current_game().state.ui_unit_counts 333 334 @property 335 def upgrades(self) -> frozenset[UpgradeId]: 336 """Every upgrade this player has finished. Raises `UncuratedIdError` if one is one the curated ids leave out.""" 337 return self._current_game().state.upgrades 338 339 @overload 340 def in_production( 341 self, unit_type: type[UnitType.AnyType], /, *unit_types: type[UnitType.AnyType] 342 ) -> tuple[InProduction, ...]: ... 343 344 @overload 345 def in_production(self, type_ids: UnitTypeId | Iterable[UnitTypeId], /) -> tuple[InProduction, ...]: ... 346 347 def in_production( 348 self, types: type[UnitType.AnyType] | UnitTypeId | Iterable[UnitTypeId], /, *unit_types: type[UnitType.AnyType] 349 ) -> tuple[InProduction, ...]: 350 """The units of the given types this player has started making or paid for, in the last observation. 351 352 There is one for each unit: a train a structure shows, queued ones included; an egg or a cocoon becoming one; a 353 structure going up, a structure morphing into one, a unit warping in; and a build a worker has been sent to 354 make, or an add-on its host has been ordered to build, until the structure stands. A reactor's two marines are 355 two. The turn's orders are not among them; they are in `api.orders.issued_to`. Takes the types as 356 `Units.of_type` does. 357 """ 358 wanted = frozenset((types,)) if isinstance(types, UnitTypeId) else _type_ids_of(types, unit_types) 359 return self._current_game().state.production.of_types(wanted) 360 361 @property 362 def researches(self) -> Mapping[UpgradeId, Research]: 363 """Each research this player has running or queued in the last observation, by upgrade, in the order the 364 observation lists the structures and each its orders. A finished one is in `upgrades`.""" 365 return self._current_game().state.production.researches 366 367 @property 368 def action_failures(self) -> tuple[ActionFailure, ...]: 369 """The orders the game refused when the last turn's were sent, one for each unit a refused command named, then 370 those it accepted earlier and gave up on since the observation before. 371 372 Raises `UncuratedIdError` if one the game gave up on names an ability the curated ids leave out. 373 """ 374 game = self._current_game() 375 return game.orders._refusals + game.state.action_failures 376 377 @property 378 def player(self) -> Player: 379 """This player: its id, its race and the one it asked for, its name, and its `start_location`.""" 380 return self._current_game().player 381 382 @property 383 def enemy(self) -> Enemy: 384 """The other player, and what is known of it. Raises `NoEnemyError` in a game with no other player, such as a 385 mini-game. 386 387 `api.enemy.upgrades` holds the upgrade levels enemy units have shown and those the bot or an extension added 388 with `assume_upgrades`, as `Enemy.upgrades` says. Everything an upgrade changes on an enemy unit, 389 `Unit.weapons` and `Unit.speed` among them, counts them. `api.enemy.start_location` is where it started, as 390 `Enemy.start_location` says. 391 """ 392 if (enemy := self._current_game().enemy) is None: 393 raise NoEnemyError("this game has no other player") 394 return enemy 395 396 @property 397 def vision(self) -> Vision: 398 """What this player sees: where it can see now, where it has seen at any point in the game, and when it last 399 saw each tile, as `Vision` says.""" 400 return self._current_game().vision 401 402 @property 403 def placement(self) -> PlacementGrids: 404 """Where a structure may stand: on the map whatever happens in the game, and now as far as this player knows; 405 and the ground this player's ordered builds are to stand on, and what it has reserved.""" 406 return self._current_game().placement 407 408 @property 409 def debug(self) -> DebugCommands: 410 """Drawing on the game's screen, cheats and debug commands, sent after each turn's orders.""" 411 return self._current_game().debug 412 413 @property 414 def camera(self) -> Camera: 415 """This player's camera: where it is centered, and moving it.""" 416 return self._current_game().camera 417 418 @property 419 def pathing(self) -> Pathing: 420 """How units get around the map as it stands now: the turn's grid of where ground units walk, paths over it, and 421 distances the game answers.""" 422 return self._current_game().pathing 423 424 @property 425 def creep(self) -> Grid[bool]: 426 """Where creep covers the ground, over the playable area.""" 427 return self._current_game().state.creep 428 429 @property 430 def effects(self) -> tuple[Effect, ...]: 431 """Every effect this player can see. Raises `UncuratedIdError` if one is an effect the curated ids leave out.""" 432 return self._current_game().state.effects 433 434 def chat(self, text: str, *, team_only: bool = False) -> None: 435 """Send `text` to every player, or to this player's team only if `team_only`, with the turn's orders: after 436 them and the camera's move, each message of the turn in the order given. The game drops chat that comes too 437 fast without a word, once some 500 bytes have gone out in a row, counting by the clock rather than in steps 438 (in game). 439 440 Raises `ValueError` for an empty text, and for one of 1040 bytes or more in UTF-8, which would kill the game 441 client (in game). 442 """ 443 game = self._current_game() 444 if not text: 445 raise ValueError("a chat message cannot be empty") 446 if (size := len(text.encode())) > _MOST_CHAT_BYTES: 447 raise ValueError( 448 f"a chat message of {_MOST_CHAT_BYTES + 1} bytes or more kills the game client, and this one is {size}" 449 ) 450 game.queue_chat(text, team_only=team_only) 451 452 def leave_game(self) -> None: 453 """Leave the game, conceding it, once the turn's handlers have run and its orders, chat and debug commands have 454 gone out. `play` then returns `Result.DEFEAT`, as the protocol counts leaving a surrender: the game reports 455 nothing to a client that has left, even when both players leave in the same step (in game). Leaving a replay 456 stops its playback, and `play` returns `Result.UNDECIDED`. Asking again in the turn changes nothing. 457 """ 458 self._current_game().leaving = True 459 460 def play( 461 self, 462 client: Client, 463 *, 464 steps_per_turn: int = 1, 465 realtime: bool = False, 466 time_limit: GameTime | None = None, 467 enemy_ladder_id: str | None = None, 468 save_replay_to: Path | str | None = None, 469 ) -> Result: 470 """Play the game `client` has joined to its end, a turn every `steps_per_turn` steps, and return how it ended 471 for this player. 472 473 `run_local`, `run_ladder`, `run_replay` and `run_recording` call this. Call it directly to play a game connected 474 some other way. `time_limit` calls a game that reaches it a tie, and stops a replay at it `Result.UNDECIDED`; 475 one that is not a `GameTime` raises `TypeError` before the game starts. `realtime` must say how the game was 476 created: a stepped game played in real time never moves, which raises `ValueError` on the first turn. 477 `enemy_ladder_id` is the ladder's id for the opponent, which `enemy.ladder_id` reads. 478 479 `save_replay_to` is a file to save the game's replay to, however the game ends: at its end, at the time 480 limit, before leaving it for `leave_game`, and after a handler raises. A save that fails is logged, never 481 raised. Before the game starts, a `save_replay_to` in no folder that exists raises `FileNotFoundError`, and one 482 that names a folder `IsADirectoryError`. 483 484 An api plays one game. Once it has started one, this and every runner raise `RuntimeError` before anything 485 else. A call that raised before the game started, on its arguments or while reading the game's map, tables and 486 first observation, leaves the api to play. 487 """ 488 self._check_has_not_played() 489 if time_limit is not None: 490 check_game_time(time_limit, "time_limit") 491 replay_path = None if save_replay_to is None else Path(save_replay_to) 492 if replay_path is not None: 493 check_file_to_write(replay_path, "save the replay into") 494 game = _Game.start(client, enemy_ladder_id=enemy_ladder_id) 495 self._game = game 496 if self._extensions_builder is None: 497 self._extensions = None 498 logger.info("Playing {} at {} steps a turn", game.game_map.name, steps_per_turn) 499 events = self._events 500 events._set_time(game.time) 501 try: 502 result = self._play_saving_the_replay( 503 game, 504 steps_per_turn=steps_per_turn, 505 realtime=realtime, 506 time_limit=time_limit, 507 save_replay_to=replay_path, 508 ) 509 if game.leaving and client.in_game: 510 logger.info("Leaving the game") 511 client.leave_game() 512 events.emit(GameEndEvent(result, time=game.time)) 513 finally: 514 # Ended, or ended by a handler that raised: no game is being played to give an event its time. 515 events._set_time(None) 516 return result 517 518 def _play_saving_the_replay( 519 self, 520 game: _Game, 521 *, 522 steps_per_turn: int, 523 realtime: bool, 524 time_limit: GameTime | None, 525 save_replay_to: Path | None, 526 ) -> Result: 527 """Build the extensions, start `game` and take its turns until it ends, or the bot asks to leave it, and return 528 how it ended. Then, however the turns ended, save its replay to `save_replay_to` if given, while the client is 529 still in the game.""" 530 try: 531 if (build_extensions := self._extensions_builder) is not None: 532 with self._events._subscribing_extensions(): 533 self._extensions = build_extensions(self) 534 self._events.emit(GameStartEvent(time=game.time)) 535 return self._play_turns(game, steps_per_turn=steps_per_turn, realtime=realtime, time_limit=time_limit) 536 finally: 537 if save_replay_to is not None: 538 _save_replay(game.client, save_replay_to) 539 540 def _play_turns(self, game: _Game, *, steps_per_turn: int, realtime: bool, time_limit: GameTime | None) -> Result: 541 """Take the turns of `game` until it ends or the bot asks to leave it, and return how it ended.""" 542 events, client = self._events, game.client 543 while (result := game.outcome()) is None: 544 if time_limit is not None and game.time >= time_limit: 545 if client.in_replay: 546 logger.info("Stopping the replay at its {:.0f} second limit", time_limit.seconds) 547 return game.finish(Result.UNDECIDED) 548 logger.info("Calling the game a tie at its {:.0f} second limit", time_limit.seconds) 549 return game.finish(Result.TIE) 550 551 events.emit(TurnStartEvent(time=game.time)) 552 events._hand_out([*game.report(events), TurnEvent(time=game.time)]) 553 try: 554 # The turn's handlers have all returned, so what they asked for goes out now. 555 game.send_turn() 556 if game.leaving: 557 # Left once the replay is saved, which the game gives no client that has left (in game). 558 return game.finish(Result.UNDECIDED if client.in_replay else Result.DEFEAT) 559 if not realtime: 560 client.step(steps_per_turn) 561 except GameEndedError: 562 # The game ended while the handlers ran, as a realtime game can. Its last observation says how. 563 game.observe() 564 else: 565 if realtime: 566 # A realtime game runs on its own, so each turn asks for the step it wants. 567 _observe_realtime(game, game.step + steps_per_turn) 568 else: 569 game.observe() 570 events._set_time(game.time) 571 return result
Everything a bot talks to. It is built before there is a game.
Construct one where the rest of your bot can reach it, module scope included, and pass it to run_local or
run_ladder for its game. An api plays one game: a program that plays several makes an api for each. Never
subclass it: your own helpers belong in your own modules, as ordinary functions.
Time is counted in steps: one step is one game loop, and 22.4 make a second. A moment or a length of game time is a
GameTime, but for the two counts of steps, step and steps_per_turn. The bot takes a turn every
steps_per_turn steps, which the game is played with. Each turn hands its handlers a TurnStartEvent, then
the events its observation reports, in the order docs/events.md gives, then a TurnEvent.
Anything of the game raises NotPlayingError until the game starts. After it ends, the api keeps answering from
it.
E is the type of extensions: an Api() is an Api[None], and one made with extensions=Extensions an
Api[Extensions]. A function that takes any api takes an Api[object].
97 def __init__( 98 self, 99 *, 100 extensions: Callable[[Any], object] | None = None, 101 time_handlers: bool = False, 102 ) -> None: 103 """Build the bot's extensions with `extensions` once the game starts, as `Api.extensions` says, and time every 104 handler call, read as `handler_timings`, if `time_handlers`. This connects to nothing. 105 106 `extensions` builds what `Api.extensions` reads, the bot's own object holding its extensions, from this api: 107 its class, whose constructor takes the api and builds each extension. 108 """ 109 self._extensions_builder = extensions 110 self._extensions: object = _NOT_BUILT 111 self._events = _EventBus(time_handlers=time_handlers) 112 # Everything that comes with the game, from the moment it starts. 113 self._game: _Game | None = None
Build the bot's extensions with extensions once the game starts, as Api.extensions says, and time every
handler call, read as handler_timings, if time_handlers. This connects to nothing.
extensions builds what Api.extensions reads, the bot's own object holding its extensions, from this api:
its class, whose constructor takes the api and builds each extension.
142 def on(self, event_type: type[Event] | EventFilter[Any], /, **options: Any) -> Any: 143 """Subscribe the decorated function to `event_type`, or mark the decorated method for `subscribe`. This works 144 before any game, so handlers can subscribe as their modules are imported. 145 146 `event_type` is an event type, whose events and its subclasses' the handler is handed, or a filter from `only` 147 or `of`. `where` on the `EventSubscriber` it returns narrows further. A type that has `of` is subscribed to only 148 through it, and a type checker refuses it bare. A handler of `Event` is handed every event, which makes NachOS 149 produce every type of event it otherwise would not, including comparing every unit with the observation 150 before; a parameterized event comes only with the parameters other handlers asked for. 151 152 A method is marked, and subscribed for each instance passed to `subscribe`: a function defined in a class body 153 that takes at least two positional arguments without defaults, the instance and the event, or wraps one through 154 `functools.wraps`. Any other function is subscribed at once, wherever it is defined, a static method taking the 155 event alone included, and so is a method already bound to its instance. Either stays subscribed until it is 156 passed to `unsubscribe`, held strongly, so it runs whether or not anything else keeps it alive. 157 158 `priority` orders the handler among the event's handlers, highest first and then in subscription order; and 159 among a turn's: every handler of one priority is handed each event of the turn it selects, in the turn's order, 160 before any handler of the next. `EventPriority.BEFORE` and `EventPriority.AFTER` are for the handlers 161 subscribed while NachOS builds the extensions, and those take no other, as `Api.extensions` says: either misuse 162 raises `ValueError`. The handler runs on every event unless held back: `min_interval` waits until that long has 163 passed since it last ran, `at_time` runs it once, on the first event at or after that time, and `once` on the 164 first event. `min_interval` with either of the others, or not above zero, raises `ValueError`, and either of the 165 two not a `GameTime`, `TypeError`. These count only the events selected, those emitted before the game included. 166 An exception it raises ends the game, unless `catch_exceptions`, which logs it and goes on. 167 168 The handler must take an event of `event_type`, which a type checker checks. One decorated for several event 169 types takes an `Event`. 170 """ 171 return self._events.on(event_type, **options)
Subscribe the decorated function to event_type, or mark the decorated method for subscribe. This works
before any game, so handlers can subscribe as their modules are imported.
event_type is an event type, whose events and its subclasses' the handler is handed, or a filter from only
or of. where on the EventSubscriber it returns narrows further. A type that has of is subscribed to only
through it, and a type checker refuses it bare. A handler of Event is handed every event, which makes NachOS
produce every type of event it otherwise would not, including comparing every unit with the observation
before; a parameterized event comes only with the parameters other handlers asked for.
A method is marked, and subscribed for each instance passed to subscribe: a function defined in a class body
that takes at least two positional arguments without defaults, the instance and the event, or wraps one through
functools.wraps. Any other function is subscribed at once, wherever it is defined, a static method taking the
event alone included, and so is a method already bound to its instance. Either stays subscribed until it is
passed to unsubscribe, held strongly, so it runs whether or not anything else keeps it alive.
priority orders the handler among the event's handlers, highest first and then in subscription order; and
among a turn's: every handler of one priority is handed each event of the turn it selects, in the turn's order,
before any handler of the next. EventPriority.BEFORE and EventPriority.AFTER are for the handlers
subscribed while NachOS builds the extensions, and those take no other, as Api.extensions says: either misuse
raises ValueError. The handler runs on every event unless held back: min_interval waits until that long has
passed since it last ran, at_time runs it once, on the first event at or after that time, and once on the
first event. min_interval with either of the others, or not above zero, raises ValueError, and either of the
two not a GameTime, TypeError. These count only the events selected, those emitted before the game included.
An exception it raises ends the game, unless catch_exceptions, which logs it and goes on.
The handler must take an event of event_type, which a type checker checks. One decorated for several event
types takes an Event.
173 def subscribe(self, instance: object) -> None: 174 """Subscribe every method of `instance` marked with `on`, until `instance` is passed to `unsubscribe`. 175 176 An unmarked override leaves the method it overrides unsubscribed. Raises `ValueError` if `instance` has no 177 marked method, or one of them is subscribed for it already, a method subscribed bound through `on` aside; and 178 `TypeError` if a marked function is under a `classmethod` or a `staticmethod`. 179 """ 180 self._events.subscribe(instance)
Subscribe every method of instance marked with on, until instance is passed to unsubscribe.
An unmarked override leaves the method it overrides unsubscribed. Raises ValueError if instance has no
marked method, or one of them is subscribed for it already, a method subscribed bound through on aside; and
TypeError if a marked function is under a classmethod or a staticmethod.
182 def unsubscribe(self, target: object) -> None: 183 """Unsubscribe `target`: a function, a bound method, or every method of an instance. 184 185 Raises `ValueError` if nothing of it is subscribed. 186 """ 187 self._events.unsubscribe(target)
Unsubscribe target: a function, a bound method, or every method of an instance.
Raises ValueError if nothing of it is subscribed.
189 def emit(self, event: Event) -> None: 190 """Hand `event` to every handler of its type or a base type that selects it and is due to run. All have returned 191 when this returns. A handler may itself emit an event. 192 193 An event made without a time is handed out as a copy with the current time, and the one passed in keeps none, 194 so it can be emitted again. Raises `ValueError` for one when no game is being played. 195 """ 196 self._events.emit(event)
Hand event to every handler of its type or a base type that selects it and is due to run. All have returned
when this returns. A handler may itself emit an event.
An event made without a time is handed out as a copy with the current time, and the one passed in keeps none,
so it can be emitted again. Raises ValueError for one when no game is being played.
198 @property 199 def handler_timings(self) -> Mapping[type[Event], Mapping[str, HandlerTiming]]: 200 """How long each handler has taken, by event type and handler name, on events emitted before the game too. 201 202 A handler is named by its module and qualified name, so every instance of a class counts under one name. Raises 203 `RuntimeError` unless the api was made with `time_handlers=True`. 204 """ 205 return self._events.timings
How long each handler has taken, by event type and handler name, on events emitted before the game too.
A handler is named by its module and qualified name, so every instance of a class counts under one name. Raises
RuntimeError unless the api was made with time_handlers=True.
207 @property 208 def extensions(self) -> E: 209 """The bot's own object holding its extensions, built by what the api was given as `extensions`, or `None` for 210 an api made without. 211 212 NachOS builds it once, with this api, after reading the game's map, tables and first observation and before 213 `GameStartEvent`, so `api.map`, `api.units` and the rest answer while it is built. Every handler subscribed 214 meanwhile runs at `EventPriority.BEFORE`, before every handler of the bot's of its event and of the turn's 215 events handed out with it, or at `EventPriority.AFTER`, after every one, in the order they subscribed; one 216 subscribed at another priority raises `ValueError`. So what an extension works out before the bot is up to date 217 when the bot's handlers read it, an order a bot's handler gives a unit an extension ordered before it goes out 218 last and stands, and an extension working after the bot sees every order the bot gave in the turn. A handler an 219 extension subscribes later is subscribed as the bot's are. 220 221 Raises `NotPlayingError` before the game starts, and `RuntimeError` while the extensions are being built, or 222 once building them raised. 223 """ 224 extensions = self._extensions 225 if extensions is _NOT_BUILT: 226 self._current_game() 227 raise RuntimeError( 228 "the extensions are not built: an extension is handed the others it needs in its constructor" 229 ) 230 # Built by what `extensions` was, typed as building an `E`; `cast` would cost a call on every read. 231 built: E = extensions # pyright: ignore[reportAssignmentType] 232 return built
The bot's own object holding its extensions, built by what the api was given as extensions, or None for
an api made without.
NachOS builds it once, with this api, after reading the game's map, tables and first observation and before
GameStartEvent, so api.map, api.units and the rest answer while it is built. Every handler subscribed
meanwhile runs at EventPriority.BEFORE, before every handler of the bot's of its event and of the turn's
events handed out with it, or at EventPriority.AFTER, after every one, in the order they subscribed; one
subscribed at another priority raises ValueError. So what an extension works out before the bot is up to date
when the bot's handlers read it, an order a bot's handler gives a unit an extension ordered before it goes out
last and stands, and an extension working after the bot sees every order the bot gave in the turn. A handler an
extension subscribes later is subscribed as the bot's are.
Raises NotPlayingError before the game starts, and RuntimeError while the extensions are being built, or
once building them raised.
245 @property 246 def client(self) -> Client: 247 """The client the game is played on.""" 248 return self._current_game().client
The client the game is played on.
250 @property 251 def map(self) -> GameMap: 252 """The map the game is played on.""" 253 return self._current_game().game_map
The map the game is played on.
255 @property 256 def expansions(self) -> tuple[Expansion, ...]: 257 """Every place on the map to build a townhall, as the game began, by pathing distance from this player's start, 258 nearest first: its own start, then its natural. Those no path reaches come last, sorted by increasing 259 straight-line distance from this player's start. Each start location is a `StartLocation`, this player's 260 `player.start_location` and the enemy's `enemy.start_location`.""" 261 return self._current_game().expansions
Every place on the map to build a townhall, as the game began, by pathing distance from this player's start,
nearest first: its own start, then its natural. Those no path reaches come last, sorted by increasing
straight-line distance from this player's start. Each start location is a StartLocation, this player's
player.start_location and the enemy's enemy.start_location.
263 @property 264 def data(self) -> GameData: 265 """The game's data tables, as they were before any upgrade.""" 266 return self._current_game().game_data
The game's data tables, as they were before any upgrade.
268 @property 269 def step(self) -> int: 270 """The step of the last observation.""" 271 return self._current_game().step
The step of the last observation.
273 @property 274 def time(self) -> GameTime: 275 """The time of the last observation: `step` as a `GameTime`.""" 276 return self._current_game().time
The time of the last observation: step as a GameTime.
278 @property 279 def result(self) -> Result | None: 280 """How the game ended for this player, or `None` while it is being played.""" 281 return self._current_game().result
How the game ended for this player, or None while it is being played.
283 @property 284 def orders(self) -> OrderBook: 285 """This player's orders for the turn. 286 287 Orders are sent in one request after the turn's last handler returns. A turn that orders nothing sends nothing. 288 """ 289 return self._current_game().orders
This player's orders for the turn.
Orders are sent in one request after the turn's last handler returns. A turn that orders nothing sends nothing.
291 @property 292 def units(self) -> Units[Unit[Any]]: 293 """Every unit in the last observation, including remembered structures out of sight and hidden units. In a 294 replay played back with the fog off, those the observation would have listed with the fog on.""" 295 return self._current_game().tracker.unit_tracker.present
Every unit in the last observation, including remembered structures out of sight and hidden units. In a replay played back with the fog off, those the observation would have listed with the fog on.
297 @property 298 def all_units(self) -> Units[Unit[Any]]: 299 """Every unit of a replay played back with the fog off, as the game lists it then: those of `units`, under the 300 same ids, and those this player did not see. Each reads as visible, in full, but one undetected in this 301 player's sight, whose health and the like the game reports as 0 (in game): it reads as last reported in full. 302 303 Raises `FogOnError` in a game, and in a replay played back with the fog on. 304 """ 305 if (whole_game_tracker := self._current_game().whole_game_tracker) is None: 306 raise FogOnError("the fog is on, so the game reports only what this player sees") 307 return whole_game_tracker.unit_tracker.present
Every unit of a replay played back with the fog off, as the game lists it then: those of units, under the
same ids, and those this player did not see. Each reads as visible, in full, but one undetected in this
player's sight, whose health and the like the game reports as 0 (in game): it reads as last reported in full.
Raises FogOnError in a game, and in a replay played back with the fog on.
309 @property 310 def known_units(self) -> Units[Unit[Any]]: 311 """Every unit not known to be dead: those in the last observation first, then those it left out.""" 312 return self._current_game().tracker.unit_tracker.known
Every unit not known to be dead: those in the last observation first, then those it left out.
314 @property 315 def score(self) -> Score: 316 """The score the game keeps for this player.""" 317 return self._current_game().state.score
The score the game keeps for this player.
319 @property 320 def resources(self) -> Resources: 321 """The minerals and vespene this player has to spend.""" 322 return self._current_game().state.resources
The minerals and vespene this player has to spend.
324 @property 325 def supply(self) -> Supply: 326 """The supply this player's units take and its structures and units provide.""" 327 return self._current_game().state.supply
The supply this player's units take and its structures and units provide.
329 @property 330 def ui_unit_counts(self) -> UiUnitCounts: 331 """The game interface's counts of this player's idle workers, army units and warp gates.""" 332 return self._current_game().state.ui_unit_counts
The game interface's counts of this player's idle workers, army units and warp gates.
334 @property 335 def upgrades(self) -> frozenset[UpgradeId]: 336 """Every upgrade this player has finished. Raises `UncuratedIdError` if one is one the curated ids leave out.""" 337 return self._current_game().state.upgrades
Every upgrade this player has finished. Raises UncuratedIdError if one is one the curated ids leave out.
347 def in_production( 348 self, types: type[UnitType.AnyType] | UnitTypeId | Iterable[UnitTypeId], /, *unit_types: type[UnitType.AnyType] 349 ) -> tuple[InProduction, ...]: 350 """The units of the given types this player has started making or paid for, in the last observation. 351 352 There is one for each unit: a train a structure shows, queued ones included; an egg or a cocoon becoming one; a 353 structure going up, a structure morphing into one, a unit warping in; and a build a worker has been sent to 354 make, or an add-on its host has been ordered to build, until the structure stands. A reactor's two marines are 355 two. The turn's orders are not among them; they are in `api.orders.issued_to`. Takes the types as 356 `Units.of_type` does. 357 """ 358 wanted = frozenset((types,)) if isinstance(types, UnitTypeId) else _type_ids_of(types, unit_types) 359 return self._current_game().state.production.of_types(wanted)
The units of the given types this player has started making or paid for, in the last observation.
There is one for each unit: a train a structure shows, queued ones included; an egg or a cocoon becoming one; a
structure going up, a structure morphing into one, a unit warping in; and a build a worker has been sent to
make, or an add-on its host has been ordered to build, until the structure stands. A reactor's two marines are
two. The turn's orders are not among them; they are in api.orders.issued_to. Takes the types as
Units.of_type does.
361 @property 362 def researches(self) -> Mapping[UpgradeId, Research]: 363 """Each research this player has running or queued in the last observation, by upgrade, in the order the 364 observation lists the structures and each its orders. A finished one is in `upgrades`.""" 365 return self._current_game().state.production.researches
Each research this player has running or queued in the last observation, by upgrade, in the order the
observation lists the structures and each its orders. A finished one is in upgrades.
367 @property 368 def action_failures(self) -> tuple[ActionFailure, ...]: 369 """The orders the game refused when the last turn's were sent, one for each unit a refused command named, then 370 those it accepted earlier and gave up on since the observation before. 371 372 Raises `UncuratedIdError` if one the game gave up on names an ability the curated ids leave out. 373 """ 374 game = self._current_game() 375 return game.orders._refusals + game.state.action_failures
The orders the game refused when the last turn's were sent, one for each unit a refused command named, then those it accepted earlier and gave up on since the observation before.
Raises UncuratedIdError if one the game gave up on names an ability the curated ids leave out.
377 @property 378 def player(self) -> Player: 379 """This player: its id, its race and the one it asked for, its name, and its `start_location`.""" 380 return self._current_game().player
This player: its id, its race and the one it asked for, its name, and its start_location.
382 @property 383 def enemy(self) -> Enemy: 384 """The other player, and what is known of it. Raises `NoEnemyError` in a game with no other player, such as a 385 mini-game. 386 387 `api.enemy.upgrades` holds the upgrade levels enemy units have shown and those the bot or an extension added 388 with `assume_upgrades`, as `Enemy.upgrades` says. Everything an upgrade changes on an enemy unit, 389 `Unit.weapons` and `Unit.speed` among them, counts them. `api.enemy.start_location` is where it started, as 390 `Enemy.start_location` says. 391 """ 392 if (enemy := self._current_game().enemy) is None: 393 raise NoEnemyError("this game has no other player") 394 return enemy
The other player, and what is known of it. Raises NoEnemyError in a game with no other player, such as a
mini-game.
api.enemy.upgrades holds the upgrade levels enemy units have shown and those the bot or an extension added
with assume_upgrades, as Enemy.upgrades says. Everything an upgrade changes on an enemy unit,
Unit.weapons and Unit.speed among them, counts them. api.enemy.start_location is where it started, as
Enemy.start_location says.
396 @property 397 def vision(self) -> Vision: 398 """What this player sees: where it can see now, where it has seen at any point in the game, and when it last 399 saw each tile, as `Vision` says.""" 400 return self._current_game().vision
What this player sees: where it can see now, where it has seen at any point in the game, and when it last
saw each tile, as Vision says.
402 @property 403 def placement(self) -> PlacementGrids: 404 """Where a structure may stand: on the map whatever happens in the game, and now as far as this player knows; 405 and the ground this player's ordered builds are to stand on, and what it has reserved.""" 406 return self._current_game().placement
Where a structure may stand: on the map whatever happens in the game, and now as far as this player knows; and the ground this player's ordered builds are to stand on, and what it has reserved.
408 @property 409 def debug(self) -> DebugCommands: 410 """Drawing on the game's screen, cheats and debug commands, sent after each turn's orders.""" 411 return self._current_game().debug
Drawing on the game's screen, cheats and debug commands, sent after each turn's orders.
413 @property 414 def camera(self) -> Camera: 415 """This player's camera: where it is centered, and moving it.""" 416 return self._current_game().camera
This player's camera: where it is centered, and moving it.
418 @property 419 def pathing(self) -> Pathing: 420 """How units get around the map as it stands now: the turn's grid of where ground units walk, paths over it, and 421 distances the game answers.""" 422 return self._current_game().pathing
How units get around the map as it stands now: the turn's grid of where ground units walk, paths over it, and distances the game answers.
424 @property 425 def creep(self) -> Grid[bool]: 426 """Where creep covers the ground, over the playable area.""" 427 return self._current_game().state.creep
Where creep covers the ground, over the playable area.
429 @property 430 def effects(self) -> tuple[Effect, ...]: 431 """Every effect this player can see. Raises `UncuratedIdError` if one is an effect the curated ids leave out.""" 432 return self._current_game().state.effects
Every effect this player can see. Raises UncuratedIdError if one is an effect the curated ids leave out.
434 def chat(self, text: str, *, team_only: bool = False) -> None: 435 """Send `text` to every player, or to this player's team only if `team_only`, with the turn's orders: after 436 them and the camera's move, each message of the turn in the order given. The game drops chat that comes too 437 fast without a word, once some 500 bytes have gone out in a row, counting by the clock rather than in steps 438 (in game). 439 440 Raises `ValueError` for an empty text, and for one of 1040 bytes or more in UTF-8, which would kill the game 441 client (in game). 442 """ 443 game = self._current_game() 444 if not text: 445 raise ValueError("a chat message cannot be empty") 446 if (size := len(text.encode())) > _MOST_CHAT_BYTES: 447 raise ValueError( 448 f"a chat message of {_MOST_CHAT_BYTES + 1} bytes or more kills the game client, and this one is {size}" 449 ) 450 game.queue_chat(text, team_only=team_only)
Send text to every player, or to this player's team only if team_only, with the turn's orders: after
them and the camera's move, each message of the turn in the order given. The game drops chat that comes too
fast without a word, once some 500 bytes have gone out in a row, counting by the clock rather than in steps
(in game).
Raises ValueError for an empty text, and for one of 1040 bytes or more in UTF-8, which would kill the game
client (in game).
452 def leave_game(self) -> None: 453 """Leave the game, conceding it, once the turn's handlers have run and its orders, chat and debug commands have 454 gone out. `play` then returns `Result.DEFEAT`, as the protocol counts leaving a surrender: the game reports 455 nothing to a client that has left, even when both players leave in the same step (in game). Leaving a replay 456 stops its playback, and `play` returns `Result.UNDECIDED`. Asking again in the turn changes nothing. 457 """ 458 self._current_game().leaving = True
Leave the game, conceding it, once the turn's handlers have run and its orders, chat and debug commands have
gone out. play then returns Result.DEFEAT, as the protocol counts leaving a surrender: the game reports
nothing to a client that has left, even when both players leave in the same step (in game). Leaving a replay
stops its playback, and play returns Result.UNDECIDED. Asking again in the turn changes nothing.
460 def play( 461 self, 462 client: Client, 463 *, 464 steps_per_turn: int = 1, 465 realtime: bool = False, 466 time_limit: GameTime | None = None, 467 enemy_ladder_id: str | None = None, 468 save_replay_to: Path | str | None = None, 469 ) -> Result: 470 """Play the game `client` has joined to its end, a turn every `steps_per_turn` steps, and return how it ended 471 for this player. 472 473 `run_local`, `run_ladder`, `run_replay` and `run_recording` call this. Call it directly to play a game connected 474 some other way. `time_limit` calls a game that reaches it a tie, and stops a replay at it `Result.UNDECIDED`; 475 one that is not a `GameTime` raises `TypeError` before the game starts. `realtime` must say how the game was 476 created: a stepped game played in real time never moves, which raises `ValueError` on the first turn. 477 `enemy_ladder_id` is the ladder's id for the opponent, which `enemy.ladder_id` reads. 478 479 `save_replay_to` is a file to save the game's replay to, however the game ends: at its end, at the time 480 limit, before leaving it for `leave_game`, and after a handler raises. A save that fails is logged, never 481 raised. Before the game starts, a `save_replay_to` in no folder that exists raises `FileNotFoundError`, and one 482 that names a folder `IsADirectoryError`. 483 484 An api plays one game. Once it has started one, this and every runner raise `RuntimeError` before anything 485 else. A call that raised before the game started, on its arguments or while reading the game's map, tables and 486 first observation, leaves the api to play. 487 """ 488 self._check_has_not_played() 489 if time_limit is not None: 490 check_game_time(time_limit, "time_limit") 491 replay_path = None if save_replay_to is None else Path(save_replay_to) 492 if replay_path is not None: 493 check_file_to_write(replay_path, "save the replay into") 494 game = _Game.start(client, enemy_ladder_id=enemy_ladder_id) 495 self._game = game 496 if self._extensions_builder is None: 497 self._extensions = None 498 logger.info("Playing {} at {} steps a turn", game.game_map.name, steps_per_turn) 499 events = self._events 500 events._set_time(game.time) 501 try: 502 result = self._play_saving_the_replay( 503 game, 504 steps_per_turn=steps_per_turn, 505 realtime=realtime, 506 time_limit=time_limit, 507 save_replay_to=replay_path, 508 ) 509 if game.leaving and client.in_game: 510 logger.info("Leaving the game") 511 client.leave_game() 512 events.emit(GameEndEvent(result, time=game.time)) 513 finally: 514 # Ended, or ended by a handler that raised: no game is being played to give an event its time. 515 events._set_time(None) 516 return result
Play the game client has joined to its end, a turn every steps_per_turn steps, and return how it ended
for this player.
run_local, run_ladder, run_replay and run_recording call this. Call it directly to play a game connected
some other way. time_limit calls a game that reaches it a tie, and stops a replay at it Result.UNDECIDED;
one that is not a GameTime raises TypeError before the game starts. realtime must say how the game was
created: a stepped game played in real time never moves, which raises ValueError on the first turn.
enemy_ladder_id is the ladder's id for the opponent, which enemy.ladder_id reads.
save_replay_to is a file to save the game's replay to, however the game ends: at its end, at the time
limit, before leaving it for leave_game, and after a handler raises. A save that fails is logged, never
raised. Before the game starts, a save_replay_to in no folder that exists raises FileNotFoundError, and one
that names a folder IsADirectoryError.
An api plays one game. Once it has started one, this and every runner raise RuntimeError before anything
else. A call that raised before the game started, on its arguments or while reading the game's map, tables and
first observation, leaves the api to play.
58class FogOnError(NachOSError, RuntimeError): 59 """The fog is on, as in every game, so the game reports only what this player sees."""
The fog is on, as in every game, so the game reports only what this player sees.
54class NoEnemyError(NachOSError, RuntimeError): 55 """The game has no other player, as a mini-game has not, so there is no enemy to answer about."""
The game has no other player, as a mini-game has not, so there is no enemy to answer about.
50class NotPlayingError(NachOSError, RuntimeError): 51 """No game has been joined, so there is nothing to answer from."""
No game has been joined, so there is nothing to answer from.