sc2nachos.extensions.speed_mining

Speed mining: workers mine minerals and collect vespene faster, each trip ending in a move that keeps their speed into the gather or return.

1"""Speed mining: workers mine minerals and collect vespene faster, each trip ending in a move that keeps their speed
2into the gather or return."""
3
4from sc2nachos.extensions.speed_mining._speed_mining import SpeedMining
5
6__all__ = ["SpeedMining"]
@final
class SpeedMining:
 44@final
 45class SpeedMining:
 46    """Speed mining: each worker handed over to mine minerals mines its field, and each worker handed over to collect
 47    vespene collects from its gas building, each trip ending in a move with the gather or the return queued behind,
 48    which keeps the worker's speed into it, where the gather or return alone slows the worker as it nears the field, the
 49    gas building or the townhall.
 50
 51    Build it once the game has started, in the bot's own object an api is given as `extensions`:
 52
 53    ```python
 54    from sc2nachos import Api
 55    from sc2nachos.extensions.speed_mining import SpeedMining
 56
 57
 58    class Extensions:
 59        def __init__(self, api: Api) -> None:
 60            self.speed_mining = SpeedMining(api)
 61
 62
 63    api = Api(extensions=Extensions)
 64    ```
 65
 66    How many workers mine and how many collect stays the bot's, and which field or gas building each works may be:
 67    `mine` hands one over to mine, two at a field at most, at a field of an expansion with a finished townhall of this
 68    player's at its center, which it picks among the fields it is given or among all. `collect` hands one over to
 69    collect, three at a gas building at most, at a finished gas building of this player's with vespene left on a geyser
 70    of such an expansion, which it picks alike. Each sends the worker there at once unless it is at that work already,
 71    but takes none it cannot send, building, burrowed or out of reach of orders, and holds a worker at one field or gas
 72    building at a time. `release` takes one or several back, `release_miners` and `release_collectors` a number of
 73    them, those whose leaving costs the least, and `miners`, `collectors`, `workers` and `workers_at` read them. On
 74    each `TurnEvent`, at `EventPriority.AFTER`, after every handler of the bot's, speed mining orders each worker it
 75    holds:
 76
 77    - A miner idle, gathering minerals, returning minerals, or on speed mining's own move, is kept mining its field:
 78      one gathering at another field, as the game sends a worker whose field is taken, or on its way to a field it was
 79      handed before, is sent to its own, and one carrying cargo but not returning it is given a return with the gather
 80      queued behind. When it comes within 0.75 to 2 of where its trip ends, it is given the move there, with the gather
 81      at the field queued behind, or a right-click on the townhall, which the worker shows as a return.
 82    - A collector idle, gathering vespene, returning cargo, or on speed mining's own move, is kept collecting from its
 83      gas building: one gathering at another gas building, or on its way to one it was handed before, is sent to its
 84      own, and one carrying cargo but not returning it is given a return with the gather queued behind. Near where its
 85      trip ends it is given the move there as a miner is, its trip read off its gather or return, since a worker
 86      carrying gas from a rich geyser shows no cargo (`Unit.is_carrying_gas`): the move of a trip to the gas building
 87      ends where a worker's circle touches the gas building's, toward the townhall's center.
 88    - A collector coming out of its gas building is given no move while a collector of the same gas building going in,
 89      on its move, given it this turn or sent it lately, has yet to pass it, the one going in farther from the gas
 90      building's center or the two touching, and is given its return back, with the gather queued behind, if it is on
 91      its move or speed mining's move is the last order it was sent. It passes through on its return.
 92    - No move is given while a unit stands in the worker's way, its circle within 0.5 of the line from the worker to
 93      where its trip ends, and a worker on the move that a unit comes in the way of is given its gather or return back.
 94      Units of both players count, on the ground and not burrowed, but structures, larvae, and the workers speed mining
 95      holds; a worker it lets go in the turn counts.
 96    - A worker attacks an enemy it can hit as it stands, unless speed mining was built with `attack_enemies=False`:
 97      its weapon cooldown at most a step, the enemy visible, on the ground, not a structure, in range
 98      (`Unit.has_in_range`), and no more than a step's turn away (`Unit.time_to_face`); the one with least life, among
 99      several. It goes back to mining or collecting once it has fired.
100    - A worker's cargo goes back to the townhall standing at the center of the expansion of its field or of its gas
101      building's geyser: one of this player's, finished.
102      An orbital, a planetary fortress, a lair and a hive count as finished, since only a morph makes them: an orbital
103      reads unfinished in the step before its morph finishes. A field or a geyser two expansions share counts as the
104      first's, by `Api.expansions`, that has such a townhall.
105    - A worker is let go, its orders left as they are, once the bot orders it: once an order issued to it this turn
106      stands, no unqueued order coming after it, that is neither a return nor a gather at a mineral field, for a
107      miner, or at a gas building, for a collector, as `mine` and `collect` hand a worker over with. Speed mining's
108      turn comes after every handler of the bot's, so the worker is let go in the turn of the order, whether or not
109      the game takes it, and `miners` and `collectors` hold it until then. A worker the bot sends to gather at another
110      field is kept, and sent to its own, as one the game sends there is. So a miner the bot sends to build does not
111      come back to its field, nor a drone it burrows: the bot hands it over again.
112    - A worker given an order this turn, or sent one lately that may not show yet, as `OrderBook.issued_to` reads with
113      `include_sent`, is left alone for the turn, and one burrowed, or doing anything but its work, as an SCV
114      repairing by autocast, until it is unburrowed, idle or back at its work.
115    - A worker is let go alike once it or its field is dead, and once no expansion holding its field has such a
116      townhall any more, as when the townhall dies or lifts off. A collector is let go alike once its gas building is
117      dead or has no vespene left, or no expansion holding its geyser has such a townhall.
118
119    Raises `NotPlayingError` if built before the game starts.
120    """
121
122    __slots__ = (
123        "_api",
124        "_attack_enemies",
125        "_attacks",
126        "_field_by_worker",
127        "_gas_building_by_worker",
128        "_trip_end_points",
129        "_trips",
130    )
131
132    def __init__(self, api: Api[object], *, attack_enemies: bool = True) -> None:
133        """Speed mining for the workers of `api`'s game, from the next `TurnEvent`, its workers attacking enemies they
134        can hit if `attack_enemies`."""
135        self._api = api
136        self._attack_enemies = attack_enemies
137        self._attacks = WorkerAttacks(api)
138        self._field_by_worker: UnitDict[OwnUnit[UnitType.Worker], Unit[UnitType.AnyMineralField]] = UnitDict()
139        self._gas_building_by_worker: UnitDict[OwnUnit[UnitType.Worker], Unit[UnitType.GasBuilding]] = UnitDict()
140        self._trip_end_points = TripEndPointBook(api.expansions)
141        self._trips = WorkerTrips(api)
142        api.on(TurnEvent, priority=EventPriority.AFTER)(self._order_the_workers)
143
144    @property
145    def miners(self) -> Mapping[OwnUnit[UnitType.Worker], Unit[UnitType.AnyMineralField]]:
146        """Each worker speed mining holds to mine minerals, with the field it mines: a read-only view, so a worker
147        handed over or let go shows at once. A dead worker is never among them."""
148        return MappingProxyType(self._field_by_worker)
149
150    @property
151    def collectors(self) -> Mapping[OwnUnit[UnitType.Worker], Unit[UnitType.GasBuilding]]:
152        """Each worker speed mining holds to collect vespene, with the gas building it collects from: a read-only view,
153        as `miners` is. A worker inside its gas building is among them, and a dead one never."""
154        return MappingProxyType(self._gas_building_by_worker)
155
156    @property
157    def workers(self) -> Mapping[OwnUnit[UnitType.Worker], Unit[UnitType.AnyResource]]:
158        """Each worker speed mining holds, with the field it mines or the gas building it collects from: `miners` and
159        `collectors` in one read-only view."""
160        # Cast: a `ChainMap` takes mutable mappings, whose values a type checker cannot widen.
161        miners = cast("MutableMapping[OwnUnit[UnitType.Worker], Unit[UnitType.AnyResource]]", self._field_by_worker)
162        collectors = cast(
163            "MutableMapping[OwnUnit[UnitType.Worker], Unit[UnitType.AnyResource]]", self._gas_building_by_worker
164        )
165        return MappingProxyType(ChainMap(miners, collectors))
166
167    def workers_at(self, resource: Unit[UnitType.AnyResource]) -> Units[OwnUnit[UnitType.Worker]]:
168        """The workers speed mining holds at `resource`, a mineral field or a gas building, in the order they were
169        handed over."""
170        if UnitType.AnyMineralField.includes(resource):
171            return Units(worker for worker, field in self._field_by_worker.items() if field is resource)
172        return Units(
173            worker for worker, gas_building in self._gas_building_by_worker.items() if gas_building is resource
174        )
175
176    def mine(
177        self,
178        worker: OwnUnit[UnitType.Worker],
179        fields: Unit[UnitType.AnyMineralField] | Iterable[Unit[UnitType.AnyMineralField]] | None = None,
180    ) -> Unit[UnitType.AnyMineralField] | None:
181        """Have `worker` mine a field until it is released, or let go as the class's docstring says, and return the
182        field, or `None` where there is no room or `worker` cannot be sent there now. A worker held at another field,
183        or at a gas building, moves to this one.
184
185        Speed mining picks the field among those of the expansions with a finished townhall of this player's at their
186        center, and only among `fields`, one or several, if given: at the expansion nearest `worker` with a field fewer
187        than two other workers mine, a field of the nearer half of the expansion's fields before one of the farther
188        half, and then the one nearest `worker`. Where there is none, as for a field of an expansion without such a
189        townhall, `mine` returns `None` and leaves `worker` as it was, mining the field it had, if any.
190
191        Handed over, `worker` is sent to the field at once: a gather at the field, behind a return of any cargo it
192        carries, minerals or vespene. So a worker pulled into a fight, or collecting vespene, mines from this turn.
193        Nothing is sent to a worker mining minerals already, which speed mining keeps at the field from the next turn,
194        nor again to one sent there lately, whose orders may not show it yet, but one given another order this turn is
195        sent there. A worker building, burrowed, or out of reach of orders (`OwnUnit.is_orderable`), as inside a
196        refinery or a transport, cannot be sent: `mine` returns `None` for it and leaves it as it was, to be handed over
197        once it can be.
198
199        Raises `ValueError` for a unit that is not a worker, an SCV, a drone or a probe, and for one of `fields` that is
200        not a mineral field.
201        """
202        _check_is_a_worker(worker)
203        only_fields = _given(fields, UnitType.AnyMineralField, "speed mining mines mineral fields")
204        field = self._nearest_field_with_room(worker, only_fields)
205        if field is None or not self._send_to_gather_at(worker, field, mining=True):
206            return None
207        # Released first, so that it counts as handed over last wherever it was held.
208        self.release(worker)
209        self._field_by_worker[worker] = field
210        return field
211
212    def collect(
213        self,
214        worker: OwnUnit[UnitType.Worker],
215        gas_buildings: Unit[UnitType.GasBuilding] | Iterable[Unit[UnitType.GasBuilding]] | None = None,
216    ) -> Unit[UnitType.GasBuilding] | None:
217        """Have `worker` collect vespene from a gas building until it is released, or let go as the class's docstring
218        says, and return the gas building, or `None` where there is no room or `worker` cannot be sent there now. A
219        worker held at another gas building, or at a field, moves to this one.
220
221        Speed mining picks the gas building among the finished ones of this player's with vespene left, standing on a
222        geyser of an expansion with a finished townhall of this player's at its center, and only among
223        `gas_buildings`, one or several, if given: at the expansion nearest `worker` with a gas building fewer than two
224        other workers collect from, the one of those nearest the expansion's center, before a third at any; where every
225        one has two, at the expansion nearest `worker` with one fewer than three others collect from, the one of those
226        farthest from its center. Where there is none, `collect` returns `None` and leaves `worker` as it was, held
227        where it was, if anywhere.
228
229        Handed over, `worker` is sent to the gas building at once, as `mine` sends a worker to its field: a gather at
230        it, behind a return of any cargo it carries. Nothing is sent to a worker collecting vespene already, nor again
231        to one sent there lately, but to one given another order this turn, and `collect` returns `None` for a worker
232        building, burrowed, or out of reach of orders, as inside a gas building, and leaves it as it was.
233
234        Raises `ValueError` for a unit that is not a worker, and for one of `gas_buildings` that is not a gas building.
235        """
236        _check_is_a_worker(worker)
237        only_gas_buildings = _given(gas_buildings, UnitType.GasBuilding, "speed mining collects from gas buildings")
238        gas_building = self._gas_building_with_room_to_pick(worker, only_gas_buildings)
239        if gas_building is None:
240            return None
241        # So that a move to where one of its trips ends reads as speed mining's from the first.
242        self._trip_end_points.work_out_gas_building(gas_building)
243        if not self._send_to_gather_at(worker, gas_building, mining=False):
244            return None
245        # Released first, so that it counts as handed over last wherever it was held.
246        self.release(worker)
247        self._gas_building_by_worker[worker] = gas_building
248        return gas_building
249
250    def release(self, workers: OwnUnit[UnitType.Worker] | Iterable[OwnUnit[UnitType.Worker]]) -> None:
251        """Stop ordering `workers`, one or several, leaving their orders as they are. Nothing happens for a worker not
252        handed over."""
253        for worker in _tuple_of_units(workers):
254            self._field_by_worker.pop(worker, None)
255            self._gas_building_by_worker.pop(worker, None)
256
257    def release_miners(self, count: int) -> Units[OwnUnit[UnitType.Worker]]:
258        """Release `count` of the miners speed mining holds, as `release` does, those whose leaving costs the least
259        first, and return them in that order, or all of them where it holds fewer: the reverse of how `mine` picks a
260        field. One speed mining would let go this turn, as one the bot has ordered, leaves first, then one at a field of
261        the farther half of its expansion's fields, then one of the nearer half; of those alike, the one handed over
262        last, the likeliest to have mined nothing yet.
263
264        Raises `ValueError` for a `count` below zero."""
265        return self._release_the_first(self._miners_cheapest_to_release_first(), count)
266
267    def release_collectors(self, count: int) -> Units[OwnUnit[UnitType.Worker]]:
268        """Release `count` of the collectors speed mining holds, as `release` does, those whose leaving costs the least
269        vespene first, and return them in that order, or all of them where it holds fewer: the reverse of how
270        `collect` fills gas buildings. One speed mining would let go this turn, as one the bot has ordered, leaves
271        first, then a gas building's third collector of those it keeps, at the gas building nearest its expansion's
272        center first, where a third adds the least, and then a gas building's others, at the one farthest from its
273        expansion's center first; of those alike, the one handed over last, the likeliest to have collected nothing
274        yet.
275
276        Raises `ValueError` for a `count` below zero."""
277        return self._release_the_first(self._collectors_cheapest_to_release_first(), count)
278
279    def _release_the_first(
280        self, workers_cheapest_first: list[OwnUnit[UnitType.Worker]], count: int
281    ) -> Units[OwnUnit[UnitType.Worker]]:
282        """Release the first `count` of `workers_cheapest_first`, or all of them where there are fewer, and return
283        them. Raises `ValueError` for a `count` below zero."""
284        if count < 0:
285            raise ValueError(f"speed mining releases no fewer than none, not {count}")
286        leaving = Units(workers_cheapest_first[:count])
287        self.release(leaving)
288        return leaving
289
290    def _miners_cheapest_to_release_first(self) -> list[OwnUnit[UnitType.Worker]]:
291        """The miners held, those whose leaving costs the least first, as `release_miners` says."""
292        townhall_by_center: dict[Point, Unit[UnitType.Townhall] | None] = {}
293        handed_over_place = {miner: place for place, miner in enumerate(self._field_by_worker)}
294        cost_of_leaving: dict[OwnUnit[UnitType.Worker], tuple[int, int]] = {}
295        for field, miners in _workers_by_resource(self._field_by_worker).items():
296            trip_to_it = self._trip_to_a_field(field, townhall_by_center)
297            # 0 for one let go this turn, 1 at a field of the farther half, 2 of the nearer.
298            if trip_to_it is None:
299                field_rank = 0
300            else:
301                alive_fields = [
302                    expansion_field
303                    for expansion_field in trip_to_it[0].expansion.mineral_fields
304                    if expansion_field.is_alive
305                ]
306                field_rank = 1 if _is_of_the_farther_half(alive_fields.index(field), len(alive_fields)) else 2
307            for miner in miners:
308                leaving_rank = 0 if self._is_ordered_by_the_bot(miner, mining=True) else field_rank
309                cost_of_leaving[miner] = (leaving_rank, -handed_over_place[miner])
310        return sorted(cost_of_leaving, key=cost_of_leaving.__getitem__)
311
312    def _collectors_cheapest_to_release_first(self) -> list[OwnUnit[UnitType.Worker]]:
313        """The collectors held, those whose leaving costs the least first, as `release_collectors` says."""
314        townhall_by_center: dict[Point, Unit[UnitType.Townhall] | None] = {}
315        handed_over_place = {collector: place for place, collector in enumerate(self._gas_building_by_worker)}
316        cost_of_leaving: dict[OwnUnit[UnitType.Worker], tuple[int, float, int]] = {}
317        for gas_building, collectors in _workers_by_resource(self._gas_building_by_worker).items():
318            trip_to_it = self._trip_to_a_gas_building(gas_building, townhall_by_center)
319            from_its_center = 0.0 if trip_to_it is None else gas_building.distance_to(trip_to_it[0].expansion.center)
320            place_at_the_gas_building = 0
321            for collector in collectors:
322                # 0 for one let go this turn, 1 for a third of those kept, the nearer its center first, 2 for the
323                # others, the farther first.
324                if trip_to_it is None or self._is_ordered_by_the_bot(collector, mining=False):
325                    cost_of_leaving[collector] = (0, 0.0, -handed_over_place[collector])
326                    continue
327                place_at_the_gas_building += 1
328                if place_at_the_gas_building > _COLLECTORS_AT_EACH_GAS_BUILDING_BEFORE_A_THIRD:
329                    leaving_rank, distance_order = 1, from_its_center
330                else:
331                    leaving_rank, distance_order = 2, -from_its_center
332                cost_of_leaving[collector] = (leaving_rank, distance_order, -handed_over_place[collector])
333        return sorted(cost_of_leaving, key=cost_of_leaving.__getitem__)
334
335    def _trip_to_a_field(
336        self, field: Unit[UnitType.AnyMineralField], townhall_by_center: dict[Point, Unit[UnitType.Townhall] | None]
337    ) -> tuple[TripEndPoints, Unit[UnitType.Townhall]] | None:
338        """The end points of the trips to `field` with the townhall taking their cargo, or `None` where speed mining
339        lets its miners go: once it is dead, or no expansion holding it has a finished townhall of this player's at its
340        center. Each expansion's townhall is read once a turn, kept in `townhall_by_center`."""
341        return None if field.is_dead else self._trip_end_points.of_field(field, townhall_by_center)
342
343    def _trip_to_a_gas_building(
344        self, gas_building: Unit[UnitType.GasBuilding], townhall_by_center: dict[Point, Unit[UnitType.Townhall] | None]
345    ) -> tuple[TripEndPoints, Unit[UnitType.Townhall]] | None:
346        """The end points of the trips to `gas_building` with the townhall taking their cargo, or `None` where speed
347        mining lets its collectors go: once it is dead or has no vespene left, as `_trip_to_a_field` says otherwise."""
348        if gas_building.is_dead or gas_building.vespene_contents == 0:
349            return None
350        return self._trip_end_points.of_gas_building(gas_building, townhall_by_center)
351
352    def _send_to_gather_at(
353        self, worker: OwnUnit[UnitType.Worker], resource: Unit[UnitType.AnyResource], *, mining: bool
354    ) -> bool:
355        """Send `worker`, being handed over at `resource`, a field to mine if `mining`, else a gas building to collect
356        from, there at once, as `mine` and `collect` say, unless it is at that work already, and return whether it
357        could be: not while it builds, is burrowed or is out of reach of orders. One the bot ordered elsewhere this turn
358        is not at that work, whatever its orders show."""
359        if not worker.is_orderable or worker.is_burrowed or worker.is_constructing:
360            return False
361        order_book = self._api.orders
362        if not _has_a_standing_order_other_than_a_hand_overs(order_book.issued_to(worker), mining=mining):
363            current_order = worker.current_order
364            if current_order is not None and self._is_its_work(worker, current_order, mining=mining):
365                return True
366            if any(
367                order.ability is AbilityId.GATHER and order.target is resource
368                for order in order_book.issued_to(worker, include_sent=True)
369            ):
370                return True
371        if carries_cargo(worker):
372            self._trips.hand_in_then_gather(worker, resource)
373        else:
374            order_book.issue(worker, AbilityId.GATHER, target=resource)
375        return True
376
377    def _nearest_field_with_room(
378        self, worker: OwnUnit[UnitType.Worker], only_fields: frozenset[Unit[UnitType.AnyMineralField]] | None
379    ) -> Unit[UnitType.AnyMineralField] | None:
380        """The field `mine` picks for `worker`, among `only_fields` unless `None`, as it says, or `None` where there is
381        none."""
382        miner_counts = _counts_of_the_others(self._field_by_worker, worker)
383        for expansion in self._expansions_with_a_finished_townhall_nearest(worker):
384            fields = [field for field in expansion.mineral_fields if field.is_alive]
385            with_room = [
386                (_is_of_the_farther_half(index, len(fields)), worker.distance_to(field), field)
387                for index, field in enumerate(fields)
388                if miner_counts[field] < _MOST_MINERS_AT_A_FIELD and (only_fields is None or field in only_fields)
389            ]
390            if with_room:
391                return min(with_room, key=lambda candidate: candidate[:2])[2]
392        return None
393
394    def _gas_building_with_room_to_pick(
395        self, worker: OwnUnit[UnitType.Worker], only_gas_buildings: frozenset[Unit[UnitType.GasBuilding]] | None
396    ) -> Unit[UnitType.GasBuilding] | None:
397        """The gas building `collect` picks for `worker`, among `only_gas_buildings` unless `None`, as it says, or
398        `None` where there is none."""
399        collector_counts = _counts_of_the_others(self._gas_building_by_worker, worker)
400        with_room_by_position = {
401            gas_building.position: gas_building
402            for gas_building in self._api.units.own.gas_buildings
403            if gas_building.is_complete
404            and gas_building.vespene_contents > 0
405            and collector_counts[gas_building] < _MOST_COLLECTORS_AT_A_GAS_BUILDING
406            and (only_gas_buildings is None or gas_building in only_gas_buildings)
407        }
408        if not with_room_by_position:
409            return None
410        # Each expansion's, nearest its center first, as its geysers are, the expansion nearest `worker` first.
411        with_room_at_each_expansion = [
412            [
413                with_room_by_position[geyser.position]
414                for geyser in expansion.geysers
415                if geyser.position in with_room_by_position
416            ]
417            for expansion in self._expansions_with_a_finished_townhall_nearest(worker)
418        ]
419        for with_room_at_the_expansion in with_room_at_each_expansion:
420            for gas_building in with_room_at_the_expansion:
421                if collector_counts[gas_building] < _COLLECTORS_AT_EACH_GAS_BUILDING_BEFORE_A_THIRD:
422                    return gas_building
423        return next(
424            (
425                with_room_at_the_expansion[-1]
426                for with_room_at_the_expansion in with_room_at_each_expansion
427                if with_room_at_the_expansion
428            ),
429            None,
430        )
431
432    def _expansions_with_a_finished_townhall_nearest(self, worker: OwnUnit[UnitType.Worker]) -> Iterator[Expansion]:
433        """The expansions with a finished townhall of this player's at their center, nearest `worker` first."""
434        for expansion in sorted(self._api.expansions, key=lambda expansion: worker.distance_to(expansion.center)):
435            if finished_own_townhall_at_center(expansion) is not None:
436                yield expansion
437
438    def _order_the_workers(self, _: TurnEvent) -> None:
439        """Order each worker held, as the class's docstring says: the miners field by field, then the collectors gas
440        building by gas building, once the workers of the fields and gas buildings no longer mined or collected from
441        are let go, and those the bot ordered, since they count among the units in a move's way."""
442        self._let_go_of_the_workers_the_bot_ordered()
443        townhall_by_center: dict[Point, Unit[UnitType.Townhall] | None] = {}
444        mined_fields = _still_worked(self._field_by_worker, self._trip_to_a_field, townhall_by_center)
445        collected_gas_buildings = _still_worked(
446            self._gas_building_by_worker, self._trip_to_a_gas_building, townhall_by_center
447        )
448        units_in_the_way: Units[Unit[Any]] | None = None
449        units_near_each_trip_end: dict[Point, Units[Unit[Any]]] = {}
450        enemies_to_attack: Units[Unit[Any]] | None = None
451
452        def units_near_the_trip_end(trip_end: Point) -> Units[Unit[Any]]:
453            """The units that can stand in the way of a move to `trip_end`, worked out once a turn, and only for a trip
454            end a worker comes near."""
455            nonlocal units_in_the_way
456            if (near := units_near_each_trip_end.get(trip_end)) is None:
457                if units_in_the_way is None:
458                    units_in_the_way = units_in_the_way_of_a_move(
459                        self._api.units, self._field_by_worker, self._gas_building_by_worker
460                    )
461                near = units_near_each_trip_end[trip_end] = units_within_reach_of(trip_end, units_in_the_way)
462            return near
463
464        def workers_to_order(
465            workers: list[OwnUnit[UnitType.Worker]], *, mining: bool
466        ) -> list[OwnUnit[UnitType.Worker]]:
467            """Those of `workers`, miners if `mining`, else collectors, that speed mining keeps at their work this turn:
468            neither left alone nor attacking. The enemies to attack are read once a turn, and only once a worker could
469            attack."""
470            nonlocal enemies_to_attack
471            free_workers = [worker for worker in workers if not self._is_left_alone(worker, mining=mining)]
472            if not free_workers or not self._attack_enemies:
473                return free_workers
474            if enemies_to_attack is None:
475                enemies_to_attack = self._api.units.enemy.visible.non_structures.ground
476            attacks = self._attacks
477            return [worker for worker in free_workers if not attacks.attacks(worker, enemies_to_attack)]
478
479        trips = self._trips
480        for field, workers, (field_trip_end_points, townhall) in mined_fields:
481            trips.speed_mine(
482                field, workers_to_order(workers, mining=True), townhall, field_trip_end_points, units_near_the_trip_end
483            )
484        for gas_building, workers, (gas_trip_end_points, townhall) in collected_gas_buildings:
485            trips.speed_collect(
486                gas_building,
487                workers,
488                workers_to_order(workers, mining=False),
489                gas_trip_end_points,
490                townhall,
491                units_near_the_trip_end,
492            )
493
494    def _let_go_of_the_workers_the_bot_ordered(self) -> None:
495        """Let go of each worker held that the bot has ordered, as `_is_ordered_by_the_bot` says, of those the turn's
496        orders name."""
497        for worker in {unit for order in self._api.orders.pending for unit in order.units}:
498            if worker in self._field_by_worker and self._is_ordered_by_the_bot(worker, mining=True):
499                del self._field_by_worker[worker]
500            elif worker in self._gas_building_by_worker and self._is_ordered_by_the_bot(worker, mining=False):
501                del self._gas_building_by_worker[worker]
502
503    def _is_ordered_by_the_bot(self, worker: OwnUnit[UnitType.Worker], *, mining: bool) -> bool:
504        """Whether the bot has ordered `worker`, a miner if `mining`, else a collector: an order issued to it this turn
505        stands that is not a hand-over's. Speed mining's turn comes after every handler of the bot's, so the turn's
506        orders are the bot's and the hand-overs'."""
507        return _has_a_standing_order_other_than_a_hand_overs(self._api.orders.issued_to(worker), mining=mining)
508
509    def _is_left_alone(self, worker: OwnUnit[UnitType.Worker], *, mining: bool) -> bool:
510        """Whether speed mining leaves `worker`, a miner if `mining`, else a collector, alone this turn: not orderable,
511        burrowed, given an order lately, or on an order that is not its work."""
512        if not worker.is_orderable or worker.is_burrowed or self._api.orders.issued_to(worker, include_sent=True):
513            return True
514        current_order = worker.current_order
515        return current_order is not None and not self._is_its_work(worker, current_order, mining=mining)
516
517    def _is_its_work(self, worker: OwnUnit[UnitType.Worker], order: Order, *, mining: bool) -> bool:
518        """Whether `order`, the current one of `worker`, is its work or speed mining's, for a worker mining minerals if
519        `mining`, else collecting vespene: a gather at a mineral field, or at a gas building; a return of minerals, or
520        of anything else, as gas from a rich geyser shows no cargo (in game); a move to where one of speed mining's
521        moves ends; or speed mining's attack. A worker returning the other kind goes back to where it got it next, by
522        itself."""
523        match order.ability:
524            case AbilityId.GATHER:
525                target = order.known_target
526                gathered_at = UnitType.AnyMineralField if mining else UnitType.GasBuilding
527                return isinstance(target, Unit) and gathered_at.includes(target)
528            case AbilityId.RETURN:
529                return worker.is_carrying_minerals == mining
530            case AbilityId.MOVE:
531                return order.known_target in self._trip_end_points
532            case AbilityId.ATTACK:
533                return self._attacks.is_speed_minings_attack(worker, order)
534            case _:
535                return False

