sc2nachos.orders

The orders a bot gives.

1"""The orders a bot gives."""
2
3from sc2nachos.orders._issued_order import IssuedOrder
4from sc2nachos.orders._order_book import OrderBook
5
6__all__ = [
7    "IssuedOrder",
8    "OrderBook",
9]
@final
class IssuedOrder:
14@final
15class IssuedOrder:
16    """An order a bot gave. A refusal by the game shows in `api.action_failures`, and what a unit then reports doing
17    in its `sc2nachos.units.Order`s."""
18
19    __slots__ = (
20        "_ability",
21        "_issued_time",
22        "_queued",
23        "_target",
24        "_units",
25        "_withdrawn",
26    )
27
28    def __init__(
29        self,
30        ability: AbilityId,
31        units: Units[OwnUnit[Any]],
32        target: Target | None,
33        *,
34        queued: bool,
35        issued_time: GameTime,
36    ) -> None:
37        """An order of `ability` to `units`, issued at `issued_time`. Made by the order book, never by a bot."""
38        self._ability = ability
39        self._units = units
40        self._target = target
41        self._queued = queued
42        self._issued_time = issued_time
43        self._withdrawn = False
44
45    def __repr__(self) -> str:
46        units = self._units[0] if len(self._units) == 1 else f"{len(self._units)} units"
47        return f"IssuedOrder({self._ability.name}, {units})"
48
49    @property
50    def ability(self) -> AbilityId:
51        """The ability ordered, as it was ordered. A unit carrying it out reads as running the same one."""
52        return self._ability
53
54    @property
55    def units(self) -> Units[OwnUnit[Any]]:
56        """The units the order was given to."""
57        return self._units
58
59    @property
60    def target(self) -> Target | None:
61        """The point or unit the order is aimed at, or `None`."""
62        return self._target
63
64    @property
65    def queued(self) -> bool:
66        """Whether the order goes behind each unit's orders instead of replacing them."""
67        return self._queued
68
69    @property
70    def issued_time(self) -> GameTime:
71        """The time of the observation the order was issued in."""
72        return self._issued_time
73
74    def withdraw(self) -> None:
75        """Take the order back while its turn's handlers run, so it never goes out. After its turn it does nothing."""
76        self._withdrawn = True

An order a bot gave. A refusal by the game shows in api.action_failures, and what a unit then reports doing in its sc2nachos.units.Orders.

IssuedOrder( ability: sc2nachos.AbilityId, units: sc2nachos.Units[sc2nachos.OwnUnit[typing.Any]], target: Target | None, *, queued: bool, issued_time: sc2nachos.GameTime)
28    def __init__(
29        self,
30        ability: AbilityId,
31        units: Units[OwnUnit[Any]],
32        target: Target | None,
33        *,
34        queued: bool,
35        issued_time: GameTime,
36    ) -> None:
37        """An order of `ability` to `units`, issued at `issued_time`. Made by the order book, never by a bot."""
38        self._ability = ability
39        self._units = units
40        self._target = target
41        self._queued = queued
42        self._issued_time = issued_time
43        self._withdrawn = False

An order of ability to units, issued at issued_time. Made by the order book, never by a bot.

ability: sc2nachos.AbilityId
49    @property
50    def ability(self) -> AbilityId:
51        """The ability ordered, as it was ordered. A unit carrying it out reads as running the same one."""
52        return self._ability

The ability ordered, as it was ordered. A unit carrying it out reads as running the same one.

units: sc2nachos.Units[sc2nachos.OwnUnit[typing.Any]]
54    @property
55    def units(self) -> Units[OwnUnit[Any]]:
56        """The units the order was given to."""
57        return self._units

The units the order was given to.

target: Target | None
59    @property
60    def target(self) -> Target | None:
61        """The point or unit the order is aimed at, or `None`."""
62        return self._target

The point or unit the order is aimed at, or None.

queued: bool
64    @property
65    def queued(self) -> bool:
66        """Whether the order goes behind each unit's orders instead of replacing them."""
67        return self._queued

Whether the order goes behind each unit's orders instead of replacing them.

issued_time: sc2nachos.GameTime
69    @property
70    def issued_time(self) -> GameTime:
71        """The time of the observation the order was issued in."""
72        return self._issued_time

The time of the observation the order was issued in.

def withdraw(self) -> None:
74    def withdraw(self) -> None:
75        """Take the order back while its turn's handlers run, so it never goes out. After its turn it does nothing."""
76        self._withdrawn = True

Take the order back while its turn's handlers run, so it never goes out. After its turn it does nothing.

