diff --git a/farming_analyzer/README.md b/farming_analyzer/README.md index cc8b918..2ca424d 100644 --- a/farming_analyzer/README.md +++ b/farming_analyzer/README.md @@ -346,6 +346,323 @@ JSON fields; existing fields keep their names and types: `fire×3`), plus a `MAP L > allowed L` entry for any charged map whose monsters exceed the `--max-level-gap` allowance. +## Encounter model and combat styles + +The older safety estimate multiplies one monster's danger by the largest +*direct* aggro pack (`max_aggro_pack`). Authored spawns are usually more +than three tiles apart, so that pack is almost always one, and with +`--max-health` every map whose single monster fits in one health bar scores +safety 1.0. In the Burnt Forest the playtester died four times on maps that +all scored 1.0. Packs of three to eight formed there from wanderers, chases +and retreats past other spawns. The encounter model (`encounter.py`) replaces +that estimate with explicit, documented heuristics. Each cites the classic +server code it stands for (`classic/server/src`); the analyzer reads that code +and the authored content as data and copies none of it. + +**What it reads per spawn.** + +- position, and aggressive or passive (`unaggressive`); +- detection radius `item_power`. The server adds 3 tiles only for a + monster that already has an enemy or attacker (`types/monster.c` + 1084-1100) and halves the radius for sleeping or blind monsters; the + halving is not modelled; +- chase range `max(9, item_power)`: an engaged monster keeps its target + until it is that far away for more than 12 checks (`types/monster.c` + 558-580, `include/global.h` 175-179). It is reported (`chase_range`) but + not used by the estimate; the style's bad-pull footprint stands in for a + chase or retreat; +- the per-action ally-call chance `1 / monster_signal_chance[Int]`, read + from `server/living.c` 154-162 (zero means never). Only spawned monsters + call and answer: a directly placed monster has no spawn-point record + (`types/monster.c` 363-374). Allies answer when they sit on a spawn point + with the same `title`, or when they share the caller's faction and stand + within `item_power * 1.5 - 1` tiles of it (`types/monster.c` 288-420). A + called passive monster fights too. Deviation: factions allied only + through an alliance parent (`faction_is_alliance()`, `server/faction.c` + 645) are not linked; +- `random_move` wanderers and their `item_race` x `item_level` box + (unbounded when both are 0; `types/monster.c` 1160-1225); +- movement speed from `set_mobile_speed()` (`server/living.c` 1851-1875): + 2x authored speed idle and 4x fighting, or 1x and 3x with `slow_move`; + `stand_still` never moves; +- casters (`can_cast_spell`), whose `ability` objects name a spell index in + `include/spellist.h`; the cast archetype's `attack_*` gives the damage + types; +- archers (`can_use_bow`, reported as `missile`). + +Spawns on the eight tiled neighbours are shifted into the map's frame and +included when they come within 12 tiles of it, so a pull near a seam sees +them. + +The ally-call table and the spell table come from `server/living.c` and +`include/spellist.h`. When either is missing the scan continues without +ally calls, or without spells and damage types, and adds a warning to +`warnings` in JSON (and a `Warning:` line in text and the report). A +consumer that pins a server source subset, such as the playtester lock's +`classic_server.required_paths`, must include both files. + +**Terrain.** From walkable tiles (terrain flags minus `no_pass` blockers; +doors count as open): + +- walkable regions (8-connected); +- open tiles, where all 8 neighbours are walkable; +- open fields, connected tiles with a clear 5x5 square; +- **kite room**: the share of tiles with at least 6 of 8 walkable + neighbours; past a crossable seam the neighbouring map counts as open; +- one-tile-wide corridor tiles, and **doorways** (corridor runs of at most + two tiles); +- dead ends; +- crossable seam tiles per cardinal direction (directions with none are + omitted). + +**A pull.** For each target spawn the character picks a pull square: a +walkable tile within the target's detection radius (adjacent for a passive +target; within the kite distance for kiting styles). A wanderer can be met +anywhere it roams. Single-pull styles take the square with the fewest +expected joiners, pack styles the most. During the fight, which lasts the +target's kill time: + +- a static aggressive spawn joins when its radius reaches the pull square + plus the style's footprint, and hits from the first second; +- a wanderer joins with the share of its walkable wander area within that + reach, widened by its random-walk spread `sqrt(idle tiles per second x + fight seconds)`. The part already within reach at the start hits at once, + the rest arrives half-way through the fight; +- an ally joins with the chance that the target's call succeeds at least + once in the fight (`1 - (1 - chance)^(actions)`), half-way through; +- melee monsters in another walkable region never join; casters and archers + can (line of sight is not modelled). + +The **bad pull** (worst case) adds a 3-tile margin to every aggressive +monster's radius and uses the style's worst footprint. The margin matches +the server's engaged widening, but applying it to idle bystanders is a +deliberate safety margin for a fight that drifts or a retreat, not server +behaviour. The bad pull also adds every wanderer and ally call that is more +likely than not to join. Those beyond the ordinary reach arrive half-way +through. + +A target the character cannot hurt (infinite kill time, for example a +fire-only character against a fire-immune monster) that is aggressive and +deals damage makes the pull **not farmable**. Its need is infinite and the +map's encounter safety 0, and a `not farmable` reason names the monster. An +unkillable monster that deals no damage is left alone: it is never pulled, +and a `left alone` reason names it. Single-target styles also leave alone +an unkillable *passive* monster. An AoE style does not: AoE damages every +monster inside its footprint (the kite distance), and a damaged monster +turns on its attacker (`types/monster.c` 479-512). So under `aoe-kite`, +passive monsters inside the footprint join the pull from the first second, +and a passive, damaging, unkillable one makes the pull not farmable. Spreads, calls and arrival times +for such a pull use a 120-second horizon so nothing overflows. + +**The clear.** Pulls are taken easiest first. After each pull its expected +joiners are removed from the map, so a wanderer that joined an early pull is +not counted again. The map's `expected_pack` and `encounter_need` come from +the hardest pull whose target is still alive with probability at least 0.5. +This models arriving on a fully populated map, which is how the playtester +died. Steady-state respawn order is not modelled. + +**Cost of a pull** (`encounter_need`, HP). An expected-value timeline: each +arrived monster hits for its incoming DPS (the same server-derived melee +model as the rest of the analyzer, against the character's AC and +protections) until it dies. The character kills arrived monsters one at a +time, cheapest first (kill seconds per DPS), and heals +`--healing-per-second` throughout without banking healing. The need is the +deepest health deficit plus each monster's secondary-risk bonus (casting, +bows, drain, poison, ...). + +**Combat styles** (`--combat-style`): + +| Style | Footprint (bad pull) | Behaviour | +| --- | --- | --- | +| `melee` | 1 (3) | single pulls, fight in place | +| `melee-pack` | 2 (4) | pulls the cluster deliberately and fights it | +| `ranged-kite` | 1 (kite distance) | opens from range, single target, steps away | +| `aoe-kite` | kite distance (+3) | gathers packs; each attack hits `--targets-per-attack` (or the `--aoe-radius` estimate) | + +Kiting styles keep a melee monster that is slower than the character away +only where there is kite room, and only while escape directions stay open. +Each attacker beyond the first is assumed to close one of eight +directions, so a slow monster's uptime is `1 - kite room x max(0, 1 - +(attackers - 1) / 8)`. Nine or more attackers hit a kiter as hard as a +melee character. Stepping away costs attack time: the kill takes `1 + open +directions x monster speed / player speed` times longer, where open +directions is the same `max(0, 1 - (attackers - 1) / 8)`, so a pinned kiter +pays no stepping-away time. Each pull is also costed standing and fighting +the same monsters, and a kiting style takes the cheaper of the two, so +kiting never costs more than standing for the same pack. + +Accepted limits of that comparison: + +- It is made within one pull only. Across styles a kiter can still rate + worse than melee, because the bad pulls hold different monsters: the + kiter's bad-pull footprint is the kite distance (4 by default) against + melee's 3, and its pull squares differ. On world_16_74, for example, + `ranged-kite` rates 0.78 against melee's 0.79. +- The standing alternative reuses the kiting fight's timeline for the + wanderer spread, ally calls and late arrivals; only damage uptime and + kill time switch to standing. The effect is small either way. A monster at least as fast as +the character, and every caster or archer, hits at full rate in every +style. A small slow pack is therefore cheap for a kiter and expensive for a +melee healer, while a huge pack is not safe for either. + +Player movement uses the same conversion as route timing (see "Topology, +AoE, and encounter simulation"). The displayed speed is added every server +tick and a move costs one unit (`socket/request.c` `CS_STAT_SPEED`, +`server/main.c` `speed_left`), so tiles per second = speed / tick length. +Without `--character-speed` the encounter model assumes displayed speed 1.0 +(`DEFAULT_CHARACTER_SPEED`), which is 8 tiles per second at the default 125 +ms tick. Pass the character's real speed. `--kite-distance` defaults to 4. + +**Safety.** With `--max-health`: + +- expected-pull safety is `1 - need / HP` (the share of the health bar left + at the trough); +- bad-pull safety is `1 / (1 + bad-pull need / HP)`, which stays ordered + where the bad pull costs several health bars; +- `encounter_safety` is `0.75 x expected + 0.25 x bad pull`. + +Without `--max-health`, both parts are relative to the cheapest pull of the +scan. A circuit takes every pull, pack, need, safety and reason field from +its hardest member (lowest encounter safety, then highest need), so they +describe one map. Counts, density, doorways and seam spawns are +circuit-wide. + +**Backward compatibility.** Without `--combat-style`, `safety_score` and +every other existing field are unchanged. The encounter fields are reported +for the `melee` style with `encounter_applied: false`. With `--combat-style`, +`spot_safety_score` is the lower of the old estimate and `encounter_safety`, +and the approach cap applies as before. `--ignore-encounters` skips the +model. JSON output now carries `"schema_version": 2`; version 1 had no +version field. New result fields (in `results`, `groups[].representative` +and `rankings`): + +- `encounter_style`, `encounter_applied`; +- `expected_pack`: attackers in the hardest expected pull; + `mean_expected_pack`: across the clear; `worst_pack`: the bad pull; +- `encounter_need`, `encounter_worst_need` (HP); +- `encounter_safety`, `encounter_expected_safety`, `encounter_worst_safety`; +- `encounter_pull`: `[map, x, y]` of the hardest pull square; +- `encounter_reasons`: short sentences behind the rating; +- `wanderer_spawns`, `caster_spawns`, `ranged_spawns`, `linking_spawns`; +- `spawn_density` (spawns per 100 walkable tiles), `doorways`, + `seam_spawns` (aggressive neighbour spawns whose engaged reach crosses + the edge). + +Example for the playtester (level 37 melee with minor healing): + +```sh +python3 -m tools.farming_analyzer 37 --melee-damage 82 --weapon-class 44 \ + --weapon-speed 3.0 --character-level 37 --max-health 333 --player-ac 58 \ + --player-protection impact=38 --player-protection cleave=39 \ + --character-speed 0.8 --combat-style melee --healing-per-second 5.5 +``` + +Not modelled: line of sight, doors opening and closing, scripted AI, pace, +circle and waypoint movement (`move_type`), monsters fleeing, steady-state +respawn order, ranged-attack cadence (a shooter's DPS uses its melee +cadence), and player decisions mid-fight. + +## Difficulty report + +`python3 -m tools.farming_analyzer report` rates authored maps for map makers +and map editors such as Tilewright. It has no player arguments. It rates +each map for a **reference character** per level band and each style: + +- HP `9 x level`, AC `1.6 x level`, DPS `0.7 x level`, healing `0.15 x level` + HP/s; +- 35% physical protection, speed 1.0, four AoE targets. + +The defaults are calibrated on the playtester at level 37 (333 HP, AC 58, +about 25 melee DPS, 5.5 HP/s healing). Override them with `--hp-per-level`, +`--ac-per-level`, `--dps-per-level`, `--healing-per-level`, +`--physical-protection` and `--speed`. + +```sh +python3 -m tools.farming_analyzer report --path 'world_1[5-8]_7[2-6]$' +python3 -m tools.farming_analyzer report --levels 20,30,40 \ + --styles melee,ranged-kite --exclude-region 'Strakewood Island' --json +``` + +`--levels auto` (the default) rates each map at its average monster level +rounded to 5, and 5 levels either side. `--time`, `--include-static` and +`--kite-distance` behave as in the ranking. Text output lists zones, then +maps with their ratings and top hotspots. + +The JSON schema (`schema` `atrinik.farming_analyzer.difficulty_report`, +`schema_version` 1) is meant for editors to read. New fields may be added; +renamed or removed fields bump `schema_version`. + +- `warnings`: missing server sources that degraded the model (see above). +- `reference_character`, `styles` (name to description), `rating_scale`: + `easy` ≥ 0.85, `fair` ≥ 0.65, `hard` ≥ 0.40, `deadly` > 0, `lethal` 0. +- `maps[]`, one per map with at least one attackable monster (not + friendly, `no_attack` or invulnerable, with no faction or the `monsters` + faction) on a spawn + point active at `--time`, passive ones included, or such a directly + placed monster with `--include-static`: + - `path` (content-relative), `name`, `region`, `width`, `height`, + `monster_levels` `{min, max, average}`, `levels` (bands rated); + - `terrain`: `walkable_tiles`, `walkable_fraction`, `regions`, + `largest_region`, `open_fraction`, `kite_room`, `open_field_tiles`, + `open_field_center` `[x, y]` or null, `corridor_tiles`, `doorways` + `[[x, y], ...]`, `dead_ends`, `seams` `{north|east|south|west: tiles}`; + - `spawns[]`: `x`, `y`, `name`, `level`, `aggressive` (probability), + `detection_radius`, `engaged_radius`, `chase_range`, `link_chance` (per AI + action), `link_group`, `faction`, `engaged_speed`, `idle_speed` (tiles + per second), `wander` (`{x0, y0, x1, y1, tiles}` or null), `caster`, + `ranged`, `damage_types`, `melee_types`, `spells`, `pull` + (`{x, y, expected, worst}`: the pull square in the modelled clear); + - `hotspots[]`: `kind`, `x`, `y` (null for `seam_reach`), `spawns`, + `monsters`, `reason`, plus kind-specific fields. Kinds: + - `hardest_pull` (with `target`); + - `dense_cluster`: aggressive spawns chained within engaged reach; + - `wanderer_overlap` or `wanderers` (with `overlap` and `coverage`); + - `caster` or `ranged` (with `damage_types`, `spells`, `passive`); + - `guarded_chokepoint`: the three doorways most within engaged reach; + - `seam_reach` (with `maps`); + - `hotspot_basis` `{level, style}`: spawns and hotspots come from the band + nearest the map's average monster level and the first style; + - `ratings[]`, one per level and style: `level`, `style`, `safety`, + `expected_safety`, `bad_pull_safety`, `rating`, `expected_attackers`, + `mean_attackers`, `bad_pull_attackers`, `expected_need`, + `bad_pull_need`, `health`, `hardest_pull` (`{x, y, target, monster}`), + `out_of_band` (monsters more than 5 levels above the band), and `reasons`. +- `zones[]`: maps grouped by region and map name: `region`, `name`, `maps`, + `monster_levels`, and `ratings[]` per level and style with `maps`, + `min_safety`, `mean_safety`, `max_safety`, `rating` (of the minimum) and + `hardest_map`. + +Coordinates are map tiles in the map's own frame. Neighbour-map spawns are +not listed in `spawns`; they appear as a `seam_reach` hotspot. + +## Encounter model: next increments + +This first increment delivers the per-map encounter model, style-aware +safety and the report. Planned next steps, in order of value: + +1. **Line of sight and doors**: use authored view blockers so walled + rooms stop casters and detection, as `perception_object_visible()` does. +2. **Retreat paths**: walk the route from the pull square to the nearest + exit or seam and charge the spawns within engaged reach of it, rather + than a disc footprint. This is what turned the 2026-11-25 retreats into + packs. +3. **Ranged cadence**: model spell `last_grace`/`magic` delays, the + one-in-`Dex` cast roll, and bow fire chance instead of melee cadence for + shooters, and use spell damage from `spellist.h` base and level damage. +4. **Steady state**: a second clear after respawn timing, for farming + rather than arrival. +5. **Patrols**: `move_type` circle, pace and waypoint movement as wander + areas. +6. **Zone routes**: rate a circuit along its traversal path, including the + seam crossings between member maps. +7. **Tilewright**: an overlay of the JSON report (hotspots, pull squares, + wander boxes, doorways) and per-edit re-rating. +8. **Server parity**: resolve faction alliance parents for ally calls and + halve detection for authored sleeping or blind monsters. +9. **CI**: run the analyzer suite in `Check`, adding a locked + `atrinik/classic` `server/src` checkout next to the existing locked + content checkout. + ## Profiles, rankings, diagnostics, and training Save validated character arguments and reuse them: @@ -578,6 +895,24 @@ analyzer stays standard-library only. Consumers supply `--content-root` and ## Validation +`test_encounter.py` covers the encounter model on synthetic spawns and +maps: pull cost, terrain structure, packs, wanderers, ally calls, walls, +styles and hotspots. It also checks the scan's backward compatibility, the +CLI and the report schema. With the content checkout present, +`BurntForestTest` checks the playtester's live level 37 melee-healer kit: +world_16_74 forms packs (bad pull at least 2) and rates clearly below its +old score; the sparse southern maps (world_15_75, world_15_76, world_16_75, +world_16_76) rate safer; world_17_72 rates hardest; AoE kiting the big +treant packs is not safe; the Forgotten Graveyard's night skeleton mages +are flagged as fire casters; and a whole-content scan of a fire-only +character, against fire-immune monsters, finishes with those maps marked +not farmable. It is content-dependent, so it asserts ranges and orderings, +and it is skipped with a `CONTENT-DEPENDENT` reason without the checkout. +The analyzer suite needs the classic server source and content checkouts, +so it is not part of CI yet. That is deferred scope, not a limitation: +`check.yml` already checks out content pinned by a lock, and a locked +`atrinik/classic` `server/src` checkout can be added the same way. + Run the focused regression suite from the repository root: ```sh diff --git a/farming_analyzer/analyzer.py b/farming_analyzer/analyzer.py index 37d5272..0e92431 100644 --- a/farming_analyzer/analyzer.py +++ b/farming_analyzer/analyzer.py @@ -10,6 +10,7 @@ from typing import Iterable from .config import ( + ABILITY_TYPE, CONSUMABLE_TYPES, EXIT_TYPE, GEAR_TYPES, @@ -25,6 +26,7 @@ SPAWN_POINT_TYPE, STATUS_ATTACK_TYPES, ) +from . import encounter as enc from .experience import ExperienceModel from .models import ( AnalysisOptions, @@ -65,6 +67,53 @@ class ApproachThreat: 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 +# Displayed speed assumed for the encounter model without --character-speed. +DEFAULT_CHARACTER_SPEED = 1.0 + + +def read_signal_table(server_root: Path) -> tuple[int, ...]: + """monster_signal_chance[] from ``server/living.c``, or () when absent.""" + path = server_root / "server" / "living.c" + if not path.is_file(): + return () + match = re.search(r"monster_signal_chance\[[^\]]*\]\s*=\s*\{(.*?)\};", + path.read_text(errors="replace"), re.S) + if not match: + return () + body = re.sub(r"//[^\n]*|/\*.*?\*/", "", match.group(1), flags=re.S) + return tuple(int(item) for item in re.findall(r"-?\d+", body)) + + +def read_spell_table(server_root: Path) -> tuple[tuple[str, str], ...]: + """(name, cast archetype) per spell index from ``include/spellist.h``.""" + path = server_root / "include" / "spellist.h" + if not path.is_file(): + return () + source = path.read_text(errors="replace") + start = source.find("spells[NROFREALSPELLS]") + if start < 0: + return () + end = source.find("};", start) + body = source[source.find("{", start) + 1:end] + table: list[tuple[str, str]] = [] + depth = 0 + entry = "" + for character in body: + if character == "{": + depth += 1 + entry = "" + continue + if character == "}": + depth -= 1 + tokens = re.findall(r'"[^"]*"|\bNULL\b', entry) + if len(tokens) >= 4: + # id, name, ..., sound, cast archetype, extra. + arch = tokens[-2].strip('"') + table.append((tokens[1].strip('"'), "" if arch == "NULL" else arch)) + continue + if depth: + entry += character + return tuple(table) class FarmingAnalyzer: @@ -92,6 +141,17 @@ def __init__(self, root: Path = ROOT, server_root: Path = SERVER_ROOT): self._threat_cache: dict[tuple[str, int | None], ApproachThreat] = {} self._spawn_cache: dict[str, list[SpawnProfile]] = {} self._npc_factions = self._load_npc_factions() + self._signal_chances: tuple[int, ...] | None = None + # Missing server sources that degrade the encounter model. + self.source_warnings: set[str] = set() + self._spell_table: tuple[tuple[str, str], ...] | None = None + self._encounter_options: AnalysisOptions | None = None + # Option-independent walkable tiles, seam crossings and terrain. + self._terrain_cache: dict[str, tuple[ + set[tuple[int, int]], dict[int, set[tuple[int, int]]], + enc.TerrainStructure]] = {} + self._encounter_spawn_cache: dict[ + tuple[str, bool], tuple[list[SpawnProfile], list[CompetitorProfile]]] = {} self.rejections: list[tuple[str, str]] = [] def _load_npc_factions(self) -> set[str]: @@ -153,6 +213,37 @@ def _load_artifacts(self) -> None: "def_arch": definition, } + def _signal_table(self) -> tuple[int, ...]: + """Read monster_signal_chance[] from classic server/living.c. + + Entry ``n`` for a monster's Int means a one in ``n`` chance per AI + action to wake allies; zero means never (types/monster.c 363-366). + A missing or unreadable table disables ally calls with a warning. + """ + if self._signal_chances is None: + self._signal_chances = read_signal_table(self.server_root) + if not self._signal_chances: + self.source_warnings.add( + "server/living.c monster_signal_chance[] not found: " + "ally calls are not modelled") + return self._signal_chances + + def _spells(self) -> tuple[tuple[str, str], ...]: + """Read (name, cast archetype) for each spell index from spellist.h. + + Monster ``ability`` objects (type 110) name a spell by its index in + that table through ``sp``; the cast archetype's ``attack_*`` values + give the damage types. A missing table leaves casters flagged without + spells or damage types, with a warning. + """ + if self._spell_table is None: + self._spell_table = read_spell_table(self.server_root) + if not self._spell_table: + self.source_warnings.add( + "include/spellist.h spells[] not found: caster spells and " + "damage types are not reported") + return self._spell_table + def _constant(self, name: str, default: int) -> int: source = (self.server_root / "include" / "config.h").read_text(errors="replace") match = re.search(rf"^#define\s+{re.escape(name)}\s+(\d+)", source, re.MULTILINE) @@ -1332,7 +1423,7 @@ def _monster_profile(self, node: dict, map_difficulty: int, for profile in profiles: loot += profile.loot * (1.0 / count) flags = tuple(sorted(set(flag for profile in profiles for flag in profile.flags))) - return MonsterProfile( + profile = MonsterProfile( node["arch"], profiles[0].name, round(sum(p.level for p in profiles) / count), sum(p.xp for p in profiles) / count, sum(p.hp for p in profiles) / count, @@ -1353,6 +1444,53 @@ def _monster_profile(self, node: dict, map_difficulty: int, loot, flags, sum(p.attacks_to_kill for p in profiles) / count, ) + self._encounter_traits(node, attrs, profile) + return profile + + def _encounter_traits(self, node: dict, attrs: dict[str, str], + profile: MonsterProfile) -> None: + """Fill the level-independent encounter inputs of a monster.""" + profile.intelligence = max(0, _integer(attrs.get("int"))) + profile.faction = attrs.get("faction", "") or "" + # set_mobile_speed(): 2x authored speed idle (1x with slow_move) and + # 4x (3x) with an enemy; one tile per action, MAX_TIME seconds per tick. + base = abs(_number(attrs.get("speed"))) + if attrs.get("stand_still") == "1": + profile.engaged_speed = 0.0 + profile.idle_speed = 0.0 + else: + # living.c 1851-1875: slow_move drops the idle doubling only. + slow = attrs.get("slow_move") == "1" + profile.engaged_speed = base * (3.0 if slow else 4.0) / self.tick_seconds + profile.idle_speed = base * (1.0 if slow else 2.0) / self.tick_seconds + if attrs.get("random_move") == "1" and attrs.get("stand_still") != "1": + limit_x = _integer(attrs.get("item_race")) + limit_y = _integer(attrs.get("item_level")) + # move_randomly() only limits the walk when either is set. + profile.wander = ((-1, -1) if limit_x == 0 and limit_y == 0 + else (max(0, limit_x), max(0, limit_y))) + profile.attack_types = tuple(sorted( + attack for attack in SERVER_ATTACK_TYPES + if _integer(attrs.get(f"attack_{attack}")) > 0)) + if attrs.get("can_cast_spell") == "1": + table = self._spells() + names = [] + types: set[str] = set() + for child in node.get("children", []): + child_attrs = merged_attrs(child, self.archetypes) + if _integer(child_attrs.get("type")) != ABILITY_TYPE: + continue + index = _integer(child_attrs.get("sp")) + if not 0 <= index < len(table): + continue + name, cast_arch = table[index] + names.append(name) + cast_attrs = self.archetypes.get(cast_arch, {}).get("attrs", {}) + types.update( + attack for attack in SERVER_ATTACK_TYPES + if _integer(cast_attrs.get(f"attack_{attack}")) > 0) + profile.spells = tuple(sorted(set(names))) + profile.spell_types = tuple(sorted(types)) def _monster_at_level(self, node: dict, attrs: dict[str, str], level: int, options: AnalysisOptions) -> MonsterProfile: @@ -1500,7 +1638,8 @@ def _spawn_point(self, node: dict, map_difficulty: int, return SpawnProfile( normalized, respawn, "spawn", _integer(attrs.get("x")), _integer(attrs.get("y")), aggressive, - attempt_seconds, attempt_probability) + attempt_seconds, attempt_probability, + link_group=attrs.get("title", "") or "") def _static_monster(self, node: dict, map_difficulty: int, reset_timeout: int, options: AnalysisOptions) -> SpawnProfile | None: @@ -1641,6 +1780,224 @@ def _collect_spawns( spawns.append(spawn) return spawns, competitors + def _spawns_cached( + self, key: str, options: AnalysisOptions, include_static: bool, + ) -> tuple[list[SpawnProfile], list[CompetitorProfile]]: + """Collect a map's spawns once per option set (own and neighbour maps).""" + if self._encounter_options != options: + self._encounter_options = options + self._encounter_spawn_cache = {} + cache_key = (key, include_static) + cached = self._encounter_spawn_cache.get(cache_key) + if cached is None: + path = self.map_root / key.lstrip("/") + parsed = parse_blocks(path) if path.is_file() else {"header": None} + cached = (([], []) if parsed.get("header") is None else + self._collect_spawns(parsed, options, include_static=include_static)) + self._encounter_spawn_cache[cache_key] = cached + return cached + + def _encounter_spawn(self, spawn: SpawnProfile, key: str, + offset: tuple[int, int], own_map: bool) -> enc.EncounterSpawn: + """Convert one spawn into the encounter model's frame of reference.""" + candidates = spawn.candidates + total = sum(probability for probability, _profile in candidates) or 1.0 + + def average(attr: str) -> float: + return sum(probability * getattr(profile, attr) + for probability, profile in candidates) / total + + dominant = max(candidates, key=lambda item: item[0])[1] + kills = [profile.kill_seconds for _probability, profile in candidates] + kill_seconds = average("kill_seconds") if all(map(math.isfinite, kills)) else math.inf + bonus = sum(probability * max(0.0, profile.danger - profile.damage_taken) + for probability, profile in candidates + if math.isfinite(profile.damage_taken)) / total + signals = self._signal_table() + + def link(profile: MonsterProfile) -> float: + intelligence = min(profile.intelligence, len(signals) - 1) + chance = signals[intelligence] if signals and intelligence >= 0 else 0 + return 1.0 / chance if chance > 0 else 0.0 + + ox, oy = offset + nodes = self._world().nodes + node = nodes.get(key) + wander_tiles: frozenset[tuple[int, int]] = frozenset() + box = None + if dominant.wander is not None and node is not None: + limit_x, limit_y = dominant.wander + x0, x1 = ((0, node.width - 1) if limit_x < 0 else + (max(0, spawn.x - limit_x), min(node.width - 1, spawn.x + limit_x))) + y0, y1 = ((0, node.height - 1) if limit_y < 0 else + (max(0, spawn.y - limit_y), min(node.height - 1, spawn.y + limit_y))) + labels = self._components(key) + home = set(self._land(key, spawn.x, spawn.y)) if ( + 0 <= spawn.x < node.width and 0 <= spawn.y < node.height) else set() + wander_tiles = frozenset( + (x + ox, y + oy) for x in range(x0, x1 + 1) for y in range(y0, y1 + 1) + if labels.get((x, y)) in home) + box = (x0 + ox, y0 + oy, x1 + ox, y1 + oy) if wander_tiles else None + caster = any("caster" in profile.flags for _p, profile in candidates) + ranged = any("ranged" in profile.flags for _p, profile in candidates) + damage_types = set(dominant.spell_types) if caster else set() + if ranged: + damage_types.add("missile") + return enc.EncounterSpawn( + x=spawn.x + ox, y=spawn.y + oy, name=dominant.name, + level=round(average("level")), aggressive=spawn.aggressive_probability, + radius=round(average("aggro_radius")), dps=average("damage_second"), + kill_seconds=kill_seconds, bonus=bonus, + map_path=self.map_root.relative_to(self.root).as_posix() + key, + local_x=spawn.x, local_y=spawn.y, own_map=own_map, + # Directly placed monsters have no spawn-point record to signal. + link_chance=(sum(probability * link(profile) + for probability, profile in candidates) / total + if spawn.source == "spawn" else 0.0), + link_group=spawn.link_group, spawn_point=spawn.source == "spawn", + faction=dominant.faction, + engaged_speed=average("engaged_speed"), idle_speed=average("idle_speed"), + wander_box=box, wander_tiles=wander_tiles, + caster=caster, ranged=ranged, damage_types=tuple(sorted(damage_types)), + spells=dominant.spells, melee_types=dominant.attack_types) + + # Neighbour spawns this many tiles beyond the map edge can still reach it. + ENCOUNTER_MARGIN = 12 + + def _encounter_frame( + self, key: str, own_spawns: list[SpawnProfile], options: AnalysisOptions, + ) -> tuple[list[enc.EncounterSpawn], set[tuple[int, int]], + dict[int, set[tuple[int, int]]]]: + """Own spawns plus tiled neighbours' spawns shifted into this map's frame.""" + nodes = self._world().nodes + node = nodes[key] + walkable, seams, _terrain = self._encounter_terrain(key) + spawns = [self._encounter_spawn(spawn, key, (0, 0), True) for spawn in own_spawns] + margin = self.ENCOUNTER_MARGIN + + def outside(x: int, y: int) -> int: + return max(max(0, -x, x - (node.width - 1)), max(0, -y, y - (node.height - 1))) + + for direction, neighbour in sorted(self._tiles(key).items()): + if direction >= len(TILE_DIRECTIONS): + continue + other = nodes[neighbour] + dx, dy = TILE_DIRECTIONS[direction] + ox = node.width if dx > 0 else (-other.width if dx < 0 else 0) + oy = node.height if dy > 0 else (-other.height if dy < 0 else 0) + neighbour_spawns, _competitors = self._spawns_cached( + neighbour, options, options.include_static) + for spawn in neighbour_spawns: + converted = self._encounter_spawn(spawn, neighbour, (ox, oy), False) + near = outside(converted.x, converted.y) <= margin or any( + outside(x, y) <= margin for x, y in converted.wander_tiles) + if near: + spawns.append(converted) + return spawns, walkable, seams + + def _encounter_terrain(self, key: str) -> tuple[ + set[tuple[int, int]], dict[int, set[tuple[int, int]]], enc.TerrainStructure]: + """Walkable tiles, crossable seam tiles by direction, and terrain of a map.""" + cached = self._terrain_cache.get(key) + if cached is not None: + return cached + nodes = self._world().nodes + node = nodes[key] + walkable = {(x, y) for y in range(node.height) for x in range(node.width) + if node.walkable(x, y)} + seams: dict[int, set[tuple[int, int]]] = {} + for direction, neighbour in sorted(self._tiles(key).items()): + if direction >= 4: + continue + other = nodes[neighbour] + dx, dy = TILE_DIRECTIONS[direction] + crossing = set() + if dy: + own_y = 0 if dy < 0 else node.height - 1 + far_y = other.height - 1 if dy < 0 else 0 + for x in range(min(node.width, other.width)): + if node.walkable(x, own_y) and other.walkable(x, far_y): + crossing.add((x, own_y)) + else: + own_x = 0 if dx < 0 else node.width - 1 + far_x = other.width - 1 if dx < 0 else 0 + for y in range(min(node.height, other.height)): + if node.walkable(own_x, y) and other.walkable(far_x, y): + crossing.add((own_x, y)) + seams[direction] = crossing + terrain = enc.analyze_terrain(node.width, node.height, walkable, seams) + self._terrain_cache[key] = (walkable, seams, terrain) + return self._terrain_cache[key] + + def map_encounter(self, key: str, own_spawns: list[SpawnProfile], + options: AnalysisOptions, style: str | None = None, + aoe_targets: float | None = None) -> enc.EncounterModel | None: + """Build the encounter model of one map for a combat style.""" + nodes = self._world().nodes + if key not in nodes or not own_spawns: + return None + spawns, walkable, _seams = self._encounter_frame(key, own_spawns, options) + terrain = self._encounter_terrain(key)[2] + return enc.estimate(spawns, walkable, terrain, + self.encounter_options(options, style, aoe_targets)) + + def encounter_options(self, options: AnalysisOptions, style: str | None = None, + aoe_targets: float | None = None) -> enc.EncounterOptions: + """Encounter inputs for a style. + + Player tiles per second use the same conversion as route timing: + the displayed speed is added every server tick and one move costs one + unit (socket/request.c CS_STAT_SPEED, server/main.c speed_left), so + tiles/s = speed / MAX_TIME seconds. Without --character-speed the + documented assumption is ``DEFAULT_CHARACTER_SPEED`` (8 tiles/s at + the default 125 ms tick). + """ + profile = enc.style_profiles(options.kite_distance)[ + style or options.combat_style or "melee"] + return enc.EncounterOptions( + profile, options.healing_per_second, + (options.character_speed or DEFAULT_CHARACTER_SPEED) / self.tick_seconds, + max(1.0, aoe_targets if aoe_targets is not None else options.targets_per_attack)) + + def _apply_encounter(self, result: MapResult, key: str, spawns: list[SpawnProfile], + options: AnalysisOptions) -> None: + if not options.model_encounters: + return + model = self.map_encounter( + key, spawns, options, aoe_targets=result.effective_targets_per_attack) + if model is None: + return + encounter_options = self.encounter_options( + options, aoe_targets=result.effective_targets_per_attack) + own = [model.spawns[index] for index in model.own] + result.encounter_style = model.style + result.encounter_applied = bool(options.combat_style) + result.expected_pack = model.expected_pack + result.mean_expected_pack = model.mean_expected_pack + result.worst_pack = model.worst_pack + result.encounter_need = model.need + result.encounter_worst_need = model.worst_need + hardest = model.hardest() + if hardest is not None: + result.encounter_pull = (result.path, hardest.x, hardest.y) + result.encounter_reasons = tuple( + enc.reasons(model, encounter_options, options.max_health)) + result.wanderer_spawns = sum( + spawn.aggressive for spawn in own if spawn.wander_tiles) + result.caster_spawns = float(sum(1 for spawn in own if spawn.caster)) + result.ranged_spawns = float(sum(1 for spawn in own if spawn.ranged)) + result.linking_spawns = float(sum(1 for spawn in own if spawn.link_chance > 0.0)) + result.spawn_density = 100.0 * len(own) / max(1, model.terrain.walkable_tiles) + result.doorways = len(model.terrain.doorways) + result.seam_spawns = len(enc.seam_reachers(model)) + if options.max_health > 0.0: + result.encounter_expected_safety = enc.safety_from_need( + model.need, options.max_health) + result.encounter_worst_safety = enc.bad_pull_safety( + model.worst_need, options.max_health) + result.encounter_safety = enc.blended_safety( + result.encounter_expected_safety, result.encounter_worst_safety) + def analyze_map(self, path: Path, options: AnalysisOptions) -> MapResult | None: relpath = str(path.relative_to(self.root)) parsed = parse_blocks(path) @@ -1651,6 +2008,11 @@ def analyze_map(self, path: Path, options: AnalysisOptions) -> MapResult | None: difficulty = _integer(one(header_attrs, "difficulty", 1), 1) spawns, competitors = self._collect_spawns( parsed, options, include_static=options.include_static) + map_key = "/" + path.relative_to(self.map_root).as_posix() + if self._encounter_options != options: + self._encounter_options = options + self._encounter_spawn_cache = {} + self._encounter_spawn_cache[(map_key, options.include_static)] = (spawns, competitors) if len(spawns) < options.minimum_spawns: self.rejections.append((relpath, f"{len(spawns)} spawns < minimum {options.minimum_spawns}")) @@ -1796,7 +2158,7 @@ def analyze_map(self, path: Path, options: AnalysisOptions) -> MapResult | None: monster_counts[f"{profile.name} L{profile.level}"] += probability for flag in profile.flags: flag_counts[flag] += probability - return MapResult( + result = MapResult( relpath, one(header_attrs, "name", path.name) or path.name, one(header_attrs, "region", "") or "", difficulty, count, xp, xp / count, hp, effective_hp, hp / count, damage / count, danger, respawn_seconds, @@ -1845,6 +2207,8 @@ def analyze_map(self, path: Path, options: AnalysisOptions) -> MapResult | None: min_monster_level=min_monster_level, avg_monster_level=avg_monster_level, ) + self._apply_encounter(result, map_key, spawns, options) + return result @staticmethod def _coordinate_key(result: MapResult) -> tuple[str, str, int, int, int] | None: @@ -2011,8 +2375,46 @@ def _combine_circuit(members: list[MapResult], options: AnalysisOptions) -> MapR min_monster_level=min(member.min_monster_level for member in members), avg_monster_level=sum( member.avg_monster_level * member.spawns for member in members) / count, + **FarmingAnalyzer._combine_encounters(members, count), ) + @staticmethod + def _combine_encounters(members: list[MapResult], count: float) -> dict: + """A circuit is rated by its hardest member map. + + Every pull, pack, need, safety and reason field comes from that one + member (lowest encounter safety, then highest need), so they describe + the same map. Spawn counts, density, doorways and seam spawns are + circuit-wide totals or averages. + """ + hardest = min(members, key=lambda member: ( + member.encounter_safety, -member.encounter_need, + -member.encounter_worst_need, member.path)) + return { + "encounter_style": members[0].encounter_style, + "encounter_applied": members[0].encounter_applied, + "expected_pack": hardest.expected_pack, + "mean_expected_pack": sum( + member.mean_expected_pack * member.spawns for member in members) / count, + "worst_pack": hardest.worst_pack, + "encounter_need": hardest.encounter_need, + "encounter_worst_need": hardest.encounter_worst_need, + "encounter_safety": hardest.encounter_safety, + "encounter_expected_safety": hardest.encounter_expected_safety, + "encounter_worst_safety": hardest.encounter_worst_safety, + "encounter_pull": hardest.encounter_pull, + "encounter_reasons": tuple( + f"{Path(hardest.path).name}: {line}" for line in hardest.encounter_reasons), + "wanderer_spawns": sum(member.wanderer_spawns for member in members), + "caster_spawns": sum(member.caster_spawns for member in members), + "ranged_spawns": sum(member.ranged_spawns for member in members), + "linking_spawns": sum(member.linking_spawns for member in members), + "spawn_density": sum( + member.spawn_density * member.spawns for member in members) / count, + "doorways": sum(member.doorways for member in members), + "seam_spawns": sum(member.seam_spawns for member in members), + } + def _circuits(self, maps: list[MapResult], options: AnalysisOptions) -> list[MapResult]: if options.circuit_size < 2: return [] @@ -2064,6 +2466,24 @@ def _score(results: list[MapResult], options: AnalysisOptions) -> list[MapResult } finite_dangers = [result.danger for result in results if math.isfinite(result.danger)] safest = min(finite_dangers) if finite_dangers else 1.0 + if options.max_health <= 0.0: + # Without a health bar, encounter safety is relative to the + # cheapest pull of the scan, like the per-monster danger. + def reference(attr: str) -> float: + needs = [getattr(result, attr) for result in results + if math.isfinite(getattr(result, attr)) and getattr(result, attr) > 0.0] + return min(needs) if needs else 1.0 + + least, least_worst = reference("encounter_need"), reference("encounter_worst_need") + for result in results: + result.encounter_expected_safety = ( + min(1.0, least / result.encounter_need) if result.encounter_need > 0.0 + else 1.0) + result.encounter_worst_safety = ( + min(1.0, least_worst / result.encounter_worst_need) + if result.encounter_worst_need > 0.0 else 1.0) + result.encounter_safety = enc.blended_safety( + result.encounter_expected_safety, result.encounter_worst_safety) for result in results: if options.max_health > 0.0: result.health_clear_fraction = result.damage_clear / options.max_health @@ -2085,6 +2505,10 @@ 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) + if options.combat_style and options.model_encounters: + # The style-aware encounter replaces the saturated + # danger x pack estimate when it is the stricter of the two. + safety = min(safety, result.encounter_safety) result.spot_safety_score = safety if result.approach_status == "path": # Approach maps use the same health budget, or the same diff --git a/farming_analyzer/cli.py b/farming_analyzer/cli.py index 7660cac..25d4e21 100644 --- a/farming_analyzer/cli.py +++ b/farming_analyzer/cli.py @@ -8,6 +8,7 @@ from .analyzer import FarmingAnalyzer from .config import ATTACK_TYPES, PHYSICAL_ATTACKS, ROOT, SERVER_ROOT +from .encounter import STYLE_NAMES from .models import AnalysisOptions from .presentation import ( group_farming_results, @@ -18,6 +19,9 @@ ) +SCHEMA_VERSION = 2 + + def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("level", type=int, help="combat skill level used by calc_skill_exp") @@ -132,6 +136,15 @@ def build_parser() -> argparse.ArgumentParser: 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("--combat-style", choices=STYLE_NAMES, default="", + help="character's combat style; makes the encounter model part of " + "safety_score (default: report it without changing safety)") + parser.add_argument("--healing-per-second", type=float, default=0.0, + help="HP healed per second while fighting, for encounter safety (default: 0)") + parser.add_argument("--kite-distance", type=int, default=4, + help="tiles a kiting style moves around its pull square (default: 4)") + parser.add_argument("--ignore-encounters", dest="model_encounters", action="store_false", + help="skip the encounter model and its fields") 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") @@ -173,6 +186,9 @@ def simulate_training(analyzer: FarmingAnalyzer, options: AnalysisOptions, def main(argv: list[str] | None = None) -> int: raw_argv = list(sys.argv[1:] if argv is None else argv) + if raw_argv[:1] == ["report"]: + from .report import main as report_main + return report_main(raw_argv[1:]) profile_parser = argparse.ArgumentParser(add_help=False) profile_parser.add_argument("--profile", type=Path) profile_args, _unknown = profile_parser.parse_known_args(raw_argv) @@ -272,6 +288,12 @@ def main(argv: list[str] | None = None) -> int: 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.healing_per_second < 0.0: + raise SystemExit("healing per second cannot be negative") + if not (1 <= args.kite_distance <= 12): + raise SystemExit("kite-distance must be between 1 and 12") + if args.combat_style and not args.model_encounters: + raise SystemExit("--combat-style requires the encounter model; drop --ignore-encounters") if args.approach_origins_only and not args.approach_origin: raise SystemExit("--approach-origins-only requires at least one --approach-origin") unknown_origins = [ @@ -334,6 +356,10 @@ def main(argv: list[str] | None = None) -> int: max_approach_maps=args.max_approach_maps, approach_origins_only=args.approach_origins_only, unreachable_approach_safety=args.unreachable_approach_safety, + combat_style=args.combat_style, + healing_per_second=args.healing_per_second, + kite_distance=args.kite_distance, + model_encounters=args.model_encounters, ) results = analyzer.scan(options) initial_rejections = list(analyzer.rejections) @@ -362,13 +388,16 @@ def main(argv: list[str] | None = None) -> int: if options.simulate_melee: assumptions["dps"] = None payload = { + # 2 adds the encounter-model fields; every version-1 field keeps + # its name, type and meaning unless --combat-style is supplied. + "schema_version": SCHEMA_VERSION, "assumptions": assumptions, "kill_xp_cap": analyzer.experience.kill_cap(args.level), "score_weights": {"xp_hour": 0.40, "money_hour": 0.15, "loot_hour": 0.10, "safety": 0.25, "maneuverability": 0.10}, "results": [asdict(result) for result in results[:args.top]], - "warnings": sorted(analyzer.treasure.warnings), + "warnings": sorted(analyzer.treasure.warnings | analyzer.source_warnings), "training": training, } if options.group_results: @@ -410,6 +439,8 @@ def main(argv: list[str] | None = None) -> int: results, options, args.top, analyzer.experience, analyzer.treasure.warnings, initial_rejections if args.explain_rejected else None) + for warning in sorted(analyzer.source_warnings): + rendered += f"\nWarning: {warning}" if training: rendered += "\n\nTraining simulation:" for stage in training: diff --git a/farming_analyzer/config.py b/farming_analyzer/config.py index 2c60173..462193a 100644 --- a/farming_analyzer/config.py +++ b/farming_analyzer/config.py @@ -30,6 +30,8 @@ def _find_workspace_root() -> Path: RANDOM_DROP_TYPE = 102 EXIT_TYPE = 66 SAVEBED_TYPE = 106 +# Monster spell abilities; ``sp`` is the index into the server spell table. +ABILITY_TYPE = 110 GEAR_TYPES = { 3, 13, 14, 15, 16, 33, 34, 35, 39, 70, 87, 99, 100, 104, 109, 113, } diff --git a/farming_analyzer/encounter.py b/farming_analyzer/encounter.py new file mode 100644 index 0000000..60e3647 --- /dev/null +++ b/farming_analyzer/encounter.py @@ -0,0 +1,1098 @@ +"""Encounter model: who joins a pull, how hard it hits, and how the map is laid out. + +This module works on plain data so it can be tested without a content +checkout. ``FarmingAnalyzer`` converts authored spawns into +``EncounterSpawn`` records in one map's coordinate frame (neighbouring +tiled maps are shifted into that frame), and passes the map's walkable +tiles. Everything here is a documented heuristic, not a simulation of the +server. The server behaviour each heuristic stands for is cited by file and +line in the classic server source (``classic/server/src``): + +- detection: an idle monster looks for an enemy within its ``item_power`` + tiles; a monster that already has an enemy or was attacked looks + 3 tiles further (``types/monster.c`` 1084-1100, ``find_nearest_enemy``). + Sleeping or blind monsters look half as far; that is not modelled; +- leash: an engaged monster keeps its enemy while it stays within + ``max(MAX_AGGRO_RANGE, item_power)`` tiles, and drops it only after + ``MAX_AGGRO_TIME`` further checks out of range (``types/monster.c`` + 558-580, ``include/global.h`` 175-179: range 9, time 12). It is reported + as ``chase_range``; the estimate uses the style's bad-pull footprint in + its place; +- linking: on every AI action with an enemy, a spawned monster rolls a one + in ``monster_signal_chance[Int]`` chance (``server/living.c`` 154-162; + zero means never) to wake idle monsters of other spawn points. Spawn + points with the same ``title`` always answer; others answer when their + monster is an ally standing within ``item_power * 1.5`` minus the + caller's distance to its enemy (``types/monster.c`` 288-345 and + 351-420). A woken passive monster fights too. Directly placed monsters + have no spawn-point record, so they neither call nor answer. Deviation: + allies are monsters of the same faction; factions joined only through an + alliance parent (``faction_is_alliance()``, ``server/faction.c`` 645) are + not resolved; +- wandering: ``random_move`` monsters step in a random direction on each + idle action, limited to ``item_race`` tiles horizontally and + ``item_level`` tiles vertically from their spawn when either is set + (``types/monster.c`` 1160-1225, ``move_randomly``); +- movement: ``set_mobile_speed()`` (``server/living.c`` 1851-1875) gives a + monster twice its authored speed idle and four times while fighting; + with ``slow_move`` once idle and three times fighting. One tile per + action; +- casters and archers attack on their own AI actions from range + (``types/monster.c`` 809-870), so stepping away does not stop them. + +Line-of-sight, doors that open or close, scripted AI and live player +positions are not modelled. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass, field, replace +from typing import Iterable + +# Server constants mirrored as documented data (include/global.h 175-179). +MAX_AGGRO_RANGE = 9 +# The server widens detection by 3 tiles only for a monster that already +# has an enemy or an attacker (types/monster.c 1092-1094). The bad pull +# applies the same 3 tiles to idle bystanders as a deliberate safety +# margin for a fight that drifts, a monster that was hit and lost its +# target, or a retreat; it has no server basis for an untouched monster. +ENGAGED_RADIUS_BONUS = 3 +# Fight length used for wandering, ally calls and arrival times when the +# character cannot kill the target (infinite kill time). Such a pull is not +# farmable and costs infinite health whatever this value is. +FIGHT_HORIZON = 120.0 +# A kiter escaping in open ground has eight directions; each pursuer beyond +# the first is assumed to close one, so nine or more slow melee attackers +# hit as if the character stood still. +KITE_ESCAPE_DIRECTIONS = 8 +# Cardinal seam directions in the server's tiled-map index order. +SEAM_NAMES = {0: "north", 1: "east", 2: "south", 3: "west"} + + +@dataclass(frozen=True) +class StyleProfile: + """How a character fights, and therefore how far a fight wanders.""" + + name: str + description: str + # Tiles the fight moves around the pull square in an ordinary pull, and + # in a bad one (stepping back to heal, being knocked around, kiting + # further than planned). + footprint: int + worst_footprint: int + # Kiting styles keep slower melee monsters at a distance. + kites: bool = False + # AoE styles damage several monsters with one attack. + aoe: bool = False + # Pack styles pick the pull square that gathers the most monsters + # rather than the fewest. + seeks_packs: bool = False + + +DEFAULT_KITE_DISTANCE = 4 +# A wanderer or an ally link belongs to the bad (worst-case) pull when it is +# more likely than not to join it. +PLAUSIBLE = 0.5 + + +def style_profiles(kite_distance: int = DEFAULT_KITE_DISTANCE) -> dict[str, StyleProfile]: + """Return the supported combat styles, keyed by their CLI names.""" + kite = max(1, kite_distance) + return { + "melee": StyleProfile( + "melee", "melee 1v1: single pulls, fight in place", 1, 3), + "melee-pack": StyleProfile( + "melee-pack", "melee against packs: pull a cluster and fight it", 2, 4, + seeks_packs=True), + # A single-target shooter opens from range and backs away along the + # side it has cleared, so its ordinary footprint is small; the kite + # distance is how far a bad pull drags it. + "ranged-kite": StyleProfile( + "ranged-kite", "ranged single target (bow or wand), kiting", 1, kite, + kites=True), + "aoe-kite": StyleProfile( + "aoe-kite", "AoE caster kiting packs", kite, kite + 3, + kites=True, aoe=True, seeks_packs=True), + } + + +STYLE_NAMES = tuple(style_profiles()) + + +@dataclass +class EncounterSpawn: + """One authored monster source in a map's coordinate frame.""" + + x: int + y: int + name: str + level: int + # Probability the spawn holds an aggressive monster (0 for passive). + aggressive: float + radius: int + # Incoming DPS while adjacent, the player's kill time, and the existing + # secondary-risk bonus (casting, bows, poison, ...) in HP. + dps: float + kill_seconds: float + bonus: float = 0.0 + map_path: str = "" + local_x: int = 0 + local_y: int = 0 + own_map: bool = True + # Per-AI-action chance to wake allies (0 = never), and the spawn + # point's ``title`` link group. + link_chance: float = 0.0 + link_group: str = "" + # Spawned by a spawn point (False for a directly placed monster). + spawn_point: bool = True + faction: str = "" + # Movement in tiles per second while fighting and while idle. + engaged_speed: float = 0.0 + idle_speed: float = 0.0 + # Wander rectangle in frame coordinates, inclusive, clipped to the + # spawn's own map, or None for a monster that stays at its spawn. + wander_box: tuple[int, int, int, int] | None = None + wander_tiles: frozenset[tuple[int, int]] = frozenset() + caster: bool = False + ranged: bool = False + damage_types: tuple[str, ...] = () + spells: tuple[str, ...] = () + melee_types: tuple[str, ...] = () + component: int | None = None + _prefix: dict | None = field(default=None, repr=False, compare=False) + + @property + def engaged_radius(self) -> int: + return self.radius + ENGAGED_RADIUS_BONUS + + @property + def chase_range(self) -> int: + return max(MAX_AGGRO_RANGE, self.radius) + + @property + def signal_radius(self) -> int: + # A caller adjacent to its enemy reaches item_power * 1.5 - 1 tiles. + return max(0, int(self.radius * 1.5) - 1) + + @property + def shoots(self) -> bool: + return self.caster or self.ranged + + def wander_fraction(self, x: int, y: int, reach: int) -> float: + """Fraction of the wander area within ``reach`` tiles of (x, y).""" + if not self.wander_tiles: + return 0.0 + if self._prefix is None: + self._prefix = _prefix_sums(self.wander_tiles) + inside = _square_count(self._prefix, x - reach, y - reach, x + reach, y + reach) + return inside / len(self.wander_tiles) + + +def _prefix_sums(tiles: Iterable[tuple[int, int]]) -> dict: + tiles = list(tiles) + x0 = min(x for x, _y in tiles) + y0 = min(y for _x, y in tiles) + x1 = max(x for x, _y in tiles) + y1 = max(y for _x, y in tiles) + width = x1 - x0 + 1 + height = y1 - y0 + 1 + grid = [[0] * (width + 1) for _ in range(height + 1)] + occupied = set(tiles) + for row in range(height): + running = 0 + for column in range(width): + running += (x0 + column, y0 + row) in occupied + grid[row + 1][column + 1] = grid[row][column + 1] + running + return {"x0": x0, "y0": y0, "x1": x1, "y1": y1, "grid": grid} + + +def _square_count(prefix: dict, xa: int, ya: int, xb: int, yb: int) -> int: + xa = max(xa, prefix["x0"]) + ya = max(ya, prefix["y0"]) + xb = min(xb, prefix["x1"]) + yb = min(yb, prefix["y1"]) + if xa > xb or ya > yb: + return 0 + grid = prefix["grid"] + ca, ra = xa - prefix["x0"], ya - prefix["y0"] + cb, rb = xb - prefix["x0"] + 1, yb - prefix["y0"] + 1 + return grid[rb][cb] - grid[ra][cb] - grid[rb][ca] + grid[ra][ca] + + +def chebyshev(ax: int, ay: int, bx: int, by: int) -> int: + return max(abs(ax - bx), abs(ay - by)) + + +@dataclass(frozen=True) +class Fighter: + """A monster in a pull. + + ``probability`` is the chance it takes part; DPS and kill time are + conditional on that. ``arrival`` is when it starts hitting, in seconds + after the pull begins, and ``bonus`` is a flat secondary-risk cost in HP. + """ + + probability: float + dps: float + kill_seconds: float + bonus: float = 0.0 + arrival: float = 0.0 + + +def pull_need(fighters: Iterable[Fighter], healing: float = 0.0, + targets: float = 1.0) -> float: + """Health a pull costs at its lowest point (the health trough). + + Expected-value timeline: every arrived monster hits for ``probability * + dps`` until it dies, the character heals ``healing`` HP per second, and + health lost cannot be negative (healing does not bank). The character + kills one arrived monster at a time, choosing the one with the least + kill seconds per incoming DPS (the order that loses the least health), + and spends ``probability * kill_seconds / targets`` on it, since AoE + styles damage ``targets`` monsters with each attack. The deepest deficit + plus each monster's secondary-risk bonus is the need. + """ + fighters = [item for item in fighters if item.probability > 0.0] + if any(not math.isfinite(item.kill_seconds) and item.dps > 0.0 for item in fighters): + return math.inf + share = max(1.0, targets) + work = [item.probability * (item.kill_seconds if math.isfinite(item.kill_seconds) else 0.0) + / share for item in fighters] + alive = set(range(len(fighters))) + now = deficit = peak = 0.0 + while alive: + arrived = [index for index in alive if fighters[index].arrival <= now + 1e-9] + upcoming = [fighters[index].arrival for index in alive + if fighters[index].arrival > now + 1e-9] + if not arrived: + later = min(upcoming) + deficit = max(0.0, deficit - healing * (later - now)) + now = later + continue + focus = min(arrived, key=lambda index: ( + work[index] / (fighters[index].probability * fighters[index].dps) + if fighters[index].dps > 0.0 else math.inf, index)) + rate = sum(fighters[index].probability * fighters[index].dps + for index in arrived) - healing + step = work[focus] + if upcoming: + step = min(step, min(upcoming) - now) + deficit = max(0.0, deficit + rate * step) + peak = max(peak, deficit) + now += step + work[focus] -= step + if work[focus] <= 1e-9: + alive.remove(focus) + return peak + sum(item.probability * item.bonus for item in fighters) + + +@dataclass(frozen=True) +class PullEstimate: + """The best pull of one target spawn.""" + + target: int + x: int + y: int + expected: float + worst: float + need: float + worst_need: float + joiners: tuple[int, ...] + worst_joiners: tuple[int, ...] + + +@dataclass(frozen=True) +class TerrainStructure: + """Walkable layout of one map, from its authored walls and blockers.""" + + width: int + height: int + walkable_tiles: int + walkable_fraction: float + regions: int + largest_region: int + open_fraction: float + kite_room: float + open_field_tiles: int + open_field_center: tuple[int, int] | None + corridor_tiles: int + doorways: tuple[tuple[int, int], ...] + dead_ends: int + seams: dict[str, int] + + +def _components(tiles: set[tuple[int, int]], + neighbours: tuple[tuple[int, int], ...]) -> list[set[tuple[int, int]]]: + remaining = set(tiles) + result = [] + while remaining: + start = remaining.pop() + component = {start} + frontier = [start] + while frontier: + x, y = frontier.pop() + for dx, dy in neighbours: + tile = (x + dx, y + dy) + if tile in remaining: + remaining.remove(tile) + component.add(tile) + frontier.append(tile) + result.append(component) + return result + + +EIGHT = ((-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)) +FOUR = ((0, -1), (1, 0), (0, 1), (-1, 0)) + + +def component_labels(walkable: set[tuple[int, int]]) -> dict[tuple[int, int], int]: + """Label walkable tiles by 8-neighbour connected region.""" + labels = {} + for index, component in enumerate( + sorted(_components(walkable, EIGHT), key=lambda item: min(item))): + for tile in component: + labels[tile] = index + return labels + + +def analyze_terrain(width: int, height: int, walkable: set[tuple[int, int]], + seams: dict[int, set[tuple[int, int]]] | None = None) -> TerrainStructure: + """Describe regions, open fields, corridors, doorways and seams. + + - regions: 8-neighbour connected walkable areas; + - open tiles: every one of the 8 neighbours is walkable; an open field + is a connected area of tiles with a clear 5x5 square around them, + which is where kiting works; + - corridor tiles: exactly two opposite cardinal neighbours are walkable, + so the passage is one tile wide. A run of at most two corridor tiles + is a doorway (a chokepoint between areas); longer runs are corridors; + - dead ends: walkable tiles with a single walkable cardinal neighbour; + - kite room: share of walkable tiles with at least 6 of 8 walkable + neighbours, so a kiter can keep stepping away; beyond a crossable + seam tile the neighbouring map counts as open; + - seams: per cardinal direction with a tiled neighbour, the number of + edge tiles that are walkable on both sides. + """ + total = max(1, width * height) + crossing = set().union(*(seams or {}).values()) if seams else set() + + def roomy(x: int, y: int) -> bool: + count = 0 + for dx, dy in EIGHT: + nx, ny = x + dx, y + dy + inside = 0 <= nx < width and 0 <= ny < height + if (nx, ny) in walkable or (not inside and (x, y) in crossing): + count += 1 + return count >= 6 + + regions = _components(walkable, EIGHT) + open_tiles = {tile for tile in walkable + if all((tile[0] + dx, tile[1] + dy) in walkable for dx, dy in EIGHT)} + clear = {tile for tile in walkable + if all((tile[0] + dx, tile[1] + dy) in walkable + for dx in range(-2, 3) for dy in range(-2, 3))} + fields = _components(clear, FOUR) + largest_field = max(fields, key=len, default=set()) + corridor = set() + dead_ends = 0 + for x, y in walkable: + north, east, south, west = ( + (x + dx, y + dy) in walkable for dx, dy in FOUR) + count = north + east + south + west + if count == 1: + dead_ends += 1 + if count == 2 and ((north and south) or (east and west)): + corridor.add((x, y)) + doorways = [] + for run in _components(corridor, EIGHT): + if len(run) <= 2: + doorways.append(min(run)) + seam_counts = {} + for direction, tiles in sorted((seams or {}).items()): + if direction in SEAM_NAMES and tiles: + seam_counts[SEAM_NAMES[direction]] = len(tiles) + center = None + if largest_field: + cx = sum(x for x, _y in largest_field) / len(largest_field) + cy = sum(y for _x, y in largest_field) / len(largest_field) + center = min(largest_field, key=lambda tile: ( + (tile[0] - cx) ** 2 + (tile[1] - cy) ** 2, tile)) + return TerrainStructure( + width, height, len(walkable), len(walkable) / total, + sum(1 for region in regions if len(region) >= 4), + max((len(region) for region in regions), default=0), + len(open_tiles) / max(1, len(walkable)), + sum(1 for tile in walkable if roomy(*tile)) / max(1, len(walkable)), + len(largest_field), center, len(corridor), + tuple(sorted(doorways)), dead_ends, seam_counts) + + +@dataclass(frozen=True) +class EncounterOptions: + """Character inputs for one encounter estimate.""" + + style: StyleProfile + healing: float = 0.0 + # Player movement in tiles per second. + player_speed: float = 8.0 + # Monsters damaged by each AoE attack (AoE styles only). + aoe_targets: float = 1.0 + + +@dataclass +class EncounterModel: + """Expected and worst pulls of one map for one combat style.""" + + style: str + spawns: list[EncounterSpawn] + pulls: list[PullEstimate] + terrain: TerrainStructure + room: float + # Chance each pull still happens (its target was not killed earlier as + # a joiner), in clear order. + weights: list[float] = field(default_factory=list) + + @property + def own(self) -> list[int]: + return [index for index, spawn in enumerate(self.spawns) if spawn.own_map] + + def _likely(self) -> list[PullEstimate]: + """Pulls that happen more likely than not (their target survived).""" + weights = self.weights or [1.0] * len(self.pulls) + likely = [pull for pull, weight in zip(self.pulls, weights) if weight >= PLAUSIBLE] + return likely or list(self.pulls) + + def hardest(self) -> PullEstimate | None: + return max(self._likely(), key=lambda pull: (pull.need, pull.worst_need, pull.expected), + default=None) + + @property + def expected_pack(self) -> float: + return max((pull.expected for pull in self._likely()), default=0.0) + + @property + def mean_expected_pack(self) -> float: + weights = self.weights or [1.0] * len(self.pulls) + if not self.pulls or sum(weights) <= 0.0: + return 0.0 + return sum(weight * pull.expected + for weight, pull in zip(weights, self.pulls)) / sum(weights) + + @property + def worst_pack(self) -> float: + return max((pull.worst for pull in self._likely()), default=0.0) + + @property + def need(self) -> float: + return max((pull.need for pull in self._likely()), default=0.0) + + @property + def worst_need(self) -> float: + return max((pull.worst_need for pull in self._likely()), default=0.0) + + +def fight_seconds(spawn: EncounterSpawn, options: EncounterOptions, + room: float, attackers: float = 1.0) -> float: + return spawn.kill_seconds / kite_attack_share(spawn, options, room, attackers) + + +def open_directions(attackers: float) -> float: + """Share of escape directions still open: each attacker beyond the + first closes one of ``KITE_ESCAPE_DIRECTIONS``.""" + return max(0.0, 1.0 - max(0.0, attackers - 1.0) / KITE_ESCAPE_DIRECTIONS) + + +def unkillable(spawn: EncounterSpawn) -> bool: + return not math.isfinite(spawn.kill_seconds) + + +def unkillable_harmless(spawn: EncounterSpawn, aoe: bool = False) -> bool: + """Cannot be killed, and will not hurt the character: skip it. + + A passive monster is left alone by single-target styles. An AoE style + provokes every passive monster inside its footprint, so for AoE only a + monster that deals no damage is harmless. + """ + if not unkillable(spawn): + return False + if aoe: + return spawn.dps <= 0.0 + return spawn.aggressive <= 0.0 or spawn.dps <= 0.0 + + +def _provoked(other: EncounterSpawn, x: int, y: int, component: int | None, + style: StyleProfile) -> float: + """Chance an AoE fight at (x, y) hits, and so provokes, a passive monster. + + AoE styles damage everything inside their footprint (the kite + distance), and a damaged monster turns on its attacker + (``types/monster.c`` 479-512, ``attacked_by`` in ``find_enemy()``). + The passive share of the spawn (``1 - aggressive``) joins from the + first second. + """ + if not style.aoe or other.aggressive >= 1.0: + return 0.0 + if (component is not None and other.component is not None and + other.component != component and not other.shoots): + return 0.0 + if chebyshev(other.x, other.y, x, y) > style.footprint: + return 0.0 + return 1.0 - other.aggressive + + +def horizon(seconds: float) -> float: + """A finite, non-negative fight length for spreads and arrival times.""" + if not math.isfinite(seconds): + return FIGHT_HORIZON + return max(0.0, seconds) + + +def melee_uptime(spawn: EncounterSpawn, options: EncounterOptions, + room: float, attackers: float = 1.0) -> float: + """Fraction of a fight in which this monster is hitting the character. + + Melee styles stand next to everything. Casters and archers hit from + range whatever the style. A kiter keeps a melee monster that is slower + than the character away only where there is kite room (``room``), and + only while escape directions stay open: each attacker beyond the first + closes one of ``KITE_ESCAPE_DIRECTIONS``. The avoided share is + ``room * max(0, 1 - (attackers - 1) / 8)``, so a pack of nine or more + hits as hard as it would a melee character. A monster at least as fast + as the character cannot be kited. + """ + if not options.style.kites or spawn.shoots: + return 1.0 + if options.player_speed <= 0.0 or spawn.engaged_speed >= options.player_speed: + return 1.0 + return 1.0 - room * open_directions(attackers) + + +def kite_attack_share(spawn: EncounterSpawn, options: EncounterOptions, + room: float, attackers: float = 1.0) -> float: + """Share of time a kiter spends attacking rather than stepping away. + + Stepping away costs ``monster speed / player speed`` of the attack time, + but only while the kiter can still step away: the penalty shrinks with + the open escape directions, so a pack that pins the kiter costs the same + time as standing and fighting. + """ + if not options.style.kites or spawn.shoots or options.player_speed <= 0.0: + return 1.0 + if spawn.engaged_speed >= options.player_speed: + return 1.0 + return 1.0 / (1.0 + open_directions(attackers) * + spawn.engaged_speed / options.player_speed) + + +def _join_probability(spawn: EncounterSpawn, x: int, y: int, reach: int, + sweep: float, component: int | None) -> float: + if spawn.aggressive <= 0.0: + return 0.0 + if (component is not None and spawn.component is not None and + spawn.component != component and not spawn.shoots): + return 0.0 + if spawn.wander_tiles: + return spawn.aggressive * spawn.wander_fraction(x, y, reach + int(sweep)) + return spawn.aggressive if chebyshev(spawn.x, spawn.y, x, y) <= reach else 0.0 + + +def _link_probability(caller: EncounterSpawn, other: EncounterSpawn, + seconds: float) -> float: + """Chance ``caller`` wakes ``other`` during a fight of ``seconds``.""" + if caller.link_chance <= 0.0 or not caller.spawn_point or not other.spawn_point: + return 0.0 + if not (caller.link_group and caller.link_group == other.link_group): + if not caller.faction or caller.faction != other.faction: + return 0.0 + if chebyshev(caller.x, caller.y, other.x, other.y) > caller.signal_radius: + return 0.0 + actions = caller.engaged_speed * horizon(seconds) + return 1.0 - (1.0 - caller.link_chance) ** actions + + +def estimate(spawns: list[EncounterSpawn], walkable: set[tuple[int, int]], + terrain: TerrainStructure, options: EncounterOptions) -> EncounterModel: + """Estimate the best pull of every spawn on the map (``own_map``). + + For a target spawn T the character picks a walkable pull square from + which T engages: within T's detection radius when T is aggressive, + adjacent when it is passive, or within kiting distance for kiting + styles. Single-pull styles take the square with the fewest expected + extra attackers; pack styles the most. + + At a pull square P, during a fight lasting T's (style-adjusted) kill + time: + + - a static aggressive spawn joins when its detection radius reaches the + fight's footprint (P plus the style's footprint); + - a wanderer joins with the share of its wander area within that reach, + widened by the random-walk spread ``sqrt(idle steps during the + fight)``; + - an ally joins with the chance that T's link rolls succeed at least + once during the fight; + - melee monsters in another walkable region cannot reach P. + + Monsters already within reach when the pull starts hit from the first + second; wanderers that walk in later and called allies arrive, on + average, half-way through T's fight. + + The bad (worst-case) pull uses a 3-tile margin on every radius (see + ``ENGAGED_RADIUS_BONUS``) and the style's worst footprint, and adds every wanderer and ally link that is more + likely than not to join; those beyond the ordinary reach arrive half-way + through the fight. + """ + labels = component_labels(walkable) + for spawn in spawns: + if spawn.component is None: + spawn.component = labels.get((spawn.x, spawn.y)) + if spawn.component is None: + around = sorted({labels[(spawn.x + dx, spawn.y + dy)] for dx, dy in EIGHT + if (spawn.x + dx, spawn.y + dy) in labels}) + spawn.component = around[0] if len(around) == 1 else None + style = options.style + room = terrain.kite_room + # A monster the character cannot kill and that cannot hurt or will not + # attack is left alone: it is never pulled. An unkillable monster that + # attacks and hurts makes its pull (and so the map) not farmable. + own = [index for index, spawn in enumerate(spawns) + if spawn.own_map and not unkillable_harmless(spawn, options.style.aoe)] + alive = [1.0] * len(spawns) + # First pass: every pull on the fully populated map, to order the clear. + first = {index: _best_pull(index, spawns, alive, walkable, labels, options, room) + for index in own} + order = sorted(own, key=lambda index: (first[index][0].need, first[index][0].expected, + spawns[index].y, spawns[index].x)) + pulls: list[PullEstimate] = [] + weights: list[float] = [] + for index in order: + presence = alive[index] + if presence <= 1e-6: + continue + pull, joined = _best_pull(index, spawns, alive, walkable, labels, options, + room) + pulls.append(pull) + weights.append(presence) + alive[index] = 0.0 + for other, probability in joined: + alive[other] = max(0.0, alive[other] - probability) + return EncounterModel(style.name, spawns, pulls, terrain, room, weights) + + +def _best_pull(index: int, spawns: list[EncounterSpawn], alive: list[float], + walkable: set[tuple[int, int]], labels: dict[tuple[int, int], int], + options: EncounterOptions, room: float, + ) -> tuple[PullEstimate, list[tuple[int, float]]]: + """Best pull of one target with the monsters still ``alive`` (0..1 each).""" + style = options.style + targets = options.aoe_targets if style.aoe else 1.0 + target = spawns[index] + raw_seconds = fight_seconds(target, options, room) + farmable = math.isfinite(raw_seconds) + seconds = horizon(raw_seconds) + late = seconds / 2.0 + candidates = _pull_squares(target, walkable, style) + x0 = min(x for x, _y in candidates) + y0 = min(y for _x, y in candidates) + x1 = max(x for x, _y in candidates) + y1 = max(y for _x, y in candidates) + # Only living spawns that could reach some candidate square matter. + relevant = [] + for other_index, other in enumerate(spawns): + presence = alive[other_index] + if other_index == index or presence <= 1e-6: + continue + linked = _link_probability(target, other, seconds) + if other.aggressive <= 0.0 and linked <= 0.0 and not style.aoe: + continue + sweep = math.sqrt(other.idle_speed * seconds) if other.wander_tiles else 0.0 + reach = max(other.radius + style.footprint + int(sweep), + other.engaged_radius + style.worst_footprint) + gap = max(x0 - other.x, other.x - x1, y0 - other.y, other.y - y1, 0) + if other.wander_tiles or gap <= reach or linked > 0.0: + relevant.append((other_index, other, presence, linked, sweep)) + best = None + for x, y in candidates: + component = labels.get((x, y)) + joiners: list[tuple[int, float, float]] = [] + worst: list[tuple[int, float]] = [] + for other_index, other, presence, linked, sweep in relevant: + reach = other.radius + style.footprint + provoked = presence * _provoked(other, x, y, component, style) + start = presence * _join_probability(other, x, y, reach, 0.0, component) + direct = (presence * _join_probability(other, x, y, reach, sweep, component) + if other.wander_tiles else start) + if provoked > 0.0: + start = 1.0 - (1.0 - start) * (1.0 - provoked) + direct = 1.0 - (1.0 - direct) * (1.0 - provoked) + total = 1.0 - (1.0 - direct) * (1.0 - presence * linked) + if total > 1e-6: + joiners.append((other_index, start, total - start)) + if presence >= PLAUSIBLE and ( + _worst_joins(other, x, y, component, style, sweep) or + linked >= PLAUSIBLE or provoked >= PLAUSIBLE): + worst.append((other_index, 0.0 if start >= PLAUSIBLE else late)) + expected = 1.0 + sum(start + extra for _other, start, extra in joiners) + distance = chebyshev(x, y, target.x, target.y) + if style.seeks_packs: + key = (-expected, -len(worst), -distance, y, x) + else: + key = (expected, len(worst), -distance, y, x) + if best is None or key < best[0]: + best = (key, x, y, joiners, worst, expected) + assert best is not None + _key, x, y, joiners, worst, expected = best + expected_fighters = [(target, 1.0, 0.0)] + for other, start, extra in joiners: + if start > 0.0: + expected_fighters.append((spawns[other], start, 0.0)) + if extra > 0.0: + expected_fighters.append((spawns[other], extra, late)) + need = _cheaper_pull(expected_fighters, options, room, expected, targets) + worst_need = _cheaper_pull( + [(target, 1.0, 0.0)] + [(spawns[other], 1.0, arrival) for other, arrival in worst], + options, room, 1.0 + len(worst), targets) + if not farmable: + # The character cannot kill the target: not a farmable pull. + need = worst_need = math.inf + pull = PullEstimate( + index, x, y, expected, 1.0 + len(worst), need, worst_need, + tuple(other for other, _start, _extra in joiners), + tuple(other for other, _arrival in worst)) + return pull, [(other, start + extra) for other, start, extra in joiners] + + +def _pull_squares(target: EncounterSpawn, walkable: set[tuple[int, int]], + style: StyleProfile) -> list[tuple[int, int]]: + """Walkable squares from which the character can start a fight with ``target``. + + An aggressive target engages within its detection radius, a passive one + must be attacked from an adjacent square, and kiting styles can open + from their kiting distance (bad-pull footprint). A wanderer can be met anywhere it roams, so + every other square of its own-map wander area (sampled on a two-tile + grid) is a candidate too. + """ + pull_range = target.radius if target.aggressive > 0.0 else 1 + if style.kites: + pull_range = max(pull_range, style.worst_footprint) + squares = { + (x, y) for x in range(target.x - pull_range, target.x + pull_range + 1) + for y in range(target.y - pull_range, target.y + pull_range + 1) + if (x, y) in walkable and (x, y) != (target.x, target.y) + } + if target.wander_tiles: + squares |= {(x, y) for x, y in target.wander_tiles + if (x, y) in walkable and x % 2 == 0 and y % 2 == 0} + return sorted(squares) or [(target.x, target.y)] + + +def _fighter(spawn: EncounterSpawn, probability: float, arrival: float, + options: EncounterOptions, room: float, attackers: float = 1.0) -> Fighter: + return Fighter( + probability, + spawn.dps * melee_uptime(spawn, options, room, attackers), + fight_seconds(spawn, options, room, attackers), + spawn.bonus, arrival) + + +def _cheaper_pull(fighters: list[tuple[EncounterSpawn, float, float]], + options: EncounterOptions, room: float, attackers: float, + targets: float) -> float: + """Health trough of a pull; a kiter stands and fights when that is cheaper. + + ``fighters`` are (spawn, probability, arrival). For a kiting style the + same pack is also costed standing still (full uptime, no stepping-away + time) and the cheaper of the two is taken, so kiting never costs more + than standing and fighting the same monsters. + """ + kite = pull_need([_fighter(spawn, probability, arrival, options, room, attackers) + for spawn, probability, arrival in fighters], + options.healing, targets) + if not options.style.kites: + return kite + standing = replace(options, style=replace(options.style, kites=False)) + stand = pull_need([_fighter(spawn, probability, arrival, standing, room, attackers) + for spawn, probability, arrival in fighters], + options.healing, targets) + return min(kite, stand) + + +def _worst_joins(other: EncounterSpawn, x: int, y: int, component: int | None, + style: StyleProfile, sweep: float) -> bool: + """Whether ``other`` belongs to the bad pull at (x, y). + + A static aggressive spawn joins when its radius plus the 3-tile margin + reaches the worst footprint. A wanderer joins when it is more likely + than not within that reach (widened by its random-walk spread) during + the fight. + """ + if other.aggressive <= 0.0: + return False + if (component is not None and other.component is not None and + other.component != component and not other.shoots): + return False + reach = other.engaged_radius + style.worst_footprint + if other.wander_tiles: + return other.wander_fraction(x, y, reach + int(sweep)) >= PLAUSIBLE + return chebyshev(other.x, other.y, x, y) <= reach + + +def safety_from_need(need: float, health: float) -> float: + """Expected-pull safety: share of the health bar left at the trough.""" + if health <= 0.0: + return 1.0 + if not math.isfinite(need): + return 0.0 + return max(0.0, min(1.0, 1.0 - need / health)) + + +def bad_pull_safety(need: float, health: float) -> float: + """Bad-pull safety: ``1 / (1 + need in health bars)``. + + The bad pull usually costs more than one health bar, where the linear + form would read zero for every dense map. This form stays ordered: + half a bar reads 0.67, one bar 0.5, three bars 0.25. + """ + if health <= 0.0: + return 1.0 + if not math.isfinite(need): + return 0.0 + return 1.0 / (1.0 + max(0.0, need) / health) + + +# Weight of the expected pull versus the bad pull in the blended safety. +EXPECTED_WEIGHT = 0.75 + + +def blended_safety(expected: float, worst: float) -> float: + """``0.75 * expected-pull safety + 0.25 * bad-pull safety``.""" + return EXPECTED_WEIGHT * expected + (1.0 - EXPECTED_WEIGHT) * worst + + +def rating(safety: float) -> str: + """Human label for a blended safety value.""" + if safety >= 0.85: + return "easy" + if safety >= 0.65: + return "fair" + if safety >= 0.40: + return "hard" + if safety > 0.0: + return "deadly" + return "lethal" + + +def hotspots(model: EncounterModel, limit: int = 12) -> list[dict]: + """Designer-facing hotspots: clusters, wanderers, chokepoints, shooters.""" + spawns = model.spawns + own = [index for index in model.own if spawns[index].aggressive > 0.0] + result: list[dict] = [] + # Dense clusters: single-linkage over the engaged radius. + remaining = set(own) + while remaining: + start = remaining.pop() + cluster = {start} + frontier = [start] + while frontier: + current = frontier.pop() + near = { + other for other in remaining + if chebyshev(spawns[current].x, spawns[current].y, + spawns[other].x, spawns[other].y) <= + max(spawns[current].engaged_radius, spawns[other].engaged_radius) + } + remaining -= near + cluster |= near + frontier.extend(near) + if len(cluster) >= 3: + members = sorted(cluster) + cx = round(sum(spawns[i].x for i in members) / len(members)) + cy = round(sum(spawns[i].y for i in members) / len(members)) + result.append({ + "kind": "dense_cluster", "x": cx, "y": cy, "spawns": len(members), + "monsters": sorted({spawns[i].name for i in members}), + "reason": f"{len(members)} aggressive spawns each within engaged " + "detection reach of another; a pull or a retreat here " + "chains into a pack", + }) + wanderers = [index for index in model.own if spawns[index].wander_tiles and + spawns[index].aggressive > 0.0] + if wanderers: + coverage: dict[tuple[int, int], int] = {} + for index in wanderers: + for tile in spawns[index].wander_tiles: + coverage[tile] = coverage.get(tile, 0) + 1 + peak_tile, peak = max(coverage.items(), key=lambda item: (item[1], -item[0][1], -item[0][0])) + walkable = max(1, model.terrain.walkable_tiles) + own_coverage = sum(1 for (x, y) in coverage + if 0 <= x < model.terrain.width and 0 <= y < model.terrain.height) + result.append({ + "kind": "wanderer_overlap" if peak >= 2 else "wanderers", + "x": peak_tile[0], "y": peak_tile[1], "spawns": len(wanderers), + "overlap": peak, + "coverage": round(min(1.0, own_coverage / walkable), 3), + "monsters": sorted({spawns[i].name for i in wanderers}), + "reason": f"{len(wanderers)} aggressive wanderers roam " + f"{min(1.0, own_coverage / walkable):.0%} of the walkable map; " + f"up to {peak} overlap on one tile, so no pull square is " + "reliably clear", + }) + guarded = [] + for x, y in model.terrain.doorways: + guards = [index for index in own + if chebyshev(spawns[index].x, spawns[index].y, x, y) <= + spawns[index].engaged_radius] + if guards: + guarded.append((x, y, guards)) + # The three doorways with the most guards; forests have many tree gaps. + for x, y, guards in sorted(guarded, key=lambda item: (-len(item[2]), item[1], item[0]))[:3]: + if guards: + result.append({ + "kind": "guarded_chokepoint", "x": x, "y": y, "spawns": len(guards), + "monsters": sorted({spawns[i].name for i in guards}), + "reason": f"doorway within engaged reach of {len(guards)} spawn(s); " + "retreating through it pulls them", + }) + for index in model.own: + spawn = spawns[index] + if spawn.shoots: + kind = "caster" if spawn.caster else "ranged" + passive = spawn.aggressive <= 0.0 + result.append({ + "kind": kind, "x": spawn.x, "y": spawn.y, "spawns": 1, + "monsters": [spawn.name], "damage_types": list(spawn.damage_types), + "spells": list(spawn.spells), "passive": passive, + "reason": f"{'passive ' if passive else ''}{spawn.name} attacks from range" + f"{' with ' + ', '.join(spawn.damage_types) if spawn.damage_types else ''}" + f"; kiting does not avoid it{' once provoked' if passive else ''}", + }) + seam_spawns = seam_reachers(model) + if seam_spawns: + result.append({ + "kind": "seam_reach", "x": None, "y": None, "spawns": len(seam_spawns), + "monsters": sorted({spawns[i].name for i in seam_spawns}), + "maps": sorted({spawns[i].map_path for i in seam_spawns}), + "reason": f"{len(seam_spawns)} spawn(s) on adjacent maps can reach " + "this map's edge tiles", + }) + hardest = model.hardest() + if hardest is not None: + target = spawns[hardest.target] + result.append({ + "kind": "hardest_pull", "x": hardest.x, "y": hardest.y, + "spawns": round(hardest.expected, 2), + "monsters": [target.name], + "target": [target.x, target.y], + "reason": f"best square to pull {target.name} at ({target.x}, {target.y}) " + f"still expects {hardest.expected:.1f} attackers " + f"(worst {hardest.worst:g})", + }) + order = {"hardest_pull": 0, "dense_cluster": 1, "wanderer_overlap": 2, + "caster": 3, "ranged": 3, "guarded_chokepoint": 4, "wanderers": 5, + "seam_reach": 6} + result.sort(key=lambda item: (order.get(item["kind"], 9), -float(item["spawns"] or 0))) + return result[:limit] + + +def seam_reachers(model: EncounterModel) -> list[int]: + """Aggressive spawns on adjacent maps whose engaged reach crosses the edge.""" + width, height = model.terrain.width, model.terrain.height + + def outside(x: int, y: int) -> int: + return max(max(0, -x, x - (width - 1)), max(0, -y, y - (height - 1))) + + result = [] + for index, spawn in enumerate(model.spawns): + if spawn.own_map or spawn.aggressive <= 0.0: + continue + reach = spawn.engaged_radius + if outside(spawn.x, spawn.y) <= reach or any( + outside(x, y) <= reach for x, y in spawn.wander_tiles): + result.append(index) + return result + + +def reasons(model: EncounterModel, options: EncounterOptions, + health: float) -> list[str]: + """Short sentences explaining a rating, most important first.""" + spawns = model.spawns + terrain = model.terrain + own = model.own + lines = [] + hardest = model.hardest() + aggressive = [index for index in own if spawns[index].aggressive > 0.0] + walkable = max(1, terrain.walkable_tiles) + lines.append( + f"{len(own)} spawns ({len(aggressive)} aggressive) on {terrain.width}x{terrain.height}" + f" ({len(own) * 100.0 / walkable:.1f} per 100 walkable tiles)") + if hardest is not None: + target = spawns[hardest.target] + joined = sorted({spawns[i].name for i in hardest.joiners}) + lines.append( + f"hardest pull: {target.name} from ({hardest.x}, {hardest.y}) expects " + f"{hardest.expected:.1f} attackers, worst {hardest.worst:g}" + + (f" (joined by {', '.join(joined)})" if joined else "")) + alive_dps = sum(spawns[i].dps * melee_uptime(spawns[i], options, model.room, + hardest.worst) + for i in (hardest.target,) + hardest.worst_joiners) + if health > 0.0: + lines.append( + f"expected pull costs {hardest.need:.0f} of {health:g} HP " + f"(worst {hardest.worst_need:.0f}); the bad pull deals {alive_dps:.1f} DPS " + f"against {options.healing:g} HP/s healing") + else: + lines.append( + f"expected pull costs {hardest.need:.0f} HP (worst " + f"{hardest.worst_need:.0f}); up to {alive_dps:.1f} DPS in against " + f"{options.healing:g} HP/s healing") + immune = sorted({spawns[index].name for index in own + if unkillable(spawns[index]) and + not unkillable_harmless(spawns[index], options.style.aoe)}) + if immune: + lines.insert(1, "not farmable: the character cannot kill " + ", ".join(immune)) + skipped = sorted({spawns[index].name for index in own + if unkillable_harmless(spawns[index], options.style.aoe)}) + if skipped: + lines.append("left alone (cannot be killed, passive or harmless): " + + ", ".join(skipped)) + wanderers = [index for index in aggressive if spawns[index].wander_tiles] + if wanderers: + lines.append(f"{len(wanderers)} aggressive wanderer(s) roam the map") + shooters = [index for index in own if spawns[index].shoots] + if shooters: + types = sorted({kind for i in shooters for kind in spawns[i].damage_types}) + lines.append( + f"{len(shooters)} caster/ranged spawn(s)" + + (f" dealing {', '.join(types)}" if types else "") + + "; they hit from range in every style") + linkers = [index for index in aggressive if spawns[index].link_chance > 0.0] + if linkers: + best = max(spawns[i].link_chance for i in linkers) + lines.append( + f"{len(linkers)} spawn(s) can call allies (up to 1 in {round(1 / best)} per action)") + if options.style.kites: + melee = [index for index in aggressive if not spawns[index].shoots] + if melee: + slow = [index for index in melee + if spawns[index].engaged_speed < options.player_speed] + if slow: + crowd = hardest.expected if hardest is not None else 1.0 + uptime = sum(melee_uptime(spawns[i], options, model.room, crowd) + for i in slow) / len(slow) + lines.append( + f"{len(slow)} melee spawn(s) slower than the character; kiting " + f"keeps them off for {1 - uptime:.0%} of the hardest pull " + f"({model.room:.0%} of walkable tiles have kite room, " + f"~{crowd:.1f} attackers closing escape directions)") + fast = len(melee) - len(slow) + if fast: + lines.append(f"{fast} melee spawn(s) as fast as the character cannot be kited") + if terrain.doorways: + lines.append(f"{len(terrain.doorways)} doorway chokepoint(s)") + if terrain.seams: + lines.append("crossable seams: " + ", ".join( + f"{name} {count}" for name, count in terrain.seams.items())) + seam = seam_reachers(model) + if seam: + lines.append(f"{len(seam)} spawn(s) across seams can reach the edge") + return lines diff --git a/farming_analyzer/models.py b/farming_analyzer/models.py index aebcaee..51ded48 100644 --- a/farming_analyzer/models.py +++ b/farming_analyzer/models.py @@ -30,6 +30,19 @@ class MonsterProfile: loot: Loot flags: tuple[str, ...] attacks_to_kill: float = 0.0 + # Encounter-model inputs that do not depend on level: stats.Int, the + # faction used for ally signals, movement in tiles per second while + # fighting and while idle, the random_move limits (-1 = unbounded, + # None = does not wander), melee attack types, and spells with the + # attack types of what they cast. + intelligence: int = 0 + faction: str = "" + engaged_speed: float = 0.0 + idle_speed: float = 0.0 + wander: tuple[int, int] | None = None + attack_types: tuple[str, ...] = () + spells: tuple[str, ...] = () + spell_types: tuple[str, ...] = () @dataclass @@ -42,6 +55,8 @@ class SpawnProfile: aggressive_probability: float = 0.0 attempt_seconds: float = math.inf attempt_probability: float = 0.0 + # Spawn points sharing a ``title`` always answer each other's signals. + link_group: str = "" def weighted(self, attr: str) -> float: return sum(probability * getattr(profile, attr) for probability, profile in self.candidates) @@ -151,6 +166,28 @@ class MapResult: approach_worst_map: str = "" approach_danger_flags: tuple[str, ...] = () approach_unknown: bool = False + # Encounter model (see encounter.py and the README). ``encounter_style`` + # names the combat style the fields describe; ``encounter_applied`` says + # whether --combat-style made it part of safety_score. + encounter_style: str = "" + encounter_applied: bool = False + expected_pack: float = 0.0 + mean_expected_pack: float = 0.0 + worst_pack: float = 0.0 + encounter_need: float = 0.0 + encounter_worst_need: float = 0.0 + encounter_safety: float = 1.0 + encounter_expected_safety: float = 1.0 + encounter_worst_safety: float = 1.0 + encounter_pull: tuple[str, int, int] = ("", 0, 0) + encounter_reasons: tuple[str, ...] = () + wanderer_spawns: float = 0.0 + caster_spawns: float = 0.0 + ranged_spawns: float = 0.0 + linking_spawns: float = 0.0 + spawn_density: float = 0.0 + doorways: int = 0 + seam_spawns: int = 0 @dataclass(frozen=True) @@ -204,6 +241,13 @@ class AnalysisOptions: max_approach_maps: int = 16 approach_origins_only: bool = False unreachable_approach_safety: float | None = None + # Encounter model: the character's combat style (empty keeps the + # pre-encounter safety_score), healing per second while fighting, and + # kiting distance in tiles. + combat_style: str = "" + healing_per_second: float = 0.0 + kite_distance: int = 4 + model_encounters: bool = True @property def simulate_melee(self) -> bool: diff --git a/farming_analyzer/presentation.py b/farming_analyzer/presentation.py index 2e675ab..24afbcb 100644 --- a/farming_analyzer/presentation.py +++ b/farming_analyzer/presentation.py @@ -175,6 +175,11 @@ def render_text(results: list[MapResult], options: AnalysisOptions, limit: int, f"Time {options.at_minute // 60:02d}:{options.at_minute % 60:02d}; {offense}; " f"spawn-check overhead {options.seconds_per_kill:g}s; " f"map overhead {options.seconds_per_map:g}s", + (f"Combat style: {options.combat_style}; healing {options.healing_per_second:g} HP/s" + f"{f', kite distance {options.kite_distance}' if 'kite' in options.combat_style else ''}; " + "spot safety is the lower of the danger x pack estimate and the encounter model" + if options.combat_style else + "Combat style: not supplied; encounter fields describe melee but do not change safety"), f"Safety target: character L{options.character_level}, AC {options.player_ac}, " f"protections {', '.join(f'{name}={amount}%' for name, amount in options.player_protections) or 'none'}; " f"HP {f'{options.max_health:g}' if options.max_health > 0.0 else 'not supplied'}", @@ -321,6 +326,23 @@ 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.encounter_style: + x, y = result.encounter_pull[1], result.encounter_pull[2] + lines.append( + f" encounter ({result.encounter_style}" + f"{'' if result.encounter_applied else ', not applied: pass --combat-style'}): " + f"hardest pull at {Path(result.encounter_pull[0]).name} ({x}, {y}) expects " + f"~{result.expected_pack:.1f} attackers (mean {result.mean_expected_pack:.1f}, " + f"bad pull {result.worst_pack:g}); costs ~{result.encounter_need:.0f} HP " + f"(bad pull {result.encounter_worst_need:.0f}); safety " + f"{result.encounter_safety * 100.0:.0f}% " + f"(expected {result.encounter_expected_safety * 100.0:.0f}%, " + f"bad pull {result.encounter_worst_safety * 100.0:.0f}%); " + f"{result.wanderer_spawns:g} wanderer(s), {result.caster_spawns:g} caster(s), " + f"{result.ranged_spawns:g} archer(s), {result.doorways} doorway(s), " + f"{result.seam_spawns} spawn(s) across seams") + for reason in result.encounter_reasons[1:4]: + lines.append(f" - {reason}") if result.approach_status == "path": lines.append( f" approach: {len(result.approach_maps)} map(s) from " diff --git a/farming_analyzer/report.py b/farming_analyzer/report.py new file mode 100644 index 0000000..67dad11 --- /dev/null +++ b/farming_analyzer/report.py @@ -0,0 +1,387 @@ +"""Per-map and per-zone difficulty report for map makers and map editors. + +``python3 -m farming_analyzer report`` rates authored maps by level band and +combat style with the encounter model (``encounter.py``) and a documented +reference character, and lists hotspots and the reasons behind each rating. +``--json`` emits the schema documented in the README ("Difficulty report"). +""" + +from __future__ import annotations + +import argparse +import json +import math +import re +from collections import defaultdict +from dataclasses import asdict, dataclass +from pathlib import Path + +from . import encounter as enc +from .analyzer import FarmingAnalyzer +from .config import PHYSICAL_ATTACKS, ROOT, SERVER_ROOT +from .models import AnalysisOptions +from .presentation import parse_time +from .sources import source_map_files + +REPORT_SCHEMA = "atrinik.farming_analyzer.difficulty_report" +REPORT_SCHEMA_VERSION = 1 +# Monsters this many levels above the band mark it as out of band. +BAND_ALLOWANCE = 5 +# Default bands: the map's average monster level rounded to five, and five +# levels either side. +AUTO_OFFSETS = (-5, 0, 5) +AOE_TARGETS = 4 + + +@dataclass(frozen=True) +class ReferenceCharacter: + """A generic character per level band, scaled linearly with level. + + The defaults are calibrated on the playtester character Sera at level + 37 (333 HP, AC 58, about 25 melee DPS with a 3 s weapon, 36-50% + physical protection, about 5.5 HP/s from minor healing). They describe a + modestly geared character, not an optimal one. + """ + + hp_per_level: float = 9.0 + ac_per_level: float = 1.6 + dps_per_level: float = 0.7 + healing_per_level: float = 0.15 + physical_protection: int = 35 + speed: float = 1.0 + + def options(self, level: int, base: AnalysisOptions) -> AnalysisOptions: + damage = max(1.0, self.dps_per_level * level * 2.0) + protections = tuple(sorted( + (attack, self.physical_protection) for attack in PHYSICAL_ATTACKS)) + return AnalysisOptions( + player_level=level, dps=damage / 2.0, seconds_per_kill=2.0, + seconds_per_map=10.0, shop_sell_fraction=0.20, + at_minute=base.at_minute, attack_type="physical_average", + minimum_spawns=1, minimum_xp_fraction=0.0, max_level_gap=200, + circuit_size=1, path_pattern=None, include_static=base.include_static, + character_level=level, player_ac=round(self.ac_per_level * level), + player_protections=protections, melee_damage=None, weapon_class=None, + weapon_speed=None, weapon_class_range=20, + player_attacks=tuple((attack, 25) for attack in PHYSICAL_ATTACKS), + damage_per_attack=damage, attack_delay=2.0, + max_health=self.hp_per_level * level, character_speed=self.speed, + model_approach=False, healing_per_second=self.healing_per_level * level, + kite_distance=base.kite_distance) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="python3 -m farming_analyzer report", + description="Rate authored maps by level band and combat style for map makers.") + parser.add_argument("--content-root", type=Path, default=ROOT) + parser.add_argument("--server-root", type=Path, default=SERVER_ROOT) + parser.add_argument("--path", dest="path_pattern", + help="case-insensitive map-path regex (default: every map with monsters)") + parser.add_argument("--exclude-region", action="append", default=[], metavar="NAME") + parser.add_argument("--levels", default="auto", + help="comma-separated level bands, or 'auto' for each map's average " + "monster level rounded to 5 and 5 either side (default)") + parser.add_argument("--styles", default=",".join(enc.STYLE_NAMES), + help=f"comma-separated styles (default: {','.join(enc.STYLE_NAMES)})") + parser.add_argument("--time", type=parse_time, default=parse_time("12:00"), metavar="HH:MM") + parser.add_argument("--include-static", action="store_true") + parser.add_argument("--kite-distance", type=int, default=enc.DEFAULT_KITE_DISTANCE) + defaults = ReferenceCharacter() + parser.add_argument("--hp-per-level", type=float, default=defaults.hp_per_level) + parser.add_argument("--ac-per-level", type=float, default=defaults.ac_per_level) + parser.add_argument("--dps-per-level", type=float, default=defaults.dps_per_level) + parser.add_argument("--healing-per-level", type=float, default=defaults.healing_per_level) + parser.add_argument("--physical-protection", type=int, + default=defaults.physical_protection) + parser.add_argument("--speed", type=float, default=defaults.speed, + help="displayed movement speed of the reference character") + parser.add_argument("--json", action="store_true", help="emit the JSON report") + return parser + + +def _levels(text: str) -> tuple[int, ...] | None: + if text.strip().lower() == "auto": + return None + try: + levels = tuple(sorted({int(item) for item in text.split(",") if item.strip()})) + except ValueError as exc: + raise SystemExit("levels must be 'auto' or comma-separated integers") from exc + if not levels or any(not 1 <= level <= 200 for level in levels): + raise SystemExit("levels must be between 1 and 200") + return levels + + +def _round(value: float, digits: int = 3) -> float | None: + return round(value, digits) if math.isfinite(value) else None + + +def _spawn_record(spawn: enc.EncounterSpawn, pull: enc.PullEstimate | None) -> dict: + box = None + if spawn.wander_box is not None: + x0, y0, x1, y1 = spawn.wander_box + box = {"x0": x0, "y0": y0, "x1": x1, "y1": y1, "tiles": len(spawn.wander_tiles)} + return { + "x": spawn.x, "y": spawn.y, "name": spawn.name, "level": spawn.level, + "aggressive": _round(spawn.aggressive), + "detection_radius": spawn.radius, + "engaged_radius": spawn.engaged_radius, + "chase_range": spawn.chase_range, + "link_chance": _round(spawn.link_chance, 4), + "link_group": spawn.link_group, + "faction": spawn.faction, + "engaged_speed": _round(spawn.engaged_speed), + "idle_speed": _round(spawn.idle_speed), + "wander": box, + "caster": spawn.caster, "ranged": spawn.ranged, + "damage_types": list(spawn.damage_types), + "melee_types": list(spawn.melee_types), + "spells": list(spawn.spells), + "pull": None if pull is None else { + "x": pull.x, "y": pull.y, "expected": _round(pull.expected, 2), + "worst": pull.worst}, + } + + +def _terrain_record(terrain: enc.TerrainStructure) -> dict: + record = asdict(terrain) + record["doorways"] = [list(tile) for tile in terrain.doorways] + record["open_field_center"] = (list(terrain.open_field_center) + if terrain.open_field_center else None) + for key in ("walkable_fraction", "open_fraction", "kite_room"): + record[key] = _round(record[key]) + return record + + +def build_report(analyzer: FarmingAnalyzer, args: argparse.Namespace) -> dict: + """Return the JSON-ready difficulty report.""" + styles = tuple(item.strip() for item in args.styles.split(",") if item.strip()) + unknown = [item for item in styles if item not in enc.STYLE_NAMES] + if unknown or not styles: + raise SystemExit(f"unknown style(s): {', '.join(unknown) or 'none given'}; " + f"choose from {', '.join(enc.STYLE_NAMES)}") + explicit = _levels(args.levels) + reference = ReferenceCharacter( + args.hp_per_level, args.ac_per_level, args.dps_per_level, + args.healing_per_level, args.physical_protection, args.speed) + probe = reference.options(1, _base_options(args)) + matcher = re.compile(args.path_pattern, re.IGNORECASE) if args.path_pattern else None + map_prefix = analyzer.map_root.relative_to(analyzer.root).as_posix() + # First pass: maps with hostile spawns and their monster levels, which do + # not depend on the character. + maps: dict[str, dict] = {} + for path in source_map_files(analyzer.map_root): + relative = str(path.relative_to(analyzer.root)) + if matcher and matcher.search(relative) is None: + continue + location = analyzer.locations.maps.get(relative) + if location is not None and analyzer.locations.region_is_excluded( + location.region, tuple(args.exclude_region)): + continue + key = "/" + path.relative_to(analyzer.map_root).as_posix() + if key not in analyzer._world().nodes: + continue + spawns, _competitors = analyzer._spawns_cached(key, probe, args.include_static) + if not spawns: + continue + levels = [profile.level for spawn in spawns for _p, profile in spawn.candidates] + average = sum(spawn.weighted("level") for spawn in spawns) / len(spawns) + bands = explicit or tuple(sorted({ + max(1, min(200, 5 * round(average / 5) + offset)) for offset in AUTO_OFFSETS})) + node = analyzer._world().nodes[key] + maps[key] = { + "path": relative, + "name": location.name if location else path.name, + "region": location.region if location else "", + "width": node.width, "height": node.height, + "monster_levels": {"min": min(levels), "max": max(levels), + "average": round(average, 1)}, + "bands": bands, "ratings": [], "spawns": [], "hotspots": [], "terrain": None, + "_spawn_count": len(spawns), + } + by_level: dict[int, list[str]] = defaultdict(list) + for key, record in maps.items(): + for level in record["bands"]: + by_level[level].append(key) + for level in sorted(by_level): + options = reference.options(level, _base_options(args)) + for key in by_level[level]: + record = maps[key] + spawns, _competitors = analyzer._spawns_cached(key, options, args.include_static) + for style in styles: + aoe = AOE_TARGETS if enc.style_profiles()[style].aoe else 1 + model = analyzer.map_encounter(key, spawns, options, style, aoe) + if model is None: + continue + encounter_options = analyzer.encounter_options(options, style, aoe) + record["ratings"].append(_rating(model, encounter_options, options, level, + record["monster_levels"]["max"])) + anchor = min(record["bands"], key=lambda band: ( + abs(band - record["monster_levels"]["average"]), band)) + if level == anchor and style == styles[0]: + pulls = {pull.target: pull for pull in model.pulls} + record["terrain"] = _terrain_record(model.terrain) + record["spawns"] = [ + _spawn_record(model.spawns[index], pulls.get(index)) + for index in model.own] + record["hotspots"] = enc.hotspots(model) + record["hotspot_basis"] = {"level": level, "style": style} + result_maps = [] + for key in sorted(maps, key=lambda item: maps[item]["path"]): + record = maps[key] + record.pop("_spawn_count") + record["levels"] = list(record.pop("bands")) + result_maps.append(record) + return { + "schema": REPORT_SCHEMA, + "schema_version": REPORT_SCHEMA_VERSION, + "generator": {"tool": "farming_analyzer", "command": "report", + "content_root": str(args.content_root)}, + "reference_character": { + "hp": f"{reference.hp_per_level:g} x level", + "ac": f"{reference.ac_per_level:g} x level", + "dps": f"{reference.dps_per_level:g} x level", + "healing_per_second": f"{reference.healing_per_level:g} x level", + "physical_protection": reference.physical_protection, + "speed": reference.speed, + "aoe_targets": AOE_TARGETS, + "kite_distance": args.kite_distance, + }, + "styles": {name: profile.description + for name, profile in enc.style_profiles(args.kite_distance).items() + if name in styles}, + "rating_scale": {"easy": ">= 0.85", "fair": ">= 0.65", "hard": ">= 0.40", + "deadly": "> 0", "lethal": "0"}, + "maps": result_maps, + "zones": _zones(result_maps, styles), + "warnings": sorted(analyzer.source_warnings), + } + + +def _base_options(args: argparse.Namespace) -> AnalysisOptions: + return AnalysisOptions( + player_level=1, dps=1.0, seconds_per_kill=2.0, seconds_per_map=10.0, + shop_sell_fraction=0.2, at_minute=args.time, attack_type="physical_average", + minimum_spawns=1, minimum_xp_fraction=0.0, max_level_gap=200, circuit_size=1, + path_pattern=None, include_static=args.include_static, character_level=1, + player_ac=1, player_protections=(), melee_damage=None, weapon_class=None, + weapon_speed=None, weapon_class_range=20, player_attacks=(), + kite_distance=args.kite_distance) + + +def _rating(model: enc.EncounterModel, encounter_options: enc.EncounterOptions, + options: AnalysisOptions, level: int, max_level: int) -> dict: + health = options.max_health + expected = enc.safety_from_need(model.need, health) + bad = enc.bad_pull_safety(model.worst_need, health) + safety = enc.blended_safety(expected, bad) + hardest = model.hardest() + reasons = enc.reasons(model, encounter_options, health) + out_of_band = max_level > level + BAND_ALLOWANCE + if out_of_band: + reasons.insert(0, f"monsters up to L{max_level}, above L{level}+{BAND_ALLOWANCE}") + return { + "level": level, "style": model.style, + "safety": _round(safety), "expected_safety": _round(expected), + "bad_pull_safety": _round(bad), "rating": enc.rating(safety), + "expected_attackers": _round(model.expected_pack, 2), + "mean_attackers": _round(model.mean_expected_pack, 2), + "bad_pull_attackers": model.worst_pack, + "expected_need": _round(model.need, 1), + "bad_pull_need": _round(model.worst_need, 1), + "health": health, + "hardest_pull": None if hardest is None else { + "x": hardest.x, "y": hardest.y, + "target": [model.spawns[hardest.target].x, model.spawns[hardest.target].y], + "monster": model.spawns[hardest.target].name}, + "out_of_band": out_of_band, + "reasons": reasons, + } + + +def _zones(maps: list[dict], styles: tuple[str, ...]) -> list[dict]: + groups: dict[tuple[str, str], list[dict]] = defaultdict(list) + for record in maps: + groups[(record["region"], record["name"])].append(record) + zones = [] + for (region, name), members in sorted(groups.items()): + ratings = [] + levels = sorted({rating["level"] for member in members for rating in member["ratings"]}) + for level in levels: + for style in styles: + rows = [(member["path"], rating) for member in members + for rating in member["ratings"] + if rating["level"] == level and rating["style"] == style] + values = [rating["safety"] for _path, rating in rows + if rating["safety"] is not None] + if not values: + continue + hardest_path, hardest = min(rows, key=lambda item: ( + item[1]["safety"] if item[1]["safety"] is not None else -1.0)) + ratings.append({ + "level": level, "style": style, "maps": len(rows), + "min_safety": min(values), + "mean_safety": round(sum(values) / len(values), 3), + "max_safety": max(values), + "rating": enc.rating(min(values)), + "hardest_map": hardest_path, + }) + zones.append({ + "region": region, "name": name, + "maps": [member["path"] for member in members], + "monster_levels": { + "min": min(member["monster_levels"]["min"] for member in members), + "max": max(member["monster_levels"]["max"] for member in members)}, + "ratings": ratings, + }) + return zones + + +def render_text(report: dict) -> str: + lines = [ + "Atrinik map difficulty report (encounter model, reference character " + f"HP {report['reference_character']['hp']}, healing " + f"{report['reference_character']['healing_per_second']} HP/s)", + "Ratings: easy >= 85% safety, fair >= 65%, hard >= 40%, deadly > 0, lethal 0.", + *(f"Warning: {warning}" for warning in report.get("warnings", ())), + "", + ] + for zone in report["zones"]: + levels = zone["monster_levels"] + lines.append(f"{zone['name']} [{zone['region'] or 'no region'}] " + f"L{levels['min']}-{levels['max']}, {len(zone['maps'])} map(s)") + for rating in zone["ratings"]: + lines.append( + f" L{rating['level']:>3} {rating['style']:<12} {rating['rating']:<7} " + f"safety {rating['min_safety']:.2f}-{rating['max_safety']:.2f}; " + f"hardest {Path(rating['hardest_map']).name}") + lines.append("") + for record in report["maps"]: + levels = record["monster_levels"] + lines.append(f"{record['path']} — {record['name']} L{levels['min']}-{levels['max']}, " + f"{len(record['spawns'])} spawns, {record['width']}x{record['height']}") + for rating in record["ratings"]: + lines.append( + f" L{rating['level']:>3} {rating['style']:<12} {rating['rating']:<7} " + f"{rating['safety']:.2f} (pull ~{rating['expected_attackers']:.1f}, bad " + f"{rating['bad_pull_attackers']:g}): {rating['reasons'][1] if len(rating['reasons']) > 1 else ''}") + for hotspot in record["hotspots"][:5]: + where = (f" ({hotspot['x']}, {hotspot['y']})" if hotspot.get("x") is not None else "") + lines.append(f" * {hotspot['kind']}{where}: {hotspot['reason']}") + return "\n".join(lines) + + +def main(argv: list[str]) -> int: + args = build_parser().parse_args(argv) + if not (1 <= args.kite_distance <= 12): + raise SystemExit("kite-distance must be between 1 and 12") + if args.hp_per_level <= 0.0 or args.dps_per_level <= 0.0 or args.speed <= 0.0: + raise SystemExit("hp, dps and speed per level must be positive") + if args.healing_per_level < 0.0 or args.ac_per_level < 0.0: + raise SystemExit("healing and AC per level cannot be negative") + if not -100 <= args.physical_protection <= 95: + raise SystemExit("physical protection must be between -100 and 95") + analyzer = FarmingAnalyzer(args.content_root, args.server_root) + report = build_report(analyzer, args) + print(json.dumps(report, indent=2) if args.json else render_text(report)) + return 0 diff --git a/farming_analyzer/tests/test_encounter.py b/farming_analyzer/tests/test_encounter.py new file mode 100644 index 0000000..e1a80af --- /dev/null +++ b/farming_analyzer/tests/test_encounter.py @@ -0,0 +1,740 @@ +"""Encounter model: pulls, packs, combat styles, terrain and the difficulty report.""" + +from __future__ import annotations + +import io +import json +import math +import tempfile +import unittest +from dataclasses import replace +from pathlib import Path +from unittest.mock import patch + +from farming_analyzer import encounter as enc +from farming_analyzer.analyzer import read_spell_table +from farming_analyzer import ( + SERVER_ROOT, + AnalysisOptions, + FarmingAnalyzer, + ROOT, + MapResult, + main, +) + + +def spawn(x: int, y: int, **changes) -> enc.EncounterSpawn: + values = dict(name="brute", level=10, aggressive=1.0, radius=3, dps=10.0, + kill_seconds=20.0, engaged_speed=1.5, idle_speed=0.8) + values.update(changes) + return enc.EncounterSpawn(x, y, **values) + + +def field(width: int = 24, height: int = 24) -> set[tuple[int, int]]: + return {(x, y) for x in range(width) for y in range(height)} + + +def model(spawns, walkable=None, style="melee", healing=0.0, aoe=1.0, width=24, height=24): + walkable = field(width, height) if walkable is None else walkable + terrain = enc.analyze_terrain(width, height, walkable) + options = enc.EncounterOptions(enc.style_profiles()[style], healing, 8.0, aoe) + return enc.estimate(list(spawns), walkable, terrain, options), options + + +class PullNeedTest(unittest.TestCase): + def test_single_monster_costs_its_damage_above_healing(self): + self.assertAlmostEqual(200.0, enc.pull_need([enc.Fighter(1.0, 10.0, 20.0)])) + self.assertAlmostEqual(100.0, enc.pull_need([enc.Fighter(1.0, 10.0, 20.0)], 5.0)) + self.assertEqual(0.0, enc.pull_need([enc.Fighter(1.0, 4.0, 20.0)], 5.0)) + + def test_pack_is_killed_in_the_cheapest_order(self): + # Kill the 1 s/2 DPS monster first: 3 DPS for 1 s, then 1 DPS for 10 s. + fighters = [enc.Fighter(1.0, 1.0, 10.0), enc.Fighter(1.0, 2.0, 1.0)] + self.assertAlmostEqual(13.0, enc.pull_need(fighters)) + + def test_late_arrivals_cost_less_and_aoe_divides_kill_time(self): + together = enc.pull_need([enc.Fighter(1.0, 10.0, 20.0), enc.Fighter(1.0, 10.0, 20.0)]) + late = enc.pull_need([enc.Fighter(1.0, 10.0, 20.0), + enc.Fighter(1.0, 10.0, 20.0, arrival=10.0)]) + self.assertAlmostEqual(600.0, together) + self.assertLess(late, together) + self.assertAlmostEqual(300.0, enc.pull_need( + [enc.Fighter(1.0, 10.0, 20.0), enc.Fighter(1.0, 10.0, 20.0)], targets=2.0)) + + def test_unkillable_damaging_monster_is_infinite(self): + self.assertTrue(math.isinf(enc.pull_need([enc.Fighter(1.0, 1.0, math.inf)]))) + self.assertEqual(0.0, enc.safety_from_need(math.inf, 100.0)) + + def test_safety_scales_are_documented_shapes(self): + self.assertEqual(1.0, enc.safety_from_need(0.0, 300.0)) + self.assertAlmostEqual(0.5, enc.safety_from_need(150.0, 300.0)) + self.assertEqual(0.0, enc.safety_from_need(450.0, 300.0)) + self.assertAlmostEqual(0.5, enc.bad_pull_safety(300.0, 300.0)) + self.assertAlmostEqual(0.25, enc.bad_pull_safety(900.0, 300.0)) + self.assertAlmostEqual(0.875, enc.blended_safety(1.0, 0.5)) + self.assertEqual("easy", enc.rating(0.9)) + self.assertEqual("deadly", enc.rating(0.1)) + + +class TerrainTest(unittest.TestCase): + def test_two_rooms_joined_by_a_doorway(self): + # Two 5x5 rooms, x 0-4 and 6-10, joined through (5, 2). + walkable = {(x, y) for x in range(5) for y in range(5)} + walkable |= {(x, y) for x in range(6, 11) for y in range(5)} + walkable.add((5, 2)) + terrain = enc.analyze_terrain(11, 5, walkable, {1: {(10, y) for y in range(5)}}) + self.assertEqual(1, terrain.regions) + self.assertEqual(((5, 2),), terrain.doorways) + self.assertEqual(1, terrain.corridor_tiles) + self.assertEqual({"east": 5}, terrain.seams) + self.assertGreater(terrain.kite_room, terrain.open_fraction) + + def test_open_field_and_dead_ends(self): + walkable = field(12, 12) | {(12, 5), (13, 5)} + terrain = enc.analyze_terrain(14, 12, walkable) + self.assertEqual(1, terrain.dead_ends) + self.assertEqual(64, terrain.open_field_tiles) + self.assertIsNotNone(terrain.open_field_center) + + +class EncounterEstimateTest(unittest.TestCase): + def test_sparse_spawns_are_single_pulls(self): + built, _options = model([spawn(2, 2), spawn(12, 12), spawn(21, 21)]) + self.assertEqual(1.0, built.expected_pack) + self.assertEqual(1.0, built.worst_pack) + self.assertAlmostEqual(200.0, built.need) + + def test_spawns_two_apart_can_still_be_pulled_one_at_a_time(self): + # With radius 3, a member of a two-tile grid is pulled from outside. + built, _options = model([spawn(x, y) for x in (4, 6, 8) for y in (4, 6)]) + self.assertEqual(1.0, built.expected_pack) + self.assertGreater(built.worst_pack, 2.0) + + def test_dense_spawns_form_packs_that_cost_more(self): + dense = [spawn(x, y) for x in (4, 5, 6) for y in (4, 5)] + built, _options = model(dense) + sparse, _options = model([spawn(2, 2), spawn(12, 12), spawn(21, 21)]) + self.assertGreaterEqual(built.expected_pack, 2.0) + self.assertGreater(built.worst_pack, built.expected_pack) + self.assertGreater(built.need, sparse.need) + safety = enc.blended_safety(enc.safety_from_need(built.need, 600.0), + enc.bad_pull_safety(built.worst_need, 600.0)) + sparse_safety = enc.blended_safety(enc.safety_from_need(sparse.need, 600.0), + enc.bad_pull_safety(sparse.worst_need, 600.0)) + self.assertLess(safety, sparse_safety) + self.assertLess(sparse_safety, 1.0) + + def test_pull_square_avoids_neighbours(self): + # A neighbour four tiles east: pulling from the west keeps it out. + built, _options = model([spawn(10, 10), spawn(14, 10)]) + pull = next(pull for pull in built.pulls if pull.target == 0) + self.assertLess(pull.x, 10) + self.assertEqual(1.0, pull.expected) + # The bad pull (engaged radius + 3 footprint) still reaches it. + self.assertEqual(2.0, pull.worst) + + def test_wanderers_join_and_are_used_up_by_the_clear(self): + wander = dict(wander_tiles=frozenset(field()), wander_box=(0, 0, 23, 23)) + built, _options = model([spawn(4, 4, **wander), spawn(20, 20, **wander), + spawn(12, 12, **wander)]) + static, _options = model([spawn(4, 4), spawn(20, 20), spawn(12, 12)]) + self.assertEqual(1.0, static.expected_pack) + self.assertGreater(built.expected_pack, 1.2) + # A wanderer that joins an early pull is not there for a later one. + self.assertLess(sum(built.weights), 3.0) + # A lone wanderer is met where nothing else can join. + alone, _options = model([spawn(4, 4), spawn(12, 12, **wander)]) + self.assertEqual(1.0, alone.expected_pack) + + def test_links_by_title_and_faction(self): + caller = dict(link_chance=1 / 6, faction="monsters") + far = spawn(20, 20, faction="monsters") + unlinked, _options = model([spawn(4, 4, **caller), far]) + self.assertEqual(1.0, unlinked.pulls[0].expected) + grouped, _options = model([spawn(4, 4, link_group="pack", **caller), + spawn(20, 20, link_group="pack", **caller)]) + self.assertGreater(grouped.expected_pack, 1.9) + # The clear takes a silent group member first, which calls no one. + one_caller, _options = model([spawn(4, 4, link_group="pack", **caller), + spawn(20, 20, faction="monsters", link_group="pack")]) + self.assertEqual(1.0, one_caller.expected_pack) + # Allies inside the caller's signal radius answer without a title. + near, _options = model([spawn(4, 4, **caller), spawn(7, 4, **caller)]) + self.assertGreater(near.expected_pack, 1.9) + silent, _options = model([spawn(4, 4, link_group="pack", faction="monsters"), + spawn(20, 20, link_group="pack")]) + self.assertEqual(1.0, silent.expected_pack) + + def test_walls_stop_melee_but_not_casters(self): + # A wall column at x = 12 splits the map into two regions. + walkable = {tile for tile in field() if tile[0] != 12} + melee, _options = model([spawn(10, 10), spawn(14, 10)], walkable) + caster, _options = model([spawn(10, 10), spawn(14, 10, caster=True, + damage_types=("fire",))], walkable) + self.assertEqual(1.0, melee.worst_pack) + self.assertEqual(2.0, caster.worst_pack) + + def test_kiting_avoids_slow_melee_but_not_fast_monsters_or_casters(self): + slow = [spawn(x, y) for x in (4, 5, 6) for y in (4, 5)] + melee, _options = model(slow) + kite, _options = model(slow, style="ranged-kite") + self.assertLess(kite.need, melee.need * 0.5) + fast = [spawn(x, y, engaged_speed=16.0) for x in (4, 5, 6) for y in (4, 5)] + fast_kite, _options = model(fast, style="ranged-kite") + self.assertGreater(fast_kite.need, kite.need * 2.0) + casters = [spawn(x, y, caster=True) for x in (4, 5, 6) for y in (4, 5)] + caster_kite, _options = model(casters, style="ranged-kite") + self.assertGreater(caster_kite.need, kite.need * 2.0) + + def test_pack_styles_seek_the_cluster_and_aoe_shares_kills(self): + cluster = [spawn(x, y) for x in (4, 6, 8) for y in (4, 6)] + [spawn(20, 20)] + # Two-tile spacing: the single-pull style isolates every member. + single, _options = model(cluster) + pack, _options = model(cluster, style="melee-pack") + self.assertGreater(pack.expected_pack, single.expected_pack) + aoe, _options = model(cluster, style="aoe-kite", aoe=4.0) + kite_one, _options = model(cluster, style="aoe-kite", aoe=1.0) + self.assertLess(aoe.need, kite_one.need) + + def test_unkillable_target_next_to_a_wanderer_is_not_farmable(self): + wander = dict(wander_tiles=frozenset(field()), wander_box=(0, 0, 23, 23)) + immune = spawn(10, 10, kill_seconds=math.inf) + for style in enc.STYLE_NAMES: + built, options = model([immune, spawn(12, 12, **wander), + spawn(14, 10, link_chance=0.2, faction="f")], + style=style) + self.assertTrue(math.isinf(built.need), style) + self.assertEqual(0.0, enc.safety_from_need(built.need, 300.0)) + self.assertTrue(any("not farmable" in line + for line in enc.reasons(built, options, 300.0))) + # An immune monster that cannot hurt, or will not attack, is left + # alone: it is never pulled and does not make the map lethal. + for harmless_target in (spawn(10, 10, kill_seconds=math.inf, dps=0.0), + spawn(10, 10, kill_seconds=math.inf, aggressive=0.0)): + harmless, options = model([harmless_target, spawn(12, 12, **wander), + spawn(20, 20)]) + self.assertTrue(math.isfinite(harmless.need)) + self.assertNotIn(0, {pull.target for pull in harmless.pulls}) + self.assertTrue(any("left alone" in line + for line in enc.reasons(harmless, options, 300.0))) + self.assertEqual(enc.FIGHT_HORIZON, enc.horizon(math.inf)) + self.assertEqual(enc.FIGHT_HORIZON, enc.horizon(math.nan)) + + def test_kiters_are_not_safe_against_a_huge_slow_pack(self): + horde = [spawn(x, y) for x in range(4, 9) for y in range(4, 8)] + self.assertEqual(20, len(horde)) + for style, aoe, ratings in (("ranged-kite", 1.0, ("fair", "hard", "deadly")), + ("aoe-kite", 4.0, ("hard", "deadly", "lethal"))): + built, _options = model(horde, style=style, aoe=aoe) + bad = enc.bad_pull_safety(built.worst_need, 600.0) + safety = enc.blended_safety(enc.safety_from_need(built.need, 600.0), bad) + self.assertGreaterEqual(built.worst_pack, 9.0, style) + # The whole horde engaged costs several health bars for a kiter. + self.assertLess(bad, 0.3, style) + self.assertIn(enc.rating(safety), ratings, style) + # A single-target shooter can still pick members off from range. + single, _options = model(horde, style="ranged-kite") + self.assertLess(single.expected_pack, 1.5) + # Uptime of slow melee grows with the attackers closing escape routes. + options = enc.EncounterOptions(enc.style_profiles()["ranged-kite"], 0.0, 8.0) + slow = spawn(0, 0) + self.assertAlmostEqual(0.1, enc.melee_uptime(slow, options, 0.9, 1.0)) + self.assertAlmostEqual(0.55, enc.melee_uptime(slow, options, 0.9, 5.0)) + self.assertEqual(1.0, enc.melee_uptime(slow, options, 0.9, 9.0)) + + def test_aoe_provokes_a_passive_immune_monster_in_its_footprint(self): + immune = spawn(6, 4, kill_seconds=math.inf, aggressive=0.0) + brutes = [spawn(4, 4), immune, spawn(20, 20)] + # Single-target styles leave the passive immune monster alone. + for style in ("melee", "ranged-kite"): + built, _options = model(brutes, style=style) + self.assertTrue(math.isfinite(built.need), style) + # AoE hits it, it turns on the character and cannot be killed. + aoe, options = model(brutes, style="aoe-kite", aoe=4.0) + self.assertTrue(math.isinf(aoe.need)) + self.assertTrue(any("not farmable" in line + for line in enc.reasons(aoe, options, 300.0))) + # A passive immune monster that deals no damage stays harmless. + harmless = [spawn(4, 4), spawn(6, 4, kill_seconds=math.inf, aggressive=0.0, dps=0.0)] + quiet, _options = model(harmless, style="aoe-kite", aoe=4.0) + self.assertTrue(math.isfinite(quiet.need)) + # Killable passive monsters inside the footprint join an AoE pull. + passive = [spawn(4, 4), spawn(6, 4, aggressive=0.0), spawn(5, 6, aggressive=0.0)] + gathered, _options = model(passive, style="aoe-kite", aoe=4.0) + single, _options = model(passive, style="ranged-kite") + self.assertGreater(gathered.expected_pack, 2.5) + self.assertEqual(1.0, single.expected_pack) + + def test_kiting_never_costs_more_than_standing_and_fighting(self): + # The same pack, costed as a kiter and as a melee character: stepping + # away must not make a pinned or cramped kiter pay more. + for engaged_speed in (0.5, 4.0, 7.5): + for room in (0.05, 0.5, 0.9): + for size in (1, 2, 5, 9, 20, 36): + pack = [(spawn(0, 0, engaged_speed=engaged_speed), 1.0, 0.0) + for _ in range(size)] + melee = enc.EncounterOptions(enc.style_profiles()["melee"], 2.0, 8.0) + stand = enc._cheaper_pull(pack, melee, room, size, 1.0) + for style in ("ranged-kite", "aoe-kite"): + kite = enc._cheaper_pull( + pack, replace(melee, style=enc.style_profiles()[style]), + room, size, 1.0) + self.assertLessEqual(kite, stand + 1e-6, + (style, engaged_speed, room, size)) + # Pinned (nine or more attackers): no stepping-away time is charged. + options = enc.EncounterOptions(enc.style_profiles()["ranged-kite"], 0.0, 8.0) + self.assertEqual(1.0, enc.kite_attack_share(spawn(0, 0), options, 0.9, 9.0)) + + def test_hordes_cost_a_kiter_no_more_than_melee(self): + # Every monster of a 20 or 36 block is in each style's bad pull. + for columns, rows in ((5, 4), (6, 6)): + horde = [spawn(x, y) for x in range(4, 4 + columns) for y in range(4, 4 + rows)] + melee, _options = model(horde) + self.assertEqual(columns * rows, melee.worst_pack) + for style, aoe in (("ranged-kite", 1.0), ("aoe-kite", 4.0)): + kite, _options = model(horde, style=style, aoe=aoe) + self.assertEqual(melee.worst_pack, kite.worst_pack, style) + self.assertLessEqual(kite.worst_need, melee.worst_need, style) + + def test_static_monsters_neither_call_nor_answer(self): + caller = dict(link_chance=1 / 6, faction="monsters", link_group="pack") + linked, _options = model([spawn(4, 4, **caller), spawn(20, 20, **caller)]) + self.assertGreater(linked.expected_pack, 1.9) + static, _options = model([spawn(4, 4, spawn_point=False, **caller), + spawn(20, 20, spawn_point=False, **caller)]) + self.assertEqual(1.0, static.expected_pack) + + def test_a_called_passive_ally_fights(self): + caller = dict(link_chance=1 / 6, faction="monsters", link_group="pack") + built, _options = model([spawn(4, 4, **caller), + spawn(20, 20, aggressive=0.0, **caller)]) + pull = next(pull for pull in built.pulls if pull.target == 0) + self.assertGreater(pull.expected, 1.9) + self.assertIn(1, pull.worst_joiners) + + def test_seams_without_crossable_tiles_are_omitted(self): + terrain = enc.analyze_terrain(4, 4, field(4, 4), {0: set(), 1: {(3, 0)}}) + self.assertEqual({"east": 1}, terrain.seams) + + def test_healing_offsets_sustained_damage(self): + built, _options = model([spawn(2, 2), spawn(12, 12)], healing=10.0) + self.assertEqual(0.0, built.need) + + def test_hotspots_and_reasons_explain_the_map(self): + dense = [spawn(x, y) for x in (4, 6, 8) for y in (4, 6)] + dense.append(spawn(18, 18, caster=True, damage_types=("fire",), spells=("firestorm",))) + dense.append(spawn(20, 4, wander_tiles=frozenset(field()), wander_box=(0, 0, 23, 23))) + dense.append(spawn(27, 10, own_map=False, map_path="maps/next")) + built, options = model(dense) + kinds = {hotspot["kind"] for hotspot in enc.hotspots(built)} + self.assertLessEqual({"hardest_pull", "dense_cluster", "caster", "wanderers"}, kinds) + self.assertIn("seam_reach", kinds) + lines = enc.reasons(built, options, 300.0) + self.assertTrue(lines[0].startswith("8 spawns (8 aggressive)")) + self.assertTrue(any("caster/ranged" in line and "fire" in line for line in lines)) + self.assertTrue(any("wanderer" in line for line in lines)) + + +ARCHETYPES = """\ +Object floor +terrain_type 1 +end +Object wall +no_pass 1 +end +Object spawn_point +type 81 +last_grace 1 +speed -0.01 +end +Object brute +name brute +type 80 +monster 1 +level 10 +maxhp 60 +dam 40 +wc 10 +ac 1 +speed 0.05 +weapon_speed 1 +item_power 3 +attack_impact 100 +faction monsters +exp 200 +end +Object deer +name deer +type 80 +monster 1 +level 10 +maxhp 60 +dam 40 +wc 10 +ac 1 +speed 0.05 +weapon_speed 1 +item_power 3 +attack_impact 100 +random_move 1 +faction monsters +exp 200 +end +Object mage +name mage +type 80 +monster 1 +level 10 +maxhp 60 +dam 20 +wc 10 +ac 1 +speed 0.05 +weapon_speed 1 +item_power 4 +can_cast_spell 1 +faction monsters +exp 200 +end +Object ability_firestorm +type 110 +sp {firestorm_index} +end +Object {firestorm_arch} +attack_fire 100 +end +Object slowpoke +name slowpoke +type 80 +monster 1 +level 10 +maxhp 60 +dam 40 +wc 10 +ac 1 +speed 0.05 +slow_move 1 +weapon_speed 1 +item_power 3 +faction monsters +exp 200 +end +""" + + +def spell_archetypes() -> str: + """The test archetypes, with firestorm's index and cast archetype read + from the server's spell table rather than assumed.""" + table = read_spell_table(SERVER_ROOT) + index = next(number for number, (name, _arch) in enumerate(table) if name == "firestorm") + return ARCHETYPES.format(firestorm_index=index, firestorm_arch=table[index][1]) + +SIZE = 24 + + +def _map(name: str, spawns: tuple[tuple[str, int, int], ...], children: str = "") -> str: + lines = ["arch map", f"name {name}", f"width {SIZE}", f"height {SIZE}", + "difficulty 10", "region forest", "end"] + for y in range(SIZE): + for x in range(SIZE): + 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"] + if monster == "mage": + lines += ["arch ability_firestorm", "end"] + lines += ["end", "end"] + return "\n".join(lines) + "\n" + children + + +DENSE = "maps/forest/world_0_0" +SPARSE = "maps/forest/world_5_5" +CRYPT = "maps/forest/world_9_9" + + +class AnalyzerEncounterTest(unittest.TestCase): + """The scan reports the encounter model and --combat-style applies it.""" + + @classmethod + def setUpClass(cls): + cls.directory = tempfile.TemporaryDirectory() + root = Path(cls.directory.name) + (root / "arch").mkdir() + (root / "arch" / "test.arc").write_text(spell_archetypes()) + maps = root / "maps" / "forest" + maps.mkdir(parents=True) + (root / "maps" / "regions.reg").write_text("region forest\nlongname Forest\nend\n") + dense = tuple(("brute", x, y) for x in (4, 5, 6) for y in (4, 5)) + ( + ("deer", 16, 16),) + (maps / "world_0_0").write_text(_map("Thicket", dense)) + (maps / "world_5_5").write_text(_map( + "Glade", (("brute", 2, 2), ("brute", 12, 12), ("brute", 21, 21)))) + (maps / "world_9_9").write_text(_map( + "Crypt", (("mage", 4, 4), ("mage", 6, 4), ("brute", 20, 20)))) + cls.analyzer = FarmingAnalyzer(root, SERVER_ROOT) + + @classmethod + def tearDownClass(cls): + cls.directory.cleanup() + + @staticmethod + def options(**changes) -> AnalysisOptions: + options = AnalysisOptions( + player_level=10, dps=6.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=1, + path_pattern="forest", 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=6.0, attack_delay=1.0, max_health=400.0, + model_approach=False) + 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_fields_are_reported_without_changing_safety(self): + plain = self.results(self.options()) + ignored = self.results(self.options(model_encounters=False)) + for path in (DENSE, SPARSE): + self.assertEqual(ignored[path].safety_score, plain[path].safety_score) + self.assertEqual(ignored[path].max_aggro_pack, plain[path].max_aggro_pack) + self.assertEqual("melee", plain[path].encounter_style) + self.assertFalse(plain[path].encounter_applied) + self.assertEqual("", ignored[path].encounter_style) + self.assertGreaterEqual(plain[DENSE].expected_pack, 2.0) + self.assertEqual(1.0, plain[SPARSE].expected_pack) + self.assertEqual(1.0, plain[DENSE].wanderer_spawns) + + def test_combat_style_breaks_the_saturated_tie(self): + old = self.results(self.options(max_health=4000.0)) + self.assertEqual(old[DENSE].safety_score, old[SPARSE].safety_score) + styled = self.results(self.options(max_health=4000.0, combat_style="melee")) + dense, sparse = styled[DENSE], styled[SPARSE] + self.assertTrue(dense.encounter_applied) + self.assertLess(dense.safety_score, sparse.safety_score) + self.assertLess(dense.safety_score, 1.0) + self.assertEqual(dense.safety_score, dense.spot_safety_score) + self.assertEqual(min(1.0, dense.encounter_safety), dense.safety_score) + + def test_kiting_style_rates_the_slow_pack_safer(self): + melee = self.results(self.options(combat_style="melee"))[DENSE] + kite = self.results(self.options(combat_style="ranged-kite"))[DENSE] + self.assertGreater(kite.encounter_safety, melee.encounter_safety) + + def test_caster_map_is_flagged_with_damage_types(self): + crypt = self.results(self.options())[CRYPT] + self.assertEqual(2.0, crypt.caster_spawns) + self.assertTrue(any("caster/ranged" in line and "fire" in line + for line in crypt.encounter_reasons)) + spawns, _competitors = self.analyzer._spawns_cached( + "/forest/world_9_9", self.options(), False) + built = self.analyzer.map_encounter("/forest/world_9_9", spawns, self.options()) + casters = [hotspot for hotspot in enc.hotspots(built) if hotspot["kind"] == "caster"] + self.assertEqual(2, len(casters)) + self.assertEqual(["fire"], casters[0]["damage_types"]) + self.assertEqual(["firestorm"], casters[0]["spells"]) + self.assertEqual(set(), self.analyzer.source_warnings) + + def test_slow_move_halves_idle_speed_only(self): + spawns, _competitors = self.analyzer._spawns_cached( + "/forest/world_9_9", self.options(), False) + brute = spawns[-1].candidates[0][1] + # living.c 1851-1875: 2x idle, 4x fighting; slow_move 1x and 3x. + self.assertAlmostEqual(0.05 * 2 / 0.125, brute.idle_speed) + self.assertAlmostEqual(0.05 * 4 / 0.125, brute.engaged_speed) + profile = self.analyzer._monster_profile( + {"arch": "slowpoke", "attrs": {}, "children": []}, 10, self.options()) + self.assertAlmostEqual(0.05 / 0.125, profile.idle_speed) + self.assertAlmostEqual(0.05 * 3 / 0.125, profile.engaged_speed) + + def test_circuit_encounter_fields_come_from_one_member(self): + results = self.results(self.options(combat_style="melee")) + dense, sparse = results[DENSE], results[SPARSE] + combined = FarmingAnalyzer._combine_encounters([sparse, dense], 10.0) + for key in ("expected_pack", "worst_pack", "encounter_need", + "encounter_worst_need", "encounter_safety", "encounter_pull"): + self.assertEqual(getattr(dense, key), combined[key], key) + self.assertTrue(all(line.startswith("world_0_0: ") + for line in combined["encounter_reasons"])) + + def test_missing_server_tables_warn(self): + with tempfile.TemporaryDirectory() as directory: + server = Path(directory) / "src" + for source in SERVER_ROOT.rglob("*"): + relative = source.relative_to(SERVER_ROOT) + if source.is_dir() or relative.as_posix() in ( + "server/living.c", "include/spellist.h"): + continue + target = server / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.symlink_to(source) + analyzer = FarmingAnalyzer(Path(self.directory.name), server) + results = {result.path: result for result in analyzer.scan(self.options())} + self.assertEqual(2.0, results[CRYPT].caster_spawns) + self.assertEqual(2, len(analyzer.source_warnings)) + self.assertTrue(any("living.c" in item for item in analyzer.source_warnings)) + self.assertTrue(any("spellist.h" in item for item in analyzer.source_warnings)) + + def test_relative_mode_without_health(self): + results = self.results(self.options(max_health=0.0, combat_style="melee")) + self.assertEqual(1.0, results[SPARSE].encounter_expected_safety) + self.assertLess(results[DENSE].encounter_safety, results[SPARSE].encounter_safety) + + def test_cli_json_schema_version_and_validation(self): + def run(*extra: str) -> dict: + stdout = io.StringIO() + with patch("sys.stdout", stdout): + main(["10", "--damage-per-attack", "6", "--attack-delay", "1", + "--max-health", "400", "--min-spawns", "1", + "--min-xp-fraction", "0", "--path", "forest", "--circuit-size", "1", + "--show-all-routes", "--json", "--ignore-approach", + "--content-root", self.directory.name, + "--server-root", str(SERVER_ROOT), *extra]) + return json.loads(stdout.getvalue()) + + payload = run("--combat-style", "melee", "--healing-per-second", "1") + self.assertEqual(2, payload["schema_version"]) + self.assertEqual("melee", payload["assumptions"]["combat_style"]) + dense = next(item for item in payload["results"] if item["path"] == DENSE) + for key in ("expected_pack", "worst_pack", "encounter_safety", "encounter_reasons", + "encounter_pull", "wanderer_spawns", "caster_spawns", "seam_spawns"): + self.assertIn(key, dense) + self.assertTrue(dense["encounter_applied"]) + with self.assertRaises(SystemExit): + run("--healing-per-second", "-1") + with self.assertRaises(SystemExit): + run("--combat-style", "melee", "--ignore-encounters") + with self.assertRaises(SystemExit): + run("--kite-distance", "0") + + def test_difficulty_report_schema(self): + stdout = io.StringIO() + with patch("sys.stdout", stdout): + main(["report", "--content-root", self.directory.name, + "--server-root", str(SERVER_ROOT), "--levels", "10", + "--styles", "melee,ranged-kite", "--json"]) + report = json.loads(stdout.getvalue()) + self.assertEqual("atrinik.farming_analyzer.difficulty_report", report["schema"]) + self.assertEqual(1, report["schema_version"]) + by_path = {record["path"]: record for record in report["maps"]} + self.assertEqual({DENSE, SPARSE, CRYPT}, set(by_path)) + dense = by_path[DENSE] + self.assertEqual({"melee", "ranged-kite"}, + {rating["style"] for rating in dense["ratings"]}) + rating = dense["ratings"][0] + for key in ("safety", "expected_safety", "bad_pull_safety", "rating", + "expected_attackers", "bad_pull_attackers", "hardest_pull", "reasons"): + self.assertIn(key, rating) + self.assertIn("dense_cluster", {hotspot["kind"] for hotspot in dense["hotspots"]}) + self.assertEqual(7, len(dense["spawns"])) + deer = next(item for item in dense["spawns"] if item["name"] == "deer") + self.assertEqual({"x0": 0, "y0": 0, "x1": 23, "y1": 23, "tiles": 576}, deer["wander"]) + self.assertEqual(9, deer["chase_range"]) + self.assertEqual(6, deer["engaged_radius"]) + self.assertIn("caster", {hotspot["kind"] for hotspot in by_path[CRYPT]["hotspots"]}) + melee = {rating["path"] if "path" in rating else path: rating + for path, record in by_path.items() for rating in record["ratings"] + if rating["style"] == "melee"} + self.assertLess(melee[DENSE]["safety"], melee[SPARSE]["safety"]) + # Zones group maps by region and map name. + zones = {zone["name"]: zone for zone in report["zones"]} + self.assertEqual({"Thicket", "Glade", "Crypt"}, set(zones)) + thicket = zones["Thicket"] + self.assertEqual([DENSE], thicket["maps"]) + self.assertEqual(melee[DENSE]["safety"], next( + item["min_safety"] for item in thicket["ratings"] if item["style"] == "melee")) + text = io.StringIO() + with patch("sys.stdout", text): + main(["report", "--content-root", self.directory.name, + "--server-root", str(SERVER_ROOT), "--levels", "10", "--styles", "melee"]) + self.assertIn("dense_cluster", text.getvalue()) + with self.assertRaises(SystemExit): + main(["report", "--content-root", self.directory.name, + "--server-root", str(SERVER_ROOT), "--styles", "dance"]) + + +SHATTERED = ROOT / "maps" / "shattered_islands" + + +@unittest.skipUnless((SHATTERED / "world_16_74").is_file(), + "CONTENT-DEPENDENT: requires the sibling content checkout " + f"at {SHATTERED.parent.parent}; Burnt Forest regression not run") +class BurntForestTest(unittest.TestCase): + """Regression for the 2026-11-25 Burnt Forest deaths of the playtester. + + Content-dependent: it reads the authored Burnt Forest maps, so it uses + ranges and orderings rather than exact values, and content edits to + these maps may legitimately move it. + """ + + @classmethod + def setUpClass(cls): + cls.analyzer = FarmingAnalyzer() + + @staticmethod + def sera(**changes) -> AnalysisOptions: + """Level 37 melee healer: her live kit on 2026-11-25.""" + options = AnalysisOptions( + player_level=37, dps=0.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=100, circuit_size=1, + path_pattern=r"shattered_islands/world_1[5-7]_7[2-6]$", include_static=False, + character_level=37, player_ac=58, + player_protections=(("cleave", 39), ("cold", 9), ("impact", 38), + ("pierce", 36), ("slash", 50)), + melee_damage=82, weapon_class=44, weapon_speed=3.0, weapon_class_range=20, + player_attacks=(("slash", 100),), max_health=333.0, character_speed=0.8, + model_approach=False, combat_style="melee", healing_per_second=5.5) + return replace(options, **changes) + + def results(self, options: AnalysisOptions) -> dict[str, MapResult]: + return {Path(result.path).name: result for result in self.analyzer.scan(options)} + + def test_dense_world_16_74_forms_packs_and_is_not_saturated(self): + old = self.results(self.sera(combat_style=""))["world_16_74"] + self.assertLessEqual(old.max_aggro_pack, 1.5) + self.assertGreater(old.safety_score, 0.95) + dense = self.results(self.sera())["world_16_74"] + self.assertGreaterEqual(dense.worst_pack, 2.0) + self.assertGreater(dense.expected_pack, 1.0) + self.assertLess(dense.encounter_safety, 0.95) + self.assertLess(dense.safety_score, old.safety_score) + self.assertGreaterEqual(dense.wanderer_spawns, 1.0) + + def test_sparse_southern_maps_rate_safer(self): + results = self.results(self.sera()) + dense = results["world_16_74"].safety_score + for name in ("world_15_75", "world_15_76", "world_16_75", "world_16_76"): + self.assertGreater(results[name].safety_score, dense, name) + # The L38-40 map where she died twice rates hardest of all. + self.assertLess(results["world_17_72"].safety_score, dense) + + def test_aoe_kiting_the_big_treant_packs_is_not_safe(self): + results = self.results(self.sera(combat_style="aoe-kite", targets_per_attack=4)) + dense = results["world_16_74"] + self.assertGreaterEqual(dense.worst_pack, 9.0) + self.assertLess(dense.encounter_safety, 0.65) + + def test_whole_content_scan_with_immune_monsters_does_not_raise(self): + # Fire-only melee: several hostile archetypes have protect_fire 100. + results = self.analyzer.scan(self.sera( + path_pattern=None, player_attacks=(("fire", 100),), max_level_gap=200, + combat_style="")) + self.assertTrue(results) + unfarmable = [result for result in results + if not math.isfinite(result.encounter_need)] + self.assertTrue(unfarmable) + self.assertTrue(all(result.encounter_safety == 0.0 for result in unfarmable)) + + def test_graveyard_skeleton_mages_are_flagged_at_night(self): + options = self.sera(player_level=20, character_level=20, at_minute=0, + path_pattern=r"shattered_islands/world_14_74$") + crypt = self.results(options)["world_14_74"] + self.assertGreaterEqual(crypt.caster_spawns, 3.0) + self.assertTrue(any("caster/ranged" in line and "fire" in line + for line in crypt.encounter_reasons)) + + +if __name__ == "__main__": + unittest.main()