sc2nachos.gamemap
The map a game is played on.
1"""The map a game is played on.""" 2 3from sc2nachos.gamemap._errors import NoExpansionError, NoMainRampError 4from sc2nachos.gamemap._expansion import Expansion, StartLocation 5from sc2nachos.gamemap._game_map import GameMap 6from sc2nachos.gamemap._ramp import Ramp 7 8__all__ = [ 9 "Expansion", 10 "GameMap", 11 "NoExpansionError", 12 "NoMainRampError", 13 "Ramp", 14 "StartLocation", 15]
49@dataclass(frozen=True, slots=True, kw_only=True) 50class Expansion: 51 """A place to build a townhall, with the mineral fields and geysers it mines. 52 53 Each group of resources lying within 6 of one another, through any chain of them, is an expansion if it has 6 to 54 10 mineral fields; fewer fields are a blocker to mine out, more a wall. Where a group's fields can be mined from 55 either side, with a geyser on each, each side is an expansion of its own, and the two share the fields. Where a 56 player starts the game, it is a `StartLocation`. 57 """ 58 59 center: Point 60 """Where the townhall's center goes: of the tile centers the game takes a townhall on, the one with the least summed 61 distance to the resources.""" 62 mineral_fields: Units[Unit[UnitType.AnyMineralField]] 63 """Its mineral fields, nearest `center` first. The same units all game, though the game changes their tags as 64 they pass in and out of sight.""" 65 geysers: Units[Unit[UnitType.AnyVespeneGeyser]] 66 """Its geysers, nearest `center` first, the same units all game.""" 67 pathing_distance_from_start: float 68 """The pathing distance from this player's start to `center`, over the ground as the game began with every mineral 69 field and geyser on it: `inf` where no path reaches.""" 70 _game_map: GameMap = field(repr=False, compare=False) 71 _unit_tracker: _UnitTracker = field(repr=False, compare=False) 72 73 @property 74 def townhall(self) -> Unit[UnitType.Townhall] | None: 75 """The townhall standing on it now, this player's or another's, in sight or remembered in the fog: the one whose 76 footprint's bounding box holds `center`. `None` if there is none; a townhall in the air stands nowhere.""" 77 for townhall in self._unit_tracker.present_townhalls: 78 footprint = townhall.footprint 79 if footprint is not None and self.center in footprint.bounding_box(at=townhall.position): 80 return townhall 81 return None 82 83 def plateau(self, *, max_distance: float = math.inf, height_tolerance: float = _HALF_A_LEVEL) -> TileSet: 84 """The ground at the expansion's level: every tile less than `height_tolerance` from the height at `center`, 85 half a level by default, walkable as the game began, and joined side by side to `center` within `max_distance` 86 of it in a straight line, without crossing a ramp. The ground under its townhall, mineral fields and geysers 87 counts, though the game's pathing grid blocks this player's own at its start (in game). Empty where `center` 88 stands on no such ground. Worked out at each call.""" 89 game_map = self._game_map 90 walkable = game_map.pathing.copy() 91 # Every townhall's footprint is the command center's. 92 walkable.fill_footprint(FOOTPRINTS[UnitTypeId.COMMAND_CENTER], at=self.center, value=True) 93 for resource in (*self.mineral_fields, *self.geysers): 94 if (footprint := resource.footprint) is not None: 95 walkable.fill_footprint(footprint, at=resource.position, value=True) 96 for ramp in game_map.ramps: 97 walkable[ramp.tiles] = False 98 ground = walkable.values & (numpy.abs(game_map.height.values - game_map.height[self.center]) < height_tolerance) 99 if max_distance < math.inf: 100 ground &= walkable.distance_from(self.center).values <= max_distance 101 # `label` is unannotated, and pyright reads the return type off an early-return branch of its body. 102 patches, _ = cast("tuple[ndarray, int]", scipy.ndimage.label(ground)) 103 patch_at_center = patches[walkable.index_of(self.center)] 104 if not patch_at_center: 105 return TileSet(()) 106 return TileSet._from_mask(walkable.origin, patches == patch_at_center) 107 108 @property 109 def _is_full_base(self) -> bool: 110 """Whether it has the fields and geysers of a full base.""" 111 return ( 112 len(self.mineral_fields) >= _MIN_MINERAL_FIELDS_OF_A_FULL_BASE 113 and len(self.geysers) == _GEYSERS_OF_A_FULL_BASE 114 ) 115 116 @staticmethod 117 def _find_all(game_map: GameMap, unit_tracker: _UnitTracker) -> tuple[Expansion, ...]: 118 """The expansions of `game_map` with the neutral units `unit_tracker` holds on it at the start, by pathing 119 distance from this player's start, nearest first, each start location a `StartLocation`. Those no path reaches 120 come last, sorted by increasing straight-line distance from this player's start. Each finds its townhall among 121 the units `unit_tracker` holds then. 122 123 The mineral fields and geysers make the expansions; every other neutral unit blocks the ground under it. Every 124 walk is over the ground as the game began with every mineral field and geyser on it. 125 """ 126 neutral_units = unit_tracker.present.neutral 127 mineral_fields = neutral_units.of_type(UnitType.AnyMineralField) 128 geysers = neutral_units.of_type(UnitType.AnyVespeneGeyser) 129 blockers = neutral_units.excluding_type(UnitType.AnyMineralField, UnitType.AnyVespeneGeyser) 130 expansion_locations = _ExpansionLocations( 131 game_map.placement, mineral_fields=mineral_fields, geysers=geysers, blockers=blockers 132 ) 133 ground = _ground_as_the_game_began(game_map, (*mineral_fields, *geysers)) 134 start = game_map.start_location 135 from_start = _walking_distances(ground, start) 136 start_locations = set(game_map.all_start_locations) 137 expansions = [ 138 Expansion( 139 center=center, 140 mineral_fields=base_fields.sorted_by_distance_to(center), 141 geysers=center_geysers.sorted_by_distance_to(center), 142 pathing_distance_from_start=from_start[center], 143 _game_map=game_map, 144 _unit_tracker=unit_tracker, 145 ) 146 for base_fields, base_geysers in _resources_of_each_base(mineral_fields, geysers) 147 for center, center_geysers in _townhall_centers_of_base(expansion_locations, base_fields, base_geysers) 148 ] 149 candidates = [expansion for expansion in expansions if expansion.center not in start_locations] 150 found = [ 151 expansion 152 if expansion.center not in start_locations 153 else StartLocation._from_expansion( 154 expansion, 155 ground=ground, 156 candidates=candidates, 157 from_center=from_start if expansion.center == start else _walking_distances(ground, expansion.center), 158 ) 159 for expansion in expansions 160 ] 161 return tuple(sorted(found, key=lambda exp: (exp.pathing_distance_from_start, start.distance_to(exp.center))))
A place to build a townhall, with the mineral fields and geysers it mines.
Each group of resources lying within 6 of one another, through any chain of them, is an expansion if it has 6 to
10 mineral fields; fewer fields are a blocker to mine out, more a wall. Where a group's fields can be mined from
either side, with a geyser on each, each side is an expansion of its own, and the two share the fields. Where a
player starts the game, it is a StartLocation.
Where the townhall's center goes: of the tile centers the game takes a townhall on, the one with the least summed distance to the resources.
Its mineral fields, nearest center first. The same units all game, though the game changes their tags as
they pass in and out of sight.
Its geysers, nearest center first, the same units all game.
The pathing distance from this player's start to center, over the ground as the game began with every mineral
field and geyser on it: inf where no path reaches.
73 @property 74 def townhall(self) -> Unit[UnitType.Townhall] | None: 75 """The townhall standing on it now, this player's or another's, in sight or remembered in the fog: the one whose 76 footprint's bounding box holds `center`. `None` if there is none; a townhall in the air stands nowhere.""" 77 for townhall in self._unit_tracker.present_townhalls: 78 footprint = townhall.footprint 79 if footprint is not None and self.center in footprint.bounding_box(at=townhall.position): 80 return townhall 81 return None
The townhall standing on it now, this player's or another's, in sight or remembered in the fog: the one whose
footprint's bounding box holds center. None if there is none; a townhall in the air stands nowhere.
83 def plateau(self, *, max_distance: float = math.inf, height_tolerance: float = _HALF_A_LEVEL) -> TileSet: 84 """The ground at the expansion's level: every tile less than `height_tolerance` from the height at `center`, 85 half a level by default, walkable as the game began, and joined side by side to `center` within `max_distance` 86 of it in a straight line, without crossing a ramp. The ground under its townhall, mineral fields and geysers 87 counts, though the game's pathing grid blocks this player's own at its start (in game). Empty where `center` 88 stands on no such ground. Worked out at each call.""" 89 game_map = self._game_map 90 walkable = game_map.pathing.copy() 91 # Every townhall's footprint is the command center's. 92 walkable.fill_footprint(FOOTPRINTS[UnitTypeId.COMMAND_CENTER], at=self.center, value=True) 93 for resource in (*self.mineral_fields, *self.geysers): 94 if (footprint := resource.footprint) is not None: 95 walkable.fill_footprint(footprint, at=resource.position, value=True) 96 for ramp in game_map.ramps: 97 walkable[ramp.tiles] = False 98 ground = walkable.values & (numpy.abs(game_map.height.values - game_map.height[self.center]) < height_tolerance) 99 if max_distance < math.inf: 100 ground &= walkable.distance_from(self.center).values <= max_distance 101 # `label` is unannotated, and pyright reads the return type off an early-return branch of its body. 102 patches, _ = cast("tuple[ndarray, int]", scipy.ndimage.label(ground)) 103 patch_at_center = patches[walkable.index_of(self.center)] 104 if not patch_at_center: 105 return TileSet(()) 106 return TileSet._from_mask(walkable.origin, patches == patch_at_center)
The ground at the expansion's level: every tile less than height_tolerance from the height at center,
half a level by default, walkable as the game began, and joined side by side to center within max_distance
of it in a straight line, without crossing a ramp. The ground under its townhall, mineral fields and geysers
counts, though the game's pathing grid blocks this player's own at its start (in game). Empty where center
stands on no such ground. Worked out at each call.
30@final 31class GameMap: 32 """The map, as the game describes it at the start. None of it changes. 33 34 The grids cover the playable area only, so a grid's `values` are indexed from the playable area's lower left 35 corner. Beyond it, pathing and placement read `False` and height raises. The grids are shared by everything that 36 reads the map, so they refuse writes: `copy()` one to change it. 37 """ 38 39 __slots__ = ( 40 "_all_start_locations", 41 "_corners", 42 "_height", 43 "_main_ramps_by_start_tile", 44 "_name", 45 "_pathing", 46 "_placement", 47 "_playable", 48 "_ramps", 49 ) 50 51 def __init__(self, info: sc2api_pb2.ResponseGameInfo, *, start_location: Point) -> None: 52 """Read the map from the game's answer to `RequestGameInfo`, with this player's start at `start_location`.""" 53 start = info.start_raw 54 playable = Rectangle._from_proto(start.playable_area) 55 origin = Tile(start.playable_area.p0.x, start.playable_area.p0.y) 56 self._name = info.map_name 57 self._playable = playable 58 placement = image_tiles(start.placement_grid, playable) != 0 59 self._pathing = _create_pathing_grid(start) 60 self._placement = Grid(placement, origin=origin, outside=False, readonly=True) 61 self._corners = _tile_corners(_corner_heights(start.terrain_height, playable)) 62 self._height = Grid(self._corners.mean(axis=-1), origin=origin, readonly=True) 63 opponent_start_locations = (Point._from_proto(location) for location in start.start_locations) 64 self._all_start_locations = (start_location, *opponent_start_locations) 65 self._ramps = find_ramps(self._pathing, self._placement, self._height) 66 self._main_ramps_by_start_tile = { 67 Tile.at(start): self._find_main_ramp(start) for start in self._all_start_locations 68 } 69 70 @classmethod 71 def _from_game(cls, info: sc2api_pb2.ResponseGameInfo, observation: sc2api_pb2.ResponseObservation) -> Self: 72 """The map of a game whose first observation is `observation`: this player starts where its townhall stands 73 in it, or in the middle of the playable area on a map that gives it none.""" 74 townhalls = ( 75 unit 76 for unit in observation.observation.raw_data.units 77 if unit.alliance == raw_pb2.Alliance.Self and unit.unit_type in UnitType.Townhall.type_ids 78 ) 79 townhall = next(townhalls, None) 80 if townhall is None: 81 start = Rectangle._from_proto(info.start_raw.playable_area).center 82 else: 83 start = Point((townhall.pos.x, townhall.pos.y)) 84 return cls(info, start_location=start) 85 86 @property 87 def name(self) -> str: 88 """The map's display name, such as `Pylon AIE`.""" 89 return self._name 90 91 @property 92 def playable_area(self) -> Rectangle: 93 """The part of the map a unit can be in.""" 94 return self._playable 95 96 @property 97 def pathing(self) -> Grid[bool]: 98 """Where a ground unit can walk at the start of the game. 99 100 Rocks block it, as do this player's own starting townhall, mineral fields and geysers, but no other resources. 101 """ 102 return self._pathing 103 104 @property 105 def placement(self) -> Grid[bool]: 106 """Where the game's placement grid lets a structure stand at the start of the game. 107 108 The game's grid reads the ground beneath every unit, so it blocks no resource, townhall, rock or tower, though 109 no structure can stand on one. 110 """ 111 return self._placement 112 113 @property 114 def height(self) -> Grid[float]: 115 """The ground height at each tile's center, in the units of a unit's `z`. 116 117 A unit at a tile's center stands within 0.05 of it nine times in ten; `height_at` is closer for any other 118 point. Some maps raise their ramps above the heights the game sends, by as much as 0.76. 119 """ 120 return self._height 121 122 def height_at(self, point: PointLike) -> float: 123 """The ground height at `point`, interpolated between the corners of its tile. 124 125 A unit standing at `point` is within 0.03 of it nine times in ten, but as far off as `height` is on a map that 126 raises its ramps. Raises `IndexError` outside the playable area. 127 """ 128 x, y = point[0], point[1] 129 column, row = math.floor(x), math.floor(y) 130 origin = self._height.origin 131 i, j = column - origin.x, row - origin.y 132 if not (0 <= i < self._corners.shape[0] and 0 <= j < self._corners.shape[1]): 133 raise IndexError(f"{Tile(column, row)!r} lies outside {self._playable!r}") 134 low_left, low_right, up_left, up_right = self._corners[i, j].tolist() 135 dx, dy = x - column, y - row 136 return ( 137 low_left 138 + (low_right - low_left) * dx 139 + (up_left - low_left) * dy 140 + (low_left - low_right - up_left + up_right) * dx * dy 141 ) 142 143 @property 144 def ramps(self) -> tuple[Ramp, ...]: 145 """Every ramp on the map, ordered by lower left tile.""" 146 return self._ramps 147 148 def _main_ramp_of(self, start: PointLike) -> Ramp | None: 149 """The ramp out of the main at the start location `start`, as `StartLocation.main_ramp` finds it, or `None` 150 where none can be walked to. Raises `ValueError` for a point on no start location's tile.""" 151 start_tile = Tile.at(start) 152 if start_tile not in self._main_ramps_by_start_tile: 153 raise ValueError(f"{start} is on no start location's tile: {self._all_start_locations}") 154 return self._main_ramps_by_start_tile[start_tile] 155 156 def _find_main_ramp(self, start: Point) -> Ramp | None: 157 """The ramp out of the main at the start location `start`, as `StartLocation.main_ramp` finds it; `None` where 158 none can be walked to, and for a start beyond the playable area, which only a map drawn for a test has.""" 159 if start not in self._playable: 160 return None 161 walkable_ground = self._pathing.copy() 162 # Every townhall's footprint is the command center's. 163 walkable_ground.fill_footprint(FOOTPRINTS[UnitTypeId.COMMAND_CENTER], at=start, value=True) 164 walking_distances = walkable_ground.cheapest_paths_from(start).distances 165 start_level = self._height[start] 166 at_its_level = [ramp for ramp in self._ramps if abs(self._height[min(ramp.top)] - start_level) < _HALF_A_LEVEL] 167 nearest_ramp = min(at_its_level, key=lambda ramp: walking_distances[ramp.tiles.center], default=None) 168 if nearest_ramp is None or walking_distances[nearest_ramp.tiles.center] == math.inf: 169 return None 170 return nearest_ramp 171 172 @property 173 def start_location(self) -> Point: 174 """Where this player's first townhall stood when the game began, a tile's center. It stays the same all game.""" 175 return self._all_start_locations[0] 176 177 @property 178 def all_start_locations(self) -> tuple[Point, ...]: 179 """Every start location on the map: this player's first, then the opponents' in the order the game names 180 them.""" 181 return self._all_start_locations 182 183 @property 184 def opponent_start_locations(self) -> tuple[Point, ...]: 185 """Every start location on the map but this player's own.""" 186 return self._all_start_locations[1:]
The map, as the game describes it at the start. None of it changes.
The grids cover the playable area only, so a grid's values are indexed from the playable area's lower left
corner. Beyond it, pathing and placement read False and height raises. The grids are shared by everything that
reads the map, so they refuse writes: copy() one to change it.
51 def __init__(self, info: sc2api_pb2.ResponseGameInfo, *, start_location: Point) -> None: 52 """Read the map from the game's answer to `RequestGameInfo`, with this player's start at `start_location`.""" 53 start = info.start_raw 54 playable = Rectangle._from_proto(start.playable_area) 55 origin = Tile(start.playable_area.p0.x, start.playable_area.p0.y) 56 self._name = info.map_name 57 self._playable = playable 58 placement = image_tiles(start.placement_grid, playable) != 0 59 self._pathing = _create_pathing_grid(start) 60 self._placement = Grid(placement, origin=origin, outside=False, readonly=True) 61 self._corners = _tile_corners(_corner_heights(start.terrain_height, playable)) 62 self._height = Grid(self._corners.mean(axis=-1), origin=origin, readonly=True) 63 opponent_start_locations = (Point._from_proto(location) for location in start.start_locations) 64 self._all_start_locations = (start_location, *opponent_start_locations) 65 self._ramps = find_ramps(self._pathing, self._placement, self._height) 66 self._main_ramps_by_start_tile = { 67 Tile.at(start): self._find_main_ramp(start) for start in self._all_start_locations 68 }
Read the map from the game's answer to RequestGameInfo, with this player's start at start_location.
86 @property 87 def name(self) -> str: 88 """The map's display name, such as `Pylon AIE`.""" 89 return self._name
The map's display name, such as Pylon AIE.
91 @property 92 def playable_area(self) -> Rectangle: 93 """The part of the map a unit can be in.""" 94 return self._playable
The part of the map a unit can be in.
96 @property 97 def pathing(self) -> Grid[bool]: 98 """Where a ground unit can walk at the start of the game. 99 100 Rocks block it, as do this player's own starting townhall, mineral fields and geysers, but no other resources. 101 """ 102 return self._pathing
Where a ground unit can walk at the start of the game.
Rocks block it, as do this player's own starting townhall, mineral fields and geysers, but no other resources.
104 @property 105 def placement(self) -> Grid[bool]: 106 """Where the game's placement grid lets a structure stand at the start of the game. 107 108 The game's grid reads the ground beneath every unit, so it blocks no resource, townhall, rock or tower, though 109 no structure can stand on one. 110 """ 111 return self._placement
Where the game's placement grid lets a structure stand at the start of the game.
The game's grid reads the ground beneath every unit, so it blocks no resource, townhall, rock or tower, though no structure can stand on one.
113 @property 114 def height(self) -> Grid[float]: 115 """The ground height at each tile's center, in the units of a unit's `z`. 116 117 A unit at a tile's center stands within 0.05 of it nine times in ten; `height_at` is closer for any other 118 point. Some maps raise their ramps above the heights the game sends, by as much as 0.76. 119 """ 120 return self._height
The ground height at each tile's center, in the units of a unit's z.
A unit at a tile's center stands within 0.05 of it nine times in ten; height_at is closer for any other
point. Some maps raise their ramps above the heights the game sends, by as much as 0.76.
122 def height_at(self, point: PointLike) -> float: 123 """The ground height at `point`, interpolated between the corners of its tile. 124 125 A unit standing at `point` is within 0.03 of it nine times in ten, but as far off as `height` is on a map that 126 raises its ramps. Raises `IndexError` outside the playable area. 127 """ 128 x, y = point[0], point[1] 129 column, row = math.floor(x), math.floor(y) 130 origin = self._height.origin 131 i, j = column - origin.x, row - origin.y 132 if not (0 <= i < self._corners.shape[0] and 0 <= j < self._corners.shape[1]): 133 raise IndexError(f"{Tile(column, row)!r} lies outside {self._playable!r}") 134 low_left, low_right, up_left, up_right = self._corners[i, j].tolist() 135 dx, dy = x - column, y - row 136 return ( 137 low_left 138 + (low_right - low_left) * dx 139 + (up_left - low_left) * dy 140 + (low_left - low_right - up_left + up_right) * dx * dy 141 )
The ground height at point, interpolated between the corners of its tile.
A unit standing at point is within 0.03 of it nine times in ten, but as far off as height is on a map that
raises its ramps. Raises IndexError outside the playable area.
143 @property 144 def ramps(self) -> tuple[Ramp, ...]: 145 """Every ramp on the map, ordered by lower left tile.""" 146 return self._ramps
Every ramp on the map, ordered by lower left tile.
172 @property 173 def start_location(self) -> Point: 174 """Where this player's first townhall stood when the game began, a tile's center. It stays the same all game.""" 175 return self._all_start_locations[0]
Where this player's first townhall stood when the game began, a tile's center. It stays the same all game.
177 @property 178 def all_start_locations(self) -> tuple[Point, ...]: 179 """Every start location on the map: this player's first, then the opponents' in the order the game names 180 them.""" 181 return self._all_start_locations
Every start location on the map: this player's first, then the opponents' in the order the game names them.
183 @property 184 def opponent_start_locations(self) -> tuple[Point, ...]: 185 """Every start location on the map but this player's own.""" 186 return self._all_start_locations[1:]
Every start location on the map but this player's own.
11class NoExpansionError(NachOSError, LookupError): 12 """No expansion of the kind asked for, the natural or a third, can be walked to from the start location."""
No expansion of the kind asked for, the natural or a third, can be walked to from the start location.
7class NoMainRampError(NachOSError, LookupError): 8 """No ramp out of the start location's main can be walked to."""
No ramp out of the start location's main can be walked to.
32@final 33@dataclass(frozen=True, slots=True) 34class Ramp: 35 """A slope a ground unit walks up to the level above. 36 37 `top` and `bottom` are the rows it is entered by, unless something stands in one: the tiles within a byte of its 38 highest and its lowest height. Its middle is `tiles.center`. 39 """ 40 41 tiles: TileSet 42 top: TileSet 43 bottom: TileSet 44 45 @property 46 def orientation(self) -> Direction: 47 """The way the ramp climbs: of the eight directions, the one nearest the line from its bottom's center to its 48 top's. Every main ramp of the pool climbs along a diagonal (corpus).""" 49 return Direction.closest(self.top.center - self.bottom.center) 50 51 @property 52 def width(self) -> int: 53 """How many tiles wide the ramp is at its top, across the way it climbs: from one end of the top to the other, 54 any gap between them included. Every main ramp of the pool is 2 wide (corpus).""" 55 step_x, step_y = self.orientation.value 56 # Across the climb, a tile's place is its coordinates turned a quarter: the next tile across along a diagonal 57 # is 2 further, along an axis 1. 58 places_across = [step_x * tile.y - step_y * tile.x for tile in self.top] 59 return (max(places_across) - min(places_across)) // (abs(step_x) + abs(step_y)) + 1 60 61 def _point_at_offset_from_the_top(self, offset: tuple[float, float]) -> Point: 62 """The point `offset` from the middle of the top, `offset` as for a ramp climbing north-east, mirrored to this 63 one's diagonal. Raises `ValueError` for a ramp climbing along an axis, which has no diagonal to mirror to.""" 64 if not self.orientation.is_diagonal: 65 raise ValueError(f"a ramp climbing {self.orientation.name} has no diagonal to mirror an offset to") 66 step_x, step_y = self.orientation.value 67 top_middle = self.top.center 68 return Point((top_middle.x + step_x * offset[0], top_middle.y + step_y * offset[1]))
A slope a ground unit walks up to the level above.
top and bottom are the rows it is entered by, unless something stands in one: the tiles within a byte of its
highest and its lowest height. Its middle is tiles.center.
45 @property 46 def orientation(self) -> Direction: 47 """The way the ramp climbs: of the eight directions, the one nearest the line from its bottom's center to its 48 top's. Every main ramp of the pool climbs along a diagonal (corpus).""" 49 return Direction.closest(self.top.center - self.bottom.center)
The way the ramp climbs: of the eight directions, the one nearest the line from its bottom's center to its top's. Every main ramp of the pool climbs along a diagonal (corpus).
51 @property 52 def width(self) -> int: 53 """How many tiles wide the ramp is at its top, across the way it climbs: from one end of the top to the other, 54 any gap between them included. Every main ramp of the pool is 2 wide (corpus).""" 55 step_x, step_y = self.orientation.value 56 # Across the climb, a tile's place is its coordinates turned a quarter: the next tile across along a diagonal 57 # is 2 further, along an axis 1. 58 places_across = [step_x * tile.y - step_y * tile.x for tile in self.top] 59 return (max(places_across) - min(places_across)) // (abs(step_x) + abs(step_y)) + 1
How many tiles wide the ramp is at its top, across the way it climbs: from one end of the top to the other, any gap between them included. Every main ramp of the pool is 2 wide (corpus).
164@final 165@dataclass(frozen=True, slots=True, kw_only=True) 166class StartLocation(Expansion): 167 """An expansion a player starts the game at, with the ground of its main, the ramp out of it, its natural and its 168 two thirds. 169 170 It is found once, as the game begins, and none of it changes. Its natural and thirds are walked to over the ground 171 as the game began with every mineral field and geyser on it, which the game's pathing grid leaves out but for this 172 player's own (in game), and never where a player starts. 173 """ 174 175 main_area: TileSet 176 """The ground of the main, its `plateau()`: every tile within half a level of the height at `center`, walkable as 177 the game began, joined side by side to `center` without crossing a ramp.""" 178 _main_ramp: Ramp | None = field(repr=False, compare=False) 179 _natural: Expansion | None = field(repr=False, compare=False) 180 _line_third: Expansion | None = field(repr=False, compare=False) 181 _triangle_third: Expansion | None = field(repr=False, compare=False) 182 183 @property 184 def main_ramp(self) -> Ramp: 185 """The ramp out of the main: of the ramps whose top is at the main's level, within half a level of the height 186 at `center`'s tile, the one whose center is the shortest walk from `center`, and of two as short, the first in 187 tile order. The walk is over the game's pathing grid as the game began, with the ground the start's townhall 188 covers opened. Raises `NoMainRampError` where no such ramp can be walked to.""" 189 if self._main_ramp is None: 190 raise NoMainRampError(f"no ramp out of the main at {self.center} can be walked to") 191 return self._main_ramp 192 193 @property 194 def natural(self) -> Expansion: 195 """The expansion nearest `center` by pathing distance where no player starts, and of two as near, the nearer in 196 a straight line. Raises `NoExpansionError` where no such expansion can be walked to, as on a map drawn for a 197 test.""" 198 if self._natural is None: 199 raise NoExpansionError(f"no expansion where no player starts can be walked to from {self.center}") 200 return self._natural 201 202 @property 203 def line_third(self) -> Expansion: 204 """The third along the way from the main through the natural: of the two full bases nearest the natural by 205 pathing distance where no player starts, the one whose straight-line distance to `center` is the larger against 206 its straight-line distance to the playable area's nearest edge. A full base has 8 mineral fields or more and 2 207 geysers. Raises `NoExpansionError` where fewer than two such bases can be walked to from the natural.""" 208 if self._line_third is None: 209 raise NoExpansionError(f"fewer than two full bases can be walked to from the natural of {self.center}") 210 return self._line_third 211 212 @property 213 def triangle_third(self) -> Expansion: 214 """The third beside the main and the natural: of the two `line_third` is chosen from, the other. Raises 215 `NoExpansionError` as `line_third` does.""" 216 if self._triangle_third is None: 217 raise NoExpansionError(f"fewer than two full bases can be walked to from the natural of {self.center}") 218 return self._triangle_third 219 220 @classmethod 221 def _from_expansion( 222 cls, expansion: Expansion, *, ground: Grid[bool], candidates: Sequence[Expansion], from_center: Grid[float] 223 ) -> Self: 224 """The start location `expansion` is, walked from over `ground`: its natural and thirds the nearest of 225 `candidates`, the expansions where no player starts, by the pathing distances `from_center` holds.""" 226 center = expansion.center 227 line_third = triangle_third = None 228 natural = next(iter(_nearest_by_walking(candidates, center, from_center)), None) 229 if natural is not None: 230 from_natural = _walking_distances(ground, natural.center) 231 full_bases = [candidate for candidate in candidates if candidate is not natural and candidate._is_full_base] 232 thirds = _nearest_by_walking(full_bases, natural.center, from_natural)[:2] 233 if len(thirds) == 2: 234 playable_area = expansion._game_map.playable_area 235 line_third, triangle_third = sorted( 236 thirds, key=lambda third: -_how_far_out_along_the_edge(third.center, center, playable_area) 237 ) 238 return cls( 239 center=center, 240 mineral_fields=expansion.mineral_fields, 241 geysers=expansion.geysers, 242 pathing_distance_from_start=expansion.pathing_distance_from_start, 243 main_area=expansion.plateau(), 244 _main_ramp=expansion._game_map._main_ramp_of(center), 245 _natural=natural, 246 _line_third=line_third, 247 _triangle_third=triangle_third, 248 _game_map=expansion._game_map, 249 _unit_tracker=expansion._unit_tracker, 250 ) 251 252 @classmethod 253 def _find_at(cls, expansions: Iterable[Expansion], point: Point) -> Self | None: 254 """The start location of `expansions` whose townhall goes at `point`, or `None` if there is none.""" 255 return next( 256 (expansion for expansion in expansions if isinstance(expansion, cls) and expansion.center == point), None 257 ) 258 259 @classmethod 260 def _find_at_opponent_starts(cls, expansions: Iterable[Expansion], game_map: GameMap) -> tuple[Self | None, ...]: 261 """The start location of `expansions` at each of `game_map`'s start locations but this player's, in the map's 262 order: `None` for one no expansion's townhall goes at.""" 263 return tuple(cls._find_at(expansions, start) for start in game_map.opponent_start_locations)
An expansion a player starts the game at, with the ground of its main, the ramp out of it, its natural and its two thirds.
It is found once, as the game begins, and none of it changes. Its natural and thirds are walked to over the ground as the game began with every mineral field and geyser on it, which the game's pathing grid leaves out but for this player's own (in game), and never where a player starts.
183 @property 184 def main_ramp(self) -> Ramp: 185 """The ramp out of the main: of the ramps whose top is at the main's level, within half a level of the height 186 at `center`'s tile, the one whose center is the shortest walk from `center`, and of two as short, the first in 187 tile order. The walk is over the game's pathing grid as the game began, with the ground the start's townhall 188 covers opened. Raises `NoMainRampError` where no such ramp can be walked to.""" 189 if self._main_ramp is None: 190 raise NoMainRampError(f"no ramp out of the main at {self.center} can be walked to") 191 return self._main_ramp
The ramp out of the main: of the ramps whose top is at the main's level, within half a level of the height
at center's tile, the one whose center is the shortest walk from center, and of two as short, the first in
tile order. The walk is over the game's pathing grid as the game began, with the ground the start's townhall
covers opened. Raises NoMainRampError where no such ramp can be walked to.
193 @property 194 def natural(self) -> Expansion: 195 """The expansion nearest `center` by pathing distance where no player starts, and of two as near, the nearer in 196 a straight line. Raises `NoExpansionError` where no such expansion can be walked to, as on a map drawn for a 197 test.""" 198 if self._natural is None: 199 raise NoExpansionError(f"no expansion where no player starts can be walked to from {self.center}") 200 return self._natural
The expansion nearest center by pathing distance where no player starts, and of two as near, the nearer in
a straight line. Raises NoExpansionError where no such expansion can be walked to, as on a map drawn for a
test.
202 @property 203 def line_third(self) -> Expansion: 204 """The third along the way from the main through the natural: of the two full bases nearest the natural by 205 pathing distance where no player starts, the one whose straight-line distance to `center` is the larger against 206 its straight-line distance to the playable area's nearest edge. A full base has 8 mineral fields or more and 2 207 geysers. Raises `NoExpansionError` where fewer than two such bases can be walked to from the natural.""" 208 if self._line_third is None: 209 raise NoExpansionError(f"fewer than two full bases can be walked to from the natural of {self.center}") 210 return self._line_third
The third along the way from the main through the natural: of the two full bases nearest the natural by
pathing distance where no player starts, the one whose straight-line distance to center is the larger against
its straight-line distance to the playable area's nearest edge. A full base has 8 mineral fields or more and 2
geysers. Raises NoExpansionError where fewer than two such bases can be walked to from the natural.
212 @property 213 def triangle_third(self) -> Expansion: 214 """The third beside the main and the natural: of the two `line_third` is chosen from, the other. Raises 215 `NoExpansionError` as `line_third` does.""" 216 if self._triangle_third is None: 217 raise NoExpansionError(f"fewer than two full bases can be walked to from the natural of {self.center}") 218 return self._triangle_third
The third beside the main and the natural: of the two line_third is chosen from, the other. Raises
NoExpansionError as line_third does.