diff --git a/farming_analyzer/README.md b/farming_analyzer/README.md index ee39d37..cc8b918 100644 --- a/farming_analyzer/README.md +++ b/farming_analyzer/README.md @@ -234,6 +234,118 @@ attempt gate rather than an exponential renewal curve. Randomized spawn phases are averaged analytically, then readiness, partial-lap combat, mana use, and rest time are solved together. +## Approach danger + +A spot is only as safe as the maps crossed to reach it. The approach search +runs over walkable components rather than whole maps: each map's walkable +tiles are split into 8-neighbour connected components, computed lazily for +the maps the search reaches and cached. A character can move: + +- through a placed `type 66` exit (not one carried in a spawn point or + container) from its own tile, or from an adjacent walkable tile when the + exit tile is blocked. It lands at the exit's `hp`/`sp`, at the target's + `enter_x`/`enter_y` when those are out of range (such as `-1`), or on an + adjacent free tile when the landing tile is blocked, as + `object_enter_map()` does. `slaying` resolves relative to the map, or from + the map root when it starts with `/`. Stairs without `slaying` use + `last_heal` (9 up, 10 down, or a horizontal direction) to pick the tiled + map and keep their own position; an exit without `slaying` but with + `hp`/`sp` moves within its own map. An auto-linked exit (no path, `hp`/`sp` + of -1, non-zero `sub_type`) may lead to any exit of the same `sub_type` + within five tiles, including on tiled neighbours, as `exit_find()` does. + Scripts, keys and locks are not followed; doors count as open; +- across a tiled map edge or corner from an edge tile to the walkable tile + beyond it. Tiling follows `derive_map_filename_tiles()` in classic + `server/src/server/map.c`: header `tile_path_N` (direction `N - 1`) wins, + otherwise any basename with two or three numeric words of at most three + characters (`cave_2_1_-1`) derives its neighbours' names when those maps + exist. Only the eight same-depth directions are walked; up/down tiles are + used only by stairs, not as seams. + +Origins are components: + +- each placed savebed's component (free); +- every walkable component of each `--approach-origin MAP` (free). `MAP` may + be written `/region/map`, `region/map`, or `maps/region/map`; an unknown + map is an error. `--approach-origins-only` uses only these, for example + "I start from my savebed"; +- town-connected surface components (charged). Surface components (depth-0 + `world_X_Y` tiles) are grouped once, with union-find over seams between + surface tiles in either direction. A group is town-connected when one of its components holds a + savebed or is joined by an exit to or from a savebed map, such as an inn + door. Islets, ship-only islands, and surface pockets entered only from + below are therefore not origins. A charged surface origin costs its map's + own danger, because the character must cross it to use its entrance. + +The `--path` filter and `--exclude-region` do not hide approach maps. + +A bottleneck search walks backwards from the components holding the spot's +spawns to an origin, minimizing the most dangerous map crossed, then the +number of components crossed, then their names, so the result is +deterministic. It crosses at most `--max-approach-maps` components between +origin and spot (default 16). A component is expanded again when reached +with fewer crossings, so a long safe path cannot block a shorter one that +fits the limit. Other components of the spot's own maps are free and are not +listed, because the spot's safety already covers them. + +Each crossed component is charged for its map's worst aggressive encounter +among the spawns standing in that component or whose own detection radius +reaches one of its tiles by Chebyshev distance, so casters, archers, flyers +and swimmers behind rock, tree or water lines still count, reusing the +spot's monster, damage, hit-chance, kill-time and protection model. Spawns +whose own detection radius reaches one pull point fight together. That pack +is charged by sequential exposure: every living monster keeps attacking until +it dies, killed in the order that minimizes damage (ascending kill time per +incoming DPS), plus each monster's secondary-risk bonus. A spawn that is +aggressive with probability `p` is charged `p` times its conditional damage +and adds `p` times its kill time to the monsters after it. For `n` identical +monsters this charges `n(n + 1)/2` kills' worth of exposure, about +`(n + 1)/2` times the farming model's `n` (danger times pack size). That is +deliberate: a farmer chooses pulls and fights one monster at a time, while a +traveller crossing the map meets the whole pack at once and every monster +still alive keeps hitting. Without `--max-health`, the worst single +aggressive spawn is charged instead, matching the relative per-monster +safety model. Directly placed monsters count even without +`--include-static`, because they are present when a traveller loads the +map. Passive monsters are skipped. AoE is not credited on the approach. +Threats are cached per map and component for the current options. + +The approach safety uses the same reference as the spot: `max_health / +approach_danger` with `--max-health`, otherwise the least dangerous eligible +spot's danger divided by `approach_danger`, capped at one. The reported +`safety_score`, and therefore the balanced score and `--ranking safety`, is +the lower of the spot and approach safeties. A spot with no path from an +origin within the limit keeps its own safety and sets `approach_unknown`; +`--unreachable-approach-safety SAFETY` (0 to 1) caps such spots instead. +Running past monsters, fight variance, and the server's poisoning pulses +(`attack_perform_poison()`: five to ten pulses of up to a third of maximum +HP) beyond the secondary-risk heuristic are not modeled, so a pack whose +expected damage is just inside one health bar still reports full safety. +`--ignore-approach` restores the spot-only score. + +Each result (`results`, `groups[].representative`, and `rankings`) adds these +JSON fields; existing fields keep their names and types: + +- `spot_safety_score`: the spot-only safety previously reported as + `safety_score`; +- `approach_status`: `path` (an origin was found), `origin` (a spawn's + component is itself an origin), `unreachable`, or `disabled`. `path` can + come with an empty `approach_maps` when a charged surface origin leads + straight into the spot; `approach_danger` is then that origin's danger; +- `approach_unknown`: true exactly when `approach_status` is `unreachable`; +- `approach_origin`: content-relative origin map, empty unless `path`; +- `approach_maps`: content-relative maps crossed, ordered from the origin + towards the spot, excluding the origin and the spot's own maps; +- `approach_danger`: the charged danger of the worst approach map, including + a charged surface origin; +- `approach_safety_score`: 0 to 1; 1 without a charged approach, or the + `--unreachable-approach-safety` cap; +- `approach_worst_map`: the map that sets `approach_danger`; +- `approach_danger_flags`: attack and behaviour flags of the monsters in each + charged map's worst encounter, summed over those maps (for example + `fire×3`), plus a `MAP L > allowed L` entry for any charged + map whose monsters exceed the `--max-level-gap` allowance. + ## Profiles, rankings, diagnostics, and training Save validated character arguments and reuse them: @@ -469,7 +581,7 @@ analyzer stays standard-library only. Consumers supply `--content-root` and Run the focused regression suite from the repository root: ```sh -python3 -m unittest tools.test_farming_analyzer +python3 -m unittest discover -s farming_analyzer/tests -t . -v ``` The fixtures are current authored maps and server tables. Tests cover the @@ -480,4 +592,11 @@ monsters, AoE clear-time and mana/crystal fight-rest cycles, Meditation's server-derived refill ramp, damage/delay DPS derivation, partially populated steady-state patrol laps, the deepest Old Outpost map, hierarchical region exclusions, depth-safe world-map circuits, the four-tile Strakewood swamp -circuit, and the two-tile Forgotten Graveyard circuit. +circuit, and the two-tile Forgotten Graveyard circuit. A synthetic world checks +that a safe circuit behind a dangerous entry map loses safety and reports +approach flags, while the same circuit behind a safe entry is unchanged, and +covers exits, tile paths, tiling, origins, and the bounded search. When the +content checkout is present, `UndergroundCityEntranceTest` checks a +Sera-like level 36 profile against the Underground City entrance's slime +cluster and approach routes. It is skipped without that checkout, so CI, +which checks out only this repository, does not run it. diff --git a/farming_analyzer/analyzer.py b/farming_analyzer/analyzer.py index 9fab88b..37d5272 100644 --- a/farming_analyzer/analyzer.py +++ b/farming_analyzer/analyzer.py @@ -1,19 +1,24 @@ """Source-derived farming location analysis.""" +import heapq import math +import posixpath import re from collections import Counter, defaultdict, deque +from dataclasses import dataclass from pathlib import Path from typing import Iterable from .config import ( CONSUMABLE_TYPES, + EXIT_TYPE, GEAR_TYPES, MONEY_TYPE, MONSTER_TYPE, PHYSICAL_ATTACKS, RANDOM_DROP_TYPE, ROOT, + SAVEBED_TYPE, SERVER_ATTACK_TYPES, SERVER_ROOT, SPAWN_POINT_MOB_TYPE, @@ -46,6 +51,22 @@ from .treasure import Loot, TreasureModel +@dataclass(frozen=True) +class ApproachThreat: + """Danger of walking through one map on the way to a farming spot.""" + + pack_danger: float + spawn_danger: float + max_level: int + flags: tuple[str, ...] + + +# Server map_tiled_coords order (server/src/server/map.c); 8 and 9 are up/down. +TILE_DIRECTIONS = ((0, -1), (1, 0), (0, 1), (-1, 0), (1, -1), (1, 1), (-1, 1), (-1, -1)) +TILE_INDEX = {direction: index for index, direction in enumerate(TILE_DIRECTIONS)} +TILED_UP, TILED_DOWN = 8, 9 + + class FarmingAnalyzer: def __init__(self, root: Path = ROOT, server_root: Path = SERVER_ROOT): self.root = root @@ -60,6 +81,16 @@ def __init__(self, root: Path = ROOT, server_root: Path = SERVER_ROOT): self.tick_seconds = self._constant("MAX_TIME", 125000) / 1_000_000.0 self.default_reset = self._constant("MAP_DEFAULTRESET", 7200) self._world_graph = None + self._map_index_cache: tuple[dict[str, frozenset[str]], frozenset[str]] | None = None + self._tile_cache: dict[str, dict[int, str]] = {} + self._component_cache: dict[str, dict[tuple[int, int], int]] = {} + self._edge_cache: dict[str, tuple[tuple[int, str, int, bool], ...]] = {} + self._predecessor_cache: dict[tuple[str, int], tuple[tuple[str, int], ...]] = {} + self._surface_groups: dict[tuple[str, int], tuple[str, int]] = {} + self._town_groups: frozenset[tuple[str, int]] | None = None + self._threat_options: AnalysisOptions | None = None + self._threat_cache: dict[tuple[str, int | None], ApproachThreat] = {} + self._spawn_cache: dict[str, list[SpawnProfile]] = {} self._npc_factions = self._load_npc_factions() self.rejections: list[tuple[str, str]] = [] @@ -317,7 +348,16 @@ def _world(self): _integer(one(header["attrs"], "width")), _integer(one(header["attrs"], "height")), ) - graph.nodes["/" + path.relative_to(self.map_root).as_posix()] = node + key = "/" + path.relative_to(self.map_root).as_posix() + graph.nodes[key] = node + node.enter = (_integer(one(header["attrs"], "enter_x", 0)), + _integer(one(header["attrs"], "enter_y", 0))) + for name, values in header["attrs"].items(): + match = re.fullmatch(r"tile_path_(\d+)", name) + if match and values and 1 <= int(match.group(1)) <= len(TILE_DIRECTIONS) + 2: + target = self._resolve_map_path(key, values[-1]) + if target is not None: + node.tile_paths[int(match.group(1)) - 1] = target for obj, parent in flatten(parsed["objects"]): attrs = merged_attrs(obj, self.archetypes) x = _integer(one( @@ -331,6 +371,18 @@ def _world(self): terrain = _integer(attrs.get("terrain_type")) if terrain: node.terrain[(x, y)] = node.terrain.get((x, y), 0) | terrain + obj_type = _integer(attrs.get("type")) + # Only exits placed on the map, not carried in an + # inventory or spawn template, lead the player elsewhere. + if parent is None and obj_type == EXIT_TYPE: + slaying = attrs.get("slaying", "") + node.exits.append(( + x, y, self._resolve_map_path(key, slaying), + _integer(attrs.get("hp")), _integer(attrs.get("sp")), + _integer(attrs.get("last_heal")), + _integer(attrs.get("sub_type")))) + elif parent is None and obj_type == SAVEBED_TYPE: + node.savebeds.append((x, y)) # Doors, exits, and teleporters are traversable server-side. if attrs.get("no_pass") == "1" and attrs.get("type") not in ( "20", "64", "66"): @@ -338,6 +390,566 @@ def _world(self): self._world_graph = graph return self._world_graph + @staticmethod + def _resolve_map_path(source: str, target: str) -> str | None: + """Resolve an authored exit or tile path the way map paths nest.""" + target = target.strip() + if not target: + return None + if not target.startswith("/"): + target = posixpath.join(posixpath.dirname(source), target) + return posixpath.normpath(target) + + @staticmethod + def _tile_coordinates(basename: str) -> tuple[str, int, int, int] | None: + """Mirror derive_map_filename_tiles() in classic server/map.c. + + Underscore-separated words longer than three characters are ignored + (old ``map_0101`` names); up to three numeric words, optionally + negative, are coordinates. Two or more make the map tiled, and the + server forms neighbour names by removing that many trailing + characters and appending the shifted coordinates. + """ + coordinates: list[int] = [] + length = 0 + for word in basename.split("_"): + if not word or len(word) > 3: + continue + if re.fullmatch(r"-?\d+", word): + coordinates.append(int(word)) + length += len(word) + 1 + if len(coordinates) >= 3: + break + if len(coordinates) < 2: + return None + z = coordinates[2] if len(coordinates) > 2 else 0 + return basename[:max(0, len(basename) - length)], coordinates[0], coordinates[1], z + + def _tiles(self, key: str) -> dict[int, str]: + """Return a map's tiled neighbours by server direction index. + + Header ``tile_path_N`` entries win; otherwise the neighbour is derived + from the coordinate name, as derive_map_filename_tiles() does, when + that map exists. + """ + cached = self._tile_cache.get(key) + if cached is not None: + return cached + nodes = self._world().nodes + tiles = dict(nodes[key].tile_paths) + coordinates = self._tile_coordinates(posixpath.basename(key)) + if coordinates is not None: + prefix, x, y, z = coordinates + parent = posixpath.dirname(key) + + def name(cx: int, cy: int, cz: int) -> str: + return posixpath.join( + parent, f"{prefix}_{cx}_{cy}" + (f"_{cz}" if cz else "")) + + for index, (dx, dy) in enumerate(TILE_DIRECTIONS): + tiles.setdefault(index, name(x + dx, y + dy, z)) + tiles.setdefault(TILED_UP, name(x, y, z + 1)) + tiles.setdefault(TILED_DOWN, name(x, y, z - 1)) + tiles = {index: target for index, target in tiles.items() + if target in nodes and target != key} + self._tile_cache[key] = tiles + return tiles + + def _components(self, key: str) -> dict[tuple[int, int], int]: + """Label a map's walkable tiles by 8-neighbour connected component.""" + cached = self._component_cache.get(key) + if cached is not None: + return cached + node = self._world().nodes[key] + labels: dict[tuple[int, int], int] = {} + label = -1 + for start_y in range(node.height): + for start_x in range(node.width): + if (start_x, start_y) in labels or not node.walkable(start_x, start_y): + continue + label += 1 + labels[(start_x, start_y)] = label + frontier = [(start_x, start_y)] + while frontier: + x, y = frontier.pop() + for dx in (-1, 0, 1): + for dy in (-1, 0, 1): + tile = (x + dx, y + dy) + if tile not in labels and node.walkable(*tile): + labels[tile] = label + frontier.append(tile) + self._component_cache[key] = labels + return labels + + def _land(self, key: str, x: int, y: int) -> tuple[int, ...]: + """Components a character occupies at (x, y), or next to it when blocked. + + Mirrors object_enter_map(): out-of-map coordinates fall back to the + map's enter_x/enter_y, and a blocked tile uses the adjacent free spots. + """ + node = self._world().nodes[key] + if not (0 <= x < node.width and 0 <= y < node.height): + x, y = node.enter + labels = self._components(key) + if (x, y) in labels: + return (labels[(x, y)],) + return tuple(sorted({ + labels[(x + dx, y + dy)] for dx in (-1, 0, 1) for dy in (-1, 0, 1) + if (x + dx, y + dy) in labels})) + + def _exit_destination(self, key: str, + exit_object: tuple[int, int, str | None, int, int, int, int] + ) -> tuple[str, int, int] | None: + """Resolve a placed exit like exit.c insert_map_func() and object_enter_map(). + + Paired exits (no path, a non-zero ``sub_type``) have several possible + destinations and are handled by _paired_exits(). + """ + nodes = self._world().nodes + x, y, destination, hp, sp, last_heal, _sub_type = exit_object + if destination is None: + tiles = self._tiles(key) + if 0 < last_heal <= len(TILE_DIRECTIONS) + 2 and last_heal - 1 in tiles: + destination, hp, sp = tiles[last_heal - 1], x, y + elif hp != -1 and sp != -1: + destination = key + else: + return None + if destination not in nodes: + return None + return destination, hp, sp + + def _paired_exits(self, key: str, + exit_object: tuple[int, int, str | None, int, int, int, int] + ) -> tuple[tuple[str, int, int], ...]: + """Return the exits an auto-linked exit can teleport to. + + Mirrors exit_find() in classic types/exit.c: an exit without a path + and with a non-zero ``sub_type`` picks a random exit of the same + ``sub_type`` within five tiles, across tiled neighbours via + get_map_from_coord(), and the character lands on that exit's tile. + """ + x, y, destination, hp, sp, last_heal, sub_type = exit_object + if destination is not None or not sub_type or ( + self._exit_destination(key, exit_object) is not None): + return () + nodes = self._world().nodes + node = nodes[key] + tiles = self._tiles(key) + found = [] + for dx in range(-5, 6): + for dy in range(-5, 6): + if not dx and not dy: + continue + tx_, ty_ = x + dx, y + dy + tx = (tx_ >= node.width) - (tx_ < 0) + ty = (ty_ >= node.height) - (ty_ < 0) + target_key = key + if tx or ty: + target_key = tiles.get(TILE_INDEX[(tx, ty)]) + if target_key is None: + continue + target = nodes[target_key] + tx_ = tx_ - node.width if tx > 0 else target.width + tx_ if tx < 0 else tx_ + ty_ = ty_ - node.height if ty > 0 else target.height + ty_ if ty < 0 else ty_ + for other in nodes[target_key].exits: + if other[0] == tx_ and other[1] == ty_ and other[6] == sub_type: + found.append((target_key, tx_, ty_)) + return tuple(found) + + def _out_edges(self, key: str) -> tuple[tuple[int, str, int, bool], ...]: + """Return (component, target map, target component, is_seam) moves. + + Exits are taken from their own tile, or an adjacent walkable tile when + the exit tile is blocked, and land at their hp/sp destination (the + target's enter_x/enter_y when out of range). Seams join edge tiles to + the walkable tile across the edge or corner, 8-neighbour style. + """ + cached = self._edge_cache.get(key) + if cached is not None: + return cached + nodes = self._world().nodes + node = nodes[key] + labels = self._components(key) + edges: set[tuple[int, str, int, bool]] = set() + for exit_object in node.exits: + resolved = self._exit_destination(key, exit_object) + destinations = ((resolved,) if resolved is not None else + self._paired_exits(key, exit_object)) + for destination, hp, sp in destinations: + for source in self._land(key, exit_object[0], exit_object[1]): + for arrival in self._land(destination, hp, sp): + if (destination, arrival) != (key, source): + edges.add((source, destination, arrival, False)) + tiles = self._tiles(key) + for (x, y), label in labels.items(): + if 0 < x < node.width - 1 and 0 < y < node.height - 1: + continue + for dx in (-1, 0, 1): + for dy in (-1, 0, 1): + nx, ny = x + dx, y + dy + tx = (nx >= node.width) - (nx < 0) + ty = (ny >= node.height) - (ny < 0) + if not tx and not ty: + continue + other = tiles.get(TILE_INDEX[(tx, ty)]) + if other is None: + continue + target = nodes[other] + mx = nx - node.width if tx > 0 else target.width + nx if tx < 0 else nx + my = ny - node.height if ty > 0 else target.height + ny if ty < 0 else ny + arrival = self._components(other).get((mx, my)) + if arrival is not None: + edges.add((label, other, arrival, True)) + result = tuple(sorted(edges)) + self._edge_cache[key] = result + return result + + def _map_index(self) -> tuple[dict[str, frozenset[str]], frozenset[str]]: + """Return the maps that can lead into each map, and surface tiles.""" + if self._map_index_cache is None: + nodes = self._world().nodes + incoming: dict[str, set[str]] = defaultdict(set) + surface = set() + for key, node in nodes.items(): + for exit_object in node.exits: + resolved = self._exit_destination(key, exit_object) + if resolved is not None: + incoming[resolved[0]].add(key) + for target, _x, _y in self._paired_exits(key, exit_object): + incoming[target].add(key) + for index, target in self._tiles(key).items(): + if index < len(TILE_DIRECTIONS): + incoming[target].add(key) + world = LocationIndex.world_coordinates(posixpath.basename(key)) + if world is not None and world[0] == "world" and world[3] == 0: + surface.add(key) + self._map_index_cache = ( + {key: frozenset(values) for key, values in incoming.items()}, + frozenset(surface)) + return self._map_index_cache + + def _predecessors(self, node: tuple[str, int]) -> tuple[tuple[str, int], ...]: + """Return the (map, component) nodes with a move into ``node``.""" + cached = self._predecessor_cache.get(node) + if cached is not None: + return cached + incoming, _surface = self._map_index() + key, label = node + result = tuple(sorted({ + (source, source_label) + for source in incoming.get(key, ()) + for source_label, target, target_label, _seam in self._out_edges(source) + if target == key and target_label == label and (source, source_label) != node + })) + self._predecessor_cache[node] = result + return result + + def _savebed_nodes(self) -> frozenset[tuple[str, int]]: + return frozenset( + (key, label) + for key, node in self._world().nodes.items() + for x, y in node.savebeds + for label in self._land(key, x, y)) + + def _surface_origin(self, node: tuple[str, int]) -> bool: + """Whether a surface component can be walked to from a town. + + A town is a surface component that holds a savebed or is joined by an + exit to or from a map that holds one, for example an inn door. Surface + components are grouped once, with union-find over seams between + surface tiles taken in either direction, so islets, ship-only islands, + and surface pockets entered only from below do not count. + """ + if self._town_groups is None: + incoming, surface = self._map_index() + savebed_maps = {key for key, value in self._world().nodes.items() + if value.savebeds} + towns = set(self._savebed_nodes()) + for key in savebed_maps: + for _label, target, target_label, _seam in self._out_edges(key): + towns.add((target, target_label)) + for source in incoming.get(key, ()): + for label, target, _target_label, _seam in self._out_edges(source): + if target == key: + towns.add((source, label)) + parent: dict[tuple[str, int], tuple[str, int]] = {} + + def find(item: tuple[str, int]) -> tuple[str, int]: + parent.setdefault(item, item) + while parent[item] != item: + parent[item] = parent[parent[item]] + item = parent[item] + return item + + for key in sorted(surface): + for label in set(self._components(key).values()): + find((key, label)) + for label, target, target_label, seam in self._out_edges(key): + if seam and target in surface: + left, right = find((key, label)), find((target, target_label)) + if left != right: + parent[max(left, right)] = min(left, right) + self._surface_groups = {item: find(item) for item in parent} + self._town_groups = frozenset( + self._surface_groups[item] for item in towns + if item in self._surface_groups) + group = self._surface_groups.get(node) + return group is not None and group in self._town_groups + + def resolve_map_key(self, path: str) -> str | None: + """Resolve a user-supplied map path to an authored map, or None. + + Accepts map-root paths (``/region/map``), content-relative paths + (``maps/region/map``), and either form with a leading slash. + """ + text = path.strip().lstrip("/") + if not text: + return None + nodes = self._world().nodes + for candidate in (text, text.removeprefix("maps/")): + key = posixpath.normpath("/" + candidate) + if key in nodes: + return key + return None + + @staticmethod + def _sequential_exposure(fighters: list[tuple[float, float, float, float]]) -> float: + """Expected damage while killing an engaged pack one at a time. + + Each fighter is (probability it is an aggressive monster, incoming DPS, + kill seconds, expected secondary-risk bonus), DPS and kill time being + conditional on that monster being present. Every living monster keeps + attacking until it dies, so its DPS is charged until its own kill; + killing in ascending kill-seconds/DPS order (Smith's rule) minimizes + that total. Presence is independent, so each monster pays + ``p * dps * (own kill + expected earlier kills)``. + """ + total = 0.0 + elapsed = 0.0 + damaging = sorted( + (item for item in fighters if item[1] > 0.0), + key=lambda item: item[2] / item[1]) + for probability, dps, kill_seconds, bonus in damaging: + total += probability * dps * (elapsed + kill_seconds) + bonus + elapsed += probability * kill_seconds + total += sum(item[3] for item in fighters if item[1] <= 0.0) + return total + + def _approach_threat(self, key: str, options: AnalysisOptions, + component: int | None = None) -> ApproachThreat: + """Measure the worst aggressive encounter met while crossing one map. + + With ``component``, a spawn is charged when it stands in (or, when + blocked, next to) that walkable component, or when its own detection + radius reaches a tile of the component by Chebyshev distance. Casters, + archers, flyers and swimmers can engage across rock, tree or water + lines that only block walking; components far apart stay distinct. + + Every hostile spawn point and directly placed monster is included, + whatever --include-static says, because a traveller meets them when + the map is loaded. Monster damage, hit chance and kill time reuse the + spot model, including the character's AC and protections; passive + monsters are not engaged. Spawns whose own detection radius reaches + one pull point fight together, charged by sequential exposure. + """ + if self._threat_options != options: + self._threat_options = options + self._threat_cache = {} + self._spawn_cache = {} + cached = self._threat_cache.get((key, component)) + if cached is not None: + return cached + threat = ApproachThreat(0.0, 0.0, 0, ()) + spawns = self._spawn_cache.get(key) + if spawns is None: + path = self.map_root / key.lstrip("/") + parsed = parse_blocks(path) if path.is_file() else {"header": None} + spawns = [] if parsed.get("header") is None else self._collect_spawns( + parsed, options, include_static=True)[0] + self._spawn_cache[key] = spawns + if component is not None and key in self._world().nodes: + tiles = [tile for tile, label in self._components(key).items() + if label == component] + + def reaches(spawn: SpawnProfile) -> bool: + if component in self._land(key, spawn.x, spawn.y): + return True + radius = spawn.weighted("aggro_radius") + return any(max(abs(spawn.x - x), abs(spawn.y - y)) <= radius + for x, y in tiles) + + spawns = [spawn for spawn in spawns if reaches(spawn)] + if spawns: + fighters: list[tuple[float, float, float, float]] = [] + weights: list[float] = [] + for spawn in spawns: + active = [(probability, profile) + for probability, profile in spawn.candidates + if "passive" not in profile.flags] + weights.append(sum(probability * profile.danger + for probability, profile in active)) + present = sum(probability for probability, _profile in active) + if present <= 0.0: + fighters.append((0.0, 0.0, 0.0, 0.0)) + continue + dps = sum(probability * profile.damage_second + for probability, profile in active) / present + kill = sum(probability * profile.kill_seconds + for probability, profile in active) / present + # An unkillable monster with a damaging attack never stops. + bonus = sum( + probability * (profile.danger - profile.damage_taken) + for probability, profile in active + if math.isfinite(profile.damage_taken)) + if not math.isfinite(kill) and dps > 0.0: + bonus = math.inf + fighters.append((present, dps, kill if math.isfinite(kill) else 0.0, bonus)) + best_pack: list[int] = [] + pack_danger = 0.0 + for target in spawns: + pack = [ + index for index, spawn in enumerate(spawns) + if weights[index] > 0.0 and + max(abs(target.x - spawn.x), abs(target.y - spawn.y)) <= + spawn.weighted("aggro_radius") + ] + danger = self._sequential_exposure([fighters[i] for i in pack]) + if danger > pack_danger or not best_pack and pack: + pack_danger = danger + best_pack = pack + flag_counts: Counter[str] = Counter() + for index in best_pack: + for probability, profile in spawns[index].candidates: + if "passive" in profile.flags: + continue + for flag in profile.flags: + flag_counts[flag] += probability + levels = [ + profile.level for index, spawn in enumerate(spawns) + if weights[index] > 0.0 + for _probability, profile in spawn.candidates + if "passive" not in profile.flags + ] + threat = ApproachThreat( + pack_danger, max(weights, default=0.0), max(levels, default=0), + tuple(f"{flag}×{amount:g}" for flag, amount in sorted( + flag_counts.items(), key=lambda item: (-item[1], item[0])))) + self._threat_cache[(key, component)] = threat + return threat + + def _apply_approach(self, result: MapResult, options: AnalysisOptions) -> None: + """Find the least dangerous authored approach from an origin. + + The search runs over (map, walkable component) nodes, so an exit only + counts from tiles the character can actually stand next to. It walks + backwards from the components holding the spot's spawns and minimizes + the most dangerous map crossed, then the number of nodes, then the + node names for determinism. Savebed and --approach-origin origins are + where the character starts and are free; a town-connected surface + component is charged its map's danger because the character must + cross it to use its entrance. + """ + if not options.model_approach: + return + nodes = self._world().nodes + explicit = { + (key, label) + for key in map(self.resolve_map_key, options.approach_origins) + if key is not None + for label in set(self._components(key).values()) + } + free = explicit if options.approach_origins_only else ( + self._savebed_nodes() | explicit) + + def is_origin(node: tuple[str, int]) -> bool: + return node in free or ( + not options.approach_origins_only and self._surface_origin(node)) + + map_prefix = self.map_root.relative_to(self.root).as_posix() + + def key_of(path: str) -> str: + return "/" + path.removeprefix(map_prefix + "/") + + member_maps = {key_of(path) for path in result.map_paths} & set(nodes) + targets = { + (key_of(path), label) + for path, x, y in result.spawn_points + if key_of(path) in nodes + for label in self._land(key_of(path), x, y) + } or { + (key, label) for key in member_maps + for label in set(self._components(key).values()) + } + if any(is_origin(node) for node in targets): + result.approach_status = "origin" + return + use_packs = options.max_health > 0.0 + + def metric(node: tuple[str, int]) -> float: + threat = self._approach_threat(node[0], options, node[1]) + return threat.pack_danger if use_packs else threat.spawn_danger + + heap: list[tuple[float, int, tuple[tuple[str, int], ...], tuple[str, int]]] = [ + (0.0, 0, (), node) for node in sorted(targets)] + # A node popped again with fewer hops may still reach an origin within + # the limit, so prune by hops rather than settling nodes once. + best_hops: dict[tuple[str, int], int] = {} + found = None + while heap: + bottleneck, hops, path, node = heapq.heappop(heap) + if is_origin(node): + found = bottleneck, path, node + break + if hops >= best_hops.get(node, math.inf): + continue + best_hops[node] = hops + for previous in self._predecessors(node): + if previous in targets or previous in path: + continue + if is_origin(previous): + cost = 0.0 if previous in free else metric(previous) + heapq.heappush(heap, (max(bottleneck, cost), hops, path, previous)) + elif hops < options.max_approach_maps: + # Other parts of the spot's own maps are the spot's danger. + cost = 0.0 if previous[0] in member_maps else metric(previous) + heapq.heappush(heap, ( + max(bottleneck, cost), hops + 1, path + (previous,), previous)) + if found is None: + result.approach_status = "unreachable" + result.approach_unknown = True + return + bottleneck, path, origin = found + ordered: list[str] = [] + for key, _label in reversed(path): + if key not in member_maps and (not ordered or ordered[-1] != key): + ordered.append(key) + charged = ([origin] if origin not in free else []) + [ + node for node in dict.fromkeys(reversed(path)) if node[0] not in member_maps] + result.approach_status = "path" + result.approach_origin = map_prefix + origin[0] + result.approach_maps = tuple(map_prefix + key for key in ordered) + result.approach_danger = bottleneck + survival_level = max(options.player_level, options.character_level) + allowed = survival_level + options.max_level_gap + flags: Counter[str] = Counter() + worst = None + level_flags: dict[str, None] = {} + for node in charged: + threat = self._approach_threat(node[0], options, node[1]) + if worst is None or metric(node) > metric(worst): + worst = node + for rendered in threat.flags: + label, _separator, amount = rendered.rpartition("×") + flags[label] += _number(amount, 1.0) + if threat.max_level > allowed: + level_flags[f"{Path(node[0]).name} L{threat.max_level} > allowed L{allowed}"] = None + if worst is not None and metric(worst) > 0.0: + result.approach_worst_map = map_prefix + worst[0] + result.approach_danger_flags = tuple( + f"{flag}×{amount:g}" for flag, amount in sorted( + flags.items(), key=lambda item: (-item[1], item[0]))) + tuple(level_flags) + def _maneuverability( self, relpath: str, spawn_points: list[tuple[int, int]], @@ -1003,13 +1615,11 @@ def _max_aggro_pack(spawns: list[SpawnProfile]) -> float: maximum = max(maximum, direct) return maximum - def analyze_map(self, path: Path, options: AnalysisOptions) -> MapResult | None: - relpath = str(path.relative_to(self.root)) - parsed = parse_blocks(path) - header = parsed.get("header") - if header is None: - return None - header_attrs = header["attrs"] + def _collect_spawns( + self, parsed: dict, options: AnalysisOptions, *, include_static: bool, + ) -> tuple[list[SpawnProfile], list[CompetitorProfile]]: + """Return hostile spawn profiles and NPC competitors of a parsed map.""" + header_attrs = parsed["header"]["attrs"] difficulty = _integer(one(header_attrs, "difficulty", 1), 1) reset_timeout = _integer(one(header_attrs, "reset_timeout", self.default_reset), self.default_reset) @@ -1025,10 +1635,22 @@ def analyze_map(self, path: Path, options: AnalysisOptions) -> MapResult | None: competitor = self._competitor_spawn(node, options) if competitor is not None: competitors.append(competitor) - elif options.include_static and parent is None and obj_type == MONSTER_TYPE: + elif include_static and parent is None and obj_type == MONSTER_TYPE: spawn = self._static_monster(node, difficulty, reset_timeout, options) if spawn is not None: spawns.append(spawn) + return spawns, competitors + + def analyze_map(self, path: Path, options: AnalysisOptions) -> MapResult | None: + relpath = str(path.relative_to(self.root)) + parsed = parse_blocks(path) + header = parsed.get("header") + if header is None: + return None + header_attrs = header["attrs"] + difficulty = _integer(one(header_attrs, "difficulty", 1), 1) + spawns, competitors = self._collect_spawns( + parsed, options, include_static=options.include_static) if len(spawns) < options.minimum_spawns: self.rejections.append((relpath, f"{len(spawns)} spawns < minimum {options.minimum_spawns}")) @@ -1463,6 +2085,20 @@ def _score(results: list[MapResult], options: AnalysisOptions) -> list[MapResult else: safety = (min(1.0, safest / max(result.danger, 0.001)) if math.isfinite(result.danger) else 0.0) + result.spot_safety_score = safety + if result.approach_status == "path": + # Approach maps use the same health budget, or the same + # least-dangerous-spot reference, as the spot itself. + reference = (options.max_health if options.max_health > 0.0 + else safest) + result.approach_safety_score = ( + min(1.0, reference / max(result.approach_danger, 0.001)) + if math.isfinite(result.approach_danger) else 0.0) + safety = min(safety, result.approach_safety_score) + elif (result.approach_status == "unreachable" and + options.unreachable_approach_safety is not None): + result.approach_safety_score = options.unreachable_approach_safety + safety = min(safety, result.approach_safety_score) result.safety_score = safety components = { "xp": result.xp_hour / maxima["xp"], @@ -1505,4 +2141,5 @@ def scan(self, options: AnalysisOptions) -> list[MapResult]: for result in combined: result.location, result.nearby_landmarks = self.locations.describe( result.map_paths, result.region, result.name) + self._apply_approach(result, options) return self._score(combined, options) diff --git a/farming_analyzer/cli.py b/farming_analyzer/cli.py index 2c30f7d..7660cac 100644 --- a/farming_analyzer/cli.py +++ b/farming_analyzer/cli.py @@ -119,6 +119,19 @@ def build_parser() -> argparse.ArgumentParser: parser.add_argument("--path", dest="path_pattern", help="case-insensitive map-path regex") parser.add_argument("--exclude-region", action="append", default=[], metavar="NAME", help="exclude a region/island ID or name; may be repeated") + parser.add_argument("--approach-origin", action="append", default=[], metavar="MAP", + help="extra map the character starts from, such as its savebed map; any of " + "its walkable parts counts; may be repeated (savebeds and town-connected " + "surface tiles are also origins unless --approach-origins-only)") + parser.add_argument("--max-approach-maps", type=int, default=16, + help="longest approach, in walkable map components between origin " + "and spot (default: 16)") + parser.add_argument("--approach-origins-only", action="store_true", + help="use only --approach-origin maps as origins, not surface tiles or savebeds") + parser.add_argument("--unreachable-approach-safety", type=float, metavar="SAFETY", + help="cap safety (0..1) of spots with no authored approach; default: no cap") + parser.add_argument("--ignore-approach", dest="model_approach", action="store_false", + help="score only the spot's own maps, not the maps crossed to reach it") parser.add_argument("--include-static", action="store_true", help="include monsters that only return after map reset/unload") parser.add_argument("--json", action="store_true", help="emit machine-readable results") @@ -254,6 +267,18 @@ def main(argv: list[str] | None = None) -> int: raise SystemExit("passive-pull-efficiency must be between 0 and 1") if not (1 <= args.circuit_size <= 8): raise SystemExit("circuit-size must be between 1 and 8") + if not (1 <= args.max_approach_maps <= 64): + raise SystemExit("max-approach-maps must be between 1 and 64") + if (args.unreachable_approach_safety is not None and + not (0.0 <= args.unreachable_approach_safety <= 1.0)): + raise SystemExit("unreachable-approach-safety must be between 0 and 1") + if args.approach_origins_only and not args.approach_origin: + raise SystemExit("--approach-origins-only requires at least one --approach-origin") + unknown_origins = [ + origin for origin in args.approach_origin + if analyzer.resolve_map_key(origin) is None] + if unknown_origins: + raise SystemExit("unknown approach origin map: " + ", ".join(unknown_origins)) if not (1 <= args.group_level_span <= 50): raise SystemExit("group-level-span must be between 1 and 50") if not (1 <= character_level <= maximum_level): @@ -304,6 +329,11 @@ def main(argv: list[str] | None = None) -> int: args.passive_pull_efficiency, args.group_results, args.group_level_span, + model_approach=args.model_approach, + approach_origins=tuple(args.approach_origin), + max_approach_maps=args.max_approach_maps, + approach_origins_only=args.approach_origins_only, + unreachable_approach_safety=args.unreachable_approach_safety, ) results = analyzer.scan(options) initial_rejections = list(analyzer.rejections) diff --git a/farming_analyzer/config.py b/farming_analyzer/config.py index 084f06a..2c60173 100644 --- a/farming_analyzer/config.py +++ b/farming_analyzer/config.py @@ -28,6 +28,8 @@ def _find_workspace_root() -> Path: MONSTER_TYPE = 80 SPAWN_POINT_MOB_TYPE = 83 RANDOM_DROP_TYPE = 102 +EXIT_TYPE = 66 +SAVEBED_TYPE = 106 GEAR_TYPES = { 3, 13, 14, 15, 16, 33, 34, 35, 39, 70, 87, 99, 100, 104, 109, 113, } diff --git a/farming_analyzer/models.py b/farming_analyzer/models.py index 65f86dd..aebcaee 100644 --- a/farming_analyzer/models.py +++ b/farming_analyzer/models.py @@ -140,6 +140,17 @@ class MapResult: pack_target_capacity: float = 1.0 min_monster_level: int = 0 avg_monster_level: float = 0.0 + # Approach: the least dangerous authored path from an origin (surface + # world tile, savebed map, or --approach-origin) to the spot's maps. + spot_safety_score: float = 0.0 + approach_status: str = "disabled" + approach_origin: str = "" + approach_maps: tuple[str, ...] = () + approach_danger: float = 0.0 + approach_safety_score: float = 1.0 + approach_worst_map: str = "" + approach_danger_flags: tuple[str, ...] = () + approach_unknown: bool = False @dataclass(frozen=True) @@ -188,6 +199,11 @@ class AnalysisOptions: passive_pull_efficiency: float = 0.20 group_results: bool = True group_level_span: int = 10 + model_approach: bool = True + approach_origins: tuple[str, ...] = () + max_approach_maps: int = 16 + approach_origins_only: bool = False + unreachable_approach_safety: float | None = None @property def simulate_melee(self) -> bool: diff --git a/farming_analyzer/presentation.py b/farming_analyzer/presentation.py index 951e0ed..2e675ab 100644 --- a/farming_analyzer/presentation.py +++ b/farming_analyzer/presentation.py @@ -5,6 +5,7 @@ import re from collections import Counter, defaultdict from dataclasses import dataclass +from pathlib import Path from .config import SERVER_ATTACK_TYPES from .experience import ExperienceModel @@ -320,6 +321,24 @@ def render_text(results: list[MapResult], options: AnalysisOptions, limit: int, f" danger: {', '.join(result.danger_flags) or 'ordinary melee'}; " f"sources: {', '.join(result.sources)}", )) + if result.approach_status == "path": + lines.append( + f" approach: {len(result.approach_maps)} map(s) from " + f"{result.approach_origin} via " + f"{' -> '.join(Path(path).name for path in result.approach_maps) or 'its exit'}; " + f"worst {Path(result.approach_worst_map).name or 'none'} " + f"(danger {result.approach_danger:.0f}, safety " + f"{result.approach_safety_score * 100.0:.0f}% vs spot " + f"{result.spot_safety_score * 100.0:.0f}%); " + f"{', '.join(result.approach_danger_flags) or 'ordinary melee'}" + ) + elif result.approach_status == "unreachable": + capped = options.unreachable_approach_safety + lines.append( + " approach: unknown — no walkable authored path from a savebed, town " + "surface, or --approach-origin within --max-approach-maps; " + + ("scored on the spot alone" if capped is None else + f"safety capped at {capped * 100.0:.0f}%")) if options.character_speed > 0.0: lines.append( f" route: ~{result.route_steps:,} authored walkable tile steps = " @@ -374,7 +393,11 @@ def render_text(results: list[MapResult], options: AnalysisOptions, limit: int, "application. Crystal applications are treated as instant optimal inputs. The supplied " "skill level is held constant. Spawn-point respawn is " "source-derived; map-reset-only monsters require the map to unload and are excluded unless " - "--include-static is used.", + "--include-static is used. Safety is also capped by the least dangerous authored approach: " + "exits, tile paths, and walkable coordinate seams between walkable components, from a " + "savebed, a town-connected surface tile, or --approach-origin, charging the worst aggressive pack on each map crossed (including " + "map-reset monsters and the entrance surface tile) by sequential exposure. Scripted teleports, keys, locked doors, and fleeing past monsters are " + "not modeled; --ignore-approach scores the spot alone.", )) if warnings: lines.append(f"Treasure-model warnings: {len(warnings)} (use --json to inspect derived values).") diff --git a/farming_analyzer/sources.py b/farming_analyzer/sources.py index 79928e5..c6b91b1 100644 --- a/farming_analyzer/sources.py +++ b/farming_analyzer/sources.py @@ -170,6 +170,14 @@ class TerrainMap: height: int terrain: dict[tuple[int, int], int] = field(default_factory=dict) blocked: set[tuple[int, int]] = field(default_factory=set) + # Placed exits as (x, y, destination map-root path or None, hp, sp, + # last_heal, sub_type); header tile_path_N links by server direction + # index N - 1; the header entry point; and placed savebed positions. + exits: list[tuple[int, int, str | None, int, int, int, int]] = field( + default_factory=list) + tile_paths: dict[int, str] = field(default_factory=dict) + enter: tuple[int, int] = (0, 0) + savebeds: list[tuple[int, int]] = field(default_factory=list) def walkable(self, x: int, y: int) -> bool: return ( diff --git a/farming_analyzer/tests/test_approach.py b/farming_analyzer/tests/test_approach.py new file mode 100644 index 0000000..0fff2c4 --- /dev/null +++ b/farming_analyzer/tests/test_approach.py @@ -0,0 +1,673 @@ +"""Approach-path danger on a synthetic authored world.""" + +from __future__ import annotations + +import io +import json +import tempfile +import unittest +from dataclasses import MISSING, fields, replace +from pathlib import Path +from unittest.mock import patch + +from farming_analyzer.analyzer import ApproachThreat +from farming_analyzer import ( + SERVER_ROOT, + AnalysisOptions, + FarmingAnalyzer, + ROOT, + MapResult, + main, +) + +ARCHETYPES = """\ +Object floor +terrain_type 1 +end +Object wall +no_pass 1 +end +Object exit +type 66 +end +Object bed_save +type 106 +end +Object spawn_point +type 81 +last_grace 1 +speed -0.01 +end +Object rat +name rat +type 80 +monster 1 +level 10 +maxhp 20 +dam 2 +wc 1 +ac 1 +speed 0.5 +weapon_speed 1 +item_power 2 +exp 200 +end +Object pudding +name cave pudding +type 80 +monster 1 +level 32 +maxhp 8 +dam 12 +wc 30 +ac 10 +speed 0.5 +weapon_speed 1 +item_power 6 +attack_fire 50 +attack_acid 50 +exp 2000 +end +Object caster +name dragon caster +type 80 +monster 1 +level 40 +maxhp 30 +dam 20 +wc 30 +ac 10 +speed 0.5 +weapon_speed 1 +item_power 3 +can_cast_spell 1 +exp 2000 +end +""" + +SIZE = 6 +ROOM = "underground_city" +DANGER = "circuit[underground_city_0_0 + underground_city_1_0]" +SAFE = "circuit[underground_city_5_0 + underground_city_6_0]" +LOST = "underground_city_9_9" + + +def _map(name: str, region: str, *, spawns: tuple[tuple[str, int, int], ...] = (), + exits: tuple[tuple, ...] = (), extra: str = "", + header: tuple[str, ...] = (), wall_x: int | None = None, + wall_y: int | None = None) -> str: + """Write a fully floored map; ``wall_x``/``wall_y`` leave a column/row bare. + + Exits are (target, x, y) or (target, x, y, hp, sp); without hp/sp the + test exit archetype lands on the target's (0, 0). + """ + lines = [ + "arch map", f"name {name}", f"width {SIZE}", f"height {SIZE}", + "difficulty 10", f"region {region}", *header, "end", + ] + for y in range(SIZE): + for x in range(SIZE): + if x != wall_x and y != wall_y: + lines += ["arch floor", f"x {x}", f"y {y}", "end"] + for monster, x, y in spawns: + lines += ["arch spawn_point", f"x {x}", f"y {y}", + f"arch {monster}", "type 83", "end", "end"] + for target, x, y, *arrival in exits: + lines += ["arch exit", f"x {x}", f"y {y}", f"slaying {target}"] + if arrival: + lines += [f"hp {arrival[0]}", f"sp {arrival[1]}"] + lines += ["end"] + return "\n".join(lines) + "\n" + extra + + +class ApproachDangerTest(unittest.TestCase): + """A safe circuit is only as safe as the map crossed to reach it.""" + + @classmethod + def setUpClass(cls): + cls.directory = tempfile.TemporaryDirectory() + root = Path(cls.directory.name) + (root / "arch").mkdir() + (root / "arch" / "test.arc").write_text(ARCHETYPES) + maps = root / "maps" + (maps / "danger").mkdir(parents=True) + (maps / "safe").mkdir() + (maps / "regions.reg").write_text( + "region surface\nlongname Surface\nend\n" + "region dungeon\nlongname Dungeon\nend\n") + # The surface tile has an inn door, so it is a town origin; it leads + # into both dungeons. + (maps / "world_0_0").write_text(_map( + "Surface", "surface", + exits=(("danger/entry", 1, 1), ("/safe/entry", 4, 4), ("inn", 0, 5)))) + (maps / "inn").write_text(_map( + "Inn", "surface", exits=(("world_0_0", 0, 0),), + extra="arch bed_save\nx 2\ny 2\nend\n")) + rats = (("rat", 1, 1), ("rat", 4, 4)) + for dungeon, x, entry_spawns in ( + ("danger", 0, (("pudding", 2, 2), ("pudding", 3, 2), + ("pudding", 2, 3))), + ("safe", 5, ())): + first, second = f"{ROOM}_{x}_0", f"{ROOM}_{x + 1}_0" + (maps / dungeon / "entry").write_text(_map( + f"{dungeon} entry", "dungeon", spawns=entry_spawns, + exits=(("../world_0_0", 0, 0), (first, 5, 5)))) + # Two seam-adjacent coordinate rooms form the farming circuit. + # Only the first has an authored exit from the entry map. + (maps / dungeon / first).write_text(_map( + f"{dungeon} cave", "dungeon", spawns=rats, + exits=(("entry", 0, 0),))) + (maps / dungeon / second).write_text(_map( + f"{dungeon} cave", "dungeon", spawns=rats)) + # Rats behind no authored exit at all. + (maps / "lost").mkdir() + (maps / "lost" / LOST).write_text(_map("lost cave", "dungeon", spawns=rats)) + cls.analyzer = FarmingAnalyzer(root, SERVER_ROOT) + + @classmethod + def tearDownClass(cls): + cls.directory.cleanup() + + @staticmethod + def options(**changes) -> AnalysisOptions: + options = AnalysisOptions( + player_level=10, dps=40.0, seconds_per_kill=2.0, + seconds_per_map=10.0, shop_sell_fraction=0.20, at_minute=12 * 60, + attack_type="physical_average", minimum_spawns=1, + minimum_xp_fraction=0.0, max_level_gap=5, circuit_size=4, + path_pattern=ROOM, include_static=False, character_level=10, + player_ac=10, player_protections=(), melee_damage=None, + weapon_class=None, weapon_speed=None, weapon_class_range=20, + player_attacks=(("impact", 25), ("cleave", 25), + ("slash", 25), ("pierce", 25)), + damage_per_attack=40.0, attack_delay=1.0, max_health=300.0, + ) + return replace(options, **changes) + + def results(self, options: AnalysisOptions) -> dict[str, MapResult]: + return {result.path: result for result in self.analyzer.scan(options)} + + def test_dangerous_approach_lowers_safety_and_is_reported(self): + results = self.results(self.options()) + danger = results[DANGER] + self.assertEqual("path", danger.approach_status) + self.assertEqual("maps/world_0_0", danger.approach_origin) + self.assertEqual(("maps/danger/entry",), danger.approach_maps) + self.assertEqual("maps/danger/entry", danger.approach_worst_map) + self.assertEqual(1.0, danger.spot_safety_score) + self.assertGreater(danger.approach_danger, 300.0) + self.assertAlmostEqual(300.0 / danger.approach_danger, + danger.approach_safety_score) + self.assertEqual(danger.approach_safety_score, danger.safety_score) + self.assertIn("fire×3", danger.approach_danger_flags) + self.assertIn("acid×3", danger.approach_danger_flags) + self.assertIn("entry L32 > allowed L15", danger.approach_danger_flags) + + def test_approach_threat_applies_character_protections(self): + bare = self.results(self.options())[DANGER] + protected = self.results(self.options( + player_protections=(("acid", 50), ("fire", 50))))[DANGER] + self.assertLess(protected.approach_danger, bare.approach_danger) + self.assertGreater(protected.safety_score, bare.safety_score) + + def test_safe_approach_leaves_identical_circuit_unchanged(self): + results = self.results(self.options()) + danger = results[DANGER] + safe = results[SAFE] + self.assertEqual(("maps/safe/entry",), safe.approach_maps) + self.assertEqual(0.0, safe.approach_danger) + self.assertEqual((), safe.approach_danger_flags) + self.assertEqual(1.0, safe.approach_safety_score) + self.assertEqual(safe.spot_safety_score, safe.safety_score) + self.assertEqual(danger.spot_safety_score, safe.spot_safety_score) + self.assertGreater(safe.safety_score, danger.safety_score) + self.assertGreater(safe.score, danger.score) + + def test_coordinate_seams_extend_the_approach(self): + results = self.results(self.options(circuit_size=1)) + far_room = next(result for result in results.values() + if result.map_paths == ("maps/danger/underground_city_1_0",)) + self.assertEqual(("maps/danger/entry", "maps/danger/underground_city_0_0"), + far_room.approach_maps) + self.assertLess(far_room.safety_score, 1.0) + + def test_relative_safety_mode_also_charges_the_approach(self): + results = self.results(self.options(max_health=0.0)) + danger = results[DANGER] + self.assertLess(danger.safety_score, danger.spot_safety_score) + + def test_ignore_approach_and_explicit_origin(self): + ignored = self.results(self.options(model_approach=False)) + danger = ignored[DANGER] + self.assertEqual("disabled", danger.approach_status) + self.assertEqual((), danger.approach_maps) + self.assertEqual(danger.spot_safety_score, danger.safety_score) + + savebed = self.results(self.options( + approach_origins=("maps/danger/underground_city_0_0",))) + danger = savebed[DANGER] + self.assertEqual("origin", danger.approach_status) + self.assertEqual(danger.spot_safety_score, danger.safety_score) + + def test_unreachable_spot_keeps_its_own_safety(self): + results = self.results(self.options( + max_approach_maps=0)) + danger = results[DANGER] + self.assertEqual("unreachable", danger.approach_status) + self.assertTrue(danger.approach_unknown) + self.assertEqual((), danger.approach_danger_flags) + self.assertEqual(danger.spot_safety_score, danger.safety_score) + + def test_disconnected_spot_is_flagged_and_optionally_capped(self): + lost = self.results(self.options())[f"maps/lost/{LOST}"] + self.assertEqual("unreachable", lost.approach_status) + self.assertTrue(lost.approach_unknown) + self.assertEqual(lost.spot_safety_score, lost.safety_score) + capped = self.results(self.options( + unreachable_approach_safety=0.3))[f"maps/lost/{LOST}"] + self.assertEqual(0.3, capped.approach_safety_score) + self.assertEqual(min(0.3, capped.spot_safety_score), capped.safety_score) + reachable = self.results(self.options( + unreachable_approach_safety=0.3))[SAFE] + self.assertEqual(reachable.spot_safety_score, reachable.safety_score) + + def test_cli_json_exposes_approach_fields_and_options(self): + def run(*extra: str) -> dict: + stdout = io.StringIO() + with patch("sys.stdout", stdout): + main([ + "10", "--damage-per-attack", "40", "--attack-delay", "1", + "--max-health", "300", "--min-spawns", "1", + "--min-xp-fraction", "0", "--path", ROOM, + "--show-all-routes", "--json", + "--content-root", self.directory.name, + "--server-root", str(SERVER_ROOT), *extra, + ]) + return {item["path"]: item for item in json.loads( + stdout.getvalue())["results"]} + + danger = run()[DANGER] + self.assertEqual(["maps/danger/entry"], danger["approach_maps"]) + self.assertEqual("maps/world_0_0", danger["approach_origin"]) + self.assertLess(danger["safety_score"], danger["spot_safety_score"]) + self.assertIn("fire×3", danger["approach_danger_flags"]) + origin = run("--approach-origin", "/maps/danger/underground_city_0_0")[DANGER] + self.assertEqual("origin", origin["approach_status"]) + with self.assertRaises(SystemExit) as raised: + run("--approach-origin", "danger/nowhere") + self.assertIn("danger/nowhere", str(raised.exception)) + with self.assertRaises(SystemExit): + run("--approach-origins-only") + lost = run("--unreachable-approach-safety", "0.25")[f"maps/lost/{LOST}"] + self.assertEqual(0.25, lost["approach_safety_score"]) + ignored = run("--ignore-approach")[DANGER] + self.assertEqual("disabled", ignored["approach_status"]) + self.assertEqual(ignored["spot_safety_score"], ignored["safety_score"]) + + +class ApproachGraphTest(unittest.TestCase): + """Authored connectivity, origin handling and the bounded search.""" + + @classmethod + def setUpClass(cls): + cls.directory = tempfile.TemporaryDirectory() + root = Path(cls.directory.name) + (root / "arch").mkdir() + (root / "arch" / "test.arc").write_text(ARCHETYPES) + maps = root / "maps" + (maps / "g").mkdir(parents=True) + (maps / "t" / "sub").mkdir(parents=True) + (maps / "regions.reg").write_text("region r\nlongname R\nend\n") + + def write(path: str, **kwargs) -> None: + (maps / path).write_text(_map(path, "r", **kwargs)) + + # Reviewer repro: O->N->M->x2->x1->S at danger 0 and M->Y(50)->S. + for source, targets in { + "O": ("N",), "N": ("M",), "M": ("x2", "Y"), "x2": ("x1",), + "x1": ("S",), "Y": ("S",), "S": ()}.items(): + write(f"g/{source}", exits=tuple((target, 0, 0) for target in targets)) + # Town: the bedroom's door joins the surface tile world_0_0, which is + # therefore a charged origin; the savebed itself is free. + write("world_0_0", exits=( + ("t/via_world", 0, 0), ("t/only_world", 0, 1), ("t/bedroom", 0, 2), + ("t/hall", 0, 3), ("t/vault", 0, 4, 1, 1), ("t/split", 0, 5, -1, -1), + ("t/cave_7_0", 1, 0, 1, 1), ("t/paired", 1, 2, 1, 1))) + write("t/bedroom", exits=(("via_world", 0, 0), ("../world_0_0", 1, 1)), + extra="arch bed_save\nx 2\ny 2\nend\n") + write("t/via_world") + write("t/only_world") + # An islet: a surface tile with no seam to a town. Its exit leads to + # t/under, which is otherwise only reachable through the hall. + write("world_5_5", exits=(("t/under", 2, 2),)) + write("t/under", exits=(("../world_5_5", 1, 1),)) + write("t/hall", exits=(("under", 1, 1),)) + # A walled-off surface pocket on a town tile: only its west half is + # joined to the inn, the east half is entered from below. + write("world_3_0", wall_x=3, exits=(("t/inn2", 1, 1), ("t/pocket", 5, 5))) + write("t/inn2", exits=(("../world_3_0", 0, 0, 1, 1),), + extra="arch bed_save\nx 2\ny 2\nend\n") + write("t/pocket", exits=(("../world_3_0", 0, 0, 5, 5),)) + # A dungeon dead end: the vault's east half holds the only exit to + # the secret room, but arrivals land in its west half. + write("t/vault", wall_x=3, exits=(("secret", 5, 5),)) + write("t/secret", exits=(("vault", 0, 0, 5, 5),)) + # Arrival by enter_x/enter_y when the exit's hp/sp is -1. + write("t/split", wall_x=3, header=("enter_x 5", "enter_y 5"), + exits=(("east_spot", 5, 4), ("west_spot", 1, 1))) + write("t/east_spot") + write("t/west_spot") + # Auto-linked exits: no path, hp/sp -1 and a shared sub_type. The pair + # on t/paired joins its two halves; another pairs across a tile seam. + def paired(x: int, y: int, sub_type: int) -> str: + return (f"arch exit\nx {x}\ny {y}\nsub_type {sub_type}\n" + "hp -1\nsp -1\nend\n") + + write("t/paired", wall_x=3, exits=(("beyond", 5, 5),), + extra=paired(1, 1, 7) + paired(5, 1, 7) + paired(1, 4, 8)) + write("t/beyond") + write("t/pair_0_0", extra=paired(5, 2, 3)) + write("t/pair_1_0", extra=paired(1, 2, 3) + paired(2, 2, 4)) + # Walk-blocking lines at x=1 and x=10 split t/wide into three parts. + # A caster at (3, 2) with detection radius 3 reaches across the first + # line but not the far part. + wide = ["arch map", "name wide", "width 16", f"height {SIZE}", + "difficulty 10", "region r", "end"] + for y in range(SIZE): + for x in range(16): + if x not in (1, 10): + wide += ["arch floor", f"x {x}", f"y {y}", "end"] + wide += ["arch spawn_point", "x 3", "y 2", "arch caster", "type 83", + "end", "end"] + (maps / "t" / "wide").write_text("\n".join(wide) + "\n") + # Seams join only the components that touch across the edge. + write("t/cave_7_0", wall_y=3) + write("t/cave_8_0", wall_y=3) + # A bed_save carried in a container does not make a savebed map. + write("t/storeroom", extra="arch wall\nx 1\ny 1\n" + "arch bed_save\nend\nend\n") + # Path resolution, tile paths, nested exits and missing targets. + write("t/sub/deep", exits=(("../up", 0, 0), ("/t/abs_target", 1, 1), + ("nowhere", 2, 2)), + header=("tile_path_2 ../tiled_east",)) + write("t/up") + write("t/abs_target") + write("t/tiled_east") + write("t/nest", spawns=(("rat", 1, 1),), + extra="arch spawn_point\nx 3\ny 3\n" + "arch exit\nslaying hidden\nend\nend\n" + "arch wall\nx 4\ny 4\narch exit\nslaying hidden\nend\nend\n") + write("t/hidden") + # Server-style tiling for any prefix: diagonals link, depths do not. + write("t/cave_1_1") + write("t/cave_2_2") + write("t/cave_2_1_-1") + write("t/cave_1_1_-1") + cls.analyzer = FarmingAnalyzer(root, SERVER_ROOT) + cls.template = ApproachDangerTest.options(path_pattern=None) + + @classmethod + def tearDownClass(cls): + cls.directory.cleanup() + + def predecessors(self, key: str) -> tuple[str, ...]: + """Maps with a move into any walkable part of ``key``.""" + labels = set(self.analyzer._components(key).values()) + return tuple(sorted({ + source for label in labels + for source, _label in self.analyzer._predecessors((key, label)) + if source != key})) + + def approach(self, spot: str, threats: dict[str, float], **changes) -> MapResult: + options = replace(self.template, **changes) + required = { + item.name: 0 for item in fields(MapResult) + if item.default is MISSING and item.default_factory is MISSING} + required.update(path=spot, name=spot, region="r") + result = MapResult(**required, map_paths=(f"maps{spot}",)) + + def threat(key, _options, _component=None): + danger = threats.get(key, 0.0) + return ApproachThreat(danger, danger, 1, ("fire×1",) if danger else ()) + + with patch.object(self.analyzer, "_approach_threat", side_effect=threat): + self.analyzer._apply_approach(result, options) + return result + + def test_hop_limited_search_keeps_a_shorter_more_dangerous_path(self): + result = self.approach( + "/g/S", {"/g/Y": 50.0}, max_approach_maps=3, + approach_origins=("/g/O",), approach_origins_only=True) + self.assertEqual("path", result.approach_status) + self.assertEqual(("maps/g/N", "maps/g/M", "maps/g/Y"), result.approach_maps) + self.assertEqual(50.0, result.approach_danger) + self.assertEqual("maps/g/Y", result.approach_worst_map) + unlimited = self.approach( + "/g/S", {"/g/Y": 50.0}, approach_origins=("maps/g/O",), + approach_origins_only=True) + self.assertEqual(0.0, unlimited.approach_danger) + self.assertEqual(("maps/g/N", "maps/g/M", "maps/g/x2", "maps/g/x1"), + unlimited.approach_maps) + + def test_surface_entrances_are_charged_and_savebeds_are_free(self): + threats = {"/world_0_0": 70.0, "/t/bedroom": 90.0} + only_world = self.approach("/t/only_world", threats) + self.assertEqual("path", only_world.approach_status) + self.assertEqual((), only_world.approach_maps) + self.assertEqual("maps/world_0_0", only_world.approach_origin) + self.assertEqual(70.0, only_world.approach_danger) + self.assertEqual("maps/world_0_0", only_world.approach_worst_map) + self.assertEqual(("fire×1",), only_world.approach_danger_flags) + via_bed = self.approach("/t/via_world", threats) + self.assertEqual("maps/t/bedroom", via_bed.approach_origin) + self.assertEqual(0.0, via_bed.approach_danger) + explicit = self.approach( + "/t/only_world", threats, approach_origins=("/world_0_0",), + approach_origins_only=True) + self.assertEqual(0.0, explicit.approach_danger) + unreachable = self.approach( + "/t/via_world", threats, approach_origins=("/g/O",), + approach_origins_only=True) + self.assertEqual("unreachable", unreachable.approach_status) + self.assertTrue(unreachable.approach_unknown) + + def test_islet_surface_exit_does_not_count(self): + self.assertFalse(self.analyzer._surface_origin(("/world_5_5", 0))) + self.assertTrue(self.analyzer._surface_origin(("/world_0_0", 0))) + under = self.approach("/t/under", {"/t/hall": 80.0}) + self.assertEqual("maps/world_0_0", under.approach_origin) + self.assertEqual(("maps/t/hall",), under.approach_maps) + self.assertEqual(80.0, under.approach_danger) + + def test_surface_pocket_entered_only_from_below_does_not_count(self): + labels = self.analyzer._components("/world_3_0") + west, east = labels[(1, 1)], labels[(5, 5)] + self.assertNotEqual(west, east) + self.assertTrue(self.analyzer._surface_origin(("/world_3_0", west))) + self.assertFalse(self.analyzer._surface_origin(("/world_3_0", east))) + pocket = self.approach("/t/pocket", {}) + self.assertEqual("unreachable", pocket.approach_status) + + def test_dungeon_dead_end_reachable_only_from_inside(self): + secret = self.approach("/t/secret", {}) + self.assertEqual("unreachable", secret.approach_status) + vault = self.analyzer._components("/t/vault") + self.assertIn(("/t/secret", 0), self.analyzer._predecessors( + ("/t/vault", vault[(5, 5)]))) + self.assertEqual((), tuple( + node for node in self.analyzer._predecessors(("/t/vault", vault[(5, 5)])) + if node[0] != "/t/secret")) + + def test_exit_arrival_uses_enter_x_and_enter_y(self): + east = self.approach("/t/east_spot", {"/t/split": 5.0}) + self.assertEqual("path", east.approach_status) + self.assertEqual(("maps/t/split",), east.approach_maps) + self.assertEqual("unreachable", self.approach("/t/west_spot", {}).approach_status) + + def test_seams_join_only_touching_components(self): + west, east = (self.analyzer._components(f"/t/cave_{x}_0") for x in (7, 8)) + north = (west[(1, 1)], "/t/cave_8_0", east[(1, 1)], True) + south = (west[(1, 5)], "/t/cave_8_0", east[(1, 5)], True) + edges = self.analyzer._out_edges("/t/cave_7_0") + self.assertIn(north, edges) + self.assertIn(south, edges) + self.assertNotIn((west[(1, 1)], "/t/cave_8_0", east[(1, 5)], True), edges) + self.assertEqual("path", self.approach("/t/cave_8_0", {}).approach_status) + south_spot = replace(self.template) + required = { + item.name: 0 for item in fields(MapResult) + if item.default is MISSING and item.default_factory is MISSING} + required.update(path="s", name="s", region="r") + result = MapResult(**required, map_paths=("maps/t/cave_8_0",), + spawn_points=(("maps/t/cave_8_0", 1, 5),)) + self.analyzer._apply_approach(result, south_spot) + self.assertEqual("unreachable", result.approach_status) + + def test_paired_exits_link_same_sub_type_within_five_tiles(self): + labels = self.analyzer._components("/t/paired") + west, east = labels[(1, 1)], labels[(5, 1)] + edges = self.analyzer._out_edges("/t/paired") + self.assertIn((west, "/t/paired", east, False), edges) + self.assertIn((east, "/t/paired", west, False), edges) + self.assertEqual("path", self.approach("/t/beyond", {}).approach_status) + self.assertEqual( + (("/t/pair_1_0", 1, 2),), + self.analyzer._paired_exits( + "/t/pair_0_0", self.analyzer._world().nodes["/t/pair_0_0"].exits[0])) + + def test_threat_charges_spawns_whose_radius_reaches_the_component(self): + labels = self.analyzer._components("/t/wide") + west, middle, east = labels[(0, 0)], labels[(4, 4)], labels[(12, 0)] + self.assertEqual(3, len({west, middle, east})) + threat = self.analyzer._approach_threat + behind_line = threat("/t/wide", self.template, west) + own = threat("/t/wide", self.template, middle) + far = threat("/t/wide", self.template, east) + self.assertGreater(behind_line.pack_danger, 0.0) + self.assertEqual(own.pack_danger, behind_line.pack_danger) + self.assertIn("caster×1", behind_line.flags) + self.assertEqual(0.0, far.pack_danger) + self.assertEqual(own.pack_danger, + threat("/t/wide", self.template).pack_danger) + + def test_savebed_detection_ignores_carried_beds(self): + self.assertEqual( + {"/t/bedroom", "/t/inn2"}, + {key for key, _label in self.analyzer._savebed_nodes()}) + self.assertEqual(frozenset({"/world_0_0", "/world_3_0", "/world_5_5"}), + self.analyzer._map_index()[1]) + + def test_exit_and_tile_path_resolution(self): + self.assertEqual(("/t/sub/deep",), self.predecessors("/t/up")) + self.assertEqual(("/t/sub/deep",), self.predecessors("/t/abs_target")) + self.assertEqual(("/t/sub/deep",), self.predecessors("/t/tiled_east")) + self.assertNotIn("/t/sub/nowhere", self.analyzer._map_index()[0]) + self.assertEqual("/t/up", FarmingAnalyzer._resolve_map_path( + "/t/sub/deep", "../up")) + self.assertEqual("/t/abs_target", FarmingAnalyzer._resolve_map_path( + "/t/sub/deep", "/t/abs_target")) + self.assertIsNone(FarmingAnalyzer._resolve_map_path("/t/sub/deep", " ")) + + def test_exits_carried_in_spawn_points_or_containers_are_ignored(self): + self.assertEqual((), self.predecessors("/t/hidden")) + self.assertEqual("unreachable", self.approach("/t/hidden", {}).approach_status) + + def test_server_tiling_links_diagonals_but_not_depths(self): + self.assertEqual(("/t/cave_2_2",), self.predecessors("/t/cave_1_1")) + self.assertEqual(("/t/cave_1_1",), self.predecessors("/t/cave_2_2")) + self.assertEqual(("/t/cave_1_1_-1",), self.predecessors("/t/cave_2_1_-1")) + self.assertEqual(("/t/cave_2_1_-1",), self.predecessors("/t/cave_1_1_-1")) + self.assertEqual(("cave", 2, 1, -1), + FarmingAnalyzer._tile_coordinates("cave_2_1_-1")) + self.assertIsNone(FarmingAnalyzer._tile_coordinates("ruins_0101")) + self.assertIsNone(FarmingAnalyzer._tile_coordinates("cave_1")) + + def test_sequential_exposure_counts_partial_aggression_once(self): + # Two certain monsters: the second is charged while the first dies. + self.assertEqual(30.0, FarmingAnalyzer._sequential_exposure( + [(1.0, 1.0, 10.0, 0.0), (1.0, 1.0, 10.0, 0.0)])) + # A monster that is aggressive half the time costs half as much. + self.assertEqual(5.0, FarmingAnalyzer._sequential_exposure( + [(0.5, 1.0, 10.0, 0.0)])) + + def test_resolve_map_key_accepts_content_and_map_root_paths(self): + for spelling in ("/t/up", "t/up", "maps/t/up", "/maps/t/up"): + self.assertEqual("/t/up", self.analyzer.resolve_map_key(spelling)) + self.assertIsNone(self.analyzer.resolve_map_key("/t/missing")) + + +UNDERGROUND_CITY = (ROOT / "maps" / "shattered_islands" / "strakewood_island" / + "underground_city") + + +@unittest.skipUnless((UNDERGROUND_CITY / "underground_city_0_0").is_file(), + "requires the sibling content checkout") +class UndergroundCityEntranceTest(unittest.TestCase): + """Regression for the 2026-11-14 deaths on the Underground City entrance.""" + + @classmethod + def setUpClass(cls): + cls.analyzer = FarmingAnalyzer() + + @staticmethod + def sera(max_health: float, **changes) -> AnalysisOptions: + """Level 36 slash melee, no fire, acid or poison protection.""" + options = replace( + ApproachDangerTest.options(path_pattern=None), + player_level=36, character_level=36, player_ac=59, dps=0.0, + damage_per_attack=0.0, attack_delay=0.0, melee_damage=65, + weapon_class=46, weapon_speed=1.0, player_attacks=(("slash", 100),), + player_protections=(("cleave", 46), ("cold", 9), ("impact", 42), + ("pierce", 41), ("slash", 57)), + max_health=max_health) + return replace(options, **changes) + + def test_entrance_slime_cluster_is_one_sequential_encounter(self): + threat = self.analyzer._approach_threat( + "/shattered_islands/strakewood_island/underground_city/" + "underground_city_0_0", self.sera(322.0)) + # Three brown cave puddings and an ochre cave jelly at (17-23, 1-3) + # all reach one pull point; killed in turn they deal ~288 damage. + self.assertEqual(("fire×3", "acid×1", "poison×1"), threat.flags) + self.assertGreater(threat.pack_danger, 244.0) + self.assertLess(threat.pack_danger, 322.0) + + def test_spot_behind_the_entrance_loses_safety_at_measured_health(self): + results = self.analyzer.scan(self.sera( + 244.0, circuit_size=1, path_pattern=r"underground_city_4_2$")) + spot = next(result for result in results + if result.map_paths[0].endswith("underground_city_4_2")) + self.assertIn( + "maps/shattered_islands/strakewood_island/underground_city/" + "underground_city_0_0", spot.approach_maps) + self.assertEqual(1.0, spot.spot_safety_score) + self.assertLess(spot.safety_score, 0.9) + labels = {flag.split("×")[0] for flag in spot.approach_danger_flags} + self.assertLessEqual({"fire", "acid", "poison"}, labels) + + def test_circuits_no_longer_use_the_inside_only_lake_exit(self): + results = self.analyzer.scan(self.sera( + 244.0, path_pattern=r"underground_city_[0-4]_[0-4]$")) + city = [result for result in results + if "underground_city" in result.path and result.approach_status == "path"] + self.assertTrue(city) + # world_2_69's exit_green stands on a two-tile pocket reached only + # from inside the city, so it is not an origin. + self.assertFalse(any(result.approach_origin.endswith("/world_2_69") + for result in city)) + prefix = ("maps/shattered_islands/strakewood_island/underground_city/" + "underground_city_") + for members in (("2_2", "2_3", "3_1", "3_2"), ("0_4", "1_2", "1_3", "1_4")): + circuit = next( + result for result in results + if sorted(result.map_paths) == [prefix + member for member in members]) + self.assertTrue( + prefix + "0_0" in circuit.approach_maps or + prefix + "5_2_-1" in circuit.approach_maps, circuit.approach_maps) + self.assertLess(circuit.safety_score, 0.9) + labels = {flag.split("×")[0] for flag in circuit.approach_danger_flags} + self.assertLessEqual({"fire", "acid", "poison"}, labels) + + +if __name__ == "__main__": + unittest.main()