@final
class OrderBook:
 51@final
 52class OrderBook:
 53    """This player's orders for the turn.
 54
 55    A bot gives orders through `api.orders` while its handlers run. They are sent in one request after the turn's
 56    last handler returns. A unit carries out only the last order it is given in a turn, plus any abilities it
 57    carries out at once.
 58    """
 59
 60    __slots__ = (
 61        "_built_abilities",
 62        "_forced",
 63        "_game_data",
 64        "_issued",
 65        "_issued_by_unit",
 66        "_last_sent",
 67        "_observations",
 68        "_sent_not_replacing",
 69        "_refusals",
 70        "_time",
 71        "_trained_abilities",
 72    )
 73
 74    def __init__(self, game_data: GameData) -> None:
 75        """A book for one game. `game_data` says what each ability does and what it must be aimed at."""
 76        self._game_data = game_data
 77        # The turn's orders in the order they were issued, and those of each unit by its id.
 78        self._issued: list[IssuedOrder] = []
 79        self._issued_by_unit: dict[int, list[IssuedOrder]] = {}
 80        # The turn's orders issued with `force`, sent even to units already carrying them out.
 81        self._forced: set[IssuedOrder] = set()
 82        # By unit id, the last unqueued order the game took that replaces the unit's orders, and the number of the
 83        # observation its turn read.
 84        self._last_sent: dict[int, tuple[IssuedOrder, int]] = {}
 85        # By unit id, each order the game took that does not replace the unit's orders, one queued, a train, a
 86        # research, an add-on or a morph, with the number of the observation its turn read, until the observations must
 87        # show it or an order replaces the unit's orders.
 88        self._sent_not_replacing: dict[int, list[tuple[IssuedOrder, int]]] = {}
 89        # What the game refused of the last turn's orders, one entry per unit a refused command named.
 90        self._refusals: tuple[ActionFailure, ...] = ()
 91        self._observations = 0
 92        self._time = GameTime.ZERO
 93        # By maker and product, the ability `train` orders, and the one `build` orders.
 94        abilities_making = _abilities_making(game_data)
 95        self._trained_abilities = {pair: ability for pair, ability in abilities_making.items() if _is_trained(*pair)}
 96        self._built_abilities = {pair: ability for pair, ability in abilities_making.items() if _is_built(*pair)}
 97
 98    def issue(
 99        self,
100        units: OwnUnit[Any] | Iterable[OwnUnit[Any]],
101        ability: AbilityId,
102        *,
103        target: PointLike | Unit[Any] | None = None,
104        queued: bool = False,
105        force: bool = False,
106    ) -> IssuedOrder:
107        """Order `units` to use `ability`, aimed at a point, a unit or nothing, and return the `IssuedOrder`.
108
109        Every unit given carries it out, and a unit given twice counts once. An ability every unit of one command
110        carries out (`AbilityData.multi_unit`) goes out as one command naming them all, so units ordered together keep
111        their spacing where the game spreads them; any other goes out as a command to each. `queued` puts the order
112        behind each unit's orders. Nothing is sent until the turn's handlers have all run.
113
114        Orders of an ability that joins other orders (`AbilityData.joins_other_orders`), given apart in one turn, go out
115        as one command where they are aimed at the same unit, or at the same point as the game keeps it, and are queued
116        alike, so units ordered one at a time keep their spacing too. An order joins the last such command before it
117        unless one of its units is named in that command or a later one, so a unit's commands go out in the order it was
118        given them; another unit's may go out ahead of commands given before them. A command aimed at one of its own
119        units, as a transport's unload where it stands is, joins nothing, and nothing joins it. The game answers a
120        command naming several units `Success` if any of them can take it, so then every order it carries counts as
121        sent: one whose units could not take it is not listed in `api.action_failures`, and the same order given them
122        again is left out as one they are carrying out until the observations would show it.
123
124        An unqueued order that replaces a unit's orders is not sent to a unit already doing it: sending it would only
125        drop what the unit has queued behind it. What a unit is doing is the last such order sent to it, while the
126        observation after its turn may not show it yet, and otherwise its first reported order. `force` sends it to
127        those units too: that is how a unit is made to drop its queue and go on with its current order. It still
128        competes with the turn's other orders like any other.
129
130        An ability that goes out as another for some types (`AbilityData.sent_as`) goes out as that one to their units,
131        in commands of its own, which join other orders' as the ability's own do. A command the game refuses is listed
132        in `api.action_failures` once for each unit it names, under the ability of that unit's order.
133
134        Raises `TypeError` for a target the ability cannot be aimed at, for an add-on with no point given to a flying
135        structure, and for a transport's unload at a point aimed at one of `units` itself, which is `UNLOAD` for that
136        one: a group given an unload at one of its own transports is two orders. Raises `ValueError` for a research
137        given to several units, and for an ability that places something at its target (`AbilityData.places_at_target`)
138        given to several aimed at one; and for a custom ability given to a type it has nothing to be sent as for, or
139        which this game's tables lack an ability it is sent as for.
140        """
141        given = _unit_tuple(units)
142        if len(given) > 1:
143            given = tuple(dict.fromkeys(given))
144        if not given:
145            raise ValueError(_NEEDS_A_UNIT)
146        row = self._game_data.abilities.get(ability)
147        sent_as = ABILITIES_SENT_AS_ANOTHER.get(ability, SENT_UNCHANGED)
148        if ability.is_custom:
149            if row is None:
150                raise ValueError(f"{ability.name} has nothing in this game's tables to be sent as")
151            _check_sent_as(ability, sent_as, given)
152        aimed = aimed_at(target)
153        check_target(ability, aimed, row)
154        _check_each_can_carry_it_out(ability, row, aimed, len(given))
155        if aimed is None:
156            _check_placed_where_flying(ability, row, given)
157        if isinstance(aimed, Unit):
158            _check_not_aimed_at_itself(ability, aimed, given)
159        order = IssuedOrder(ability, Units(given), aimed, queued=queued, issued_time=self._time)
160        self._add(order)
161        if force:
162            self._forced.add(order)
163        return order
164
165    def train(
166        self,
167        units: OwnUnit[Any] | Iterable[OwnUnit[Any]],
168        unit_type: UnitTypeId,
169        *,
170        target: PointLike | Unit[Any] | None = None,
171        queued: bool = False,
172        force: bool = False,
173    ) -> IssuedOrder:
174        """Order `units` to make a unit of `unit_type` and return the `IssuedOrder`, as `issue` orders the ability
175        their type makes it with: a barracks's `BARRACKS_TRAIN_MARINE`, a warp gate's `WARP_GATE_WARP_IN_ZEALOT`, aimed
176        at a point, a larva's `LARVA_MORPH_DRONE`.
177
178        It orders what a structure or a larva makes that is not a structure; `build` orders a structure a worker makes
179        and an add-on, and `issue` the rest, a morph such as an orbital command's or a baneling's among them.
180
181        Raises `ValueError` where one of `units` does not train `unit_type`, saying what does, and where two of them
182        make it with different abilities, as a gateway and a warp gate a zealot: they are ordered apart. Raises
183        otherwise as `issue` does.
184        """
185        given = _unit_tuple(units)
186        ability = self._ability_making(given, unit_type, self._trained_abilities, "train")
187        return self.issue(given, ability, target=target, queued=queued, force=force)
188
189    def build(
190        self,
191        units: OwnUnit[Any] | Iterable[OwnUnit[Any]],
192        unit_type: UnitTypeId,
193        *,
194        target: PointLike | Unit[Any] | None = None,
195        queued: bool = False,
196        force: bool = False,
197    ) -> IssuedOrder:
198        """Order `units` to make a structure of `unit_type` and return the `IssuedOrder`, as `issue` orders the
199        ability their type makes it with: an SCV's `SCV_BUILD_SUPPLY_DEPOT` aimed at a point, a drone's
200        `DRONE_MORPH_EXTRACTOR` aimed at a geyser, a barracks's `BUILD_TECH_LAB`.
201
202        It orders a structure a worker makes, and an add-on; `train` orders what a structure or a larva makes that is
203        not a structure, and `issue` the rest, a morph such as an orbital command's or a lair's among them.
204
205        Raises `ValueError` where one of `units` does not build `unit_type`, saying what does, and where two of them
206        make it with different abilities. Raises otherwise as `issue` does: `ValueError` for workers given one site.
207        """
208        given = _unit_tuple(units)
209        ability = self._ability_making(given, unit_type, self._built_abilities, "build")
210        return self.issue(given, ability, target=target, queued=queued, force=force)
211
212    def research(
213        self, unit: OwnUnit[Any], upgrade: UpgradeId, *, queued: bool = False, force: bool = False
214    ) -> IssuedOrder:
215        """Order `unit` to research `upgrade` and return the `IssuedOrder`, as `issue` orders the upgrade's
216        `research_ability`: Stimpack's `BARRACKS_TECH_LAB_RESEARCH_STIMPACK`.
217
218        Raises `ValueError` where nothing researches `upgrade`, and where `unit`'s type is not one of its
219        `researchers`: a barracks's upgrades are its tech lab's. Raises otherwise as `issue` does.
220        """
221        row = self._game_data.upgrades.get(upgrade)
222        if row is None or row.research_ability is None:
223            raise ValueError(f"nothing researches {upgrade.name}")
224        if unit.type_id not in row.researchers:
225            researchers = _listed_with_or(row.researchers)
226            raise ValueError(f"{upgrade.name} is researched by {researchers}, not {_with_article(unit.type_id)}")
227        return self.issue(unit, row.research_ability, queued=queued, force=force)
228
229    def _ability_making(
230        self,
231        units: tuple[OwnUnit[Any], ...],
232        product: UnitTypeId,
233        abilities: Mapping[tuple[UnitTypeId, UnitTypeId], AbilityId],
234        method: str,
235    ) -> AbilityId:
236        """The one ability `units` make `product` with, of `abilities`, those the order book's `method` orders.
237        Raises `ValueError` as `train` and `build` say."""
238        if not units:
239            raise ValueError(_NEEDS_A_UNIT)
240        makers_by_ability: dict[AbilityId, list[UnitTypeId]] = {}
241        for maker in dict.fromkeys(unit.type_id for unit in units):
242            ability = abilities.get((maker, product))
243            if ability is None:
244                raise ValueError(self._why_not_made(maker, product, method))
245            makers_by_ability.setdefault(ability, []).append(maker)
246        if len(makers_by_ability) > 1:
247            makers = " and ".join(_with_article(maker) for makers in makers_by_ability.values() for maker in makers)
248            used = " and ".join(ability.name for ability in makers_by_ability)
249            made = _with_article(product)
250            raise ValueError(f"{makers} make {made} with different abilities, {used}: order them apart")
251        return next(iter(makers_by_ability))
252
253    def _why_not_made(self, maker: UnitTypeId, product: UnitTypeId, method: str) -> str:
254        """Why `method` cannot order a `maker` to make a `product`: what orders it instead, or what makes one."""
255        abilities_making = _abilities_making(self._game_data)
256        if (ability := abilities_making.get((maker, product))) is not None:
257            ordered_by = "train" if _is_trained(maker, product) else "build" if _is_built(maker, product) else "issue"
258            made_with = f"{_with_article(maker)} makes {_with_article(product)} with {ability.name}"
259            return f"{made_with}, which `{ordered_by}` orders, not `{method}`"
260        makers = {made_by for made_by, made in abilities_making if made is product}
261        if makers:
262            return f"{_with_article(maker)} does not make {_with_article(product)}: {_listed_with_or(makers)} does"
263        if (own_add_on := _own_add_on_of_kind(maker, product, abilities_making)) is not None:
264            return f"nothing makes a bare {product.name}: {_with_article(maker)} makes {_with_article(own_add_on)}"
265        return f"nothing makes {_with_article(product)}"
266
267    def issued_to(self, unit: OwnUnit[Any], *, include_sent: bool = False) -> tuple[IssuedOrder, ...]:
268        """The orders issued to `unit` so far this turn, in the order they were issued. Withdrawn orders are left out.
269        With `include_sent`, first come the orders that went out to it lately and that the observations may not show
270        yet: the last one sent that replaced its orders, and those sent since that did not, queued ones, trains,
271        researches, add-ons and morphs, but not what it carries out at once.
272
273        A handler late in a turn reads this to leave alone a unit an earlier handler has ordered, since only the last
274        order a unit is given goes out.
275        """
276        turns = self._issued_by_unit.get(unit.id, ())
277        sent = self._sent_but_not_observed_yet(unit) if include_sent else ()
278        return (*sent, *(order for order in turns if not order._withdrawn))
279
280    @property
281    def pending(self) -> tuple[IssuedOrder, ...]:
282        """Every order issued this turn and still to be sent. Withdrawn orders are left out."""
283        return tuple(order for order in self._issued if not order._withdrawn)
284
285    @property
286    def pending_cost(self) -> Cost:
287        """What the bank does not show yet: the cost of the orders of `pending` that will go out, each its ability's
288        `cost` in the game's tables for each unit it goes out to. A unit given orders that replace one another pays for
289        the last, and one already carrying an order out pays nothing for it again. Its time is every order's added up,
290        though the units may carry them out side by side."""
291        total = Cost(0, 0)
292        for order, units in self._orders_to_send(self._issued, self._forced):
293            row = self._game_data.abilities.get(order.ability)
294            if row is not None:
295                total += row.cost * len(units)
296        return total
297
298    def _send(self, client: Client, *, then: Sequence[sc2api_pb2.Action] = ()) -> None:
299        """Send the turn's orders and after them `then`, actions that belong to no order, in one request, and keep what
300        the game refused of the orders. Sends nothing if there is nothing to send."""
301        issued, forced = self._issued, self._forced
302        self._issued, self._issued_by_unit, self._forced = [], {}, set()
303        self._refusals = ()
304        unit_commands = unit_commands_giving(self._orders_to_send(issued, forced))
305        actions = [*(unit_command.to_action() for unit_command in unit_commands), *then]
306        if not actions:
307            return
308        results = client.act(actions).result
309        if len(results) < len(unit_commands):
310            raise ProtocolError(f"the game answered {len(results)} of the {len(unit_commands)} commands it was sent")
311        # What comes after the commands is answered after them, and belongs to no order.
312        refusals: list[ActionFailure] = []
313        for unit_command, result in zip(unit_commands, results, strict=False):
314            action_result = ActionResult.read(result)
315            for order, units in unit_command.parts:
316                if action_result is ActionResult.SUCCESS:
317                    self._remember_sent(order, units)
318                else:
319                    refusals += [ActionFailure(self._time, unit, order.ability, action_result) for unit in units]
320        self._refusals = tuple(refusals)
321
322    def _observe(self, time: GameTime, lost: Iterable[Unit[Any]]) -> None:
323        """Take in the observation at `time`, which found `lost` dead or no longer this player's."""
324        self._time = time
325        self._observations += 1
326        for unit in lost:
327            self._last_sent.pop(unit.id, None)
328            self._sent_not_replacing.pop(unit.id, None)
329        recent = self._observations - _SHOWN_WITHIN + 1
330        for unit_id, sent in list(self._sent_not_replacing.items()):
331            if not (sent := [(order, sent_at) for order, sent_at in sent if sent_at >= recent]):
332                del self._sent_not_replacing[unit_id]
333            else:
334                self._sent_not_replacing[unit_id] = sent
335
336    def _orders_to_send(
337        self, issued: Sequence[IssuedOrder], forced: Collection[IssuedOrder]
338    ) -> Iterator[tuple[IssuedOrder, tuple[OwnUnit[Any], ...]]]:
339        """Each order of `issued` that goes out, with the units it goes out to.
340
341        An order that acts at once, or that is queued behind a unit's orders, competes with nothing. Of the
342        rest, a unit keeps only the last it was given. An order is then left out for the units already carrying it
343        out, unless it is in `forced`. A withdrawn order, or one left with no unit, is not sent.
344        """
345        holder: dict[int, IssuedOrder] = {}
346        for order in issued:
347            if not order._withdrawn:
348                for unit in order.units:
349                    if self._competes_for(order, unit):
350                        holder[unit.id] = order
351        for order in issued:
352            if order._withdrawn:
353                continue
354            units = tuple(
355                unit for unit in order.units if holder.get(unit.id) is order or not self._competes_for(order, unit)
356            )
357            if order not in forced:
358                units = self._units_not_carrying_it_out(order, units)
359            if units:
360                yield order, units
361
362    def _competes_for(self, order: IssuedOrder, unit: OwnUnit[Any]) -> bool:
363        """Whether `order` competes with the turn's other orders for `unit`, which then takes the last of them.
364
365        Every unqueued order does, a structure's train included, whatever it would do to the unit. A queued order
366        competes with nothing, and nor does an ability the unit's type carries out at once: the unit does both (in
367        game). Each unit of a group is judged by its own type.
368        """
369        if order.queued:
370            return False
371        row = self._game_data.abilities.get(order.ability)
372        return _behavior_for(row, unit) is not OrderBehavior.KEEPS_ORDERS
373
374    def _add(self, order: IssuedOrder) -> None:
375        """Count `order` among the turn's, last."""
376        self._issued.append(order)
377        for unit_id in {unit.id for unit in order.units}:
378            self._issued_by_unit.setdefault(unit_id, []).append(order)
379
380    def _remember_sent(self, order: IssuedOrder, units: Sequence[OwnUnit[Any]]) -> None:
381        """Record `order`, which the game took, as sent to each of `units`: the last sent to a unit whose orders it
382        replaces, unqueued, and otherwise one sent that does not replace them, unless the unit carries it out at
383        once."""
384        row = self._game_data.abilities.get(order.ability)
385        for unit in units:
386            behavior = _behavior_for(row, unit)
387            if not order.queued and behavior is OrderBehavior.REPLACES:
388                self._last_sent[unit.id] = (order, self._observations)
389                self._sent_not_replacing.pop(unit.id, None)
390            elif order.queued or behavior is not OrderBehavior.KEEPS_ORDERS:
391                self._sent_not_replacing.setdefault(unit.id, []).append((order, self._observations))
392
393    def _units_not_carrying_it_out(
394        self, order: IssuedOrder, units: tuple[OwnUnit[Any], ...]
395    ) -> tuple[OwnUnit[Any], ...]:
396        """The units of `units` that `order` would change anything for: all of them for a queued order, else all but
397        those whose orders it replaces and which are already doing it."""
398        if order.queued:
399            return units
400        row = self._game_data.abilities.get(order.ability)
401        return tuple(
402            unit
403            for unit in units
404            if _behavior_for(row, unit) is not OrderBehavior.REPLACES
405            or not self._is_doing(unit, order.ability, order.target)
406        )
407
408    def _is_doing(self, unit: OwnUnit[Any], ability: AbilityId, target: Target | None) -> bool:
409        """Whether `unit` is doing `ability` at `target`: the last order sent to it says, while it may not show yet,
410        and otherwise its first reported order."""
411        sent = self._sent_and_not_shown(unit)
412        if sent is not None:
413            return sent.ability is ability and same_target(sent.target, target)
414        return self._unit_is_at(unit, ability, target)
415
416    def _sent_and_not_shown(self, unit: OwnUnit[Any]) -> IssuedOrder | None:
417        """The last order sent to `unit` that replaced its orders, while the observations may not show it yet."""
418        last = self._last_sent.get(unit.id)
419        if last is not None and self._observations - last[1] < _SHOWN_WITHIN:
420            return last[0]
421        return None
422
423    def _sent_but_not_observed_yet(self, unit: OwnUnit[Any]) -> list[IssuedOrder]:
424        """The orders that went out to `unit` lately and that the observations may not show yet: the last sent that
425        replaced its orders, and those sent since that did not."""
426        orders = []
427        if (sent := self._sent_and_not_shown(unit)) is not None:
428            orders.append(sent)
429        recent = self._observations - _SHOWN_WITHIN + 1
430        orders += [order for order, sent_at in self._sent_not_replacing.get(unit.id, ()) if sent_at >= recent]
431        return orders
432
433    def _unit_is_at(self, unit: OwnUnit[Any], ability: AbilityId, target: Target | None) -> bool:
434        """Whether `unit`'s first order runs `ability` at `target`. A unit the last observation left out, in a
435        transport for one, is at nothing."""
436        orders = unit._latest_report.orders
437        if not unit.is_listed or not orders:
438            return False
439        first = orders[0]
440        if _ability_of_unit_order(first) is not ability:
441            return False
442        match first.WhichOneof("target"):
443            case "target_world_space_pos":
444                point = first.target_world_space_pos
445                return isinstance(target, Point) and same_point(target, point.x, point.y)
446            case "target_unit_tag":
447                return isinstance(target, Unit) and unit._unit_target_of_order(first) is target
448            case _:
449                return target is None