Speed mining: each worker handed over to mine minerals mines its field, and each worker handed over to collect vespene collects from its gas building, each trip ending in a move with the gather or the return queued behind, which keeps the worker's speed into it, where the gather or return alone slows the worker as it nears the field, the gas building or the townhall.

Build it once the game has started, in the bot's own object an api is given as extensions:

from sc2nachos import Api
from sc2nachos.extensions.speed_mining import SpeedMining


class Extensions:
    def __init__(self, api: Api) -> None:
        self.speed_mining = SpeedMining(api)


api = Api(extensions=Extensions)

How many workers mine and how many collect stays the bot's, and which field or gas building each works may be: mine hands one over to mine, two at a field at most, at a field of an expansion with a finished townhall of this player's at its center, which it picks among the fields it is given or among all. collect hands one over to collect, three at a gas building at most, at a finished gas building of this player's with vespene left on a geyser of such an expansion, which it picks alike. Each sends the worker there at once unless it is at that work already, but takes none it cannot send, building, burrowed or out of reach of orders, and holds a worker at one field or gas building at a time. release takes one or several back, release_miners and release_collectors a number of them, those whose leaving costs the least, and miners, collectors, workers and workers_at read them. On each TurnEvent, at EventPriority.AFTER, after every handler of the bot's, speed mining orders each worker it holds:

  • A miner idle, gathering minerals, returning minerals, or on speed mining's own move, is kept mining its field: one gathering at another field, as the game sends a worker whose field is taken, or on its way to a field it was handed before, is sent to its own, and one carrying cargo but not returning it is given a return with the gather queued behind. When it comes within 0.75 to 2 of where its trip ends, it is given the move there, with the gather at the field queued behind, or a right-click on the townhall, which the worker shows as a return.
  • A collector idle, gathering vespene, returning cargo, or on speed mining's own move, is kept collecting from its gas building: one gathering at another gas building, or on its way to one it was handed before, is sent to its own, and one carrying cargo but not returning it is given a return with the gather queued behind. Near where its trip ends it is given the move there as a miner is, its trip read off its gather or return, since a worker carrying gas from a rich geyser shows no cargo (Unit.is_carrying_gas): the move of a trip to the gas building ends where a worker's circle touches the gas building's, toward the townhall's center.
  • A collector coming out of its gas building is given no move while a collector of the same gas building going in, on its move, given it this turn or sent it lately, has yet to pass it, the one going in farther from the gas building's center or the two touching, and is given its return back, with the gather queued behind, if it is on its move or speed mining's move is the last order it was sent. It passes through on its return.
  • No move is given while a unit stands in the worker's way, its circle within 0.5 of the line from the worker to where its trip ends, and a worker on the move that a unit comes in the way of is given its gather or return back. Units of both players count, on the ground and not burrowed, but structures, larvae, and the workers speed mining holds; a worker it lets go in the turn counts.
  • A worker attacks an enemy it can hit as it stands, unless speed mining was built with attack_enemies=False: its weapon cooldown at most a step, the enemy visible, on the ground, not a structure, in range (Unit.has_in_range), and no more than a step's turn away (Unit.time_to_face); the one with least life, among several. It goes back to mining or collecting once it has fired.
  • A worker's cargo goes back to the townhall standing at the center of the expansion of its field or of its gas building's geyser: one of this player's, finished. An orbital, a planetary fortress, a lair and a hive count as finished, since only a morph makes them: an orbital reads unfinished in the step before its morph finishes. A field or a geyser two expansions share counts as the first's, by Api.expansions, that has such a townhall.
  • A worker is let go, its orders left as they are, once the bot orders it: once an order issued to it this turn stands, no unqueued order coming after it, that is neither a return nor a gather at a mineral field, for a miner, or at a gas building, for a collector, as mine and collect hand a worker over with. Speed mining's turn comes after every handler of the bot's, so the worker is let go in the turn of the order, whether or not the game takes it, and miners and collectors hold it until then. A worker the bot sends to gather at another field is kept, and sent to its own, as one the game sends there is. So a miner the bot sends to build does not come back to its field, nor a drone it burrows: the bot hands it over again.
  • A worker given an order this turn, or sent one lately that may not show yet, as OrderBook.issued_to reads with include_sent, is left alone for the turn, and one burrowed, or doing anything but its work, as an SCV repairing by autocast, until it is unburrowed, idle or back at its work.
  • A worker is let go alike once it or its field is dead, and once no expansion holding its field has such a townhall any more, as when the townhall dies or lifts off. A collector is let go alike once its gas building is dead or has no vespene left, or no expansion holding its geyser has such a townhall.

