sc2nachos.testing

Units for a bot's tests, made without a game: MadeUpUnits takes in the UnitReports of one observation after another and answers the units NachOS makes of them, on the game's data it ships, load_game_data, or on other data.

1"""Units for a bot's tests, made without a game: `MadeUpUnits` takes in the `UnitReport`s of one observation after
2another and answers the units NachOS makes of them, on the game's data it ships, `load_game_data`, or on other data."""
3
4from sc2nachos.testing._made_up_units import MadeUpUnits
5from sc2nachos.testing._shipped_game_data import load_game_data
6from sc2nachos.testing._unit_report import ReportedOrder, ReportedTarget, UnitReport
7
8__all__ = ["MadeUpUnits", "ReportedOrder", "ReportedTarget", "UnitReport", "load_game_data"]
class MadeUpUnits:
19class MadeUpUnits:
20    """The units of a game made up for a test, taken in one observation after another, as NachOS takes them in from a
21    game: the same `Unit` and `OwnUnit` objects, kept up to date, with no game client. What they are ordered goes into
22    `MadeUpUnits.orders`, and is never sent.
23
24    This player is player 1, and the enemy player 2. The units read their types from `game_data`, by default build
25    75689's, as `load_game_data` reads it.
26    """
27
28    def __init__(self, game_data: GameData | None = None) -> None:
29        game_data = load_game_data() if game_data is None else game_data
30        enemy = Enemy(
31            player_id=ENEMY_PLAYER_ID,
32            requested_race=Race.RANDOM,
33            name=None,
34            race=None,
35            ladder_id=None,
36            game_data=game_data,
37        )
38        self._order_book = OrderBook(game_data)
39        self._tracker = _Tracker(game_data, enemy, order_book=self._order_book)
40        self._step: int | None = None
41
42    @property
43    def game_data(self) -> GameData:
44        """The game's data the units read their types from."""
45        return self._tracker.game_data
46
47    @property
48    def orders(self) -> OrderBook:
49        """Every order the units were given since they were made up, through `sc2nachos.units.OwnUnit.issue` or this
50        book's `issue`, as `api.orders` holds a turn's. Nothing is sent, so none leaves the book."""
51        return self._order_book
52
53    @property
54    def units(self) -> Units[Unit[Any]]:
55        """Every unit the latest observation listed."""
56        return self._tracker.unit_tracker.present
57
58    def observe(
59        self, *reports: UnitReport, step: int | None = None, dead: Iterable[UnitReport | int] = ()
60    ) -> list[Any]:
61        """Take in an observation at `step` that lists the units of `reports` and reports `dead` dead, by their reports
62        or tags, and return the units of `reports` in their order: this player's as `OwnUnit`, the others as `Unit`.
63
64        `step` is by default the step after the latest observation's, and 0 for the first. A unit reported under a
65        tag already seen is the same object as before, read anew; one seen before and not reported now is no longer
66        listed. Raises `ValueError` for a step not after the latest observation's, as a game's steps only go on.
67        """
68        if step is None:
69            step = 0 if self._step is None else self._step + 1
70        elif self._step is not None and step <= self._step:
71            raise ValueError(f"an observation at step {step} cannot follow one at step {self._step}")
72        dead_tags = [report.tag if isinstance(report, UnitReport) else report for report in dead]
73        observation = raw_pb2.ObservationRaw(
74            units=[report._as_reported() for report in reports], event=raw_pb2.Event(dead_units=dead_tags)
75        )
76        # Set first: an update that raises partway, as for a type the curated ids leave out, has taken in part of the
77        # observation at this step, so the next one must come after it.
78        self._step = step
79        self._order_book._observe(GameTime(steps=step), ())
80        self._tracker.update(observation, step)
81        unit_tracker = self._tracker.unit_tracker
82        return [unit_tracker.by_tag(report.tag) for report in reports]

The units of a game made up for a test, taken in one observation after another, as NachOS takes them in from a game: the same Unit and OwnUnit objects, kept up to date, with no game client. What they are ordered goes into MadeUpUnits.orders, and is never sent.

This player is player 1, and the enemy player 2. The units read their types from game_data, by default build 75689's, as load_game_data reads it.

MadeUpUnits(game_data: sc2nachos.gamedata.GameData | None = None)
28    def __init__(self, game_data: GameData | None = None) -> None:
29        game_data = load_game_data() if game_data is None else game_data
30        enemy = Enemy(
31            player_id=ENEMY_PLAYER_ID,
32            requested_race=Race.RANDOM,
33            name=None,
34            race=None,
35            ladder_id=None,
36            game_data=game_data,
37        )
38        self._order_book = OrderBook(game_data)
39        self._tracker = _Tracker(game_data, enemy, order_book=self._order_book)
40        self._step: int | None = None
game_data: sc2nachos.gamedata.GameData
42    @property
43    def game_data(self) -> GameData:
44        """The game's data the units read their types from."""
45        return self._tracker.game_data