This player's orders for the turn.

A bot gives orders through api.orders while its handlers run. They are sent in one request after the turn's last handler returns. A unit carries out only the last order it is given in a turn, plus any abilities it carries out at once.

OrderBook(game_data: sc2nachos.gamedata.GameData)
74    def __init__(self, game_data: GameData) -> None:
75        """A book for one game. `game_data` says what each ability does and what it must be aimed at."""
76        self._game_data = game_data
77        # The turn's orders in the order they were issued, and those of each unit by its id.
78        self._issued: list[IssuedOrder] = []
79        self._issued_by_unit: dict[int, list[IssuedOrder]] = {}
80        # The turn's orders issued with `force`, sent even to units already carrying them out.
81        self._forced: set[IssuedOrder] = set()
82        # By unit id, the last unqueued order the game took that replaces the unit's orders, and the number of the
83        # observation its turn read.
84        self._last_sent: dict[int, tuple[IssuedOrder, int]] = {}
85        # By unit id, each order the game took that does not replace the unit's orders, one queued, a train, a
86        # research, an add-on or a morph, with the number of the observation its turn read, until the observations must
87        # show it or an order replaces the unit's orders.
88        self._sent_not_replacing: dict[int, list[tuple[IssuedOrder, int]]] = {}
89        # What the game refused of the last turn's orders, one entry per unit a refused command named.
90        self._refusals: tuple[ActionFailure, ...] = ()
91        self._observations = 0
92        self._time = GameTime.ZERO
93        # By maker and product, the ability `train` orders, and the one `build` orders.
94        abilities_making = _abilities_making(game_data)
95        self._trained_abilities = {pair: ability for pair, ability in abilities_making.items() if _is_trained(*pair)}
96        self._built_abilities = {pair: ability for pair, ability in abilities_making.items() if _is_built(*pair)}