Raises NotPlayingError if built before the game starts.

SpeedMining(api: sc2nachos.Api[object], *, attack_enemies: bool = True)
132    def __init__(self, api: Api[object], *, attack_enemies: bool = True) -> None:
133        """Speed mining for the workers of `api`'s game, from the next `TurnEvent`, its workers attacking enemies they
134        can hit if `attack_enemies`."""
135        self._api = api
136        self._attack_enemies = attack_enemies
137        self._attacks = WorkerAttacks(api)
138        self._field_by_worker: UnitDict[OwnUnit[UnitType.Worker], Unit[UnitType.AnyMineralField]] = UnitDict()
139        self._gas_building_by_worker: UnitDict[OwnUnit[UnitType.Worker], Unit[UnitType.GasBuilding]] = UnitDict()
140        self._trip_end_points = TripEndPointBook(api.expansions)
141        self._trips = WorkerTrips(api)
142        api.on(TurnEvent, priority=EventPriority.AFTER)(self._order_the_workers)

Speed mining for the workers of api's game, from the next TurnEvent, its workers attacking enemies they can hit if attack_enemies.

144    @property
145    def miners(self) -> Mapping[OwnUnit[UnitType.Worker], Unit[UnitType.AnyMineralField]]:
146        """Each worker speed mining holds to mine minerals, with the field it mines: a read-only view, so a worker
147        handed over or let go shows at once. A dead worker is never among them."""
148        return MappingProxyType(self._field_by_worker)