The game's data the units read their types from.

orders: sc2nachos.orders.OrderBook
47    @property
48    def orders(self) -> OrderBook:
49        """Every order the units were given since they were made up, through `sc2nachos.units.OwnUnit.issue` or this
50        book's `issue`, as `api.orders` holds a turn's. Nothing is sent, so none leaves the book."""
51        return self._order_book

Every order the units were given since they were made up, through sc2nachos.units.OwnUnit.issue or this book's issue, as api.orders holds a turn's. Nothing is sent, so none leaves the book.

units: sc2nachos.Units[sc2nachos.Unit[typing.Any]]
53    @property
54    def units(self) -> Units[Unit[Any]]:
55        """Every unit the latest observation listed."""
56        return self._tracker.unit_tracker.present

Every unit the latest observation listed.

def observe( self, *reports: UnitReport, step: int | None = None, dead: Iterable[UnitReport | int] = ()) -> list[typing.Any]:
58    def observe(
59        self, *reports: UnitReport, step: int | None = None, dead: Iterable[UnitReport | int] = ()
60    ) -> list[Any]:
61        """Take in an observation at `step` that lists the units of `reports` and reports `dead` dead, by their reports
62        or tags, and return the units of `reports` in their order: this player's as `OwnUnit`, the others as `Unit`.
63
64        `step` is by default the step after the latest observation's, and 0 for the first. A unit reported under a
65        tag already seen is the same object as before, read anew; one seen before and not reported now is no longer
66        listed. Raises `ValueError` for a step not after the latest observation's, as a game's steps only go on.
67        """
68        if step is None:
69            step = 0 if self._step is None else self._step + 1
70        elif self._step is not None and step <= self._step:
71            raise ValueError(f"an observation at step {step} cannot follow one at step {self._step}")
72        dead_tags = [report.tag if isinstance(report, UnitReport) else report for report in dead]
73        observation = raw_pb2.ObservationRaw(
74            units=[report._as_reported() for report in reports], event=raw_pb2.Event(dead_units=dead_tags)
75        )
76        # Set first: an update that raises partway, as for a type the curated ids leave out, has taken in part of the
77        # observation at this step, so the next one must come after it.
78        self._step = step
79        self._order_book._observe(GameTime(steps=step), ())
80        self._tracker.update(observation, step)
81        unit_tracker = self._tracker.unit_tracker
82        return [unit_tracker.by_tag(report.tag) for report in reports]

Take in an observation at step that lists the units of reports and reports dead dead, by their reports or tags, and return the units of reports in their order: this player's as OwnUnit, the others as Unit.

step is by default the step after the latest observation's, and 0 for the first. A unit reported under a tag already seen is the same object as before, read anew; one seen before and not reported now is no longer listed. Raises ValueError for a step not after the latest observation's, as a game's steps only go on.

type ReportedOrder = tuple[sc2nachos.AbilityId, ReportedTarget] | tuple[sc2nachos.AbilityId, ReportedTarget, float]

An order as a unit reports it, which the unit reads as a sc2nachos.units.Order: the ability, its target, and its progress from 0 to 1, by default 0.

type ReportedTarget = Union[ForwardRef('Point'), ForwardRef('Point3D'), tuple[float, float], tuple[float, float, float], UnitReport, int, NoneType]

What an order is aimed at: a point on the ground, the unit a report describes, the tag of a unit, or nothing.