A book for one game. game_data says what each ability does and what it must be aimed at.

def issue( self, units: Union[sc2nachos.OwnUnit[Any], Iterable[sc2nachos.OwnUnit[Any]]], ability: sc2nachos.AbilityId, *, target: 'PointLike | Unit[Any] | None' = None, queued: bool = False, force: bool = False) -> IssuedOrder:
 98    def issue(
 99        self,
100        units: OwnUnit[Any] | Iterable[OwnUnit[Any]],
101        ability: AbilityId,
102        *,
103        target: PointLike | Unit[Any] | None = None,
104        queued: bool = False,
105        force: bool = False,
106    ) -> IssuedOrder:
107        """Order `units` to use `ability`, aimed at a point, a unit or nothing, and return the `IssuedOrder`.
108
109        Every unit given carries it out, and a unit given twice counts once. An ability every unit of one command
110        carries out (`AbilityData.multi_unit`) goes out as one command naming them all, so units ordered together keep
111        their spacing where the game spreads them; any other goes out as a command to each. `queued` puts the order
112        behind each unit's orders. Nothing is sent until the turn's handlers have all run.
113
114        Orders of an ability that joins other orders (`AbilityData.joins_other_orders`), given apart in one turn, go out
115        as one command where they are aimed at the same unit, or at the same point as the game keeps it, and are queued
116        alike, so units ordered one at a time keep their spacing too. An order joins the last such command before it
117        unless one of its units is named in that command or a later one, so a unit's commands go out in the order it was
118        given them; another unit's may go out ahead of commands given before them. A command aimed at one of its own
119        units, as a transport's unload where it stands is, joins nothing, and nothing joins it. The game answers a
120        command naming several units `Success` if any of them can take it, so then every order it carries counts as
121        sent: one whose units could not take it is not listed in `api.action_failures`, and the same order given them
122        again is left out as one they are carrying out until the observations would show it.
123
124        An unqueued order that replaces a unit's orders is not sent to a unit already doing it: sending it would only
125        drop what the unit has queued behind it. What a unit is doing is the last such order sent to it, while the
126        observation after its turn may not show it yet, and otherwise its first reported order. `force` sends it to
127        those units too: that is how a unit is made to drop its queue and go on with its current order. It still
128        competes with the turn's other orders like any other.
129
130        An ability that goes out as another for some types (`AbilityData.sent_as`) goes out as that one to their units,
131        in commands of its own, which join other orders' as the ability's own do. A command the game refuses is listed
132        in `api.action_failures` once for each unit it names, under the ability of that unit's order.
133
134        Raises `TypeError` for a target the ability cannot be aimed at, for an add-on with no point given to a flying
135        structure, and for a transport's unload at a point aimed at one of `units` itself, which is `UNLOAD` for that
136        one: a group given an unload at one of its own transports is two orders. Raises `ValueError` for a research
137        given to several units, and for an ability that places something at its target (`AbilityData.places_at_target`)
138        given to several aimed at one; and for a custom ability given to a type it has nothing to be sent as for, or
139        which this game's tables lack an ability it is sent as for.
140        """
141        given = _unit_tuple(units)
142        if len(given) > 1:
143            given = tuple(dict.fromkeys(given))
144        if not given:
145            raise ValueError(_NEEDS_A_UNIT)
146        row = self._game_data.abilities.get(ability)
147        sent_as = ABILITIES_SENT_AS_ANOTHER.get(ability, SENT_UNCHANGED)
148        if ability.is_custom:
149            if row is None:
150                raise ValueError(f"{ability.name} has nothing in this game's tables to be sent as")
151            _check_sent_as(ability, sent_as, given)
152        aimed = aimed_at(target)
153        check_target(ability, aimed, row)
154        _check_each_can_carry_it_out(ability, row, aimed, len(given))
155        if aimed is None:
156            _check_placed_where_flying(ability, row, given)
157        if isinstance(aimed, Unit):
158            _check_not_aimed_at_itself(ability, aimed, given)
159        order = IssuedOrder(ability, Units(given), aimed, queued=queued, issued_time=self._time)
160        self._add(order)
161        if force:
162            self._forced.add(order)
163        return order

