sc2nachos.events
The events the api hands out as a game goes on, and what selects them for a handler.
A game hands out GameStartEvent, then a turn for each observation but the last, then GameEndEvent. A turn hands
out TurnStartEvent, then the events its observation reports, then TurnEvent. only, of and where select some
events of a type. The Any… events, such as AnyUnitEvent, are bases through which a handler takes a whole kind of
event, and are never handed out themselves. A subclass of Event is a bot's own event, sent with api.emit.
docs/events.md lists every event: its fields, what selects it, and when it comes.
1"""The events the api hands out as a game goes on, and what selects them for a handler. 2 3A game hands out `GameStartEvent`, then a turn for each observation but the last, then `GameEndEvent`. A turn hands 4out `TurnStartEvent`, then the events its observation reports, then `TurnEvent`. `only`, `of` and `where` select some 5events of a type. The `Any…` events, such as `AnyUnitEvent`, are bases through which a handler takes a whole kind of 6event, and are never handed out themselves. A subclass of `Event` is a bot's own event, sent with `api.emit`. 7`docs/events.md` lists every event: its fields, what selects it, and when it comes. 8""" 9 10from sc2nachos.events._done import Done 11from sc2nachos.events._event import ( 12 AlertEvent, 13 AnyAreaEvent, 14 AnyBuffEvent, 15 AnyChatEvent, 16 AnyUnitDiedEvent, 17 AnyUnitEvent, 18 AnyUnitTypeChangedEvent, 19 AnyUpgradeEvent, 20 AnyVitalEvent, 21 EnemyRaceKnownEvent, 22 EnemyUnitCloakChangedEvent, 23 EnemyUnitDamagedEvent, 24 EnemyUnitDiedEvent, 25 EnemyUnitEnergyLostEvent, 26 EnemyUnitEnteredAreaEvent, 27 EnemyUnitEnteredSightEvent, 28 EnemyUnitFirstSeenEvent, 29 EnemyUnitGainedBuffEvent, 30 EnemyUnitLeftAreaEvent, 31 EnemyUnitLeftSightEvent, 32 EnemyUnitLostBuffEvent, 33 EnemyUnitTypeChangedEvent, 34 EnemyUnitVitalDroppedEvent, 35 EnemyUnitVitalReachedEvent, 36 Event, 37 GameEndEvent, 38 GameStartEvent, 39 NeutralUnitDiedEvent, 40 OpponentChatEvent, 41 OwnActionEvent, 42 OwnChatEvent, 43 OwnConstructionFinishedEvent, 44 OwnConstructionStartedEvent, 45 OwnUnitBecameIdleEvent, 46 OwnUnitCloakChangedEvent, 47 OwnUnitCreatedEvent, 48 OwnUnitDamagedEvent, 49 OwnUnitDiedEvent, 50 OwnUnitEnergyLostEvent, 51 OwnUnitEnteredAreaEvent, 52 OwnUnitGainedBuffEvent, 53 OwnUnitLeftAreaEvent, 54 OwnUnitLostBuffEvent, 55 OwnUnitTypeChangedEvent, 56 OwnUnitVitalDroppedEvent, 57 OwnUnitVitalReachedEvent, 58 OwnUpgradeFinishedEvent, 59 OwnUpgradeStartedEvent, 60 OwnUpgradeStoppedEvent, 61 OwnWarpInFinishedEvent, 62 OwnWarpInStartedEvent, 63 ParameterizedEvent, 64 TurnEvent, 65 TurnStartEvent, 66 UnitAllianceChangedEvent, 67 UnitFoundDeadEvent, 68) 69from sc2nachos.events._event_filter import EventFilter 70from sc2nachos.events._event_priority import EventPriority 71from sc2nachos.events._event_subscriber import EventSubscriber 72from sc2nachos.events._handler_timing import HandlerTiming 73 74__all__ = [ 75 "AlertEvent", 76 "AnyAreaEvent", 77 "AnyBuffEvent", 78 "AnyChatEvent", 79 "AnyUnitDiedEvent", 80 "AnyUnitEvent", 81 "AnyUnitTypeChangedEvent", 82 "AnyUpgradeEvent", 83 "AnyVitalEvent", 84 "Done", 85 "EnemyRaceKnownEvent", 86 "EnemyUnitCloakChangedEvent", 87 "EnemyUnitDamagedEvent", 88 "EnemyUnitDiedEvent", 89 "EnemyUnitEnergyLostEvent", 90 "EnemyUnitEnteredAreaEvent", 91 "EnemyUnitEnteredSightEvent", 92 "EnemyUnitFirstSeenEvent", 93 "EnemyUnitGainedBuffEvent", 94 "EnemyUnitLeftAreaEvent", 95 "EnemyUnitLeftSightEvent", 96 "EnemyUnitLostBuffEvent", 97 "EnemyUnitTypeChangedEvent", 98 "EnemyUnitVitalDroppedEvent", 99 "EnemyUnitVitalReachedEvent", 100 "Event", 101 "EventFilter", 102 "EventPriority", 103 "EventSubscriber", 104 "GameEndEvent", 105 "GameStartEvent", 106 "HandlerTiming", 107 "NeutralUnitDiedEvent", 108 "OpponentChatEvent", 109 "OwnActionEvent", 110 "OwnChatEvent", 111 "OwnConstructionFinishedEvent", 112 "OwnConstructionStartedEvent", 113 "OwnUnitBecameIdleEvent", 114 "OwnUnitCloakChangedEvent", 115 "OwnUnitCreatedEvent", 116 "OwnUnitDamagedEvent", 117 "OwnUnitDiedEvent", 118 "OwnUnitEnergyLostEvent", 119 "OwnUnitEnteredAreaEvent", 120 "OwnUnitGainedBuffEvent", 121 "OwnUnitLeftAreaEvent", 122 "OwnUnitLostBuffEvent", 123 "OwnUnitTypeChangedEvent", 124 "OwnUnitVitalDroppedEvent", 125 "OwnUnitVitalReachedEvent", 126 "OwnUpgradeFinishedEvent", 127 "OwnUpgradeStartedEvent", 128 "OwnUpgradeStoppedEvent", 129 "OwnWarpInFinishedEvent", 130 "OwnWarpInStartedEvent", 131 "ParameterizedEvent", 132 "TurnEvent", 133 "TurnStartEvent", 134 "UnitAllianceChangedEvent", 135 "UnitFoundDeadEvent", 136]
509class AlertEvent(Event): 510 """The game alerted this player. Several in one observation come in the order the game raised them.""" 511 512 alert: Alert 513 """The alert. Its docstring says when the game raises it.""" 514 515 @classmethod 516 def only(cls, alert: Alert, /, *alerts: Alert) -> EventFilter[Self]: 517 """The events of these alerts, for `on`.""" 518 return EventFilter(cls, keys=frozenset((alert, *alerts))) 519 520 @classmethod 521 def _key_of(cls, *made_of: Any) -> Hashable: 522 return made_of[0] 523 524 def _key(self) -> Hashable: 525 return self._key_of(self.alert)
The game alerted this player. Several in one observation come in the order the game raised them.
515 @classmethod 516 def only(cls, alert: Alert, /, *alerts: Alert) -> EventFilter[Self]: 517 """The events of these alerts, for `on`.""" 518 return EventFilter(cls, keys=frozenset((alert, *alerts)))
The events of these alerts, for on.
397class AnyAreaEvent(ParameterizedEvent): 398 """A unit has crossed the edge of an area. NachOS never hands one out itself. 399 400 A handler of `AnyAreaEvent.of(area)` is handed every crossing of its edge, in and out, by this player's units and 401 the enemy's alike. 402 """ 403 404 unit: Unit[Any] 405 area: Area 406 """The area, as given to `of`.""" 407 408 @classmethod 409 def of(cls, area: Area, /) -> EventFilter[Self]: 410 """The events of units crossing the edge of `area`, for `on`.""" 411 return EventFilter(cls, keys=frozenset((area,))) 412 413 @classmethod 414 def _key_of(cls, *made_of: Any) -> Hashable: 415 return made_of[1] 416 417 def _key(self) -> Hashable: 418 return self._key_of(self.unit, self.area)
A unit has crossed the edge of an area. NachOS never hands one out itself.
A handler of AnyAreaEvent.of(area) is handed every crossing of its edge, in and out, by this player's units and
the enemy's alike.
330class AnyBuffEvent(Event): 331 """A unit has gained or lost a buff. `only` selects by the buff. NachOS never hands one out itself. 332 333 A handler of it is handed every buff gained or lost, by this player's units and the enemy's alike. 334 """ 335 336 unit: Unit[Any] 337 buff: BuffId 338 339 @classmethod 340 def only(cls, buff: BuffId, /, *buffs: BuffId) -> EventFilter[Self]: 341 """The events of these buffs, for `on`.""" 342 return EventFilter(cls, keys=frozenset((buff, *buffs))) 343 344 @classmethod 345 def _key_of(cls, *made_of: Any) -> Hashable: 346 return made_of[1] 347 348 def _key(self) -> Hashable: 349 return self._key_of(self.unit, self.buff)
A unit has gained or lost a buff. only selects by the buff. NachOS never hands one out itself.
A handler of it is handed every buff gained or lost, by this player's units and the enemy's alike.
339 @classmethod 340 def only(cls, buff: BuffId, /, *buffs: BuffId) -> EventFilter[Self]: 341 """The events of these buffs, for `on`.""" 342 return EventFilter(cls, keys=frozenset((buff, *buffs)))
The events of these buffs, for on.
490class AnyChatEvent(Event): 491 """A player, this one included, sent a message to the game's chat (in game). NachOS never hands one out itself: 492 this player's comes as `OwnChatEvent` and another player's as `OpponentChatEvent`, and one from a player the game's 493 info lists as an observer gets none.""" 494 495 player_id: int 496 """The id of the player who sent it.""" 497 text: str
A player, this one included, sent a message to the game's chat (in game). NachOS never hands one out itself:
this player's comes as OwnChatEvent and another player's as OpponentChatEvent, and one from a player the game's
info lists as an observer gets none.
456class AnyUnitDiedEvent(AnyUnitEvent): 457 """The game has reported a unit dead: killed, cancelled, an egg that hatched, a MULE that expired, or a drone when 458 the structure it became finishes or is killed, or a step later (in game). NachOS never hands one out itself: a unit 459 of this player's comes as `OwnUnitDiedEvent`, one of the enemy's as `EnemyUnitDiedEvent` and one of the map's as 460 `NeutralUnitDiedEvent`, and an ally's gets none. A unit reported dead never also gets `UnitFoundDeadEvent`."""
The game has reported a unit dead: killed, cancelled, an egg that hatched, a MULE that expired, or a drone when
the structure it became finishes or is killed, or a step later (in game). NachOS never hands one out itself: a unit
of this player's comes as OwnUnitDiedEvent, one of the enemy's as EnemyUnitDiedEvent and one of the map's as
NeutralUnitDiedEvent, and an ally's gets none. A unit reported dead never also gets UnitFoundDeadEvent.
81class AnyUnitEvent(Event): 82 """Something happened to one unit. `only` selects by the unit's type. NachOS never hands one out itself. 83 84 A handler of it is handed every event with a `unit`, whoever's the unit is, except the buff, vital, area and upgrade 85 events, which have bases of their own. Where an event comes in an own and an enemy kind, the side 86 is the one the unit is on at the time, whose class it has: a unit a neural parasite holds is the holder's. 87 """ 88 89 unit: Unit[Any] 90 91 @classmethod 92 def only( 93 cls, unit_type: type[UnitType.AnyType] | UnitTypeId, /, *unit_types: type[UnitType.AnyType] | UnitTypeId 94 ) -> EventFilter[Self]: 95 """The events of units of these types, for `on`. Each is a `UnitType`, a group of them, or a `UnitTypeId`. A 96 unit is matched by its type at the time of the event.""" 97 return EventFilter(cls, keys=_unit_type_ids_in((unit_type, *unit_types))) 98 99 @classmethod 100 def _key_of(cls, *made_of: Any) -> Hashable: 101 return made_of[0].type_id 102 103 def _key(self) -> Hashable: 104 return self._key_of(self.unit)
Something happened to one unit. only selects by the unit's type. NachOS never hands one out itself.
A handler of it is handed every event with a unit, whoever's the unit is, except the buff, vital, area and upgrade
events, which have bases of their own. Where an event comes in an own and an enemy kind, the side
is the one the unit is on at the time, whose class it has: a unit a neural parasite holds is the holder's.
91 @classmethod 92 def only( 93 cls, unit_type: type[UnitType.AnyType] | UnitTypeId, /, *unit_types: type[UnitType.AnyType] | UnitTypeId 94 ) -> EventFilter[Self]: 95 """The events of units of these types, for `on`. Each is a `UnitType`, a group of them, or a `UnitTypeId`. A 96 unit is matched by its type at the time of the event.""" 97 return EventFilter(cls, keys=_unit_type_ids_in((unit_type, *unit_types)))
The events of units of these types, for on. Each is a UnitType, a group of them, or a UnitTypeId. A
unit is matched by its type at the time of the event.
119class AnyUnitTypeChangedEvent(AnyUnitEvent): 120 """A unit has changed type: it burrowed, sieged, lowered, became a cocoon, or finished a morph. `only` selects it by 121 the type it changed to. NachOS never hands one out itself: a unit of this player's comes as 122 `OwnUnitTypeChangedEvent` and one of the enemy's as `EnemyUnitTypeChangedEvent`, and an ally's or the map's gets 123 none.""" 124 125 previous_type: UnitTypeId 126 """The type it was."""
A unit has changed type: it burrowed, sieged, lowered, became a cocoon, or finished a morph. only selects it by
the type it changed to. NachOS never hands one out itself: a unit of this player's comes as
OwnUnitTypeChangedEvent and one of the enemy's as EnemyUnitTypeChangedEvent, and an ally's or the map's gets
none.
174class AnyUpgradeEvent(Event): 175 """Something happened to one upgrade. `only` selects by the upgrade. NachOS never hands one out itself: this 176 player's researches come as `OwnUpgradeStartedEvent`, `OwnUpgradeStoppedEvent` and `OwnUpgradeFinishedEvent`, and 177 an extension may hand out its own.""" 178 179 upgrade: UpgradeId 180 181 @classmethod 182 def only(cls, upgrade: UpgradeId, /, *upgrades: UpgradeId) -> EventFilter[Self]: 183 """The events of these upgrades, for `on`.""" 184 return EventFilter(cls, keys=frozenset((upgrade, *upgrades))) 185 186 @classmethod 187 def _key_of(cls, *made_of: Any) -> Hashable: 188 return made_of[0] 189 190 def _key(self) -> Hashable: 191 return self._key_of(self.upgrade)
Something happened to one upgrade. only selects by the upgrade. NachOS never hands one out itself: this
player's researches come as OwnUpgradeStartedEvent, OwnUpgradeStoppedEvent and OwnUpgradeFinishedEvent, and
an extension may hand out its own.
181 @classmethod 182 def only(cls, upgrade: UpgradeId, /, *upgrades: UpgradeId) -> EventFilter[Self]: 183 """The events of these upgrades, for `on`.""" 184 return EventFilter(cls, keys=frozenset((upgrade, *upgrades)))
The events of these upgrades, for on.
249class AnyVitalEvent(ParameterizedEvent): 250 """A unit's health, shields or energy crossed a value. NachOS never hands one out itself. 251 252 A handler of `AnyVitalEvent.of(...)` is handed both reaching and dropping below the value, by this player's units 253 and the enemy's alike. 254 """ 255 256 unit: Unit[Any] 257 vital: VitalType 258 """Which of health, shields and energy crossed the value.""" 259 value: float 260 """The value crossed, as given to `of`.""" 261 262 @classmethod 263 def of( 264 cls, vital: VitalType, value: float, /, *unit_types: type[UnitType.AnyType] | UnitTypeId 265 ) -> EventFilter[Self]: 266 """The events of units whose `vital` crosses `value`, for `on`, limited to `unit_types` if any are given. Each 267 of `unit_types` is a `UnitType`, a group of them, or a `UnitTypeId`. 268 269 Raises `ValueError` unless `value` is above 0, and at most 1 for a fraction. 270 """ 271 if not value > 0 or (vital.is_fraction and value > 1): 272 most = " and at most 1" if vital.is_fraction else "" 273 raise ValueError(f"a {vital.value} is crossed above 0{most}, not at {value}") 274 types = _unit_type_ids_in(unit_types) if unit_types else _EVERY_TYPE 275 return EventFilter(cls, keys=frozenset((vital, float(value), type_id) for type_id in types)) 276 277 @classmethod 278 def _key_of(cls, *made_of: Any) -> Hashable: 279 unit, vital, value = made_of 280 return vital, value, unit.type_id 281 282 def _key(self) -> Hashable: 283 return self._key_of(self.unit, self.vital, self.value)
A unit's health, shields or energy crossed a value. NachOS never hands one out itself.
A handler of AnyVitalEvent.of(...) is handed both reaching and dropping below the value, by this player's units
and the enemy's alike.
262 @classmethod 263 def of( 264 cls, vital: VitalType, value: float, /, *unit_types: type[UnitType.AnyType] | UnitTypeId 265 ) -> EventFilter[Self]: 266 """The events of units whose `vital` crosses `value`, for `on`, limited to `unit_types` if any are given. Each 267 of `unit_types` is a `UnitType`, a group of them, or a `UnitTypeId`. 268 269 Raises `ValueError` unless `value` is above 0, and at most 1 for a fraction. 270 """ 271 if not value > 0 or (vital.is_fraction and value > 1): 272 most = " and at most 1" if vital.is_fraction else "" 273 raise ValueError(f"a {vital.value} is crossed above 0{most}, not at {value}") 274 types = _unit_type_ids_in(unit_types) if unit_types else _EVERY_TYPE 275 return EventFilter(cls, keys=frozenset((vital, float(value), type_id) for type_id in types))
7@final 8class Done: 9 """A handler returns this class itself to be called no more. 10 11 Any other return value is ignored. 12 """ 13 14 def __new__(cls) -> NoReturn: 15 raise TypeError("a handler returns `Done` itself, not an instance of it")
A handler returns this class itself to be called no more.
Any other return value is ignored.
72class EnemyRaceKnownEvent(Event): 73 """The enemy's race is known: on the first turn, wherever the game gives it or the enemy did not ask for Random, 74 and against a computer that did, on the turn its first unit is seen. It comes once a game, and never in a game with 75 no other player.""" 76 77 race: Race 78 """The race the enemy plays."""
The enemy's race is known: on the first turn, wherever the game gives it or the enemy did not ask for Random, and against a computer that did, on the turn its first unit is seen. It comes once a game, and never in a game with no other player.
322class EnemyUnitCloakChangedEvent(AnyUnitEvent): 323 """A unit of the enemy's in sight now and in the observation before has cloaked or uncloaked, or become detected or 324 undetected. Burrowing is not a cloak: a burrowed unit nothing detects is not listed at all (in game).""" 325 326 previous_cloak_state: CloakState 327 """The cloak it had."""
A unit of the enemy's in sight now and in the observation before has cloaked or uncloaked, or become detected or undetected. Burrowing is not a cloak: a burrowed unit nothing detects is not listed at all (in game).
224class EnemyUnitDamagedEvent(AnyUnitEvent): 225 """A unit of the enemy's visible now and in the observation before has lost health or shields, and kept its 226 type.""" 227 228 damage: float 229 """The health and shields it lost since the observation before, less what it regained in between."""
A unit of the enemy's visible now and in the observation before has lost health or shields, and kept its type.
469class EnemyUnitDiedEvent(AnyUnitDiedEvent): 470 """The game has reported a unit of the enemy's dead. Only deaths this player sees are reported (in game)."""
The game has reported a unit of the enemy's dead. Only deaths this player sees are reported (in game).
241class EnemyUnitEnergyLostEvent(AnyUnitEvent): 242 """A unit of the enemy's visible now and in the observation before has less energy, and kept its type: it cast a 243 spell, or lost energy to a feedback or an EMP.""" 244 245 energy_lost: float 246 """The energy it lost since the observation before, less what it regenerated in between."""
A unit of the enemy's visible now and in the observation before has less energy, and kept its type: it cast a spell, or lost energy to a feedback or an EMP.
428class EnemyUnitEnteredAreaEvent(AnyAreaEvent): 429 """A unit of the enemy's in sight is inside the area given to `of`, having last been seen in sight outside it, or 430 first seen in sight inside it once the area has been watched for a turn. One in the fog counts for neither."""
A unit of the enemy's in sight is inside the area given to of, having last been seen in sight outside it, or
first seen in sight inside it once the area has been watched for a turn. One in the fog counts for neither.
387class EnemyUnitEnteredSightEvent(AnyUnitEvent): 388 """A unit of the enemy's has come into sight: seen for the first time, back in the observation, or out of the fog. 389 A unit that cloaks where it stands stays in sight."""
A unit of the enemy's has come into sight: seen for the first time, back in the observation, or out of the fog. A unit that cloaks where it stands stays in sight.
114class EnemyUnitFirstSeenEvent(AnyUnitEvent): 115 """A unit of the enemy's is seen for the first time, in sight or in the fog. One first seen in sight also gets 116 `EnemyUnitEnteredSightEvent`."""
A unit of the enemy's is seen for the first time, in sight or in the fog. One first seen in sight also gets
EnemyUnitEnteredSightEvent.
361class EnemyUnitGainedBuffEvent(AnyBuffEvent): 362 """A unit of the enemy's visible now and in the observation before has a buff it did not have then. An enemy unit 363 nothing detects shows no buffs, so one becoming detected gains none (in game). Several on one unit come in id 364 order.""" 365 366 buff: BuffId 367 """The buff it gained."""
A unit of the enemy's visible now and in the observation before has a buff it did not have then. An enemy unit nothing detects shows no buffs, so one becoming detected gains none (in game). Several on one unit come in id order.
440class EnemyUnitLeftAreaEvent(AnyAreaEvent): 441 """A unit of the enemy's in sight is outside the area given to `of`, having last been seen in sight inside it. One 442 that dies inside it, or goes out of sight there, has not left it."""
A unit of the enemy's in sight is outside the area given to of, having last been seen in sight inside it. One
that dies inside it, or goes out of sight there, has not left it.
392class EnemyUnitLeftSightEvent(AnyUnitEvent): 393 """A unit of the enemy's that was in sight in the observation before is not now, and is not dead. A unit of this 394 player's the enemy took over in sight gets it with no `EnemyUnitEnteredSightEvent` before."""
A unit of the enemy's that was in sight in the observation before is not now, and is not dead. A unit of this
player's the enemy took over in sight gets it with no EnemyUnitEnteredSightEvent before.
379class EnemyUnitLostBuffEvent(AnyBuffEvent): 380 """A unit of the enemy's visible now and in the observation before no longer has a buff it had then. Several on 381 one unit come in id order.""" 382 383 buff: BuffId 384 """The buff it lost."""
A unit of the enemy's visible now and in the observation before no longer has a buff it had then. Several on one unit come in id order.
135class EnemyUnitTypeChangedEvent(AnyUnitTypeChangedEvent): 136 """A unit of the enemy's has changed type. A change out of sight comes when the unit is next seen."""
A unit of the enemy's has changed type. A change out of sight comes when the unit is next seen.
308class EnemyUnitVitalDroppedEvent(AnyVitalEvent): 309 """A visible unit of the enemy's has less than the value given to `of`, having last been seen visible at or 310 above it. Not for a unit first seen below it, and not again until it has been seen at or above it."""
A visible unit of the enemy's has less than the value given to of, having last been seen visible at or
above it. Not for a unit first seen below it, and not again until it has been seen at or above it.
294class EnemyUnitVitalReachedEvent(AnyVitalEvent): 295 """A visible unit of the enemy's has at least the value given to `of`, having last been seen visible below it. 296 One that regenerated past it out of sight is reported when next seen. Not for a unit first seen at it, and not 297 again until it has been seen below it."""
A visible unit of the enemy's has at least the value given to of, having last been seen visible below it.
One that regenerated past it out of sight is reported when next seen. Not for a unit first seen at it, and not
again until it has been seen below it.
22class Event(metaclass=_EventMeta): 23 """Something that happened in the game, stamped with the time the bot learns of it. 24 25 A subclass is a new event, made a frozen, slotted dataclass of the fields it declares; adding `@dataclass` to 26 it fails. A handler of a class is handed the events of its subclasses too. 27 """ 28 29 time: GameTime = field(default=_NO_TIME, kw_only=True) 30 """The time of the observation it comes with. An event made without one is emitted as a copy with the current 31 time.""" 32 33 @classmethod 34 def _key_of(cls, *made_of: Any) -> Hashable: 35 """The key `only` or `of` selects an event of this type by, from what it is made of: its fields but `time`, in 36 order. `None` for a type with neither.""" 37 return None 38 39 def _key(self) -> Hashable: 40 """The key `only` or `of` selects this event by, for a type that has either.""" 41 return None
Something that happened in the game, stamped with the time the bot learns of it.
A subclass is a new event, made a frozen, slotted dataclass of the fields it declares; adding @dataclass to
it fails. A handler of a class is handed the events of its subclasses too.
The time of the observation it comes with. An event made without one is emitted as a copy with the current time.
13@final 14class EventFilter[E: Event]: 15 """The events of one type a handler is handed: those with some keys, those a predicate passes, or both. 16 17 `only` and `of` on an event class make one, and `api.on` takes it in place of an event type; `where` on the 18 `EventSubscriber` that `api.on` returns adds a predicate. The events handed out are of the type itself. 19 """ 20 21 __slots__ = ("event_type", "keys", "predicate") 22 23 def __init__( 24 self, 25 event_type: type[E], 26 /, 27 *, 28 keys: frozenset[Hashable] | None = None, 29 predicate: Callable[[E], bool] | None = None, 30 ) -> None: 31 """The events of `event_type` with one of `keys`, if given, that `predicate` passes, if given. Made by `only`, 32 `of` and `where`, never by a bot.""" 33 self.event_type = event_type 34 """The type of the events it hands on.""" 35 self.keys = keys 36 """The keys of the events it hands on, or `None` for any.""" 37 self.predicate = predicate 38 """The predicate an event must pass to be handed on, or `None` for none.""" 39 40 def __repr__(self) -> str: 41 return f"EventFilter({', '.join(self._details())})" 42 43 def _details(self) -> list[str]: 44 """The type, keys and predicate as a repr shows them: a few keys listed, more only counted.""" 45 details = [self.event_type.__name__] 46 if (keys := self.keys) is not None: 47 details.append(f"keys={sorted(keys, key=repr)!r}" if len(keys) <= 4 else f"keys=<{len(keys)} keys>") 48 if self.predicate is not None: 49 details.append(f"predicate={getattr(self.predicate, '__qualname__', self.predicate)}") 50 return details
The events of one type a handler is handed: those with some keys, those a predicate passes, or both.
only and of on an event class make one, and api.on takes it in place of an event type; where on the
EventSubscriber that api.on returns adds a predicate. The events handed out are of the type itself.
23 def __init__( 24 self, 25 event_type: type[E], 26 /, 27 *, 28 keys: frozenset[Hashable] | None = None, 29 predicate: Callable[[E], bool] | None = None, 30 ) -> None: 31 """The events of `event_type` with one of `keys`, if given, that `predicate` passes, if given. Made by `only`, 32 `of` and `where`, never by a bot.""" 33 self.event_type = event_type 34 """The type of the events it hands on.""" 35 self.keys = keys 36 """The keys of the events it hands on, or `None` for any.""" 37 self.predicate = predicate 38 """The predicate an event must pass to be handed on, or `None` for none."""
The events of event_type with one of keys, if given, that predicate passes, if given. Made by only,
of and where, never by a bot.
7class EventPriority(ReadableIntEnum): 8 """A handler's place among an event's handlers: higher priorities run first, equal ones in subscription order. 9 10 `BEFORE` and `AFTER` are an extension's, and the only ones it takes: a handler subscribed while NachOS builds the 11 extensions runs at one of them, before or after every handler of the bot's of the events handed out with its own, 12 as `Api.extensions` says, and no other handler may. 13 """ 14 15 AFTER = 0 16 LOWEST = 1 17 VERY_LOW = 2 18 LOW = 3 19 MEDIUM = 4 20 HIGH = 5 21 VERY_HIGH = 6 22 HIGHEST = 7 23 BEFORE = 8
A handler's place among an event's handlers: higher priorities run first, equal ones in subscription order.
BEFORE and AFTER are an extension's, and the only ones it takes: a handler subscribed while NachOS builds the
extensions runs at one of them, before or after every handler of the bot's of the events handed out with its own,
as Api.extensions says, and no other handler may.
18@final 19class EventSubscriber[E: Event]: 20 """The decorator `api.on` returns, for a handler of `E`: a function taking one, or a method taking one after 21 `self`. It subscribes the function it decorates to the events it selects, or marks the method it decorates for 22 `api.subscribe`, with the options `on` was given. `where` narrows what it selects. 23 24 A handler taking any `Event` keeps its own type, so it can be decorated for several events. One taking a narrower 25 type is typed as a callable of the event it is decorated for. 26 """ 27 28 __slots__ = ("_bus", "_options", "_selects") 29 30 def __init__(self, bus: _EventBus, selects: EventFilter[Any], options: dict[str, Any]) -> None: 31 """A decorator subscribing to `bus` what `selects` selects, with `options`, the rest of what `on` was given, 32 which only `on` checks.""" 33 self._bus = bus 34 self._selects = selects 35 # The rest of what `on` was given: the priority, the cadence and whether to catch exceptions. 36 self._options = options 37 38 # A function taking any `Event` keeps its own type, so it can be decorated for several event types. 39 @overload 40 def __call__[F: Callable[[Event], object]](self, handler: F, /) -> F: ... 41 42 # A method taking any `Event` after `self`, likewise. 43 @overload 44 def __call__[F: Callable[[Any, Event], object]](self, handler: F, /) -> F: ... 45 46 # A function taking the event it is decorated for, or a base of it, typed as a callable of that event; one taking 47 # another event matches no overload, so a type checker refuses it. 48 @overload 49 def __call__[H: Event, R](self: EventSubscriber[H], handler: Callable[[H], R], /) -> Callable[[H], R]: ... 50 51 # A method taking that event after `self`, likewise. 52 @overload 53 def __call__[S, H: Event, R](self: EventSubscriber[H], handler: Callable[[S, H], R], /) -> Callable[[S, H], R]: ... 54 55 def __call__(self, handler: Any, /) -> Any: 56 function: object = handler 57 instance = None 58 if isinstance(function, MethodType): 59 function, instance = function.__func__, function.__self__ 60 if not isinstance(function, FunctionType): 61 raise TypeError(f"a handler is a function or a method, not {handler!r}") 62 if inspect.iscoroutinefunction(function): 63 raise TypeError(f"{function.__qualname__} is a coroutine function, and handlers are called synchronously") 64 self._bus._add(function, self._selects, self._options, instance=instance) 65 return handler 66 67 def where(self, predicate: Callable[[E], bool], /) -> EventSubscriber[E]: 68 """This decorator, narrowed to the events `predicate` also passes. `once` and the like count only those.""" 69 selects = self._selects 70 if (first := selects.predicate) is None: 71 both = predicate 72 else: 73 74 def both(event: Any, /) -> bool: 75 return first(event) and predicate(event) 76 77 narrowed = EventFilter(selects.event_type, keys=selects.keys, predicate=both) 78 return EventSubscriber(self._bus, narrowed, self._options)
The decorator api.on returns, for a handler of E: a function taking one, or a method taking one after
self. It subscribes the function it decorates to the events it selects, or marks the method it decorates for
api.subscribe, with the options on was given. where narrows what it selects.
A handler taking any Event keeps its own type, so it can be decorated for several events. One taking a narrower
type is typed as a callable of the event it is decorated for.
30 def __init__(self, bus: _EventBus, selects: EventFilter[Any], options: dict[str, Any]) -> None: 31 """A decorator subscribing to `bus` what `selects` selects, with `options`, the rest of what `on` was given, 32 which only `on` checks.""" 33 self._bus = bus 34 self._selects = selects 35 # The rest of what `on` was given: the priority, the cadence and whether to catch exceptions. 36 self._options = options
A decorator subscribing to bus what selects selects, with options, the rest of what on was given,
which only on checks.
67 def where(self, predicate: Callable[[E], bool], /) -> EventSubscriber[E]: 68 """This decorator, narrowed to the events `predicate` also passes. `once` and the like count only those.""" 69 selects = self._selects 70 if (first := selects.predicate) is None: 71 both = predicate 72 else: 73 74 def both(event: Any, /) -> bool: 75 return first(event) and predicate(event) 76 77 narrowed = EventFilter(selects.event_type, keys=selects.keys, predicate=both) 78 return EventSubscriber(self._bus, narrowed, self._options)
This decorator, narrowed to the events predicate also passes. once and the like count only those.
61class GameEndEvent(Event): 62 """The game has ended. The observation it ended on gets no turn.""" 63 64 result: Result 65 """How it ended for this player."""
The game has ended. The observation it ended on gets no turn.
49class GameStartEvent(Event): 50 """A game has started. Everything the api answers now comes from it."""
A game has started. Everything the api answers now comes from it.
8@final 9@dataclass(slots=True) 10class HandlerTiming: 11 """How long one handler has taken.""" 12 13 calls: int 14 """The number of calls.""" 15 total_seconds: float 16 """Wall-clock seconds over all calls.""" 17 max_seconds: float 18 """Wall-clock seconds of the slowest call.""" 19 20 @property 21 def seconds_per_call(self) -> float: 22 """Wall-clock seconds per call, on average.""" 23 return self.total_seconds / self.calls
How long one handler has taken.
473class NeutralUnitDiedEvent(AnyUnitDiedEvent): 474 """The game has reported a unit of the map's dead, as it does a mineral field killed (in game)."""
The game has reported a unit of the map's dead, as it does a mineral field killed (in game).
504class OpponentChatEvent(AnyChatEvent): 505 """A player other than this one, and not listed as an observer, sent a message. The game names no teams, so in a 506 game of more than two an ally's message comes as this too."""
A player other than this one, and not listed as an observer, sent a message. The game names no teams, so in a game of more than two an ally's message comes as this too.
483class OwnActionEvent(Event): 484 """The game carried out an action of this player's.""" 485 486 action: Action 487 """The action. Its `time` is when the game carried it out."""
The game carried out an action of this player's.
500class OwnChatEvent(AnyChatEvent): 501 """This player sent a message: through `api.chat`, or typed into its game window."""
This player sent a message: through api.chat, or typed into its game window.
155class OwnConstructionFinishedEvent(AnyUnitEvent): 156 """A structure of this player's that got `OwnConstructionStartedEvent` has finished.""" 157 158 unit: OwnUnit[Any]
A structure of this player's that got OwnConstructionStartedEvent has finished.
148class OwnConstructionStartedEvent(AnyUnitEvent): 149 """A structure of this player's is first seen unfinished, add-ons and creep tumors included. Not an auto-turret, 150 which is first seen finished (in game).""" 151 152 unit: OwnUnit[Any]
A structure of this player's is first seen unfinished, add-ons and creep tumors included. Not an auto-turret, which is first seen finished (in game).
445class OwnUnitBecameIdleEvent(AnyUnitEvent): 446 """A finished unit of this player's has no orders, and none NachOS sent it that the observations may not show yet, 447 having had orders or such an order in the observation before, been unfinished or another side's, or not been 448 listed: a unit trained with no rally, a structure just finished, a worker whose mineral field ran out, a unit whose 449 order the game dropped, a unit a neural parasite just took over. One that holds no order, a larva, or a depot even 450 as it lowers (in game), gets it once. A sieged tank and a burrowed lurker hold the order that made the form, so 451 neither is idle in it (in game).""" 452 453 unit: OwnUnit[Any]
A finished unit of this player's has no orders, and none NachOS sent it that the observations may not show yet, having had orders or such an order in the observation before, been unfinished or another side's, or not been listed: a unit trained with no rally, a structure just finished, a worker whose mineral field ran out, a unit whose order the game dropped, a unit a neural parasite just took over. One that holds no order, a larva, or a depot even as it lowers (in game), gets it once. A sieged tank and a burrowed lurker hold the order that made the form, so neither is idle in it (in game).
313class OwnUnitCloakChangedEvent(AnyUnitEvent): 314 """A unit of this player's has cloaked or uncloaked. Cloaked, it reads `CLOAKED_ALLIED` whether or not the enemy 315 detects it, so no event says it was detected (in game).""" 316 317 unit: OwnUnit[Any] 318 previous_cloak_state: CloakState 319 """The cloak it had."""
A unit of this player's has cloaked or uncloaked. Cloaked, it reads CLOAKED_ALLIED whether or not the enemy
detects it, so no event says it was detected (in game).
107class OwnUnitCreatedEvent(AnyUnitEvent): 108 """A unit of this player's is first seen: one the game started with, or one trained, hatched, placed, or starting 109 to warp in.""" 110 111 unit: OwnUnit[Any]
A unit of this player's is first seen: one the game started with, or one trained, hatched, placed, or starting to warp in.
216class OwnUnitDamagedEvent(AnyUnitEvent): 217 """A unit of this player's has lost health or shields since the observation before, and kept its type.""" 218 219 unit: OwnUnit[Any] 220 damage: float 221 """The health and shields it lost since the observation before, less what it regained in between."""
A unit of this player's has lost health or shields since the observation before, and kept its type.
463class OwnUnitDiedEvent(AnyUnitDiedEvent): 464 """The game has reported a unit of this player's dead.""" 465 466 unit: OwnUnit[Any]
The game has reported a unit of this player's dead.
232class OwnUnitEnergyLostEvent(AnyUnitEvent): 233 """A unit of this player's has less energy than in the observation before, and kept its type: it cast a spell, or 234 lost energy to a feedback or an EMP.""" 235 236 unit: OwnUnit[Any] 237 energy_lost: float 238 """The energy it lost since the observation before, less what it regenerated in between."""
A unit of this player's has less energy than in the observation before, and kept its type: it cast a spell, or lost energy to a feedback or an EMP.
421class OwnUnitEnteredAreaEvent(AnyAreaEvent): 422 """A unit of this player's is inside the area given to `of`, having last been seen outside it, or first seen inside 423 it once the area has been watched for a turn.""" 424 425 unit: OwnUnit[Any]
A unit of this player's is inside the area given to of, having last been seen outside it, or first seen inside
it once the area has been watched for a turn.
352class OwnUnitGainedBuffEvent(AnyBuffEvent): 353 """A unit of this player's has a buff it did not have in the observation before: a spell, a stim, a cloak, or a 354 worker picking up minerals or gas, which it does every trip. Several on one unit come in id order.""" 355 356 unit: OwnUnit[Any] 357 buff: BuffId 358 """The buff it gained."""
A unit of this player's has a buff it did not have in the observation before: a spell, a stim, a cloak, or a worker picking up minerals or gas, which it does every trip. Several on one unit come in id order.
433class OwnUnitLeftAreaEvent(AnyAreaEvent): 434 """A unit of this player's is outside the area given to `of`, having last been seen inside it. One that dies inside 435 it, or leaves the observation there, has not left it.""" 436 437 unit: OwnUnit[Any]
A unit of this player's is outside the area given to of, having last been seen inside it. One that dies inside
it, or leaves the observation there, has not left it.
370class OwnUnitLostBuffEvent(AnyBuffEvent): 371 """A unit of this player's no longer has a buff it had in the observation before: it wore off, was ended, or a 372 worker delivered its minerals or gas. Several on one unit come in id order.""" 373 374 unit: OwnUnit[Any] 375 buff: BuffId 376 """The buff it lost."""
A unit of this player's no longer has a buff it had in the observation before: it wore off, was ended, or a worker delivered its minerals or gas. Several on one unit come in id order.
129class OwnUnitTypeChangedEvent(AnyUnitTypeChangedEvent): 130 """A unit of this player's has changed type.""" 131 132 unit: OwnUnit[Any]
A unit of this player's has changed type.
300class OwnUnitVitalDroppedEvent(AnyVitalEvent): 301 """A visible unit of this player's has less than the value given to `of`, having last been seen visible at or 302 above it: `of(VitalType.LIFE_FRACTION, 1.0)` is a unit hurt. Not for a unit first seen below it, and not again 303 until it has been seen at or above it.""" 304 305 unit: OwnUnit[Any]
A visible unit of this player's has less than the value given to of, having last been seen visible at or
above it: of(VitalType.LIFE_FRACTION, 1.0) is a unit hurt. Not for a unit first seen below it, and not again
until it has been seen at or above it.
286class OwnUnitVitalReachedEvent(AnyVitalEvent): 287 """A visible unit of this player's has at least the value given to `of`, having last been seen visible below 288 it: `of(VitalType.LIFE_FRACTION, 1.0)` is a unit back to full. Not for a unit first seen at it, and not again until 289 it has been seen below it.""" 290 291 unit: OwnUnit[Any]
A visible unit of this player's has at least the value given to of, having last been seen visible below
it: of(VitalType.LIFE_FRACTION, 1.0) is a unit back to full. Not for a unit first seen at it, and not again until
it has been seen below it.
212class OwnUpgradeFinishedEvent(AnyUpgradeEvent): 213 """This player has finished researching an upgrade. Several in one observation come in id order."""
This player has finished researching an upgrade. Several in one observation come in id order.
194class OwnUpgradeStartedEvent(AnyUpgradeEvent): 195 """A research of this player's first shows in a structure's orders, queued behind another included, which the game 196 charges at once. From now on `api.researches` holds it.""" 197 198 unit: OwnUnit[Any] 199 """The structure researching it."""
A research of this player's first shows in a structure's orders, queued behind another included, which the game
charges at once. From now on api.researches holds it.
202class OwnUpgradeStoppedEvent(AnyUpgradeEvent): 203 """A research of this player's shows in no structure's orders, having shown in the observation before, and the 204 upgrade has not arrived: it was cancelled, or its structure died. A finished research never reads as stopped, since 205 its order leaves the structure in the step its upgrade arrives (in game). One that leaves a structure and shows in 206 another between two observations is neither stopped nor started.""" 207 208 unit: OwnUnit[Any] 209 """The structure that was researching it."""
A research of this player's shows in no structure's orders, having shown in the observation before, and the upgrade has not arrived: it was cancelled, or its structure died. A finished research never reads as stopped, since its order leaves the structure in the step its upgrade arrives (in game). One that leaves a structure and shows in another between two observations is neither stopped nor started.
168class OwnWarpInFinishedEvent(AnyUnitEvent): 169 """A unit of this player's has finished warping in.""" 170 171 unit: OwnUnit[Any]
A unit of this player's has finished warping in.
161class OwnWarpInStartedEvent(AnyUnitEvent): 162 """A unit of this player's has started warping in: it is first seen unfinished. It gets `OwnUnitCreatedEvent` 163 too.""" 164 165 unit: OwnUnit[Any]
A unit of this player's has started warping in: it is first seen unfinished. It gets OwnUnitCreatedEvent
too.
44class ParameterizedEvent(Event): 45 """An event that exists only for given parameters. A handler subscribes through `of`, which takes them; `on` 46 refuses the bare type."""
An event that exists only for given parameters. A handler subscribes through of, which takes them; on
refuses the bare type.
The bot's turn, after the events the new observation reports.
53class TurnStartEvent(Event): 54 """A turn is starting. It comes before the turn's other events."""
A turn is starting. It comes before the turn's other events.
139class UnitAllianceChangedEvent(AnyUnitEvent): 140 """A unit has changed sides to or from this player's: a neural parasite took it over or let it go. To the vital and 141 area events of the side it left, it is a unit gone from the observation, and to those of the side it joined, one 142 first seen. It neither enters nor leaves sight.""" 143 144 previous_alliance: Alliance 145 """The side it was on."""
A unit has changed sides to or from this player's: a neural parasite took it over or let it go. To the vital and area events of the side it left, it is a unit gone from the observation, and to those of the side it joined, one first seen. It neither enters nor leaves sight.
477class UnitFoundDeadEvent(AnyUnitEvent): 478 """A unit is dead without the game reporting it: a structure remembered in the fog whose spot came into sight 479 empty (in game), or a drone not reported dead an update after its structure finished or was killed, which no game 480 has needed."""
A unit is dead without the game reporting it: a structure remembered in the fog whose spot came into sight empty (in game), or a drone not reported dead an update after its structure finished or was killed, which no game has needed.