@dataclass(frozen=True, slots=True)
class UnitReport:
 30@dataclass(frozen=True, slots=True)
 31class UnitReport:
 32    """A unit as the game reports it in one observation, for `MadeUpUnits` to take in.
 33
 34    By default it is this player's unit, finished, in sight and not cloaked, of half a tile's radius, doing nothing.
 35    Each field
 36    reads back as the property of a `Unit` or `OwnUnit` of the same name, `at` as `position`. A field not given reads
 37    zero, as one the game leaves out does, and a maximum not given reads as its value. `dataclasses.replace` makes the
 38    report of the same unit in a later observation.
 39    """
 40
 41    tag: int
 42    """The game's name for the unit. A report under the same tag in a later observation is of the same unit."""
 43    type_id: UnitTypeId
 44    _: KW_ONLY
 45    at: PointLike = (10.0, 10.0)
 46    """Where the unit stands, on the ground. A point of three coordinates raises `ValueError`: give `height`."""
 47    height: float = 0.0
 48    alliance: Alliance = Alliance.OWN
 49    """Whose unit it is. `ALLY` raises `ValueError`: the game made up has two players."""
 50    visibility: Visibility = Visibility.VISIBLE
 51    build_progress: float = 1.0
 52    health: float = 0.0
 53    health_max: float | None = None
 54    """The most health the unit can have, by default `health`."""
 55    shield: float = 0.0
 56    shield_max: float | None = None
 57    """The most shield the unit can have, by default `shield`."""
 58    energy: float = 0.0
 59    energy_max: float | None = None
 60    """The most energy the unit can have, by default `energy`."""
 61    radius: float = 0.5
 62    facing: float = 0.0
 63    cloak_state: CloakState = CloakState.NOT_CLOAKED
 64    buffs: Collection[BuffId] = ()
 65    orders: Sequence[ReportedOrder] = ()
 66    """What the unit is doing, the current order first."""
 67    is_selected: bool = False
 68    is_flying: bool = False
 69    is_burrowed: bool = False
 70    is_hallucination: bool = False
 71    is_powered: bool = False
 72    is_active: bool = False
 73    detect_range: float = 0.0
 74    radar_range: float = 0.0
 75    attack_upgrade_level: int = 0
 76    armor_upgrade_level: int = 0
 77    shield_upgrade_level: int = 0
 78    mineral_contents: int = 0
 79    vespene_contents: int = 0
 80    assigned_harvesters: int = 0
 81    ideal_harvesters: int = 0
 82    cargo_used: int = 0
 83    cargo_max: int = 0
 84    weapon_cooldown: GameTime | None = None
 85    buff_duration_max: GameTime | None = None
 86    buff_duration_remaining: GameTime | None = None
 87    add_on: UnitReport | int | None = None
 88    """The unit's add-on: its report, or its tag."""
 89    engaged_target: UnitReport | int | None = None
 90    """The unit the unit is attacking: its report, or its tag."""
 91
 92    def __post_init__(self) -> None:
 93        """Raise `ValueError` for a point of three coordinates, and for an ally's unit."""
 94        if len(self.at) != 2:
 95            raise ValueError(f"a unit stands at two coordinates, not {tuple(self.at)}; give its height as height")
 96        if self.alliance not in _PLAYER_IDS_BY_ALLIANCE:
 97            raise ValueError(f"a made-up game has no {self.alliance.name} units, only own, enemy and neutral ones")
 98
 99    def _as_reported(self) -> raw_pb2.Unit:
100        """The report as the game sends it."""
101        return raw_pb2.Unit(
102            tag=self.tag,
103            unit_type=self.type_id,
104            alliance=self.alliance.value,
105            owner=_PLAYER_IDS_BY_ALLIANCE[self.alliance],
106            display_type=self.visibility.value,
107            pos=common_pb2.Point(x=self.at[0], y=self.at[1], z=self.height),
108            build_progress=self.build_progress,
109            health=self.health,
110            health_max=self.health if self.health_max is None else self.health_max,
111            shield=self.shield,
112            shield_max=self.shield if self.shield_max is None else self.shield_max,
113            energy=self.energy,
114            energy_max=self.energy if self.energy_max is None else self.energy_max,
115            radius=self.radius,
116            facing=self.facing,
117            cloak=self.cloak_state.value,
118            buff_ids=sorted(self.buffs),
119            orders=[_order_as_reported(order) for order in self.orders],
120            is_selected=self.is_selected,
121            is_flying=self.is_flying,
122            is_burrowed=self.is_burrowed,
123            is_hallucination=self.is_hallucination,
124            is_powered=self.is_powered,
125            is_active=self.is_active,
126            detect_range=self.detect_range,
127            radar_range=self.radar_range,
128            attack_upgrade_level=self.attack_upgrade_level,
129            armor_upgrade_level=self.armor_upgrade_level,
130            shield_upgrade_level=self.shield_upgrade_level,
131            mineral_contents=self.mineral_contents,
132            vespene_contents=self.vespene_contents,
133            assigned_harvesters=self.assigned_harvesters,
134            ideal_harvesters=self.ideal_harvesters,
135            cargo_space_taken=self.cargo_used,
136            cargo_space_max=self.cargo_max,
137            weapon_cooldown=0.0 if self.weapon_cooldown is None else self.weapon_cooldown.steps,
138            buff_duration_max=0 if self.buff_duration_max is None else self.buff_duration_max.nearest_step,
139            buff_duration_remain=0
140            if self.buff_duration_remaining is None
141            else self.buff_duration_remaining.nearest_step,
142            add_on_tag=_tag_of(self.add_on),
143            engaged_target_tag=_tag_of(self.engaged_target),
144        )