Order units to use ability, aimed at a point, a unit or nothing, and return the IssuedOrder.

Every unit given carries it out, and a unit given twice counts once. An ability every unit of one command carries out (AbilityData.multi_unit) goes out as one command naming them all, so units ordered together keep their spacing where the game spreads them; any other goes out as a command to each. queued puts the order behind each unit's orders. Nothing is sent until the turn's handlers have all run.

Orders of an ability that joins other orders (AbilityData.joins_other_orders), given apart in one turn, go out as one command where they are aimed at the same unit, or at the same point as the game keeps it, and are queued alike, so units ordered one at a time keep their spacing too. An order joins the last such command before it unless one of its units is named in that command or a later one, so a unit's commands go out in the order it was given them; another unit's may go out ahead of commands given before them. A command aimed at one of its own units, as a transport's unload where it stands is, joins nothing, and nothing joins it. The game answers a command naming several units Success if any of them can take it, so then every order it carries counts as sent: one whose units could not take it is not listed in api.action_failures, and the same order given them again is left out as one they are carrying out until the observations would show it.

An unqueued order that replaces a unit's orders is not sent to a unit already doing it: sending it would only drop what the unit has queued behind it. What a unit is doing is the last such order sent to it, while the observation after its turn may not show it yet, and otherwise its first reported order. force sends it to those units too: that is how a unit is made to drop its queue and go on with its current order. It still competes with the turn's other orders like any other.