Each worker speed mining holds to mine minerals, with the field it mines: a read-only view, so a worker handed over or let go shows at once. A dead worker is never among them.

150    @property
151    def collectors(self) -> Mapping[OwnUnit[UnitType.Worker], Unit[UnitType.GasBuilding]]:
152        """Each worker speed mining holds to collect vespene, with the gas building it collects from: a read-only view,
153        as `miners` is. A worker inside its gas building is among them, and a dead one never."""
154        return MappingProxyType(self._gas_building_by_worker)

Each worker speed mining holds to collect vespene, with the gas building it collects from: a read-only view, as miners is. A worker inside its gas building is among them, and a dead one never.

156    @property
157    def workers(self) -> Mapping[OwnUnit[UnitType.Worker], Unit[UnitType.AnyResource]]:
158        """Each worker speed mining holds, with the field it mines or the gas building it collects from: `miners` and
159        `collectors` in one read-only view."""
160        # Cast: a `ChainMap` takes mutable mappings, whose values a type checker cannot widen.
161        miners = cast("MutableMapping[OwnUnit[UnitType.Worker], Unit[UnitType.AnyResource]]", self._field_by_worker)
162        collectors = cast(
163            "MutableMapping[OwnUnit[UnitType.Worker], Unit[UnitType.AnyResource]]", self._gas_building_by_worker
164        )
165        return MappingProxyType(ChainMap(miners, collectors))