A unit as the game reports it in one observation, for MadeUpUnits to take in.

By default it is this player's unit, finished, in sight and not cloaked, of half a tile's radius, doing nothing. Each field reads back as the property of a Unit or OwnUnit of the same name, at as position. A field not given reads zero, as one the game leaves out does, and a maximum not given reads as its value. dataclasses.replace makes the report of the same unit in a later observation.

UnitReport( tag: int, type_id: sc2nachos.UnitTypeId, *, at: 'PointLike' = (10.0, 10.0), height: float = 0.0, alliance: sc2nachos.units.Alliance = <Alliance.OWN: 1>, visibility: sc2nachos.units.Visibility = <Visibility.VISIBLE: 1>, build_progress: float = 1.0, health: float = 0.0, health_max: float | None = None, shield: float = 0.0, shield_max: float | None = None, energy: float = 0.0, energy_max: float | None = None, radius: float = 0.5, facing: float = 0.0, cloak_state: sc2nachos.units.CloakState = <CloakState.NOT_CLOAKED: 3>, buffs: Collection[sc2nachos.BuffId] = (), orders: Sequence[ReportedOrder] = (), is_selected: bool = False, is_flying: bool = False, is_burrowed: bool = False, is_hallucination: bool = False, is_powered: bool = False, is_active: bool = False, detect_range: float = 0.0, radar_range: float = 0.0, attack_upgrade_level: int = 0, armor_upgrade_level: int = 0, shield_upgrade_level: int = 0, mineral_contents: int = 0, vespene_contents: int = 0, assigned_harvesters: int = 0, ideal_harvesters: int = 0, cargo_used: int = 0, cargo_max: int = 0, weapon_cooldown: sc2nachos.GameTime | None = None, buff_duration_max: sc2nachos.GameTime | None = None, buff_duration_remaining: sc2nachos.GameTime | None = None, add_on: UnitReport | int | None = None, engaged_target: UnitReport | int | None = None)
tag: int

The game's name for the unit. A report under the same tag in a later observation is of the same unit.

at: 'PointLike'

Where the unit stands, on the ground. A point of three coordinates raises ValueError: give height.

height: float

Whose unit it is. ALLY raises ValueError: the game made up has two players.

build_progress: float
health: float
health_max: float | None

The most health the unit can have, by default health.

shield: float
shield_max: float | None

The most shield the unit can have, by default shield.

energy: float
energy_max: float | None

The most energy the unit can have, by default energy.

radius: float
facing: float
buffs: Collection[sc2nachos.BuffId]
orders: Sequence[ReportedOrder]

What the unit is doing, the current order first.

is_selected: bool
is_flying: bool
is_burrowed: bool
is_hallucination: bool
is_powered: bool
is_active: bool
detect_range: float
radar_range: float
attack_upgrade_level: int
armor_upgrade_level: int
shield_upgrade_level: int
mineral_contents: int
vespene_contents: int
assigned_harvesters: int
ideal_harvesters: int
cargo_used: int
cargo_max: int
weapon_cooldown: sc2nachos.GameTime | None
buff_duration_max: sc2nachos.GameTime | None
buff_duration_remaining: sc2nachos.GameTime | None
add_on: UnitReport | int | None

The unit's add-on: its report, or its tag.

engaged_target: UnitReport | int | None

The unit the unit is attacking: its report, or its tag.

def load_game_data(*, base_build: int = 75689) -> sc2nachos.gamedata.GameData:
17def load_game_data(*, base_build: int = 75689) -> GameData:
18    """The game's data, its tables, as StarCraft II of `base_build` answers them at the start of a game, read afresh in
19    about 15 ms: by default build 75689's, StarCraft II 4.10 for Linux, the build NachOS is tested against. Raises
20    `ValueError` for a build NachOS ships no data of."""
21    shipped_file = resources.files("sc2nachos.testing").joinpath(f"game_data_{base_build}.binpb.xz")
22    if not shipped_file.is_file():
23        shipped_builds = ", ".join(str(build) for build in _shipped_base_builds())
24        raise ValueError(f"NachOS ships no game data of build {base_build}, only of {shipped_builds}")
25    return GameData(sc2api_pb2.ResponseData.FromString(lzma.decompress(shipped_file.read_bytes())))

The game's data, its tables, as StarCraft II of base_build answers them at the start of a game, read afresh in about 15 ms: by default build 75689's, StarCraft II 4.10 for Linux, the build NachOS is tested against. Raises ValueError for a build NachOS ships no data of.