An ability that goes out as another for some types (AbilityData.sent_as) goes out as that one to their units, in commands of its own, which join other orders' as the ability's own do. A command the game refuses is listed in api.action_failures once for each unit it names, under the ability of that unit's order.

Raises TypeError for a target the ability cannot be aimed at, for an add-on with no point given to a flying structure, and for a transport's unload at a point aimed at one of units itself, which is UNLOAD for that one: a group given an unload at one of its own transports is two orders. Raises ValueError for a research given to several units, and for an ability that places something at its target (AbilityData.places_at_target) given to several aimed at one; and for a custom ability given to a type it has nothing to be sent as for, or which this game's tables lack an ability it is sent as for.

def train( self, units: Union[sc2nachos.OwnUnit[Any], Iterable[sc2nachos.OwnUnit[Any]]], unit_type: sc2nachos.UnitTypeId, *, target: 'PointLike | Unit[Any] | None' = None, queued: bool = False, force: bool = False) -> IssuedOrder:
165    def train(
166        self,
167        units: OwnUnit[Any] | Iterable[OwnUnit[Any]],
168        unit_type: UnitTypeId,
169        *,
170        target: PointLike | Unit[Any] | None = None,
171        queued: bool = False,
172        force: bool = False,
173    ) -> IssuedOrder:
174        """Order `units` to make a unit of `unit_type` and return the `IssuedOrder`, as `issue` orders the ability
175        their type makes it with: a barracks's `BARRACKS_TRAIN_MARINE`, a warp gate's `WARP_GATE_WARP_IN_ZEALOT`, aimed
176        at a point, a larva's `LARVA_MORPH_DRONE`.
177
178        It orders what a structure or a larva makes that is not a structure; `build` orders a structure a worker makes
179        and an add-on, and `issue` the rest, a morph such as an orbital command's or a baneling's among them.
180
181        Raises `ValueError` where one of `units` does not train `unit_type`, saying what does, and where two of them
182        make it with different abilities, as a gateway and a warp gate a zealot: they are ordered apart. Raises
183        otherwise as `issue` does.
184        """
185        given = _unit_tuple(units)
186        ability = self._ability_making(given, unit_type, self._trained_abilities, "train")
187        return self.issue(given, ability, target=target, queued=queued, force=force)