Each worker speed mining holds, with the field it mines or the gas building it collects from: miners and collectors in one read-only view.

167    def workers_at(self, resource: Unit[UnitType.AnyResource]) -> Units[OwnUnit[UnitType.Worker]]:
168        """The workers speed mining holds at `resource`, a mineral field or a gas building, in the order they were
169        handed over."""
170        if UnitType.AnyMineralField.includes(resource):
171            return Units(worker for worker, field in self._field_by_worker.items() if field is resource)
172        return Units(
173            worker for worker, gas_building in self._gas_building_by_worker.items() if gas_building is resource
174        )

The workers speed mining holds at resource, a mineral field or a gas building, in the order they were handed over.

176    def mine(
177        self,
178        worker: OwnUnit[UnitType.Worker],
179        fields: Unit[UnitType.AnyMineralField] | Iterable[Unit[UnitType.AnyMineralField]] | None = None,
180    ) -> Unit[UnitType.AnyMineralField] | None:
181        """Have `worker` mine a field until it is released, or let go as the class's docstring says, and return the
182        field, or `None` where there is no room or `worker` cannot be sent there now. A worker held at another field,
183        or at a gas building, moves to this one.
184
185        Speed mining picks the field among those of the expansions with a finished townhall of this player's at their
186        center, and only among `fields`, one or several, if given: at the expansion nearest `worker` with a field fewer
187        than two other workers mine, a field of the nearer half of the expansion's fields before one of the farther
188        half, and then the one nearest `worker`. Where there is none, as for a field of an expansion without such a
189        townhall, `mine` returns `None` and leaves `worker` as it was, mining the field it had, if any.
190
191        Handed over, `worker` is sent to the field at once: a gather at the field, behind a return of any cargo it
192        carries, minerals or vespene. So a worker pulled into a fight, or collecting vespene, mines from this turn.
193        Nothing is sent to a worker mining minerals already, which speed mining keeps at the field from the next turn,
194        nor again to one sent there lately, whose orders may not show it yet, but one given another order this turn is
195        sent there. A worker building, burrowed, or out of reach of orders (`OwnUnit.is_orderable`), as inside a
196        refinery or a transport, cannot be sent: `mine` returns `None` for it and leaves it as it was, to be handed over
197        once it can be.
198
199        Raises `ValueError` for a unit that is not a worker, an SCV, a drone or a probe, and for one of `fields` that is
200        not a mineral field.
201        """
202        _check_is_a_worker(worker)
203        only_fields = _given(fields, UnitType.AnyMineralField, "speed mining mines mineral fields")
204        field = self._nearest_field_with_room(worker, only_fields)
205        if field is None or not self._send_to_gather_at(worker, field, mining=True):
206            return None
207        # Released first, so that it counts as handed over last wherever it was held.
208        self.release(worker)
209        self._field_by_worker[worker] = field
210        return field