Order units to make a unit of unit_type and return the IssuedOrder, as issue orders the ability their type makes it with: a barracks's BARRACKS_TRAIN_MARINE, a warp gate's WARP_GATE_WARP_IN_ZEALOT, aimed at a point, a larva's LARVA_MORPH_DRONE.

It orders what a structure or a larva makes that is not a structure; build orders a structure a worker makes and an add-on, and issue the rest, a morph such as an orbital command's or a baneling's among them.

Raises ValueError where one of units does not train unit_type, saying what does, and where two of them make it with different abilities, as a gateway and a warp gate a zealot: they are ordered apart. Raises otherwise as issue does.

def build( self, units: Union[sc2nachos.OwnUnit[Any], Iterable[sc2nachos.OwnUnit[Any]]], unit_type: sc2nachos.UnitTypeId, *, target: 'PointLike | Unit[Any] | None' = None, queued: bool = False, force: bool = False) -> IssuedOrder:
189    def build(
190        self,
191        units: OwnUnit[Any] | Iterable[OwnUnit[Any]],
192        unit_type: UnitTypeId,
193        *,
194        target: PointLike | Unit[Any] | None = None,
195        queued: bool = False,
196        force: bool = False,
197    ) -> IssuedOrder:
198        """Order `units` to make a structure of `unit_type` and return the `IssuedOrder`, as `issue` orders the
199        ability their type makes it with: an SCV's `SCV_BUILD_SUPPLY_DEPOT` aimed at a point, a drone's
200        `DRONE_MORPH_EXTRACTOR` aimed at a geyser, a barracks's `BUILD_TECH_LAB`.
201
202        It orders a structure a worker makes, and an add-on; `train` orders what a structure or a larva makes that is
203        not a structure, and `issue` the rest, a morph such as an orbital command's or a lair's among them.
204
205        Raises `ValueError` where one of `units` does not build `unit_type`, saying what does, and where two of them
206        make it with different abilities. Raises otherwise as `issue` does: `ValueError` for workers given one site.
207        """
208        given = _unit_tuple(units)
209        ability = self._ability_making(given, unit_type, self._built_abilities, "build")
210        return self.issue(given, ability, target=target, queued=queued, force=force)