Have worker mine a field until it is released, or let go as the class's docstring says, and return the field, or None where there is no room or worker cannot be sent there now. A worker held at another field, or at a gas building, moves to this one.

Speed mining picks the field among those of the expansions with a finished townhall of this player's at their center, and only among fields, one or several, if given: at the expansion nearest worker with a field fewer than two other workers mine, a field of the nearer half of the expansion's fields before one of the farther half, and then the one nearest worker. Where there is none, as for a field of an expansion without such a townhall, mine returns None and leaves worker as it was, mining the field it had, if any.

Handed over, worker is sent to the field at once: a gather at the field, behind a return of any cargo it carries, minerals or vespene. So a worker pulled into a fight, or collecting vespene, mines from this turn. Nothing is sent to a worker mining minerals already, which speed mining keeps at the field from the next turn, nor again to one sent there lately, whose orders may not show it yet, but one given another order this turn is sent there. A worker building, burrowed, or out of reach of orders (OwnUnit.is_orderable), as inside a refinery or a transport, cannot be sent: mine returns None for it and leaves it as it was, to be handed over once it can be.

Raises ValueError for a unit that is not a worker, an SCV, a drone or a probe, and for one of fields that is not a mineral field.

def collect( self, worker: sc2nachos.OwnUnit[sc2nachos.UnitType.Worker], gas_buildings: Union[sc2nachos.Unit[sc2nachos.UnitType.GasBuilding], Iterable[sc2nachos.Unit[sc2nachos.UnitType.GasBuilding]], NoneType] = None) -> Optional[sc2nachos.Unit[sc2nachos.UnitType.GasBuilding]]:
212    def collect(
213        self,
214        worker: OwnUnit[UnitType.Worker],
215        gas_buildings: Unit[UnitType.GasBuilding] | Iterable[Unit[UnitType.GasBuilding]] | None = None,
216    ) -> Unit[UnitType.GasBuilding] | None:
217        """Have `worker` collect vespene from a gas building until it is released, or let go as the class's docstring
218        says, and return the gas building, or `None` where there is no room or `worker` cannot be sent there now. A
219        worker held at another gas building, or at a field, moves to this one.
220
221        Speed mining picks the gas building among the finished ones of this player's with vespene left, standing on a
222        geyser of an expansion with a finished townhall of this player's at its center, and only among
223        `gas_buildings`, one or several, if given: at the expansion nearest `worker` with a gas building fewer than two
224        other workers collect from, the one of those nearest the expansion's center, before a third at any; where every
225        one has two, at the expansion nearest `worker` with one fewer than three others collect from, the one of those
226        farthest from its center. Where there is none, `collect` returns `None` and leaves `worker` as it was, held
227        where it was, if anywhere.
228
229        Handed over, `worker` is sent to the gas building at once, as `mine` sends a worker to its field: a gather at
230        it, behind a return of any cargo it carries. Nothing is sent to a worker collecting vespene already, nor again
231        to one sent there lately, but to one given another order this turn, and `collect` returns `None` for a worker
232        building, burrowed, or out of reach of orders, as inside a gas building, and leaves it as it was.
233
234        Raises `ValueError` for a unit that is not a worker, and for one of `gas_buildings` that is not a gas building.
235        """
236        _check_is_a_worker(worker)
237        only_gas_buildings = _given(gas_buildings, UnitType.GasBuilding, "speed mining collects from gas buildings")
238        gas_building = self._gas_building_with_room_to_pick(worker, only_gas_buildings)
239        if gas_building is None:
240            return None
241        # So that a move to where one of its trips ends reads as speed mining's from the first.
242        self._trip_end_points.work_out_gas_building(gas_building)
243        if not self._send_to_gather_at(worker, gas_building, mining=False):
244            return None
245        # Released first, so that it counts as handed over last wherever it was held.
246        self.release(worker)
247        self._gas_building_by_worker[worker] = gas_building
248        return gas_building

Have worker collect vespene from a gas building until it is released, or let go as the class's docstring says, and return the gas building, or None where there is no room or worker cannot be sent there now. A worker held at another gas building, or at a field, moves to this one.

Speed mining picks the gas building among the finished ones of this player's with vespene left, standing on a geyser of an expansion with a finished townhall of this player's at its center, and only among gas_buildings, one or several, if given: at the expansion nearest worker with a gas building fewer than two other workers collect from, the one of those nearest the expansion's center, before a third at any; where every one has two, at the expansion nearest worker with one fewer than three others collect from, the one of those farthest from its center. Where there is none, collect returns None and leaves worker as it was, held where it was, if anywhere.

Handed over, worker is sent to the gas building at once, as mine sends a worker to its field: a gather at it, behind a return of any cargo it carries. Nothing is sent to a worker collecting vespene already, nor again to one sent there lately, but to one given another order this turn, and collect returns None for a worker building, burrowed, or out of reach of orders, as inside a gas building, and leaves it as it was.

Raises ValueError for a unit that is not a worker, and for one of gas_buildings that is not a gas building.

def release( self, workers: Union[sc2nachos.OwnUnit[sc2nachos.UnitType.Worker], Iterable[sc2nachos.OwnUnit[sc2nachos.UnitType.Worker]]]) -> None:
250    def release(self, workers: OwnUnit[UnitType.Worker] | Iterable[OwnUnit[UnitType.Worker]]) -> None:
251        """Stop ordering `workers`, one or several, leaving their orders as they are. Nothing happens for a worker not
252        handed over."""
253        for worker in _tuple_of_units(workers):
254            self._field_by_worker.pop(worker, None)
255            self._gas_building_by_worker.pop(worker, None)