Order units to make a structure of unit_type and return the IssuedOrder, as issue orders the ability their type makes it with: an SCV's SCV_BUILD_SUPPLY_DEPOT aimed at a point, a drone's DRONE_MORPH_EXTRACTOR aimed at a geyser, a barracks's BUILD_TECH_LAB.

It orders a structure a worker makes, and an add-on; train orders what a structure or a larva makes that is not a structure, and issue the rest, a morph such as an orbital command's or a lair's among them.

Raises ValueError where one of units does not build unit_type, saying what does, and where two of them make it with different abilities. Raises otherwise as issue does: ValueError for workers given one site.

def research( self, unit: sc2nachos.OwnUnit[typing.Any], upgrade: sc2nachos.UpgradeId, *, queued: bool = False, force: bool = False) -> IssuedOrder:
212    def research(
213        self, unit: OwnUnit[Any], upgrade: UpgradeId, *, queued: bool = False, force: bool = False
214    ) -> IssuedOrder:
215        """Order `unit` to research `upgrade` and return the `IssuedOrder`, as `issue` orders the upgrade's
216        `research_ability`: Stimpack's `BARRACKS_TECH_LAB_RESEARCH_STIMPACK`.
217
218        Raises `ValueError` where nothing researches `upgrade`, and where `unit`'s type is not one of its
219        `researchers`: a barracks's upgrades are its tech lab's. Raises otherwise as `issue` does.
220        """
221        row = self._game_data.upgrades.get(upgrade)
222        if row is None or row.research_ability is None:
223            raise ValueError(f"nothing researches {upgrade.name}")
224        if unit.type_id not in row.researchers:
225            researchers = _listed_with_or(row.researchers)
226            raise ValueError(f"{upgrade.name} is researched by {researchers}, not {_with_article(unit.type_id)}")
227        return self.issue(unit, row.research_ability, queued=queued, force=force)

Order unit to research upgrade and return the IssuedOrder, as issue orders the upgrade's research_ability: Stimpack's BARRACKS_TECH_LAB_RESEARCH_STIMPACK.

Raises ValueError where nothing researches upgrade, and where unit's type is not one of its researchers: a barracks's upgrades are its tech lab's. Raises otherwise as issue does.

def issued_to( self, unit: sc2nachos.OwnUnit[typing.Any], *, include_sent: bool = False) -> tuple[IssuedOrder, ...]:
267    def issued_to(self, unit: OwnUnit[Any], *, include_sent: bool = False) -> tuple[IssuedOrder, ...]:
268        """The orders issued to `unit` so far this turn, in the order they were issued. Withdrawn orders are left out.
269        With `include_sent`, first come the orders that went out to it lately and that the observations may not show
270        yet: the last one sent that replaced its orders, and those sent since that did not, queued ones, trains,
271        researches, add-ons and morphs, but not what it carries out at once.
272
273        A handler late in a turn reads this to leave alone a unit an earlier handler has ordered, since only the last
274        order a unit is given goes out.
275        """
276        turns = self._issued_by_unit.get(unit.id, ())
277        sent = self._sent_but_not_observed_yet(unit) if include_sent else ()
278        return (*sent, *(order for order in turns if not order._withdrawn))

The orders issued to unit so far this turn, in the order they were issued. Withdrawn orders are left out. With include_sent, first come the orders that went out to it lately and that the observations may not show yet: the last one sent that replaced its orders, and those sent since that did not, queued ones, trains, researches, add-ons and morphs, but not what it carries out at once.

A handler late in a turn reads this to leave alone a unit an earlier handler has ordered, since only the last order a unit is given goes out.

pending: tuple[IssuedOrder, ...]
280    @property
281    def pending(self) -> tuple[IssuedOrder, ...]:
282        """Every order issued this turn and still to be sent. Withdrawn orders are left out."""
283        return tuple(order for order in self._issued if not order._withdrawn)

Every order issued this turn and still to be sent. Withdrawn orders are left out.

pending_cost: sc2nachos.Cost
285    @property
286    def pending_cost(self) -> Cost:
287        """What the bank does not show yet: the cost of the orders of `pending` that will go out, each its ability's
288        `cost` in the game's tables for each unit it goes out to. A unit given orders that replace one another pays for
289        the last, and one already carrying an order out pays nothing for it again. Its time is every order's added up,
290        though the units may carry them out side by side."""
291        total = Cost(0, 0)
292        for order, units in self._orders_to_send(self._issued, self._forced):
293            row = self._game_data.abilities.get(order.ability)
294            if row is not None:
295                total += row.cost * len(units)
296        return total

What the bank does not show yet: the cost of the orders of pending that will go out, each its ability's cost in the game's tables for each unit it goes out to. A unit given orders that replace one another pays for the last, and one already carrying an order out pays nothing for it again. Its time is every order's added up, though the units may carry them out side by side.