Stop ordering workers, one or several, leaving their orders as they are. Nothing happens for a worker not handed over.

def release_miners( self, count: int) -> sc2nachos.Units[sc2nachos.OwnUnit[sc2nachos.UnitType.Worker]]:
257    def release_miners(self, count: int) -> Units[OwnUnit[UnitType.Worker]]:
258        """Release `count` of the miners speed mining holds, as `release` does, those whose leaving costs the least
259        first, and return them in that order, or all of them where it holds fewer: the reverse of how `mine` picks a
260        field. One speed mining would let go this turn, as one the bot has ordered, leaves first, then one at a field of
261        the farther half of its expansion's fields, then one of the nearer half; of those alike, the one handed over
262        last, the likeliest to have mined nothing yet.
263
264        Raises `ValueError` for a `count` below zero."""
265        return self._release_the_first(self._miners_cheapest_to_release_first(), count)

Release count of the miners speed mining holds, as release does, those whose leaving costs the least first, and return them in that order, or all of them where it holds fewer: the reverse of how mine picks a field. One speed mining would let go this turn, as one the bot has ordered, leaves first, then one at a field of the farther half of its expansion's fields, then one of the nearer half; of those alike, the one handed over last, the likeliest to have mined nothing yet.

Raises ValueError for a count below zero.

def release_collectors( self, count: int) -> sc2nachos.Units[sc2nachos.OwnUnit[sc2nachos.UnitType.Worker]]:
267    def release_collectors(self, count: int) -> Units[OwnUnit[UnitType.Worker]]:
268        """Release `count` of the collectors speed mining holds, as `release` does, those whose leaving costs the least
269        vespene first, and return them in that order, or all of them where it holds fewer: the reverse of how
270        `collect` fills gas buildings. One speed mining would let go this turn, as one the bot has ordered, leaves
271        first, then a gas building's third collector of those it keeps, at the gas building nearest its expansion's
272        center first, where a third adds the least, and then a gas building's others, at the one farthest from its
273        expansion's center first; of those alike, the one handed over last, the likeliest to have collected nothing
274        yet.
275
276        Raises `ValueError` for a `count` below zero."""
277        return self._release_the_first(self._collectors_cheapest_to_release_first(), count)

Release count of the collectors speed mining holds, as release does, those whose leaving costs the least vespene first, and return them in that order, or all of them where it holds fewer: the reverse of how collect fills gas buildings. One speed mining would let go this turn, as one the bot has ordered, leaves first, then a gas building's third collector of those it keeps, at the gas building nearest its expansion's center first, where a third adds the least, and then a gas building's others, at the one farthest from its expansion's center first; of those alike, the one handed over last, the likeliest to have collected nothing yet.

Raises ValueError for a count below zero.