From f7f61b475dc53efef860ef35a5ca0768b7c08ccd Mon Sep 17 00:00:00 2001 From: Smoebo Date: Fri, 20 Nov 2026 18:25:58 -0500 Subject: [PATCH 1/7] An enemy rider can fall: knocked prone or carried by a pushed mount it saves to stay on, a push at the rider takes it alone out of the saddle, and a mount that goes down drops it A rider knocked prone, or whose mount is pushed, pulled or force-moved, makes the DC 10 Dexterity save from its own stat block once as the call finishes, and a failure leaves it prone beside its mount (issue 1055). A push, pull or forced move that names the rider moves the rider alone, prone where the push ends, with no save, and the mount stays (ruling 6). A mount knocked prone or dropped to 0 costs its rider its reaction to land standing, and a rider with none falls prone. Co-Authored-By: Claude Fable 5.2 --- scripts/test-enforce-enemy-rider-falls.mjs | 300 +++++++++++++++++++++ src/lib/dm/encounter-tools.ts | 13 +- src/lib/dm/enemy-damage.ts | 13 +- src/lib/dm/enemy-reactions.ts | 2 +- src/lib/dm/enemy-rider-falls.ts | 264 ++++++++++++++++++ src/lib/dm/enemy-riders.ts | 8 +- src/lib/dm/map-tools.ts | 91 ++++++- src/lib/dm/mt-fb-spend.ts | 9 +- src/lib/dm/zone-triggers.ts | 7 + 9 files changed, 692 insertions(+), 15 deletions(-) create mode 100644 scripts/test-enforce-enemy-rider-falls.mjs create mode 100644 src/lib/dm/enemy-rider-falls.ts diff --git a/scripts/test-enforce-enemy-rider-falls.mjs b/scripts/test-enforce-enemy-rider-falls.mjs new file mode 100644 index 0000000000..16bcf330c6 --- /dev/null +++ b/scripts/test-enforce-enemy-rider-falls.mjs @@ -0,0 +1,300 @@ +// How an enemy rider loses its seat (issue 1055, ruling 6 and the rules as +// written). +// +// "If an effect moves your mount against its will while you're on it, you +// must succeed on a DC 10 Dexterity saving throw or fall off the mount, +// landing prone in a space within 5 feet of it. If you're knocked prone while +// mounted, you must make the same saving throw. If your mount is knocked +// prone, you can use your reaction to dismount it as it falls and land on +// your feet. Otherwise, you are dismounted and fall prone in a space within +// 5 feet it" (SRD 5.1, Mounting and Dismounting). +// +// Ruling 6: a push or a pull that names the rider takes the rider alone, out +// of the saddle, prone where the push ends, with no save; the mount stays. +// The two checks asked for with the rulings: a rider that cannot act fails +// the save with no roll, and a mount that Disengages provokes nothing. +import assert from "node:assert/strict"; +import "./lib/enforce-world.mjs"; +import { suite } from "./lib/enforce-harness.mjs"; +import { openWorld } from "./lib/enforce-world.mjs"; +import { caster, closeTables } from "./lib/enforce-spell-kit.mjs"; +import { layMap } from "./lib/enforce-spells.mjs"; +import { mapOf, OPEN, tokenOf } from "./lib/enforce-zones.mjs"; +import { diff, revertTurn, snapshot } from "./lib/sweep-lifecycle.mjs"; + +const { test, finish } = suite("test-enforce-enemy-rider-falls"); +const { listTokens } = await import("../src/lib/db/battle-maps.ts"); +const { saveEncounter } = await import("../src/lib/db/encounters.ts"); +const { settleEnemyRiders } = await import("../src/lib/dm/enemy-rider-falls.ts"); +const { pushTokenAway } = await import("../src/lib/dm/map-tools.ts"); + +const HERO = () => caster("paladin", "cha", [], [], 5, { speed: 30 }); +const ownToken = (world, refId) => listTokens(mapOf(world).id).find((token) => token.refId === refId) ?? null; +const at = (world, refId) => [ownToken(world, refId)?.x, ownToken(world, refId)?.y]; +const live = (world, id) => world.enemies().find((enemy) => enemy.id === id); +const prone = (world, id) => live(world, id).conditions.includes("prone"); +const mounted = (world, rider) => live(world, rider.id).ridesEnemyId !== undefined; +const beside = (a, b, wide = 1) => a.x >= b.x - 1 && a.x <= b.x + wide && a.y >= b.y - 1 && a.y <= b.y + wide; +const d20s = (world) => world.diceLog().filter((die) => die.sides === 20).length; + +// A hero at (11,4) beside a rider on its mount at (12,4), on an open board. +// The order is the hero, the rider, the mount, with the pointer on the hero. +async function pair({ mount = "wolf" } = {}) { + const world = await openWorld({ gameSettings: { ttsEnabled: false } }); + const hero = world.addHero(HERO()); + await world.beginFight([{ monster: "goblin", mount }]); + const up = world.enemies().find((enemy) => enemy.ridesEnemyId); + const under = world.enemies().find((enemy) => enemy.id === up?.ridesEnemyId); + assert.ok(up && under, "setup: the fight has no rider on a mount"); + await layMap(world, OPEN(), { [hero.id]: { x: 11, y: 4 }, [up.id]: { x: 12, y: 4 } }); + const encounter = world.encounter(); + const entry = (id) => encounter.order.find((row) => (row.characterId ?? row.enemyId) === id); + saveEncounter({ ...encounter, order: [entry(hero.id), entry(up.id), entry(under.id)], turnIndex: 0, turnBudget: null, reactionsUsed: [] }); + world.clearDice(); + world.diceLog(); + return { world, hero, rider: up, mount: under }; +} + +function turnOf(world, enemyId) { + const encounter = world.encounter(); + saveEncounter({ ...encounter, turnIndex: encounter.order.findIndex((entry) => entry.enemyId === enemyId), turnBudget: null }); +} + +// The hero's shove, won: their d20, the target's, then whatever the test +// expects the engine to roll after it. +async function shove(world, hero, targetId, how, ...then) { + world.dice(20, 1, ...then); + const out = await world.invoke("take_action", { characterId: hero.id, action: "shove", targetEnemyId: targetId, shove: how }); + assert.equal(out.ok, true, out.error); + assert.equal(out.result.success, true, `the shove was lost: ${JSON.stringify(out.result)}`); + return out; +} + +// The pair has parted with both on the board: the mount on a token of its +// own where the pair stood, the rider on its own beside it. +function assertParted(world, rider, mount, where = [12, 4], wide = 1) { + assert.equal(mounted(world, rider), false, "the rider is still mounted"); + assert.deepEqual(at(world, mount.id), where, "the mount does not stand where the pair stood, on a token of its own"); + const fallen = ownToken(world, rider.id); + assert.ok(fallen, "the rider has no token"); + assert.ok(beside(fallen, ownToken(world, mount.id), wide), `the rider at (${fallen.x},${fallen.y}) is not within 5 feet of its mount`); +} + +await test("A rider knocked prone makes the DC 10 Dexterity save from its own block, and a failure takes it off its mount, prone beside it.", async () => { + const { world, hero, rider, mount } = await pair(); + // A goblin's Dexterity is 14: a 3 on the die is 5. + await shove(world, hero, rider.id, "prone", 3); + assert.equal(world.clearDice(), 0, "the save to stay mounted was not rolled"); + assertParted(world, rider, mount); + assert.equal(prone(world, rider.id), true, "the fallen rider is not prone"); + assert.equal(prone(world, mount.id), false); +}); + +await test("A rider knocked prone who makes the save keeps its seat, still prone, and one prone asks one save.", async () => { + const { world, hero, rider, mount } = await pair(); + await shove(world, hero, rider.id, "prone", 15); + assert.equal(world.clearDice(), 0, "the save to stay mounted was not rolled"); + assert.equal(live(world, rider.id).ridesEnemyId, mount.id, "a made save took the rider off"); + assert.equal(prone(world, rider.id), true); + assert.equal(ownToken(world, mount.id), null); + world.diceLog(); + const later = await world.invoke("damage_enemy", { enemyId: rider.id, amount: 1, reason: "test" }); + assert.equal(later.ok, true, later.error); + assert.equal(d20s(world), 0, "a rider who kept its seat was asked again for the same prone"); + assert.equal(live(world, rider.id).ridesEnemyId, mount.id); +}); + +await test("The mount pushed against its will carries the pair, and its rider saves once as the call finishes: a made save keeps the seat.", async () => { + const { world, hero, rider, mount } = await pair(); + await shove(world, hero, mount.id, "push", 15); + assert.equal(world.clearDice(), 0, "the rider of a pushed mount made no save"); + assert.deepEqual(at(world, rider.id), [13, 4], "the pair's token did not go with the pushed mount"); + assert.equal(live(world, rider.id).ridesEnemyId, mount.id); + assert.equal(prone(world, rider.id), false); +}); + +await test("The mount pushed against its will throws a rider who fails the save: prone beside the mount, which stands where the push left the pair.", async () => { + const { world, hero, rider, mount } = await pair(); + await shove(world, hero, mount.id, "push", 2); + assert.equal(world.clearDice(), 0); + assertParted(world, rider, mount, [13, 4]); + assert.equal(prone(world, rider.id), true, "the thrown rider is not prone"); +}); + +await test("A forced move_token that names the mount is the mount moved against its will: one save, however far it went.", async () => { + const { world, rider, mount } = await pair(); + world.dice(2); + const dragged = await world.invoke("move_token", { token: mount.id, x: 16, y: 4, forced: true }); + assert.equal(dragged.ok, true, dragged.error); + assert.equal(world.clearDice(), 0, "the rider of a dragged mount made no save"); + assert.equal(d20s(world), 1, "the rider saved more than once for one move"); + assertParted(world, rider, mount, [16, 4]); + assert.equal(prone(world, rider.id), true); +}); + +await test("Ruling 6: a push that names the rider takes the rider alone out of the saddle, prone where the push ends, with no save; the mount stays.", async () => { + const { world, hero, rider, mount } = await pair(); + // A die left over would be the save the ruling says is not made. + await shove(world, hero, rider.id, "push", 20); + assert.equal(world.clearDice(), 1, "the rider pushed from the saddle made a save to stay on"); + assert.equal(mounted(world, rider), false, "the pushed rider is still mounted"); + assert.deepEqual(at(world, rider.id), [13, 4], "the rider did not end where the push ends"); + assert.deepEqual(at(world, mount.id), [12, 4], "the push at the rider moved the mount it never touched"); + assert.equal(prone(world, rider.id), true, "the rider pushed from the saddle did not land prone"); + assert.equal(prone(world, mount.id), false); +}); + +await test("Ruling 6: a push that would end inside a Large mount's space sets the rider down in the nearest open square just outside it.", async () => { + const { world, hero, rider, mount } = await pair({ mount: "warhorse" }); + // The warhorse holds (12,4) to (13,5); the push from (11,4) ends at (13,4). + await shove(world, hero, rider.id, "push"); + assert.equal(mounted(world, rider), false); + assert.deepEqual(at(world, mount.id), [12, 4]); + const fallen = ownToken(world, rider.id); + const inside = fallen.x >= 12 && fallen.x <= 13 && fallen.y >= 4 && fallen.y <= 5; + assert.equal(inside, false, `the rider lies at (${fallen.x},${fallen.y}), inside its mount's space`); + assert.ok(beside(fallen, { x: 12, y: 4 }, 2), `the rider at (${fallen.x},${fallen.y}) is not just outside the mount`); + assert.ok(Math.max(Math.abs(fallen.x - 13), Math.abs(fallen.y - 4)) <= 1, "the rider is not in the open square nearest where the push ended"); + assert.equal(prone(world, rider.id), true); +}); + +await test("Ruling 6: a forced move_token that names the rider carries the rider alone to that square, prone, and leaves the mount.", async () => { + const { world, rider, mount } = await pair(); + world.dice(20); + const thrown = await world.invoke("move_token", { token: rider.id, x: 15, y: 6, forced: true }); + assert.equal(thrown.ok, true, thrown.error); + assert.equal(world.clearDice(), 1, "a rider carried from the saddle made a save"); + assert.match(thrown.result.note ?? "", /out of the saddle/); + assert.deepEqual(at(world, rider.id), [15, 6]); + assert.deepEqual(at(world, mount.id), [12, 4]); + assert.equal(mounted(world, rider), false); + assert.equal(prone(world, rider.id), true); +}); + +await test("Ruling 6: both pushed together move as the pair, and the rider saves once.", async () => { + const { world, hero, rider, mount } = await pair(); + const campaign = world.campaign(); + const encounterId = world.encounter().id; + assert.equal(pushTokenAway(campaign, encounterId, hero.id, mount.id).moved, true); + const second = pushTokenAway(campaign, encounterId, hero.id, rider.id); + assert.equal(second.moved, false, "the rider was pushed again after its mount carried it"); + assert.match(second.reason, /pair moved as one/); + world.diceLog(); + world.dice(15); + const lines = settleEnemyRiders(campaign, []); + assert.equal(world.clearDice(), 0); + assert.equal(d20s(world), 1, "the rider saved more than once"); + assert.equal(lines.length, 1); + assert.match(lines[0], /kept its seat/); + assert.deepEqual(at(world, rider.id), [13, 4]); + assert.equal(live(world, rider.id).ridesEnemyId, mount.id); +}); + +await test("The mount knocked prone: its rider spends its reaction to land on its feet beside it, with no save.", async () => { + const { world, hero, rider, mount } = await pair(); + await shove(world, hero, mount.id, "prone", 20); + assert.equal(world.clearDice(), 1, "the rider of a fallen mount was asked a save"); + assertParted(world, rider, mount); + assert.equal(prone(world, mount.id), true); + assert.equal(prone(world, rider.id), false, "a rider with its reaction fell prone"); + assert.ok(world.encounter().reactionsUsed.includes(rider.id), "landing on its feet cost the rider no reaction"); +}); + +await test("The mount knocked prone under a rider with no reaction left: the rider falls prone within 5 feet.", async () => { + const { world, hero, rider, mount } = await pair(); + saveEncounter({ ...world.encounter(), reactionsUsed: [rider.id] }); + await shove(world, hero, mount.id, "prone"); + assertParted(world, rider, mount); + assert.equal(prone(world, rider.id), true, "a rider with no reaction landed on its feet"); +}); + +await test("The mount dropped to 0: its rider lands on its feet with its reaction, and the result of the blow says so.", async () => { + const { world, rider, mount } = await pair(); + const slain = await world.invoke("damage_enemy", { enemyId: mount.id, amount: 99, reason: "test" }); + assert.equal(slain.ok, true, slain.error); + assert.match(slain.result.pair ?? "", /spends its reaction/, JSON.stringify(slain.result)); + assert.equal(mounted(world, rider), false); + assert.deepEqual(at(world, rider.id), [12, 4]); + assert.equal(prone(world, rider.id), false); + assert.ok(world.encounter().reactionsUsed.includes(rider.id), "the reaction was not spent"); +}); + +await test("The mount dropped to 0 under a rider that cannot react: the rider falls prone, and no reaction is spent.", async () => { + const { world, rider, mount } = await pair(); + const held = await world.invoke("set_condition", { enemyId: rider.id, condition: "paralyzed", reason: "test" }); + assert.equal(held.ok, true, held.error); + const slain = await world.invoke("damage_enemy", { enemyId: mount.id, amount: 99, reason: "test" }); + assert.equal(slain.ok, true, slain.error); + assert.match(slain.result.pair ?? "", /falls prone/, JSON.stringify(slain.result)); + assert.equal(prone(world, rider.id), true, "a paralyzed rider landed on its feet"); + assert.equal(world.encounter().reactionsUsed.includes(rider.id), false); +}); + +for (const condition of ["paralyzed", "stunned", "petrified"]) { + await test(`The check asked with the rulings: a ${condition} rider fails the save with no die rolled when its mount is moved.`, async () => { + const { world, rider, mount } = await pair(); + const laid = await world.invoke("set_condition", { enemyId: rider.id, condition, reason: "test" }); + assert.equal(laid.ok, true, laid.error); + assert.equal(live(world, rider.id).ridesEnemyId, mount.id, `${condition} alone took the rider off`); + world.diceLog(); + world.dice(20); + const dragged = await world.invoke("move_token", { token: mount.id, x: 14, y: 4, forced: true }); + assert.equal(dragged.ok, true, dragged.error); + assert.equal(world.clearDice(), 1, `a ${condition} rider rolled the save`); + assert.equal(d20s(world), 0); + assertParted(world, rider, mount, [14, 4]); + assert.equal(prone(world, rider.id), true); + }); +} + +await test("The check asked with the rulings: a rider that falls unconscious drops prone and fails the save with no die, so it always falls.", async () => { + const { world, rider, mount } = await pair(); + world.dice(20); + const laid = await world.invoke("set_condition", { enemyId: rider.id, condition: "unconscious", reason: "a sleeping draught" }); + assert.equal(laid.ok, true, laid.error); + assert.equal(world.clearDice(), 1, "an unconscious rider rolled the save"); + assertParted(world, rider, mount); + assert.equal(prone(world, rider.id), true); +}); + +await test("The check asked with the rulings: a mount that Disengages provokes nothing, so neither it nor its rider is struck as the pair leaves a hero's reach.", async () => { + const { world, hero, rider, mount } = await pair(); + turnOf(world, mount.id); + const hp = [live(world, rider.id).currentHp, live(world, mount.id).currentHp]; + world.diceLog(); + const away = await world.invoke("move_token", { token: mount.id, x: 18, y: 4, disengage: true }); + assert.equal(away.ok, true, away.error); + assert.ok(away.result.disengaged, "the walk says nothing of the Disengage"); + assert.equal(away.result.opportunityAttacks, undefined, "the pair was struck as it left"); + assert.equal(d20s(world), 0, "an attack was rolled against the pair"); + assert.deepEqual([live(world, rider.id).currentHp, live(world, mount.id).currentHp], hp); + assert.equal(world.encounter().reactionsUsed.includes(hero.id), false, "the hero's reaction was spent"); + assert.deepEqual(at(world, rider.id), [18, 4]); + assert.equal(live(world, rider.id).ridesEnemyId, mount.id, "a walk the mount chose asked its rider to save"); +}); + +await test("Without the Disengage the same walk is struck: the check above is not passing for want of anyone to strike.", async () => { + const { world, mount } = await pair(); + turnOf(world, mount.id); + world.dice(2); + const away = await world.invoke("move_token", { token: mount.id, x: 18, y: 4 }); + world.clearDice(); + assert.equal(away.ok, true, away.error); + assert.ok(away.result.opportunityAttacks?.length, `leaving a hero's reach drew no opportunity attack: ${JSON.stringify(away.result)}`); +}); + +await test("Undoing the GM turn that pushed a rider out of the saddle puts the pair back on its one token.", async () => { + const { world, hero, rider, mount } = await pair(); + const before = snapshot(); + const out = await shove(world, hero, rider.id, "push"); + assert.equal(mounted(world, rider), false); + await revertTurn(world, out.turnId); + assert.deepEqual(diff(before, snapshot()), [], "after Revert this turn the table differs from the one the turn found"); + assert.equal(live(world, rider.id).ridesEnemyId, mount.id, "the undo left the rider on foot"); + assert.deepEqual(at(world, rider.id), [12, 4]); + assert.equal(ownToken(world, mount.id), null, "the mount kept the token the undone turn gave it"); + assert.equal(prone(world, rider.id), false, "the undo left the rider prone"); +}); + +closeTables(); +finish(); diff --git a/src/lib/dm/encounter-tools.ts b/src/lib/dm/encounter-tools.ts index 6f991e0c24..7600a0ba2c 100644 --- a/src/lib/dm/encounter-tools.ts +++ b/src/lib/dm/encounter-tools.ts @@ -154,6 +154,7 @@ import { endEncounterTool, endTurnTool, enemyAttackTool, startEncounterTool, typ import { RUN_PREPARED_ENCOUNTER, runPreparedEncounter } from "@/lib/dm/prepared-encounter-tool"; import { asEventTurn, fireFightEvents } from "@/lib/dm/fight-events"; import { proneRiders, settleProneRiders } from "@/lib/dm/mount-thrown"; +import { pronePairs, settleEnemyRiders } from "@/lib/dm/enemy-rider-falls"; import { settleMovedRiders } from "@/lib/dm/mount-tools"; import { onFoot, riderCarriedBy, takesOwnTurn } from "@/lib/dm/mount-link"; import { rollDeathSave } from "@/lib/dm/death"; @@ -1608,6 +1609,9 @@ export type TurnHolder = { // The mounted riders already prone (mount-thrown.ts): the call that lays a // rider prone is the one that asks for their save. proneRiders: string[]; + // The enemies in a pair already prone (enemy-rider-falls.ts), for the same + // reason. + pronePairs: string[]; }; export function turnHolder(campaignId: string): TurnHolder | null { @@ -1622,6 +1626,7 @@ export function turnHolder(campaignId: string): TurnHolder | null { floor: fightFloor(campaignId), partyCouldRise: partyCanRise(encounter), proneRiders: proneRiders(campaignId), + pronePairs: pronePairs(campaignId), }; } @@ -1664,7 +1669,12 @@ function resumeAfter(before: Pick, order: Ord export function settleTurn(campaign: Campaign, before: TurnHolder | null): string[] { // A rider the call pushed, pulled or dragged makes the same save, asked // first: one thrown by the move is prone by the fall, which asks no second. - const thrown = [...settleMovedRiders(campaign), ...(before ? settleProneRiders(campaign, before.proneRiders) : [])]; + // An enemy on another enemy is asked the same way (enemy-rider-falls.ts). + const thrown = [ + ...settleMovedRiders(campaign), + ...(before ? settleProneRiders(campaign, before.proneRiders) : []), + ...settleEnemyRiders(campaign, before?.pronePairs ?? null), + ]; if (before) { passOnFrom(campaign, before); // The call may have downed the last of the party (a blow on a dying or a @@ -2609,6 +2619,7 @@ function settleBackstopRiders(campaign: Campaign, holder: TurnHolder | null) { if (holder) { settleProneRiders(campaign, holder.proneRiders); } + settleEnemyRiders(campaign, holder?.pronePairs ?? null); } function playEnemiesDue(campaign: Campaign, turn: DmTurn) { diff --git a/src/lib/dm/enemy-damage.ts b/src/lib/dm/enemy-damage.ts index 2ac40f2dd4..2eec0c0ad2 100644 --- a/src/lib/dm/enemy-damage.ts +++ b/src/lib/dm/enemy-damage.ts @@ -36,7 +36,7 @@ import { BURNING_OIL_DAMAGE, COVERED_IN_OIL, oilCatches } from "@/lib/srd/gear-w import { enemyDefenseLines, meetEnemyPart } from "@/lib/dm/enemy-defenses"; import { authoredIgnoresResistance } from "@/lib/dm/authored-saves"; import { isKnockedOut, knockedOutConditions } from "@/lib/dm/knockout"; -import { partPair } from "@/lib/dm/enemy-riders"; +import { pairWhenDown } from "@/lib/dm/enemy-rider-falls"; import { endConditionsHeldBy, endVowsOn } from "@/lib/dm/enemy-conditions"; import { abilityRefusal, enemyHpCap, findMonsterAbility, hasTrait, REGENERATION_STOPPED, regenerationOf, spendAbility } from "@/lib/dm/monster-abilities"; import { absorbs, relentlessThreshold } from "@/lib/dm/monster-traits"; @@ -691,8 +691,10 @@ export function applyEnemyDamage( base.spellEffects = spellEffects; } // Down but on the board: a rider lies beside its mount, a mount under its - // rider's feet (issue 1055, enemy-riders.ts). - const laid = knockout || regenerating ? partPair(campaign, enemy, false) : null; + // rider's feet (issue 1055, enemy-riders.ts). The rider of a mount that + // went down lands on its feet with its reaction, or falls prone + // (enemy-rider-falls.ts). + const laid = knockout || regenerating ? pairWhenDown(campaign, encounter, enemy, false) : null; if (laid) { base.pair = laid; publishBattleMapUpdate(campaign.id); @@ -718,8 +720,9 @@ export function applyEnemyDamage( // Its mount keeps the space the pair held; its rider keeps their token // (issue 1055, ruling 4: enemy-riders.ts). With no board the two part // all the same: a rider was left on a dead mount, and a mount under a - // dead rider. - const parted = partPair(campaign, enemy, true); + // dead rider. The rider of a slain mount lands on its feet with its + // reaction, or falls prone (enemy-rider-falls.ts). + const parted = pairWhenDown(campaign, encounter, enemy, true); if (parted) { base.pair = parted; } diff --git a/src/lib/dm/enemy-reactions.ts b/src/lib/dm/enemy-reactions.ts index 880d9d50ce..5f3434a057 100644 --- a/src/lib/dm/enemy-reactions.ts +++ b/src/lib/dm/enemy-reactions.ts @@ -60,7 +60,7 @@ export function tryParry(input: DefenseInput): { bonus: number; note: string } | } // Whether the creature can take a reaction at all now. -function reactionFree(encounter: Encounter, enemy: EncounterEnemy): boolean { +export function reactionFree(encounter: Encounter, enemy: EncounterEnemy): boolean { return ( !encounter.reactionsUsed.includes(enemy.id) && !conditionBlocksReactions(enemy.conditions) && diff --git a/src/lib/dm/enemy-rider-falls.ts b/src/lib/dm/enemy-rider-falls.ts new file mode 100644 index 0000000000..6fe2c7ab74 --- /dev/null +++ b/src/lib/dm/enemy-rider-falls.ts @@ -0,0 +1,264 @@ +// How an enemy rider loses its seat (issue 1055, ruling 6 and the rules as +// written). +// +// "If an effect moves your mount against its will while you're on it, you +// must succeed on a DC 10 Dexterity saving throw or fall off the mount, +// landing prone in a space within 5 feet of it. If you're knocked prone while +// mounted, you must make the same saving throw. If your mount is knocked +// prone, you can use your reaction to dismount it as it falls and land on +// your feet. Otherwise, you are dismounted and fall prone in a space within +// 5 feet it" (SRD 5.1, Mounting and Dismounting). +// +// A pair made in the first piece (enemy-riders.ts) only came apart when one +// of the two left the fight: a goblin knocked prone on its wolf stayed in the +// saddle with no roll, a wolf shoved across the board took its goblin along +// for nothing, and a shove at the goblin moved the wolf too, a creature the +// shove never touched. +// +// Four ways off, each asked once: +// - the rider is pushed, pulled or carried off by an effect that named it: +// it ends where the push ends and lands prone, with no save of its own +// (it already resisted the push), and the mount stays (ruling 6); +// - the mount is moved against its will: the rider saves as the call +// finishes, since a push goes a square at a time and one call may push +// several times (the doors only mark the mount, as mount-moved.ts does +// for a character); +// - the rider is knocked prone: the same save, asked where the call +// finishes, since prone reaches an enemy from many doors (mount-thrown.ts +// does the same for a character); +// - the mount is knocked prone or drops to 0: no save. The rider's reaction +// lands it on its feet; with none to take it falls prone. +// +// The save is the rider's own, from its stat block (forced-save.ts), so an +// unconscious, paralyzed, stunned or petrified rider fails with no die +// rolled. +// +// Must not import map-tools, encounter-tools or enemy-damage: they call in. + +import type { Campaign } from "@/lib/db/campaigns"; +import { getBattleMapForEncounter, getTokenByRef, listHiddenRefIds, listTokens, moveToken } from "@/lib/db/battle-maps"; +import { getDmTurn } from "@/lib/db/dm-turns"; +import { getActiveEncounter, getEnemy, listEnemies, saveEncounter, type Encounter, type EncounterEnemy } from "@/lib/db/encounters"; +import { insertCampaignMessage } from "@/lib/db/messages"; +import { publishWithSeq } from "@/lib/events"; +import { reactionFree } from "@/lib/dm/enemy-reactions"; +import { mountOf, partPair, riderOf } from "@/lib/dm/enemy-riders"; +import { rollEnemySave } from "@/lib/dm/forced-save"; +import { currentTurnId } from "@/lib/dm/job-control"; +import { tableNoteSeq } from "@/lib/dm/narration-slot"; +import { laySpellConditionsOnEnemy } from "@/lib/dm/spell-effects"; +import { isConditionNamed } from "@/lib/srd/feature-names"; +import { DISMOUNT_SAVE_DC } from "@/lib/srd/mounts"; + +type XY = { x: number; y: number }; + +const isProne = (enemy: Pick) => enemy.conditions.some((entry) => isConditionNamed(entry, "prone")); + +// Where this enemy's own token stands, as words for a result. +function spotOf(enemy: EncounterEnemy): string { + const map = getBattleMapForEncounter(enemy.encounterId); + const token = map ? listTokens(map.id).find((entry) => entry.refId === enemy.id) : null; + return token ? ` at (${token.x},${token.y})` : ""; +} + +// A rider coming off is told to the table, as a character's fall is +// (mount-thrown.ts): the result of the call reaches only a model, and a +// person running the fight from the console would see a token split with no +// word of why. Nothing is said of a pair the party cannot see. +function tableNote(campaign: Pick, rider: EncounterEnemy, content: string) { + const map = getBattleMapForEncounter(rider.encounterId); + if (map && listHiddenRefIds(map.id).includes(rider.id)) { + return; + } + const seq = tableNoteSeq(campaign.id); + const message = insertCampaignMessage({ campaignId: campaign.id, seq, authorType: "system", glyph: "cue-travel", content }); + publishWithSeq(campaign.id, seq, "message_added", { message }); +} + +// The mounts a call has moved against their will, their riders not yet asked. +const moved = new Map>(); + +// What a door deep in a call did to a rider, told where the call finishes +// (settleEnemyRiders): a shove's own result says only where its target went. +const told = new Map(); +const tell = (campaignId: string, line: string) => told.set(campaignId, [...(told.get(campaignId) ?? []), line]); + +// Called by whatever moves an enemy without it choosing to: marks it when it +// carries a rider. +export function enemyMountMoved(campaignId: string, enemyId: string) { + const enemy = getEnemy(enemyId); + if (!enemy || !riderOf(listEnemies(enemy.encounterId), enemy.id)) { + return; + } + const mounts = moved.get(campaignId) ?? new Set(); + mounts.add(enemyId); + moved.set(campaignId, mounts); +} + +// Whether this call has already moved the mount this rider sits on: a push +// that then names the rider too has pushed both together, and the pair has +// gone as one (ruling 6: "the pair moves and the rider saves once"). +export function movedWithMount(campaignId: string, rider: Pick): boolean { + return Boolean(rider.ridesEnemyId && moved.get(campaignId)?.has(rider.ridesEnemyId)); +} + +// Ruling 6: an effect that named the rider takes it out of the saddle. It +// ends at `at`, or in the open square nearest it when the mount's own space +// or anyone else holds that square, and lands prone. The mount stays where +// the pair stood, on a token of its own. Returns where the rider landed, or +// null when this enemy rides nothing; the GM is told as the call finishes. +export function shovedFromSaddle(campaign: Pick, rider: EncounterEnemy, at: XY): { at: XY } | null { + const mount = mountOf(listEnemies(rider.encounterId), rider); + if (!mount || partPair(campaign, rider, false, at) === null) { + return null; + } + laySpellConditionsOnEnemy(rider.id, ["prone"], {}); + tableNote(campaign, rider, `${rider.displayName} is knocked out of the saddle; ${mount.displayName} stays.`); + const map = getBattleMapForEncounter(rider.encounterId); + const token = map ? listTokens(map.id).find((entry) => entry.refId === rider.id) : null; + const landed = token ? { x: token.x, y: token.y } : at; + tell( + campaign.id, + `${rider.displayName} is taken out of the saddle and lands prone${token ? ` at (${landed.x},${landed.y})` : ""}, no longer mounted, with no save to stay on: the effect named the rider, who already resisted it. ${mount.displayName} stays where the pair stood, riderless, on a token of its own, and keeps its turn.`, + ); + return { at: landed }; +} + +// A push, a pull or a forced move that names one enemy and ends at `at`. +// The rider goes alone, out of the saddle; a mount goes with its rider on it, +// who is asked the save as the call finishes; anyone else is only moved. +// Returns where the named creature ended, or null when it has no token to +// move. +export function forcedEnemyMove(campaign: Pick, mapId: string, enemy: EncounterEnemy, at: XY): { at: XY } | null { + const token = getTokenByRef(mapId, enemy.id); + if (!token) { + return null; + } + if (enemy.ridesEnemyId) { + if (movedWithMount(campaign.id, enemy)) { + return { at: { x: token.x, y: token.y } }; + } + const thrown = shovedFromSaddle(campaign, enemy, at); + if (thrown) { + return thrown; + } + } + moveToken(token.id, at.x, at.y, token.movedThisRound); + enemyMountMoved(campaign.id, enemy.id); + return { at }; +} + +// The DC 10 Dexterity save to stay mounted, from the rider's own block. A +// failure takes the rider off: it lies prone in the open square nearest the +// mount, which keeps the space the pair held. +function saddleSave(campaign: Campaign, rider: EncounterEnemy, mount: EncounterEnemy, why: "knocked prone" | "mount moved"): { kept: boolean; line: string } { + const turnId = currentTurnId(); + const turn = turnId ? getDmTurn(turnId) : null; + const save = rollEnemySave(campaign.id, rider, "dex", DISMOUNT_SAVE_DC, { + record: { ...(turn ? { turn } : {}), detail: `${rider.displayName}: DEX save to stay on ${mount.displayName}` }, + }); + const how = why === "knocked prone" ? `was knocked prone while riding ${mount.displayName}` : `was on ${mount.displayName} as it was moved against its will`; + const rolled = save.autoFailed || save.total === null + ? "the DEX save fails with no roll, as it cannot act" + : `DEX save ${save.total} against DC ${DISMOUNT_SAVE_DC}`; + if (save.success) { + return { kept: true, line: `${rider.displayName} ${how} and kept its seat (${rolled}): still mounted${why === "knocked prone" ? ", still prone" : ""}.` }; + } + partPair(campaign, rider, false); + laySpellConditionsOnEnemy(rider.id, ["prone"], {}); + tableNote(campaign, rider, why === "knocked prone" ? `${rider.displayName} is knocked prone and falls from ${mount.displayName}.` : `${rider.displayName} is thrown from ${mount.displayName}.`); + return { + kept: false, + line: `${rider.displayName} ${how} and fell off (${rolled}): no longer mounted, prone${spotOf(rider)}. ${mount.displayName} stands where the pair stood, riderless, on a token of its own, and keeps its turn.`, + }; +} + +// The mount has gone down under its rider, who is on foot already: its +// reaction lands it on its feet, and with none to take it falls prone. The +// reaction is the creature's one a round, spent on the encounter the caller +// holds so a later save of that encounter keeps it. +function landsOrFalls(campaign: Pick, encounter: Encounter, rider: EncounterEnemy, mountName: string): string { + const live = getEnemy(rider.id) ?? rider; + if (live.status !== "alive") { + return ""; + } + if (reactionFree(encounter, live)) { + encounter.reactionsUsed = [...encounter.reactionsUsed, live.id]; + saveEncounter(encounter); + tableNote(campaign, live, `${mountName} goes down; ${live.displayName} jumps clear and lands on its feet.`); + return `${live.displayName} spends its reaction to dismount as its mount falls and lands on its feet${spotOf(live)}.`; + } + laySpellConditionsOnEnemy(live.id, ["prone"], {}); + tableNote(campaign, live, `${mountName} goes down and ${live.displayName} falls with it.`); + return `${live.displayName} has no reaction to take, so it falls prone${spotOf(live)}.`; +} + +// The pair this enemy is half of comes apart as it drops to 0 (enemy-damage.ts): +// what partPair does, and for a mount that went down, what became of the +// rider it carried. +export function pairWhenDown(campaign: Pick, encounter: Encounter, enemy: EncounterEnemy, leaves: boolean): string | null { + const rider = riderOf(listEnemies(enemy.encounterId), enemy.id); + const parted = partPair(campaign, enemy, leaves); + if (!parted || !rider) { + return parted; + } + return `${parted} ${landsOrFalls(campaign, encounter, rider, enemy.displayName)}`.trim(); +} + +// The enemies in a pair that are prone as an engine call begins +// (encounter-tools.ts turnHolder): the call did not knock them prone, so it +// asks nothing of them. A rider who kept its seat while prone is here on the +// next call, which is what makes one prone ask one save. +export function pronePairs(campaignId: string): string[] { + const encounter = getActiveEncounter(campaignId); + if (!encounter) { + return []; + } + const enemies = listEnemies(encounter.id); + const paired = new Set(enemies.flatMap((enemy) => (enemy.ridesEnemyId ? [enemy.id, enemy.ridesEnemyId] : []))); + return enemies.filter((enemy) => paired.has(enemy.id) && isProne(enemy)).map((enemy) => enemy.id); +} + +// Asked where an engine call finishes (encounter-tools.ts settleTurn): each +// rider whose mount the call knocked prone or moved, and each rider the call +// knocked prone. `proneBefore` is null where nobody held the turn as the call +// began; a mount moved is still asked then. Returns what happened to each, +// for the call's result. +export function settleEnemyRiders(campaign: Campaign, proneBefore: readonly string[] | null): string[] { + const marked = moved.get(campaign.id) ?? new Set(); + moved.delete(campaign.id); + const happened: string[] = told.get(campaign.id) ?? []; + told.delete(campaign.id); + const encounter = getActiveEncounter(campaign.id); + if (!encounter) { + return happened; + } + for (const row of listEnemies(encounter.id)) { + const rider = row.ridesEnemyId ? getEnemy(row.id) : null; + const mount = rider ? mountOf(listEnemies(encounter.id), rider) : null; + if (!rider || !mount || rider.status !== "alive" || mount.status !== "alive") { + continue; + } + // The mount knocked prone: no save, whatever else the call did to them. + if (proneBefore && isProne(mount) && !proneBefore.includes(mount.id)) { + partPair(campaign, rider, false); + const live = getActiveEncounter(campaign.id) ?? encounter; + happened.push(`${mount.displayName} is knocked prone under ${rider.displayName}. ${landsOrFalls(campaign, live, rider, mount.displayName)} ${mount.displayName} lies where the pair stood, on a token of its own, and keeps its turn.`); + continue; + } + // Moved first: a rider thrown by the move is prone by the fall, which + // asks no second save. + if (marked.has(mount.id)) { + const save = saddleSave(campaign, rider, mount, "mount moved"); + happened.push(save.line); + if (!save.kept) { + continue; + } + } + const now = getEnemy(rider.id) ?? rider; + if (proneBefore && isProne(now) && !proneBefore.includes(rider.id)) { + happened.push(saddleSave(campaign, now, mount, "knocked prone").line); + } + } + return happened; +} diff --git a/src/lib/dm/enemy-riders.ts b/src/lib/dm/enemy-riders.ts index ebf30d1540..6f951ad8f2 100644 --- a/src/lib/dm/enemy-riders.ts +++ b/src/lib/dm/enemy-riders.ts @@ -87,8 +87,10 @@ export function linkPairs(inserted: readonly EncounterEnemy[], carries: Readonly // 4), and keeps its turn. A rider who stays on the board (knocked out) lies // in the nearest open square beside it. Returns what became of the one left, // for the result of the call that parted them, or null when `enemy` was half -// of no pair. -export function partPair(campaign: Pick, enemy: EncounterEnemy, leaves: boolean): string | null { +// of no pair. `near` is where a rider who stays on the board was sent (a push +// out of the saddle, enemy-rider-falls.ts): they land there, or in the open +// square nearest it when the mount or anyone else holds it. +export function partPair(campaign: Pick, enemy: EncounterEnemy, leaves: boolean, near?: { x: number; y: number }): string | null { const enemies = listEnemies(enemy.encounterId); const rider = enemy.ridesEnemyId ? enemy : riderOf(enemies, enemy.id); const mount = rider ? mountOf(enemies, rider) : null; @@ -117,7 +119,7 @@ export function partPair(campaign: Pick, enemy: EncounterEnemy, const unlinked = listEnemies(enemy.encounterId); const tokens = listTokens(map.id); const footprints = footprintLookup(new Map(unlinked.map((entry) => [entry.id, entry]))); - const [spot] = findSpawnTiles(map.terrain, map.width, map.height, occupiedTiles(map, tokens, null, footprints), 1, [{ x: shared.x, y: shared.y }], []); + const [spot] = findSpawnTiles(map.terrain, map.width, map.height, occupiedTiles(map, tokens, null, footprints), 1, [near ?? { x: shared.x, y: shared.y }], []); if (spot) { insertToken({ mapId: map.id, campaignId: campaign.id, kind: "enemy", refId: rider.id, name: rider.displayName, x: spot.x, y: spot.y }); } diff --git a/src/lib/dm/map-tools.ts b/src/lib/dm/map-tools.ts index d7ac89b7e7..feee9d2acc 100644 --- a/src/lib/dm/map-tools.ts +++ b/src/lib/dm/map-tools.ts @@ -1,5 +1,6 @@ import { pushImmune } from "@/lib/srd/genre-b-steampunk-moves"; import { mountMoved } from "@/lib/dm/mount-moved"; +import { enemyMountMoved, forcedEnemyMove, movedWithMount, shovedFromSaddle } from "@/lib/dm/enemy-rider-falls"; import { roadRaging } from "@/lib/dm/genre-gb-road-rage"; import { readiedHeld } from "@/lib/dm/readied-kinds"; import { boardLight } from "@/lib/dm/light-timers"; @@ -738,6 +739,34 @@ export function handleMoveToken( if (occupied.has(tileIndex(map.width, args.x, args.y))) { return { error: `(${args.x},${args.y}) is occupied by another combatant.`, retry: true }; } + // A push, a drag or a carry that names a rider takes the rider alone out of + // the saddle, and the mount stays (issue 1055, ruling 6: + // enemy-rider-falls.ts). The rider is its own size on the way, and a square + // inside its mount's space sets it down just outside. + if (args.forced && resolved.kind === "enemy" && resolved.enemy?.ridesEnemyId) { + const rider = resolved.enemy; + const way = findPath(map.terrain, map.width, map.height, occupied, resolved.token, { x: args.x, y: args.y }, 1, resolved.token.movement === "fly", false); + if (!way) { + return { error: `No path to (${args.x},${args.y}); walls block the way.`, retry: true }; + } + const from = { x: resolved.token.x, y: resolved.token.y }; + const together = movedWithMount(campaign.id, rider); + const out = forcedEnemyMove(campaign, map.id, rider, { x: args.x, y: args.y }); + if (out) { + publishBattleMapUpdate(campaign.id); + releaseGrapplesOutOfReach(campaign); + const zoneEffects = together ? [] : zonesAfterMove(campaign, encounter.id, { kind: "enemy", refId: rider.id }, from, walkedPart(way, out.at), {}); + return { + ok: true, + name: moverName, + at: `(${out.at.x},${out.at.y})`, + ...(zoneEffects.length ? { zoneEffects } : {}), + note: together + ? `${moverName} went with its mount, which this call already moved: the pair moved as one, and the rider saves once to stay on.` + : `${moverName} was taken out of the saddle and lies prone at (${out.at.x},${out.at.y}); its mount stays where the pair stood. No save to stay mounted.`, + }; + } + } // An enemy walking on its own passes its allies and squeezes where it // must (enemy-approach.ts enemyMoveTraits); a forced move does neither. const traits = @@ -931,6 +960,12 @@ export function handleMoveToken( if (args.forced && resolved.token.kind === "pc" && (landing.x !== origin.x || landing.y !== origin.y)) { mountMoved(campaign.id, moverId); } + // The same for an enemy's mount, named by the forced move + // (enemy-rider-falls.ts); a forced move that named its rider was answered + // above, and took the rider alone. + if (args.forced && resolved.kind === "enemy" && resolved.enemy && (landing.x !== origin.x || landing.y !== origin.y)) { + enemyMountMoved(campaign.id, resolved.enemy.id); + } // The Disengage and this walk were the turn it was owed; its own turn // follows on fresh movement, with no Disengage (enemy-actions.ts // spendEnemyDisengage). @@ -1000,6 +1035,40 @@ export function handleMoveToken( }; } +// A push or a pull that names an enemy rider takes the rider alone (issue +// 1055, ruling 6): the square it is sent to may lie inside its own mount's +// space, which is no obstacle to leaving it (the rider then lands just +// outside). Null when the one named rides nothing; a reason when the push +// that moved its mount a moment ago has already carried it. +function riderNamed( + campaignId: string, + mapId: string, + targetRef: string, + shared: BattleToken, + at: { x: number; y: number }, +): { rider: EncounterEnemy; insideMount: boolean } | { reason: string } | null { + const rider = getEnemy(targetRef); + if (!rider?.ridesEnemyId || shared.refId !== rider.id) { + return null; + } + if (movedWithMount(campaignId, rider)) { + return { reason: "it went with its mount, which this already moved: the pair moved as one, and the rider saves once to stay on" }; + } + const wide = footprintLookup(new Map([[rider.id, rider]]))(shared); + return { rider, insideMount: at.x >= shared.x && at.x < shared.x + wide && at.y >= shared.y && at.y < shared.y + wide }; +} + +// The rider leaves the saddle for `at`, prone, and the mount stays. +function leavesSaddle(campaign: Campaign, rider: EncounterEnemy, at: { x: number; y: number }): { moved: true; at: { x: number; y: number } } | { moved: false; reason: string } { + const thrown = shovedFromSaddle(campaign, rider, at); + if (!thrown) { + return { moved: false, reason: "there is no saddle to leave" }; + } + releaseGrapplesOutOfReach(campaign); + publishBattleMapUpdate(campaign.id); + return { moved: true, at: thrown.at }; +} + // A shove: the target goes one square straight away from whoever pushed it. // Forced movement, so nothing is spent and nothing is provoked. The square // has to be open floor with nobody on it; otherwise the target stays. @@ -1025,19 +1094,28 @@ export function pushTokenAway( x: target.x + Math.sign(target.x - pusher.x), y: target.y + Math.sign(target.y - pusher.y), }; + const saddle = target.kind === "enemy" ? riderNamed(campaign.id, map.id, targetRef, target, at) : null; + if (saddle && "reason" in saddle) { + return { moved: false, reason: saddle.reason }; + } if (at.x < 0 || at.y < 0 || at.x >= map.width || at.y >= map.height) { return { moved: false, reason: "the edge of the map is behind it" }; } if (blocksMove(tileAt(map.terrain, map.width, at.x, at.y))) { return { moved: false, reason: "a wall is behind it" }; } - if (occupiedTiles(map, listTokens(map.id), target).has(tileIndex(map.width, at.x, at.y))) { + if (!saddle?.insideMount && occupiedTiles(map, listTokens(map.id), target).has(tileIndex(map.width, at.x, at.y))) { return { moved: false, reason: "someone stands behind it" }; } + if (saddle) { + return leavesSaddle(campaign, saddle.rider, at); + } moveToken(target.id, at.x, at.y, target.movedThisRound); // A rider pushed is a mount moved against its will (mount-moved.ts). if (target.kind === "pc") { mountMoved(campaign.id, target.refId); + } else if (target.kind === "enemy") { + enemyMountMoved(campaign.id, targetRef); } // A push is forced movement, and "the condition also ends if an effect // removes the grappled creature from the reach of the grappler ... such @@ -1072,16 +1150,25 @@ export function pullTokenToward( x: target.x + Math.sign(puller.x - target.x), y: target.y + Math.sign(puller.y - target.y), }; + const saddle = target.kind === "enemy" ? riderNamed(campaign.id, map.id, targetRef, target, at) : null; + if (saddle && "reason" in saddle) { + return { moved: false, reason: saddle.reason }; + } if (blocksMove(tileAt(map.terrain, map.width, at.x, at.y))) { return { moved: false, reason: "a wall is in the way" }; } - if (occupiedTiles(map, listTokens(map.id), target).has(tileIndex(map.width, at.x, at.y))) { + if (!saddle?.insideMount && occupiedTiles(map, listTokens(map.id), target).has(tileIndex(map.width, at.x, at.y))) { return { moved: false, reason: "someone stands in the way" }; } + if (saddle) { + return leavesSaddle(campaign, saddle.rider, at); + } moveToken(target.id, at.x, at.y, target.movedThisRound); // A rider pulled is a mount moved against its will (mount-moved.ts). if (target.kind === "pc") { mountMoved(campaign.id, target.refId); + } else if (target.kind === "enemy") { + enemyMountMoved(campaign.id, targetRef); } // A push is forced movement, and "the condition also ends if an effect // removes the grappled creature from the reach of the grappler ... such diff --git a/src/lib/dm/mt-fb-spend.ts b/src/lib/dm/mt-fb-spend.ts index cf847bf774..96967e4431 100644 --- a/src/lib/dm/mt-fb-spend.ts +++ b/src/lib/dm/mt-fb-spend.ts @@ -13,7 +13,7 @@ // can see within 30 feet of you. A creature left in the air // falls and lands prone." It was a line asking the GM to // move the token. -import { getBattleMapForEncounter, getTokenByRef, listTokens, moveToken } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, getTokenByRef, listTokens } from "@/lib/db/battle-maps"; import type { DmTurn } from "@/lib/db/dm-turns"; import { getActiveEncounter, getEnemy, type EncounterEnemy } from "@/lib/db/encounters"; import { listSheets } from "@/lib/db/sheets"; @@ -28,6 +28,7 @@ import { canEnemyAct } from "@/lib/dm/can-act"; import { tilesApart } from "@/lib/dm/board-reach"; import { resolveEnemyRef } from "@/lib/dm/enemy-damage"; import { enemyAttackProfile } from "@/lib/dm/enemy-profile"; +import { forcedEnemyMove } from "@/lib/dm/enemy-rider-falls"; import { enemyStrikesEnemy } from "@/lib/dm/enemy-strike"; import { withOpportunityTurn } from "@/lib/dm/opportunity-strike"; import type { ToolError } from "@/lib/dm/tool-errors"; @@ -93,7 +94,8 @@ export function throwFoe(ctx: SpendContext, enemy: EncounterEnemy, feet: number) if (at.x < 0 || at.y < 0 || at.x >= map.width || at.y >= map.height) continue; if (blocksMove(tileAt(map.terrain, map.width, at.x, at.y)) || taken.has(tileIndex(map.width, at.x, at.y))) continue; if (tilesApart(holder, { ...token, x: at.x, y: at.y }) * 5 > feet) continue; - moveToken(token.id, at.x, at.y, token.movedThisRound); + // As the pair it may be half of: a rider thrown goes alone (enemy-rider-falls.ts). + forcedEnemyMove(ctx.campaign, map.id, enemy, at); publishEphemeral(ctx.campaign.id, "battle_map_updated", {}); return { thrown: `${name} is thrown to (${at.x},${at.y}), ${tilesApart(holder, { ...token, x: at.x, y: at.y }) * 5} feet from ${ctx.sheet.name}. Another unoccupied space within ${feet} feet of them is a move_token (forced); variant "up" throws it into the air to fall.` }; } @@ -125,7 +127,8 @@ export function pushFoe(ctx: SpendContext, enemy: EncounterEnemy, feet: number): if (at.x === token.x && at.y === token.y) { return { pushed: `${name} has no open square behind it and stays where it is.` }; } - moveToken(token.id, at.x, at.y, token.movedThisRound); + // As the pair it may be half of: a rider pushed goes alone (enemy-rider-falls.ts). + forcedEnemyMove(ctx.campaign, map.id, enemy, at); publishEphemeral(ctx.campaign.id, "battle_map_updated", {}); return { pushed: `${name} is pushed ${Math.max(Math.abs(at.x - token.x), Math.abs(at.y - token.y)) * 5} feet, to (${at.x},${at.y}).` }; } diff --git a/src/lib/dm/zone-triggers.ts b/src/lib/dm/zone-triggers.ts index e90d598206..1ca602e7e6 100644 --- a/src/lib/dm/zone-triggers.ts +++ b/src/lib/dm/zone-triggers.ts @@ -17,6 +17,7 @@ // the lines for the table. import { mountMoved } from "@/lib/dm/mount-moved"; +import { forcedEnemyMove } from "@/lib/dm/enemy-rider-falls"; import { maskKeepsOut } from "@/lib/dm/genre-cc-a-drones"; import { bindsWorthResisting } from "@/lib/dm/legendary-logic"; import type { Campaign } from "@/lib/db/campaigns"; @@ -134,6 +135,12 @@ function pushAlong(map: BattleMap, zone: SpellZone, token: BattleToken, feet: nu if (at.x === token.x && at.y === token.y) { return null; } + // An enemy is moved as the pair it may be half of (enemy-rider-falls.ts): a + // rider the area caught goes alone, out of the saddle. + const enemy = token.kind === "enemy" ? getEnemy(token.refId) : null; + if (enemy) { + return forcedEnemyMove({ id: map.campaignId }, map.id, enemy, at)?.at ?? null; + } moveToken(token.id, at.x, at.y, token.movedThisRound); return at; } From 910572e86f28986d0184fcb6d77204c4ed1291b3 Mon Sep 17 00:00:00 2001 From: Smoebo Date: Fri, 20 Nov 2026 18:26:46 -0500 Subject: [PATCH 2/7] The falls suite drops an import it never used Co-Authored-By: Claude Fable 5.2 --- scripts/test-enforce-enemy-rider-falls.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/test-enforce-enemy-rider-falls.mjs b/scripts/test-enforce-enemy-rider-falls.mjs index 16bcf330c6..d528e359a8 100644 --- a/scripts/test-enforce-enemy-rider-falls.mjs +++ b/scripts/test-enforce-enemy-rider-falls.mjs @@ -19,7 +19,7 @@ import { suite } from "./lib/enforce-harness.mjs"; import { openWorld } from "./lib/enforce-world.mjs"; import { caster, closeTables } from "./lib/enforce-spell-kit.mjs"; import { layMap } from "./lib/enforce-spells.mjs"; -import { mapOf, OPEN, tokenOf } from "./lib/enforce-zones.mjs"; +import { mapOf, OPEN } from "./lib/enforce-zones.mjs"; import { diff, revertTurn, snapshot } from "./lib/sweep-lifecycle.mjs"; const { test, finish } = suite("test-enforce-enemy-rider-falls"); From 5f88398c4e53af8be72a220076b7c1e67859b50e Mon Sep 17 00:00:00 2001 From: Smoebo Date: Fri, 20 Nov 2026 19:08:49 -0500 Subject: [PATCH 3/7] The restart sweep classes the two stores the falls keep for the length of one call Co-Authored-By: Claude Fable 5.2 --- scripts/test-enforce-sweep-lifecycle-restart.mjs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/test-enforce-sweep-lifecycle-restart.mjs b/scripts/test-enforce-sweep-lifecycle-restart.mjs index 4e569a0ffc..ec9931312d 100644 --- a/scripts/test-enforce-sweep-lifecycle-restart.mjs +++ b/scripts/test-enforce-sweep-lifecycle-restart.mjs @@ -95,6 +95,8 @@ const REGISTRY = { "queue.ts:__odmDmDropped": { kind: PLUMBING, what: "the queue" }, "queue.ts:__odmDmDepths": { kind: PLUMBING, what: "the queue" }, "status.ts:__odmDmStatus": { kind: PLUMBING, what: "the status line" }, + "enemy-rider-falls.ts:moved": { kind: PLUMBING, what: "the enemy mounts a call moved against their will, marked as it moves them, their riders asked the save as it finishes" }, + "enemy-rider-falls.ts:told": { kind: PLUMBING, what: "what a call did to an enemy rider, said in the same call's result as it finishes" }, "mount-moved.ts:moved": { kind: PLUMBING, what: "the riders a call moved against their will, marked as it moves them and asked their save as it finishes" }, "steed-fall.ts:decided": { kind: PLUMBING, what: "a rider's fall, decided as the steed went and read by the same call" }, "table-wait.ts:__odmTableWait": { kind: PLUMBING, what: "timers for a waiting table" }, From b98454f9dcb4c371e83171c8c57cf33de3a3c80f Mon Sep 17 00:00:00 2001 From: Smoebo Date: Fri, 20 Nov 2026 20:15:21 -0500 Subject: [PATCH 4/7] A test holds that a pull at the rider draws it alone from the saddle, and a pull at the mount draws the pair Co-Authored-By: Claude Fable 5.2 --- scripts/test-enforce-enemy-rider-falls.mjs | 27 +++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/scripts/test-enforce-enemy-rider-falls.mjs b/scripts/test-enforce-enemy-rider-falls.mjs index d528e359a8..308089a139 100644 --- a/scripts/test-enforce-enemy-rider-falls.mjs +++ b/scripts/test-enforce-enemy-rider-falls.mjs @@ -26,7 +26,7 @@ const { test, finish } = suite("test-enforce-enemy-rider-falls"); const { listTokens } = await import("../src/lib/db/battle-maps.ts"); const { saveEncounter } = await import("../src/lib/db/encounters.ts"); const { settleEnemyRiders } = await import("../src/lib/dm/enemy-rider-falls.ts"); -const { pushTokenAway } = await import("../src/lib/dm/map-tools.ts"); +const { pullTokenToward, pushTokenAway } = await import("../src/lib/dm/map-tools.ts"); const HERO = () => caster("paladin", "cha", [], [], 5, { speed: 30 }); const ownToken = (world, refId) => listTokens(mapOf(world).id).find((token) => token.refId === refId) ?? null; @@ -171,6 +171,31 @@ await test("Ruling 6: a forced move_token that names the rider carries the rider assert.equal(prone(world, rider.id), true); }); +await test("Ruling 6: a pull that names the rider draws the rider alone out of the saddle, and a pull that names the mount draws the pair, whose rider then saves.", async () => { + const { world, hero, rider, mount } = await pair(); + await layMap(world, OPEN(), { [hero.id]: { x: 8, y: 4 }, [rider.id]: { x: 12, y: 4 } }); + const campaign = world.campaign(); + const encounterId = world.encounter().id; + // The mount first: the pair comes a square nearer, and the rider is asked. + assert.equal(pullTokenToward(campaign, encounterId, hero.id, mount.id).moved, true); + assert.deepEqual(at(world, rider.id), [11, 4], "the pull at the mount did not draw the pair's token"); + assert.equal(ownToken(world, mount.id), null); + world.diceLog(); + world.dice(15); + assert.match(settleEnemyRiders(campaign, [])[0] ?? "", /kept its seat/); + assert.equal(world.clearDice(), 0, "the rider of a pulled mount made no save"); + // Then the rider, in a call of its own: out of the saddle, with no save. + const drawn = pullTokenToward(campaign, encounterId, hero.id, rider.id); + assert.equal(drawn.moved, true, drawn.reason); + assert.deepEqual(at(world, rider.id), [10, 4], "the rider did not end where the pull ends"); + assert.deepEqual(at(world, mount.id), [11, 4], "the pull at the rider moved its mount"); + assert.equal(mounted(world, rider), false); + assert.equal(prone(world, rider.id), true); + world.dice(20); + settleEnemyRiders(campaign, []); + assert.equal(world.clearDice(), 1, "a rider pulled from the saddle made a save"); +}); + await test("Ruling 6: both pushed together move as the pair, and the rider saves once.", async () => { const { world, hero, rider, mount } = await pair(); const campaign = world.campaign(); From 7c88990456363dee99e582838dc5edfe16ba6c56 Mon Sep 17 00:00:00 2001 From: Smoebo Date: Fri, 20 Nov 2026 23:02:14 -0500 Subject: [PATCH 5/7] A ridden mount is pushed, held and struck by a standing spell area in its own name, and tests hold the cast push, the thrown foe and the psionic push for a pair A mount carrying a rider has no token of its own, and three places in the area code looked for one. A mount whose turn started in Gust of Wind was never asked its save, a mount caught by Web walked on to the square it was making for, and an area that pushes had no token to move. Each now finds the pair's token, and the push moves the mount as the pair, so its rider saves once to stay on. Co-Authored-By: Claude Fable 5.2 --- scripts/test-enforce-enemy-rider-falls.mjs | 187 ++++++++++++++++++++- src/lib/dm/zone-triggers.ts | 28 ++- 2 files changed, 203 insertions(+), 12 deletions(-) diff --git a/scripts/test-enforce-enemy-rider-falls.mjs b/scripts/test-enforce-enemy-rider-falls.mjs index 308089a139..d84a26ca51 100644 --- a/scripts/test-enforce-enemy-rider-falls.mjs +++ b/scripts/test-enforce-enemy-rider-falls.mjs @@ -17,9 +17,10 @@ import assert from "node:assert/strict"; import "./lib/enforce-world.mjs"; import { suite } from "./lib/enforce-harness.mjs"; import { openWorld } from "./lib/enforce-world.mjs"; +import { combatKit, TRAINED } from "./lib/enforce-combat.mjs"; import { caster, closeTables } from "./lib/enforce-spell-kit.mjs"; import { layMap } from "./lib/enforce-spells.mjs"; -import { mapOf, OPEN } from "./lib/enforce-zones.mjs"; +import { mapOf, OPEN, zonesOf } from "./lib/enforce-zones.mjs"; import { diff, revertTurn, snapshot } from "./lib/sweep-lifecycle.mjs"; const { test, finish } = suite("test-enforce-enemy-rider-falls"); @@ -27,8 +28,17 @@ const { listTokens } = await import("../src/lib/db/battle-maps.ts"); const { saveEncounter } = await import("../src/lib/db/encounters.ts"); const { settleEnemyRiders } = await import("../src/lib/dm/enemy-rider-falls.ts"); const { pullTokenToward, pushTokenAway } = await import("../src/lib/dm/map-tools.ts"); +const { onPersonsTurn } = await import("../src/lib/dm/invoke.ts"); +const { saveZones } = await import("../src/lib/dm/zone-store.ts"); +const { zoneTurnStart } = await import("../src/lib/dm/zone-triggers.ts"); const HERO = () => caster("paladin", "cha", [], [], 5, { speed: 30 }); +// A hero of a martial subclass, every ability 16. +const MARTIAL = (cls, subclass, level, weapon) => ({ + class: cls, subclass, level, maxHp: 100, ac: 12, acOverride: true, proficiencies: TRAINED, + abilities: { str: 16, dex: 16, con: 16, int: 16, wis: 16, cha: 16 }, + equipment: [{ name: weapon, qty: 1, equipped: true }], +}); const ownToken = (world, refId) => listTokens(mapOf(world).id).find((token) => token.refId === refId) ?? null; const at = (world, refId) => [ownToken(world, refId)?.x, ownToken(world, refId)?.y]; const live = (world, id) => world.enemies().find((enemy) => enemy.id === id); @@ -39,9 +49,9 @@ const d20s = (world) => world.diceLog().filter((die) => die.sides === 20).length // A hero at (11,4) beside a rider on its mount at (12,4), on an open board. // The order is the hero, the rider, the mount, with the pointer on the hero. -async function pair({ mount = "wolf" } = {}) { +async function pair({ mount = "wolf", hero: who = HERO() } = {}) { const world = await openWorld({ gameSettings: { ttsEnabled: false } }); - const hero = world.addHero(HERO()); + const hero = world.addHero(who); await world.beginFight([{ monster: "goblin", mount }]); const up = world.enemies().find((enemy) => enemy.ridesEnemyId); const under = world.enemies().find((enemy) => enemy.id === up?.ridesEnemyId); @@ -321,5 +331,176 @@ await test("Undoing the GM turn that pushed a rider out of the saddle puts the p assert.equal(prone(world, rider.id), false, "the undo left the rider prone"); }); +// ---- the other doors that push: a spell's area, a thrown foe, a psionic push ---- + +const gust = (world, druid, ...enemyIds) => + world.invoke("aoe_damage", { casterCharacterId: druid.id, spell: "Gust of Wind", enemyIds, saveAbility: "str", dc: 15, level: 2 }); +const DRUID = () => caster("druid", "wis", ["Gust of Wind"]); + +await test("A spell that pushes as it is cast (Gust of Wind) carries the pair when it names the mount, and its rider saves once as the call finishes.", async () => { + const { world, hero, rider, mount } = await pair({ hero: DRUID() }); + // The wolf's Strength save against the wind, then the goblin's to stay on. + world.dice(1, 2); + const out = await gust(world, hero, mount.id); + assert.equal(out.ok, true, out.error); + assert.equal(world.clearDice(), 0, "the rider of a mount the wind pushed made no save"); + assertParted(world, rider, mount, [15, 4]); + assert.equal(prone(world, rider.id), true); +}); + +await test("Ruling 6 for a spell that pushes as it is cast: the wind that names the rider takes it alone out of the saddle, with no save to stay on.", async () => { + const { world, hero, rider, mount } = await pair({ hero: DRUID() }); + world.dice(1, 20); + const out = await gust(world, hero, rider.id); + assert.equal(out.ok, true, out.error); + assert.equal(world.clearDice(), 1, "the rider the wind took made a save to stay on"); + assert.equal(mounted(world, rider), false, "the rider the wind took is still mounted"); + assert.deepEqual(at(world, rider.id), [15, 4]); + assert.deepEqual(at(world, mount.id), [12, 4], "the wind at the rider moved the mount"); + assert.equal(prone(world, rider.id), true); +}); + +await test("Ruling 6 for a spell that pushes as it is cast: the wind that names the mount and then its rider moves the pair as one, and the rider saves once.", async () => { + const { world, hero, rider, mount } = await pair({ hero: DRUID() }); + // Each one's Strength save, then the one save to stay on. + world.dice(1, 1, 15); + const out = await gust(world, hero, mount.id, rider.id); + assert.equal(out.ok, true, out.error); + assert.equal(world.clearDice(), 0); + assert.equal(live(world, rider.id).ridesEnemyId, mount.id, "a made save took the rider off"); + assert.deepEqual(at(world, rider.id), [15, 4], "the pair was not pushed once, as one"); + assert.equal(ownToken(world, mount.id), null); +}); + +// Gust of Wind left standing: "Each creature that starts its turn in the +// line must succeed on a Strength saving throw or be pushed 15 feet away +// from you." The line runs east from the druid at (11,4), over the pair. +function windOver(world, druid) { + const map = mapOf(world); + const cells = [12, 13, 14, 15, 16, 17, 18].map((x) => 4 * map.width + x); + saveZones(map.id, [{ id: "gust-pair", spell: "Gust of Wind", casterId: druid.id, casterKind: "pc", casterName: druid.name, origin: { x: 11, y: 4 }, toward: { x: 20, y: 4 }, cells, concentration: false, castRound: world.encounter().round, untilRound: null, slotLevel: 2, dc: 15 }]); +} +const turnStartsFor = (world, enemyId) => onPersonsTurn(world.campaign(), () => zoneTurnStart(world.campaign(), world.encounter(), [enemyId])); + +await test("A mount whose turn starts in a standing area that pushes is pushed with its rider on it, who saves once to stay on.", async () => { + const { world, hero, rider, mount } = await pair({ hero: DRUID() }); + windOver(world, hero); + world.dice(1, 2); + const lines = turnStartsFor(world, mount.id); + assert.equal(world.clearDice(), 0, `the wind asked the mount no save, or its rider none to stay on: ${JSON.stringify(lines)}`); + assertParted(world, rider, mount, [15, 4]); + assert.equal(prone(world, rider.id), true); +}); + +await test("Ruling 6 in a standing area: a rider whose turn starts in the wind is pushed alone out of the saddle, with no save to stay on.", async () => { + const { world, hero, rider, mount } = await pair({ hero: DRUID() }); + windOver(world, hero); + world.dice(1, 20); + turnStartsFor(world, rider.id); + assert.equal(world.clearDice(), 1, "the rider the wind took made a save to stay on"); + assert.equal(mounted(world, rider), false, "the rider the wind took is still mounted"); + assert.deepEqual(at(world, rider.id), [15, 4]); + assert.deepEqual(at(world, mount.id), [12, 4], "the wind at the rider moved the mount"); + assert.equal(prone(world, rider.id), true); +}); + +const rage = (world, hero) => { + const sheet = world.sheet(hero.id); + world.patch(hero.id, { conditions: [...sheet.conditions, "raging"], conditionMeta: { ...sheet.conditionMeta, raging: { rounds: 10 } } }); +}; +const impel = (world, hero, targetId) => world.invoke("use_resource", { characterId: hero.id, resource: "Mighty Impel", targetEnemyId: targetId }); +const GIANT = () => MARTIAL("barbarian", "Path of the Giant", 10, "Greataxe"); + +await test("A thrown mount (Mighty Impel) lands with its rider on it, who saves once to stay on.", async () => { + const { world, hero, rider, mount } = await pair({ hero: GIANT() }); + rage(world, hero); + world.dice(2, 2); + const out = await impel(world, hero, mount.id); + assert.equal(out.ok, true, out.error); + assert.equal(out.result.saved, false, JSON.stringify(out.result)); + assert.equal(world.clearDice(), 0, "the rider of a thrown mount made no save"); + // Thirty feet from the barbarian at (11,4), along the line through the pair. + assertParted(world, rider, mount, [17, 4]); + assert.equal(prone(world, rider.id), true); +}); + +await test("Ruling 6 for a thrown foe: Mighty Impel at the rider throws it alone from the saddle, prone where it lands, and the mount stays.", async () => { + const { world, hero, rider, mount } = await pair({ hero: GIANT() }); + rage(world, hero); + world.dice(2, 20); + const out = await impel(world, hero, rider.id); + assert.equal(out.ok, true, out.error); + assert.equal(out.result.saved, false, JSON.stringify(out.result)); + assert.equal(world.clearDice(), 1, "the thrown rider made a save to stay on"); + assert.equal(mounted(world, rider), false); + assert.deepEqual(at(world, rider.id), [17, 4]); + assert.deepEqual(at(world, mount.id), [12, 4], "the throw at the rider moved the mount"); + assert.equal(prone(world, rider.id), true); +}); + +const PSI = () => MARTIAL("fighter", "Psi Warrior", 15, "Longsword"); +// Telekinetic Thrust follows a Psionic Strike, which follows a weapon hit: +// both are landed on the creature first, sturdy enough to stand them. +async function thrust(world, hero, rider, mount, target, ...then) { + const kit = await combatKit(world); + for (const enemy of [rider, mount]) kit.setEnemy(enemy.id, { maxHp: 300, currentHp: 300 }); + world.dice(15, 4, 4, 4, 4); + const hit = await world.invoke("pc_attack", { characterId: hero.id, enemyId: target.id, targetEnemyId: target.id }); + world.clearDice(); + assert.equal(hit.ok, true, hit.error); + world.dice(4, 4, 4); + const strike = await world.invoke("use_resource", { characterId: hero.id, resource: "Psionic Strike", targetEnemyId: target.id }); + world.clearDice(); + assert.equal(strike.ok, true, strike.error); + world.diceLog(); + world.dice(2, ...then); + const out = await world.invoke("use_resource", { characterId: hero.id, resource: "Telekinetic Adept", variant: "push", targetEnemyId: target.id }); + assert.equal(out.ok, true, out.error); + assert.equal(out.result.saved, false, JSON.stringify(out.result)); + return out; +} + +await test("A psionic push at the mount (Telekinetic Thrust) carries the pair 10 feet, and its rider saves once to stay on.", async () => { + const { world, hero, rider, mount } = await pair({ hero: PSI() }); + await thrust(world, hero, rider, mount, mount, 2); + assert.equal(world.clearDice(), 0, "the rider of a mount pushed by Telekinetic Thrust made no save"); + assertParted(world, rider, mount, [14, 4]); + assert.equal(prone(world, rider.id), true); +}); + +await test("Ruling 6 for a psionic push: Telekinetic Thrust at the rider pushes it alone from the saddle, prone, and the mount stays.", async () => { + const { world, hero, rider, mount } = await pair({ hero: PSI() }); + await thrust(world, hero, rider, mount, rider, 20); + assert.equal(world.clearDice(), 1, "the rider pushed from the saddle made a save to stay on"); + assert.equal(mounted(world, rider), false); + assert.deepEqual(at(world, rider.id), [14, 4]); + assert.deepEqual(at(world, mount.id), [12, 4], "the push at the rider moved the mount"); + assert.equal(prone(world, rider.id), true); +}); + +// ---- a mount an area holds ---- + +await test("A mount the webs catch as it walks is held on the square it was caught on, its rider still on its back.", async () => { + const { world, hero, rider, mount } = await pair({ hero: caster("wizard", "int", ["Web"]) }); + const cast = await world.invoke("use_spell_slot", { characterId: hero.id, spell: "Web", level: 2, atX: 16, atY: 4 }); + assert.equal(cast.ok, true, cast.error); + const web = zonesOf(world).find((zone) => zone.spell === "Web"); + const width = mapOf(world).width; + const columns = web.cells.filter((cell) => Math.floor(cell / width) === 4).map((cell) => cell % width).sort((a, b) => a - b); + const [entry, further] = columns; + assert.ok(entry > 12 && further === entry + 1, `setup: the webs lie on columns ${columns.join(",")} of the pair's row`); + turnOf(world, mount.id); + // The wolf's Dexterity save against the webs. The Disengage keeps the + // hero's opportunity attack out of the dice. + world.dice(1); + const out = await world.invoke("move_token", { token: mount.id, x: further, y: 4, disengage: true }); + assert.equal(world.clearDice(), 0, "the mount walked into the webs with no save"); + assert.equal(out.ok, true, out.error); + assert.ok(live(world, mount.id).conditions.includes("restrained"), "the webs did not hold the mount"); + assert.deepEqual(at(world, rider.id), [entry, 4], "the restrained mount walked on past the square the webs caught it on"); + assert.equal(live(world, rider.id).ridesEnemyId, mount.id, "a mount held by the webs lost its rider"); + assert.equal(ownToken(world, mount.id), null); +}); + closeTables(); finish(); diff --git a/src/lib/dm/zone-triggers.ts b/src/lib/dm/zone-triggers.ts index 1ca602e7e6..2f6f544730 100644 --- a/src/lib/dm/zone-triggers.ts +++ b/src/lib/dm/zone-triggers.ts @@ -22,7 +22,7 @@ import { maskKeepsOut } from "@/lib/dm/genre-cc-a-drones"; import { bindsWorthResisting } from "@/lib/dm/legendary-logic"; import type { Campaign } from "@/lib/db/campaigns"; import { closeStandInTurn, openStandInTurn, type DmTurn } from "@/lib/db/dm-turns"; -import { getBattleMap, getBattleMapForEncounter, listHiddenRefIds, listTokens, moveToken, type BattleMap } from "@/lib/db/battle-maps"; +import { getBattleMap, getBattleMapForEncounter, getTokenByRef, listHiddenRefIds, listTokens, moveToken, type BattleMap } from "@/lib/db/battle-maps"; import type { RollAttacker } from "@/lib/db/rolls"; import { rollCard } from "@/lib/dm/roll-card"; import { spellBombardment } from "@/lib/dm/ar-ws-bombardment"; @@ -114,7 +114,9 @@ const holds = (conditions: string[], name: string) => conditions.some((entry) => // Pushes a creature `feet` along the line away from the zone's caster, // square by square, stopping at a wall, the edge or another creature. -function pushAlong(map: BattleMap, zone: SpellZone, token: BattleToken, feet: number): XY | null { +// `enemy` is the enemy pushed, which is not always whose token moves: a +// ridden mount stands on its rider's token. +function pushAlong(map: BattleMap, zone: SpellZone, token: BattleToken, feet: number, enemy: EncounterEnemy | null = null): XY | null { const toward = zone.toward ?? token; const distance = Math.max(1, chebyshev(zone.origin.x, zone.origin.y, toward.x, toward.y)); const ux = Math.round((toward.x - zone.origin.x) / distance); @@ -136,8 +138,8 @@ function pushAlong(map: BattleMap, zone: SpellZone, token: BattleToken, feet: nu return null; } // An enemy is moved as the pair it may be half of (enemy-rider-falls.ts): a - // rider the area caught goes alone, out of the saddle. - const enemy = token.kind === "enemy" ? getEnemy(token.refId) : null; + // rider the area caught goes alone, out of the saddle, and a mount goes with + // its rider on it. if (enemy) { return forcedEnemyMove({ id: map.campaignId }, map.id, enemy, at)?.at ?? null; } @@ -371,8 +373,10 @@ function afterFailOnEnemy(map: BattleMap, zone: SpellZone, trigger: ZoneTrigger, lines.push(`${enemy.displayName} spends its action this turn retching.`); } if (trigger.pushFeet) { - const token = listTokens(map.id).find((entry) => entry.refId === enemy.id); - const at = token ? pushAlong(map, zone, token, trigger.pushFeet) : null; + // A ridden mount has no token of its own: the pair's is found for it. + // Looked up by its own id, the mount an area pushed stood where it was. + const token = getTokenByRef(map.id, enemy.id); + const at = token ? pushAlong(map, zone, token, trigger.pushFeet, getEnemy(enemy.id) ?? enemy) : null; if (at) { lines.push(`${enemy.displayName} is pushed to (${at.x},${at.y}).`); } @@ -550,7 +554,9 @@ function areasAfterMove( } } if (stopAt) { - const token = listTokens(map.id).find((entry) => entry.refId === victim.id); + // The pair's token for a ridden mount, which has none of its own: a mount + // the webs caught walked on to the square it was making for. + const token = getTokenByRef(map.id, victim.id); if (token && (token.x !== stopAt.x || token.y !== stopAt.y)) { moveToken(token.id, stopAt.x, stopAt.y, token.movedThisRound); lines.push(`It is held fast at (${stopAt.x},${stopAt.y}).`); @@ -673,8 +679,12 @@ function momentFor( ): string[] { const lines: string[] = []; for (const id of combatantIds) { - const token = tokens.find((entry) => entry.refId === id); - const victim = token ? victimOf(token) : null; + // A ridden mount stands on its rider's token and suffers the area in its + // own name, on its own turn. Looked up by its own id alone it had no + // token, and its turn began and ended inside an area untouched. + const own = tokens.find((entry) => entry.refId === id); + const token = own ?? (getEnemy(id) ? getTokenByRef(map.id, id) : null); + const victim: Victim | null = own ? victimOf(own) : token ? { kind: "enemy", id } : null; if (!token || !victim) { continue; } From 803382fc4e3f27c064ccf247650ed86de2dcc744 Mon Sep 17 00:00:00 2001 From: Smoebo Date: Sat, 21 Nov 2026 09:27:09 -0500 Subject: [PATCH 6/7] A mount with a rider on it is a creature on the board: a blast or a laid area catches it apart from its rider, it threatens, an aura it holds has squares, and the GM's board text gives it a line Co-Authored-By: Claude Fable 5.2 --- .../test-enforce-ridden-mount-standings.mjs | 231 ++++++++++++++++++ src/lib/battlemap/serialize.ts | 7 +- src/lib/battlemap/view.ts | 6 +- src/lib/db/battle-maps.ts | 70 +++++- src/lib/dm/aoe-shape.ts | 16 +- src/lib/dm/attack-spatial.ts | 8 +- src/lib/dm/authored-heal-area.ts | 3 +- src/lib/dm/authored-hooks.ts | 4 +- src/lib/dm/cauterizing-flames.ts | 4 +- src/lib/dm/confusion.ts | 4 +- src/lib/dm/genre-b-zones.ts | 4 +- src/lib/dm/genre-cc-a-spends.ts | 4 +- src/lib/dm/genre-cc-a-turns.ts | 4 +- src/lib/dm/hide-traits.ts | 8 +- src/lib/dm/map-tools.ts | 9 +- src/lib/dm/spirit-projection.ts | 4 +- src/lib/dm/summon-store.ts | 4 +- src/lib/dm/turn.ts | 7 +- src/lib/dm/zone-cast.ts | 8 +- src/lib/dm/zone-quake.ts | 4 +- src/lib/dm/zone-store.ts | 4 +- src/lib/dm/zone-triggers.ts | 23 +- 22 files changed, 379 insertions(+), 57 deletions(-) create mode 100644 scripts/test-enforce-ridden-mount-standings.mjs diff --git a/scripts/test-enforce-ridden-mount-standings.mjs b/scripts/test-enforce-ridden-mount-standings.mjs new file mode 100644 index 0000000000..f1e31b334a --- /dev/null +++ b/scripts/test-enforce-ridden-mount-standings.mjs @@ -0,0 +1,231 @@ +// A mount with a rider on it is a creature on the board (issues 1036 and +// 1055). +// +// The pair stands on one token, the rider's (ruling 1 of each issue), so the +// pieces on the board (db/battle-maps.ts listTokens) hold no entry for the +// mount. Every rule that read that list to ask who stands where passed the +// mount over: a Fireball over a goblin on a wolf burned the goblin alone, +// and a search of the list for the wolf's own id found nobody. +// +// "An area that catches both creatures resolves each one separately" +// (issue 1055, ruling 6). The rules that ask who stands where now read +// listStandings, where a ridden mount stands under its own id on its +// rider's token. +import assert from "node:assert/strict"; +import "./lib/enforce-world.mjs"; +import { suite } from "./lib/enforce-harness.mjs"; +import { openWorld } from "./lib/enforce-world.mjs"; +import { combatKit } from "./lib/enforce-combat.mjs"; +import { caster, closeTables } from "./lib/enforce-spell-kit.mjs"; +import { castOnOwnTurn, fightDummies, layMap } from "./lib/enforce-spells.mjs"; +import { holdTurn, mapOf, nextTurn, OPEN, zonesOf } from "./lib/enforce-zones.mjs"; + +const { test, finish } = suite("test-enforce-ridden-mount-standings"); +const { listHiddenRefIds, listStandings, listTokens, setTokenHidden } = await import("../src/lib/db/battle-maps.ts"); +const { saveEncounter } = await import("../src/lib/db/encounters.ts"); +const { liveZones, saveZones } = await import("../src/lib/dm/zone-store.ts"); +const { characterShootsInMelee } = await import("../src/lib/dm/attack-spatial.ts"); +const { lashOut } = await import("../src/lib/dm/confusion.ts"); +const { serializeMapForPrompt } = await import("../src/lib/battlemap/serialize.ts"); +const { buildPlayerMapView } = await import("../src/lib/battlemap/view.ts"); + +const ownToken = (world, refId) => listTokens(mapOf(world).id).find((token) => token.refId === refId) ?? null; +const live = (world, id) => world.enemies().find((enemy) => enemy.id === id); +const NL = String.fromCharCode(10); +const has = (world, id, condition) => live(world, id).conditions.includes(condition); + +// A hero at (`heroAt`,4) and a goblin on a wolf at (12,4), on an open board. +// The order is the hero, the rider, the mount, with the pointer on the hero. +async function pair(who, { heroAt = 4, mount = "wolf" } = {}) { + const world = await openWorld({ gameSettings: { ttsEnabled: false } }); + const hero = world.addHero(who); + await world.beginFight([{ monster: "goblin", mount }]); + const up = world.enemies().find((enemy) => enemy.ridesEnemyId); + const under = world.enemies().find((enemy) => enemy.id === up?.ridesEnemyId); + assert.ok(up && under, "setup: the fight has no rider on a mount"); + await layMap(world, OPEN(), { [hero.id]: { x: heroAt, y: 4 }, [up.id]: { x: 12, y: 4 } }); + const encounter = world.encounter(); + const entry = (id) => encounter.order.find((row) => (row.characterId ?? row.enemyId) === id); + saveEncounter({ ...encounter, order: [entry(hero.id), entry(up.id), entry(under.id)], turnIndex: 0, turnBudget: null, reactionsUsed: [] }); + world.clearDice(); + world.diceLog(); + return { world, hero, rider: up, mount: under }; +} + +// Both sturdy enough to stand a Fireball, so what each lost can be read. +async function sturdy(world, ...enemies) { + const kit = await combatKit(world); + for (const enemy of enemies) kit.setEnemy(enemy.id, { maxHp: 300, currentHp: 300 }); +} + +// ---- the list itself ---- + +await test("A ridden mount stands on the board under its own id, on its rider's token and before its rider; the pieces on the board stay one.", async () => { + const { world, rider, mount } = await pair(caster("wizard", "int", ["Fireball"])); + const map = mapOf(world); + assert.equal(listTokens(map.id).filter((token) => token.kind === "enemy").length, 1, "the pair is not one piece on the board"); + const standing = listStandings(map.id).filter((token) => token.kind === "enemy"); + assert.deepEqual(standing.map((token) => token.refId), [mount.id, rider.id]); + const [under, up] = standing; + assert.equal(under.id, up.id, "the mount does not stand on its rider's token"); + assert.deepEqual([under.x, under.y, under.name], [12, 4, mount.displayName]); +}); + +await test("A mount under a rider the GM keeps hidden is hidden with it.", async () => { + const { world, rider, mount } = await pair(caster("wizard", "int", ["Fireball"])); + const map = mapOf(world); + assert.deepEqual(listHiddenRefIds(map.id), []); + setTokenHidden(ownToken(world, rider.id).id, true); + assert.deepEqual([...listHiddenRefIds(map.id)].sort(), [mount.id, rider.id].sort(), "the mount of a hidden rider reads as shown"); +}); + +// ---- areas ---- + +await test("A blast laid on the board catches the mount and its rider, each one separately (Fireball).", async () => { + const { world, hero, rider, mount } = await pair(caster("wizard", "int", ["Fireball"])); + await sturdy(world, rider, mount); + const out = await world.invoke("aoe_damage", { casterCharacterId: hero.id, spell: "Fireball", level: 3, atX: 13, atY: 4 }); + world.clearDice(); + assert.equal(out.ok, true, out.error); + assert.ok(live(world, rider.id).currentHp < 300, "the fire missed the rider"); + assert.ok(live(world, mount.id).currentHp < 300, "the fire passed over the mount under its rider"); +}); + +await test("A mount named for an area it does not stand in is refused, as its rider is.", async () => { + const { world, hero, mount } = await pair(caster("wizard", "int", ["Shatter"])); + const out = await world.invoke("aoe_damage", { casterCharacterId: hero.id, spell: "Shatter", level: 2, enemyIds: [mount.id], atX: 20, atY: 4 }); + world.clearDice(); + assert.equal(out.ok, false, "a mount 40 feet from the burst was taken as inside it"); + assert.equal(live(world, mount.id).currentHp, live(world, mount.id).maxHp); +}); + +await test("An area that catches whoever stands on it as it is laid catches the mount with its rider (Entangle).", async () => { + const { world, hero, rider, mount } = await pair(caster("druid", "wis", ["Entangle"])); + // Each one's Strength save, failed. + world.dice(1, 1); + const out = await world.invoke("aoe_damage", { casterCharacterId: hero.id, spell: "Entangle", level: 1, atX: 12, atY: 4 }); + world.clearDice(); + assert.equal(out.ok, true, out.error); + assert.ok(has(world, rider.id, "restrained"), "the vines missed the rider"); + assert.ok(has(world, mount.id, "restrained"), "the vines passed over the mount under its rider"); +}); + +await test("The ground that shakes at the end of its caster's turn throws the mount down as well as its rider (Earthquake).", async () => { + const { world, hero, rider, mount } = await pair(caster("cleric", "wis", ["Earthquake"], [], 15), { heroAt: 2 }); + world.dice(...new Array(12).fill(20)); + const cast = await world.invoke("use_spell_slot", { characterId: hero.id, spell: "Earthquake", level: 8, atX: 12, atY: 4 }); + world.clearDice(); + assert.equal(cast.ok, true, cast.error); + assert.ok(zonesOf(world).some((zone) => zone.spell === "Earthquake"), "setup: the area is laid"); + assert.equal(has(world, mount.id, "prone"), false, "setup: the mount fell as the spell was cast"); + holdTurn(world, hero.id); + world.dice(...new Array(8).fill(1)); + nextTurn(world); + world.clearDice(); + assert.ok(has(world, mount.id, "prone"), "the mount under its rider kept its feet with no save"); + assert.ok(has(world, rider.id, "prone"), "the rider kept its feet"); +}); + +await test("An aura held by a ridden mount lies around the square the pair stands on.", async () => { + const { world, mount } = await pair(caster("wizard", "int", ["Fireball"])); + const map = mapOf(world); + saveZones(map.id, [{ id: "aura-mount", spell: "Spirit Guardians", casterId: mount.id, casterKind: "enemy", casterName: mount.displayName, origin: { x: 0, y: 0 }, toward: null, cells: [], concentration: false, castRound: world.encounter().round, untilRound: null, slotLevel: 3, dc: 13 }]); + const [aura] = liveZones(mapOf(world), world.encounter()); + assert.ok(aura, "setup: the aura does not hold"); + assert.ok(aura.cells.includes(4 * map.width + 12), "the aura of a ridden mount covers no squares"); +}); + +// ---- reach, and a creature looked up by its own id ---- + +await test("A mount whose rider cannot act still threatens the archer beside the pair.", async () => { + const { world, hero, rider } = await pair(caster("wizard", "int", ["Fireball"]), { heroAt: 11 }); + assert.equal(characterShootsInMelee(world.encounter().id, hero.id, []), true, "setup: the pair beside the archer does not threaten"); + const kit = await combatKit(world); + kit.setEnemy(rider.id, { conditions: ["stunned"] }); + assert.equal(characterShootsInMelee(world.encounter().id, hero.id, []), true, "with its rider stunned, the mount beside the archer threatens nobody"); +}); + +await test("A confused creature beside a pair may lash out at the mount as well as the rider.", async () => { + const { world, hero, mount } = await pair(caster("wizard", "int", ["Fireball"]), { heroAt: 11 }); + // Two creatures in reach, so the die picks: a 1 is the first of them. + world.dice(1); + const line = lashOut(world.campaign(), world.encounter(), "sheet", hero.id, hero.name); + assert.equal(world.clearDice(), 0, `the mount was no creature in reach, so no die picked: ${line}`); + assert.ok(line.includes(mount.displayName), line); +}); + +await test("An attack refused for range names the mount among the foes it does reach, and an unknown name is answered with the mount's among those on the board.", async () => { + const world = await openWorld({ gameSettings: { ttsEnabled: false } }); + const hero = world.addHero({ class: "fighter", level: 5, maxHp: 60, abilities: { str: 16, dex: 12, con: 14 }, equipment: [{ name: "Longsword", qty: 1, equipped: true }] }); + await world.beginFight([{ monster: "goblin", mount: "wolf" }, { monster: "goblin" }]); + const rider = world.enemies().find((enemy) => enemy.ridesEnemyId); + const mount = world.enemies().find((enemy) => enemy.id === rider.ridesEnemyId); + const far = world.enemies().find((enemy) => enemy.id !== rider.id && enemy.id !== mount.id); + await layMap(world, OPEN(), { [hero.id]: { x: 11, y: 4 }, [rider.id]: { x: 12, y: 4 }, [far.id]: { x: 20, y: 4 } }); + holdTurn(world, hero.id); + world.clearDice(); + const out = await world.invoke("pc_attack", { characterId: hero.id, enemyId: far.id, targetEnemyId: far.id }); + world.clearDice(); + assert.equal(out.ok, false); + assert.match(out.error, /Within reach: /, out.error); + assert.ok(out.error.split("Within reach: ")[1].includes(mount.displayName), `the mount beside the attacker is not named as in reach: ${out.error}`); + const lost = await world.invoke("move_token", { token: "Nobody By That Name", x: 1, y: 1 }); + assert.equal(lost.ok, false); + assert.ok(lost.error.includes(mount.displayName), `the mount is not among the names the board holds: ${lost.error}`); +}); + +// ---- what the GM's model and the players' board are told ---- + +await test("The board written out for the GM's model has a line for the mount, with its own id and conditions, under the letter the pair shares.", async () => { + const { world, rider, mount } = await pair(caster("wizard", "int", ["Fireball"])); + const map = mapOf(world); + const text = serializeMapForPrompt({ ...map, terrain: map.drawnTerrain }, listStandings(map.id), new Map([[mount.id, "prone"]])); + const line = text.split(NL).find((entry) => entry.startsWith("Combatants: ")); + const entries = line.replace("Combatants: ", "").split("; "); + const under = entries.find((entry) => entry.includes(`[enemyId=${mount.id}]`)); + const up = entries.find((entry) => entry.includes(`[enemyId=${rider.id}]`)); + assert.ok(under, `the mount has no line among the combatants: ${line}`); + assert.match(under, /at \(12,4\) \[prone\]$/, under); + const letter = under.split("=")[0]; + assert.equal(up.split("=")[0], letter, "the pair does not share one letter"); + assert.ok(!up.includes("[prone]"), "the mount's condition was written on its rider"); + // The rows of the grid, their row numbers cut off. + const grid = text.split(NL).filter((entry) => /^[ 0-9][0-9] \S+$/.test(entry)).map((entry) => entry.slice(3)).join(""); + assert.equal(grid.split(letter).length - 1, 1, `the pair is not drawn once: ${grid}`); +}); + +// ---- a character's own mount (issue 1036) ---- + +await test("A character's independent mount stands under its own sheet on its rider's token: its turn lights the pair's figure, and a blast over the pair burns both.", async () => { + const world = await openWorld({ gameSettings: { ttsEnabled: false } }); + const paladin = world.addHero(caster("paladin", "cha", ["Find Steed"], [], 5, { speed: 30, maxHp: 60 })); + const wizard = world.addHero(caster("wizard", "int", ["Fireball"])); + const cast = await world.invoke("cast_buff", { characterId: paladin.id, spell: "Find Steed", level: 2, variant: "warhorse" }); + assert.equal(cast.ok, true, cast.error); + const steed = world.sheets().find((sheet) => sheet.summon?.spell === "Find Steed"); + const [enemy] = await fightDummies(world, 1, { heroFaces: { [paladin.id]: 20 } }); + castOnOwnTurn(world); + await layMap(world, OPEN(), { [paladin.id]: { x: 12, y: 3 }, [steed.id]: { x: 13, y: 3 }, [wizard.id]: { x: 2, y: 3 }, [enemy.id]: { x: 22, y: 8 } }); + holdTurn(world, paladin.id); + const up = await world.invoke("mount_up", { characterId: paladin.id, mount: "Warhorse", controlled: false }); + assert.equal(up.ok, true, up.error); + const map = mapOf(world); + assert.equal(ownToken(world, steed.id), null, "setup: the steed kept a token of its own"); + const [under, rider] = listStandings(map.id).filter((token) => token.refId === steed.id || token.refId === paladin.id); + assert.deepEqual([under.refId, under.kind, rider.refId, under.id], [steed.id, "pc", paladin.id, rider.id]); + holdTurn(world, steed.id); + const view = buildPlayerMapView(world.campaignId, world.owner.id, { fullVision: true }); + assert.equal(view.turn?.tokenId, rider.id, "the steed's turn lights no figure on the players' board"); + const before = { steed: world.sheet(steed.id).currentHp, paladin: world.sheet(paladin.id).currentHp }; + holdTurn(world, wizard.id); + const fire = await world.invoke("aoe_damage", { casterCharacterId: wizard.id, spell: "Fireball", level: 3, atX: rider.x, atY: rider.y }); + world.clearDice(); + assert.equal(fire.ok, true, fire.error); + assert.ok(world.sheet(paladin.id).currentHp < before.paladin, "the fire missed the rider"); + // A steed the fire drops to 0 is gone from the table. + const burnt = world.sheet(steed.id); + assert.ok(!burnt || burnt.currentHp < before.steed, "the fire passed over the steed under its rider"); +}); + +closeTables(); +finish(); diff --git a/src/lib/battlemap/serialize.ts b/src/lib/battlemap/serialize.ts index 04391e6e85..e8c42f7fea 100644 --- a/src/lib/battlemap/serialize.ts +++ b/src/lib/battlemap/serialize.ts @@ -23,6 +23,8 @@ export type SerializableMap = { }; // PCs get A-Z in party order; enemies get digits then lowercase letters. +// A mount and the rider on it are one piece on the board (the two entries +// of db/battle-maps.ts listStandings share a token), so they share a letter. export function tokenGlyphs(tokens: BattleToken[]): Map { const glyphs = new Map(); const pcLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; @@ -30,6 +32,9 @@ export function tokenGlyphs(tokens: BattleToken[]): Map { let pcAt = 0; let enemyAt = 0; for (const token of tokens) { + if (glyphs.has(token.id)) { + continue; + } if (token.kind === "pc") { glyphs.set(token.id, pcLetters[pcAt % pcLetters.length]); pcAt += 1; @@ -138,7 +143,7 @@ export function serializeMapForPrompt( `Fixed lights at ${map.lights.map((light) => `(${light.x},${light.y})`).join(", ")} (bright ${map.lights[0].brightRadius} tiles).`, ); } - const carriers = tokens.filter((token) => token.lightRadius > 0); + const carriers = tokens.filter((token, at) => token.lightRadius > 0 && tokens.findIndex((other) => other.id === token.id) === at); if (carriers.length) { lightParts.push(`Carrying light: ${carriers.map((token) => token.name).join(", ")}.`); } diff --git a/src/lib/battlemap/view.ts b/src/lib/battlemap/view.ts index a87dce2cf0..a5e8f03ef6 100644 --- a/src/lib/battlemap/view.ts +++ b/src/lib/battlemap/view.ts @@ -35,6 +35,7 @@ import { getBattleMapForEncounter, getExplored, getTokenByRef, + listStandings, listTokens, mergeExplored, type BattleMap, @@ -524,7 +525,10 @@ export function buildPlayerMapView( const tokenAuras: PlayerMapView["tokenAuras"] = {}; const tokenFootprint: PlayerMapView["tokenFootprint"] = {}; const tokenElevation: PlayerMapView["tokenElevation"] = {}; - const tokenByRef = new Map(tokens.map((token) => [token.refId, token])); + // A mount under a rider is found on its rider's token (listStandings): on + // the mount's turn the pair's figure is the one lit, and a line drawn from + // or to the mount ends on it. + const tokenByRef = new Map(listStandings(map.id).map((token) => [token.refId, token])); const effectAuras = new Map>(); for (const effect of listEffects(campaignId)) { // An effect the party cannot tell is there draws no ring on their board. diff --git a/src/lib/db/battle-maps.ts b/src/lib/db/battle-maps.ts index 8c62c0f010..7c10916a0f 100644 --- a/src/lib/db/battle-maps.ts +++ b/src/lib/db/battle-maps.ts @@ -465,6 +465,61 @@ export function listTokens(mapId: string): BattleToken[] { return rows.map(mapToken); } +// The mounts carried on this map's table, by the id of the rider whose token +// each one shares: a character's independent mount (issue 1036) and an +// enemy's (issue 1055). +function carriedMounts(mapId: string): Map { + const carried = new Map(); + const map = getDatabase().prepare(`SELECT campaign_id FROM battle_maps WHERE id = ?`).get(mapId) as { campaign_id?: string } | undefined; + if (!map?.campaign_id) { + return carried; + } + for (const [riderId, mount] of Object.entries(getMounts(map.campaign_id))) { + if (independentMount(mount)) { + carried.set(riderId, { id: mount.sheetId, name: mount.name, kind: "pc" }); + } + } + const pairs = getDatabase() + .prepare( + `SELECT rider.id AS rider, mount.id AS id, mount.display_name AS name + FROM encounter_enemies rider JOIN encounter_enemies mount ON mount.id = rider.rides_enemy_id + WHERE rider.campaign_id = ?`, + ) + .all(map.campaign_id) as Array<{ rider: string; id: string; name: string }>; + for (const pair of pairs) { + carried.set(pair.rider, { id: pair.id, name: pair.name, kind: "enemy" }); + } + return carried; +} + +// Everyone standing on the board, for a rule that asks who stands where: +// who an area catches, who is within reach, where this creature is. +// listTokens is the pieces on the board, and a mount with a rider on it is +// no piece (ruling 1 of issues 1036 and 1055: one token, the rider's), so +// a Fireball laid over a goblin on a wolf burned the goblin and never asked +// the wolf, and a search of the list for the wolf's own id found nobody. +// Here the mount stands too, as an entry of its own on its rider's token: +// the same token id and square, under the mount's own id, name and kind. +// It comes before its rider, so a rule that takes each creature in turn +// reaches the mount first and a push that takes both moves the pair as one +// (issue 1055, ruling 6). +// +// Not for code that draws, counts, places or moves the pieces themselves: +// the two entries of a pair are one row, and a write by token id made for +// each would be made twice. +export function listStandings(mapId: string): BattleToken[] { + const tokens = listTokens(mapId); + const carried = carriedMounts(mapId); + if (!carried.size) { + return tokens; + } + const own = new Set(tokens.map((token) => token.refId)); + return tokens.flatMap((token) => { + const mount = carried.get(token.refId); + return mount && !own.has(mount.id) ? [{ ...token, refId: mount.id, name: mount.name, kind: mount.kind }, token] : [token]; + }); +} + // A combatant's token. An independent mount carrying its rider has none of // its own: the pair stands on the rider's token (issue 1036, ruling 2: "the // rider's token rides on the mount", never two tokens on a square), so the @@ -596,12 +651,23 @@ export function renameTokenByRef(mapId: string, refId: string, name: string) { // Ref ids of every token the DM is keeping off the table. The initiative // tracker asks for these too, so one flag hides a combatant in both places -// (src/lib/db/encounters.ts). +// (src/lib/db/encounters.ts). A mount under a hidden rider is hidden with +// it: the flag is on the one token the pair shares, and asked by the mount's +// own id it read as shown, so a hidden pair's mount was named to the table. export function listHiddenRefIds(mapId: string): string[] { const rows = getDatabase() .prepare(`SELECT ref_id FROM battle_tokens WHERE map_id = ? AND hidden = 1`) .all(mapId) as Array<{ ref_id: string }>; - return rows.map((row) => row.ref_id); + const hidden = rows.map((row) => row.ref_id); + if (!hidden.length) { + return hidden; + } + const carried = carriedMounts(mapId); + const own = new Set(hidden); + return [...hidden, ...hidden.flatMap((riderId) => { + const mount = carried.get(riderId); + return mount && !own.has(mount.id) ? [mount.id] : []; + })]; } export function deleteToken(tokenId: string) { diff --git a/src/lib/dm/aoe-shape.ts b/src/lib/dm/aoe-shape.ts index ac5c9bf1a4..4a458f6bb4 100644 --- a/src/lib/dm/aoe-shape.ts +++ b/src/lib/dm/aoe-shape.ts @@ -10,7 +10,7 @@ // the DM's word places the area there. import { getEnemy } from "@/lib/db/encounters"; -import { getBattleMapForEncounter, listTokens } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, listStandings } from "@/lib/db/battle-maps"; import { findSpellByName } from "@/lib/content"; import { authoredSpellRow } from "@/lib/srd/spell-mechanics"; import { templateTiles, type TemplateShape } from "@/lib/battlemap/template"; @@ -74,7 +74,7 @@ export function areaProblem(input: { if (!map || !input.creatures.length) { return null; } - const tokens = listTokens(map.id); + const tokens = listStandings(map.id); const caster = tokens.find((token) => token.refId === input.casterId); const placed = input.creatures .map((creature) => { @@ -184,7 +184,7 @@ export function creaturesInBlast(input: { if (!map) { return null; } - const tokens = listTokens(map.id); + const tokens = listStandings(map.id); const casterToken = tokens.find((token) => token.refId === input.casterId); const caster = casterToken ? { x: casterToken.x, y: casterToken.y } : null; const pick = blastPickOf(input.area); @@ -209,7 +209,7 @@ export function creaturesInBlast(input: { // its size, a character by its own. function standingIn( width: number, - tokens: ReturnType, + tokens: ReturnType, cells: ReadonlySet, options: { skip: string | null; spareParty: boolean }, ): { enemyIds: string[]; characterIds: string[]; echoes: string[] } { @@ -218,12 +218,16 @@ function standingIn( // An Echo Knight's echo in the area: no creature, but it makes the save // with its knight's bonus (mt-fb-echo.ts echoAreaSave). const echoes: string[] = []; + // The caster an area leaves out is left out with the creature it shares a + // token with: a rider's cone starts at the edge of the space the pair + // fills, so it holds neither the rider nor the mount under them. + const skipped = options.skip ? (tokens.find((token) => token.refId === options.skip)?.id ?? null) : null; for (const token of tokens) { if (echoOwnerOf(token) && cells.has(tileIndex(width, token.x, token.y))) { echoes.push(token.refId); continue; } - if (token.refId === options.skip) { + if (token.refId === options.skip || token.id === skipped) { continue; } if (token.kind === "enemy") { @@ -261,7 +265,7 @@ export function creaturesInLaidZone(input: { if (!row || !map) { return null; } - const tokens = listTokens(map.id); + const tokens = listStandings(map.id); const casterToken = tokens.find((token) => token.refId === input.casterId); const caster = casterToken ? { x: casterToken.x, y: casterToken.y } : null; const fromCaster = row.shape === "aura" || row.shape === "line" || Boolean(row.self); diff --git a/src/lib/dm/attack-spatial.ts b/src/lib/dm/attack-spatial.ts index 2921eaa801..2abfed80d9 100644 --- a/src/lib/dm/attack-spatial.ts +++ b/src/lib/dm/attack-spatial.ts @@ -8,7 +8,7 @@ import { oneWithTheRuins } from "@/lib/dm/genre-gb-ruins"; import { fortifiedCover } from "@/lib/dm/cannon-board-dra"; -import { getBattleMapForEncounter, getTokenByRef, listTokens } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, getTokenByRef, listStandings, listTokens } from "@/lib/db/battle-maps"; import { getEncounter, getEnemy, type Encounter, type EncounterEnemy } from "@/lib/db/encounters"; import { otherSide, type CombatSide } from "@/lib/dm/combat-sides-logic"; import { sideOf } from "@/lib/dm/combatant"; @@ -83,7 +83,7 @@ export function wallsBeside(encounterId: string, ref: string): string[] { if (!map || !self) { return []; } - return listTokens(map.id) + return listStandings(map.id) .filter((token) => token.id !== self.id && tilesApart(self, token) <= 1 && walledApart(map, self, token)) .map((token) => token.refId); } @@ -130,7 +130,9 @@ function sidesOf(encounterId: string): Pick { // The squares of the creatures on `side` that threaten, but `except`. function threatSpots(encounterId: string, mapId: string, side: CombatSide, except: string[]) { const encounter = sidesOf(encounterId); - return listTokens(mapId) + // A mount under a rider threatens from the pair's space in its own right: + // it does when its rider cannot (listStandings). + return listStandings(mapId) .filter((token) => !except.includes(token.refId) && threateningSide(encounter, token) === side) .map(spotOf); } diff --git a/src/lib/dm/authored-heal-area.ts b/src/lib/dm/authored-heal-area.ts index be9c4cea57..b9f250a1f3 100644 --- a/src/lib/dm/authored-heal-area.ts +++ b/src/lib/dm/authored-heal-area.ts @@ -66,7 +66,8 @@ function walkOf(campaign: Campaign, encounter: Encounter | null, sheet: Characte }); const board = { terrain: map.terrain, width: map.width, height: map.height, occupied: occupiedTiles(map, tokens, token, footprintOf), flying: token.movement === "fly", traits, footprint: footprintOf(token) }; const on = targets.flatMap((target) => { - const placed = tokens.find((entry) => entry.refId === target.id); + // A hurt mount with its rider on it stands on the rider's token. + const placed = getTokenByRef(map.id, target.id); return placed ? [{ id: target.id, tiles: spaceOf(placed) }] : []; }); const budget = speedToTiles(pcMoveBudget(campaign.id, encounter, map, sheet, token).speed); diff --git a/src/lib/dm/authored-hooks.ts b/src/lib/dm/authored-hooks.ts index a3d4136b17..25b09aa2f0 100644 --- a/src/lib/dm/authored-hooks.ts +++ b/src/lib/dm/authored-hooks.ts @@ -37,7 +37,7 @@ import { UNWAVERING_STRIKE } from "@/lib/dm/feature-bonus-attacks"; import { untilTurnEnd } from "@/lib/dm/turn-end"; import { FLAMES_OF_PHLEGETHOS } from "@/lib/srd/feat-combat"; import type { Campaign } from "@/lib/db/campaigns"; -import { getBattleMapForEncounter, listTokens } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, listStandings } from "@/lib/db/battle-maps"; import { tilesApart } from "@/lib/dm/board-reach"; import { @@ -670,7 +670,7 @@ export function authoredSneakEdge(encounterId: string, sheetId: string, enemyId: if (!duel || !map) { return null; } - const tokens = listTokens(map.id); + const tokens = listStandings(map.id); const me = tokens.find((token) => token.refId === sheetId); const target = tokens.find((token) => token.refId === enemyId); if (!me || !target || tilesApart(me, target) > 1) { diff --git a/src/lib/dm/cauterizing-flames.ts b/src/lib/dm/cauterizing-flames.ts index 7b10f97217..f0f8094082 100644 --- a/src/lib/dm/cauterizing-flames.ts +++ b/src/lib/dm/cauterizing-flames.ts @@ -15,7 +15,7 @@ // the board; "enters that space" is read as standing in it when the reaction // is called, since the move that took it there is already made. import { getActiveEncounter, type Encounter } from "@/lib/db/encounters"; -import { getBattleMapForEncounter, getTokenByRef, listTokens } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, getTokenByRef, listStandings } from "@/lib/db/battle-maps"; import { getSheetById, listSheets, patchSheet } from "@/lib/db/sheets"; import { publishPersisted } from "@/lib/events"; import { holdsFeature, isConditionNamed } from "@/lib/srd/feature-names"; @@ -52,7 +52,7 @@ export function layFlamesOnDeath(campaignId: string, dead: { id: string; size?: const where = map ? getTokenByRef(map.id, dead.id) : null; if (!encounter || !map || !where) return; if (dead.size && sizeRank(dead.size) < sizeRank("small")) return; - const tokens = listTokens(map.id); + const tokens = listStandings(map.id); for (const stale of listSheets(campaignId)) { const druid = getSheetById(stale.id) ?? stale; if (druid.deathSaves?.dead || !holdsFeature(druid, "Cauterizing Flames")) continue; diff --git a/src/lib/dm/confusion.ts b/src/lib/dm/confusion.ts index 6fc880aaf7..95e7ef6184 100644 --- a/src/lib/dm/confusion.ts +++ b/src/lib/dm/confusion.ts @@ -16,7 +16,7 @@ // turn start, under the clock path that must not reach the damage modules. import type { Campaign } from "@/lib/db/campaigns"; -import { getBattleMapForEncounter, getTokenByRef, listTokens } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, getTokenByRef, listStandings } from "@/lib/db/battle-maps"; import { getEnemy, patchEnemyConditions, type Encounter } from "@/lib/db/encounters"; import { getSheetById, patchSheet } from "@/lib/db/sheets"; import { publishPersisted } from "@/lib/events"; @@ -60,7 +60,7 @@ export function lashOut(campaign: Campaign, encounter: Encounter, kind: "sheet" } const reach = reachOf(kind, id); const mine = tokenFootprint(me); - const inReach = listTokens(map.id).filter((token) => { + const inReach = listStandings(map.id).filter((token) => { if (token.refId === id || (token.kind !== "pc" && token.kind !== "enemy")) { return false; } diff --git a/src/lib/dm/genre-b-zones.ts b/src/lib/dm/genre-b-zones.ts index 1a8c5a7106..b9b489467b 100644 --- a/src/lib/dm/genre-b-zones.ts +++ b/src/lib/dm/genre-b-zones.ts @@ -7,7 +7,7 @@ // // Off a board the use is paid and the GM places the area in the story. -import { getBattleMapForEncounter, getTokenByRef, listTokens } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, getTokenByRef, listStandings } from "@/lib/db/battle-maps"; import { getActiveBoard, getEnemy } from "@/lib/db/encounters"; import { chebyshev } from "@/lib/battlemap/types"; import { placeSpellZone } from "@/lib/dm/zone-cast"; @@ -33,7 +33,7 @@ function landing(input: Lay, spec: GenreZoneSpec): ToolError | { x: number; y: n return null; } const alive = (refId: string) => getEnemy(refId)?.status === "alive"; - const foes = listTokens(map.id).filter((token) => token.kind === "enemy" && alive(token.refId)); + const foes = listStandings(map.id).filter((token) => token.kind === "enemy" && alive(token.refId)); const apart = (token: { x: number; y: number }) => chebyshev(own.x, own.y, token.x, token.y); const named = input.targetEnemyId ? foes.find((token) => token.refId === input.targetEnemyId) : null; if (input.targetEnemyId && !named) { diff --git a/src/lib/dm/genre-cc-a-spends.ts b/src/lib/dm/genre-cc-a-spends.ts index b7fa1d9dca..d3d42e5c01 100644 --- a/src/lib/dm/genre-cc-a-spends.ts +++ b/src/lib/dm/genre-cc-a-spends.ts @@ -53,7 +53,7 @@ import { holdsFeature } from "@/lib/srd/feature-names"; import { resolveSpendEffect } from "@/lib/dm/authored-spend-effects"; import { refreshTeeth } from "@/lib/dm/genre-cc-a-turns"; import { RAT_TIDE, RAT_TIDE_GROWN } from "@/lib/battlemap/zones-genre-cc-a"; -import { getBattleMapForEncounter, listTokens } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, listStandings } from "@/lib/db/battle-maps"; import { zonesAfterMove } from "@/lib/dm/zone-triggers"; import { isNamed } from "@/lib/srd/feature-names"; import { raiseSquire } from "@/lib/dm/genre-cc-a-squire"; @@ -125,7 +125,7 @@ function ratTide(ctx: SpendContext): Resolution { const zone = map?.spellZones.filter((entry) => entry.casterId === ctx.sheet.id && isNamed(entry.spell, ctx.spend.name)).at(-1); const caught: string[] = []; if (map && zone) { - for (const token of listTokens(map.id)) { + for (const token of listStandings(map.id)) { if (token.refId === ctx.sheet.id || (token.kind !== "enemy" && token.kind !== "pc") || !zone.cells.includes(token.y * map.width + token.x)) { continue; } diff --git a/src/lib/dm/genre-cc-a-turns.ts b/src/lib/dm/genre-cc-a-turns.ts index c0ea7fa1e8..1de1cf9968 100644 --- a/src/lib/dm/genre-cc-a-turns.ts +++ b/src/lib/dm/genre-cc-a-turns.ts @@ -15,7 +15,7 @@ // // The swarm's squares are the area the Rat Tide laid (zones-genre-cc-a.ts). import type { Campaign } from "@/lib/db/campaigns"; -import { getBattleMapForEncounter, getTokenByRef, listTokens } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, getTokenByRef, listStandings } from "@/lib/db/battle-maps"; import { getEnemy, listEnemies, patchEnemyConditions, type Encounter } from "@/lib/db/encounters"; import { getSheetById } from "@/lib/db/sheets"; import type { ConditionMetaMap } from "@/lib/dm/condition-logic"; @@ -103,7 +103,7 @@ export function refreshTeeth(campaign: Campaign, encounter: Encounter): string[] if (!board) { return []; } - const tokens = listTokens(board.map.id); + const tokens = listStandings(board.map.id); const swarms = swarmsOf(board).filter((zone) => { const lord = getSheetById(zone.casterId); return Boolean(lord && holdsGenreFeature(lord, "vermin_lord", "The Walls Have Teeth")); diff --git a/src/lib/dm/hide-traits.ts b/src/lib/dm/hide-traits.ts index f1d9fa0ad8..3e7d2c5edc 100644 --- a/src/lib/dm/hide-traits.ts +++ b/src/lib/dm/hide-traits.ts @@ -14,7 +14,7 @@ import { hasSkulker } from "@/lib/srd/feat-combat"; import { zoneHidesFrom } from "@/lib/dm/zone-rules"; import { attackSight, characterSenses, enemySenses } from "@/lib/dm/attack-light"; import type { Campaign } from "@/lib/db/campaigns"; -import { getBattleMapForEncounter, getTokenByRef, listTokens } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, getTokenByRef, listStandings } from "@/lib/db/battle-maps"; import { listEnemies } from "@/lib/db/encounters"; import { getSheetById } from "@/lib/db/sheets"; import { coverBetween, hasLineOfSight } from "@/lib/battlemap/los"; @@ -86,11 +86,13 @@ export function seenClearlyDespiteTraits( } const stealthy = holdsFeature(sheet, "naturally stealthy"); const mySize = rank(sheetSize(sheet)); - const tokens = listTokens(map.id); + const tokens = listStandings(map.id); // A creature one size larger than the hider standing in the sight lines. + // A mount under a rider is one, read by its own size; the hider's own + // mount, on the token they share, is not. const screened = (fromX: number, fromY: number) => tokens.some((token) => { - if (token.refId === sheet.id || (token.x === fromX && token.y === fromY)) { + if (token.refId === sheet.id || token.id === hider.id || (token.x === fromX && token.y === fromY)) { return false; } const other = getSheetById(token.refId); diff --git a/src/lib/dm/map-tools.ts b/src/lib/dm/map-tools.ts index feee9d2acc..ba2e5dfe56 100644 --- a/src/lib/dm/map-tools.ts +++ b/src/lib/dm/map-tools.ts @@ -24,7 +24,7 @@ import { createBattleMap, getBattleMapForEncounter, getTokenByRef, - listTokens, + listStandings, listTokens, moveToken, placeTokens, resetTurnBudgets, @@ -316,7 +316,7 @@ function resolveAnyToken( // A name the board holds no single token for: the names it does hold. function unknownCombatant(map: BattleMap, name: string): ToolError { - return { error: `No combatant on the battle map is called "${name}"; it holds ${listTokens(map.id).map((token) => token.name).join(", ")}.`, retry: true }; + return { error: `No combatant on the battle map is called "${name}"; it holds ${listStandings(map.id).map((token) => token.name).join(", ")}.`, retry: true }; } // Whether `token` may teleport to (x, y): on the map, open floor, nobody @@ -1205,7 +1205,8 @@ export function allyAdjacentToEnemy( // the party dominates is. const encounter = getEncounter(encounterId); const mine = encounter ? sideOf(encounter, "sheet", attackerCharacterId) : "party"; - return listTokens(map.id).some( + // A mount under a rider is a creature beside the target too (listStandings). + return listStandings(map.id).some( (token) => token.refId !== attackerCharacterId && token.refId !== enemyId && @@ -1338,7 +1339,7 @@ export function checkPcAttackRange( } // The foes this same attack reaches from where they stand, for the next // call to aim at instead. - const tokens = listTokens(map.id); + const tokens = listStandings(map.id); const within = (tiles: number) => { const line = standingFoesLine(encounter.campaignId, encounter, (id) => { const token = tokens.find((entry) => entry.refId === id); diff --git a/src/lib/dm/spirit-projection.ts b/src/lib/dm/spirit-projection.ts index 03c047bbf9..c8a33a7a73 100644 --- a/src/lib/dm/spirit-projection.ts +++ b/src/lib/dm/spirit-projection.ts @@ -27,7 +27,7 @@ // The passage itself is the board's (ar-ws-umbral-logic.ts // movesThroughEverything, read by passage.ts pcMoveTraits). import { regainHitPoints } from "@/lib/dm/regain"; -import { getBattleMapForEncounter, insertToken, listTokens, removeTokenByRef } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, insertToken, listStandings, listTokens, removeTokenByRef } from "@/lib/db/battle-maps"; import type { Campaign } from "@/lib/db/campaigns"; import { closeStandInTurn, openStandInTurn, type DmTurn } from "@/lib/db/dm-turns"; import { getActiveEncounter, saveEncounter, turnKey, type Encounter, type EncounterEnemy } from "@/lib/db/encounters"; @@ -143,7 +143,7 @@ export function enemyStrikesBody( } // "Any attack that hits the creature is a critical hit if the attacker is // within 5 feet of the creature" (Unconscious). - const striker = listTokens(map.id).find((token) => token.kind === "enemy" && token.refId === enemy.id); + const striker = listStandings(map.id).find((token) => token.kind === "enemy" && token.refId === enemy.id); const critical = natural === 20 || Boolean(striker && apart(striker, body) <= 1); const damage = rollCard(campaign, turn, null, "damage", `${enemy.displayName}: ${attack.name} at ${body.name}${critical ? " (critical)" : ""}`, critical ? critDamageExpression(attack.damage) : attack.damage, enemyAttacker(enemy)); const amount = Math.max(0, damage.total); diff --git a/src/lib/dm/summon-store.ts b/src/lib/dm/summon-store.ts index a8228e64f0..f49046d354 100644 --- a/src/lib/dm/summon-store.ts +++ b/src/lib/dm/summon-store.ts @@ -27,7 +27,7 @@ import { getActiveEncounter, saveEncounter, setEncounterAway, type Encounter, ty import { getBattleMapForEncounter, insertToken, - listTokens, + listStandings, listTokens, removeTokenByRef, type BattleMap, } from "@/lib/db/battle-maps"; @@ -229,7 +229,7 @@ function placeInFight( // A token for each creature in a free square beside `caster`. function standOnBoard(campaign: Campaign, map: BattleMap, caster: Pick, created: CharacterSheet[]) { - const tokens = listTokens(map.id); + const tokens = listStandings(map.id); const anchor = tokens.find((token) => token.refId === caster.id); const spots = findSpawnTiles( map.terrain, diff --git a/src/lib/dm/turn.ts b/src/lib/dm/turn.ts index b4a68162f6..ab97b862dc 100644 --- a/src/lib/dm/turn.ts +++ b/src/lib/dm/turn.ts @@ -353,7 +353,7 @@ import { fightNames, getActiveEncounter, listEnemies, type Encounter, type Encou import { atTheFight } from "@/lib/dm/fight-away-logic"; import { takesOwnTurn } from "@/lib/dm/mount-link"; import { enemyMoveBudget, enemyMovementNote } from "@/lib/dm/enemy-speed"; -import { getBattleMapForEncounter, getTokenByRef, listTokens, type BattleMap } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, getTokenByRef, listStandings, type BattleMap } from "@/lib/db/battle-maps"; import { pcMoveBudget } from "@/lib/battlemap/view"; import { serializeMapForPrompt } from "@/lib/battlemap/serialize"; import { suggestEnemies } from "@/lib/bestiary"; @@ -707,7 +707,10 @@ function buildMapText(encounterId: string, sheets: CharacterSheet[]): string | n } } // The drawn board, so the model sees the doors, with the shut ones named. - return serializeMapForPrompt({ ...map, terrain: map.drawnTerrain }, listTokens(map.id), statuses, tokenFootprint); + // A mount under a rider has a line of its own, with its conditions and + // the ranges to it (listStandings): it had none, and only the rider's + // note said it was there. + return serializeMapForPrompt({ ...map, terrain: map.drawnTerrain }, listStandings(map.id), statuses, tokenFootprint); } function loadContext(campaign: Campaign): TurnContext { diff --git a/src/lib/dm/zone-cast.ts b/src/lib/dm/zone-cast.ts index 06f5834c55..513ee1f19f 100644 --- a/src/lib/dm/zone-cast.ts +++ b/src/lib/dm/zone-cast.ts @@ -17,7 +17,7 @@ // Off the map nothing is laid, and the spell resolves as before. import type { Campaign } from "@/lib/db/campaigns"; -import { getBattleMapForEncounter, getTokenByRef, listTokens, setTokenLight, type BattleMap } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, getTokenByRef, listStandings, setTokenLight, type BattleMap } from "@/lib/db/battle-maps"; import { getClock } from "@/lib/db/clock"; import { getActiveBoard, getEnemy, patchEnemyConditions, setEnemyConcentration } from "@/lib/db/encounters"; import { getSheetById, patchSheet } from "@/lib/db/sheets"; @@ -74,7 +74,7 @@ function middleOf(points: XY[]): XY | null { } // The nearest creature on the other side from the caster. -function nearestFoe(tokens: ReturnType, caster: { kind: ZoneCasterKind; id: string }, from: XY): XY | null { +function nearestFoe(tokens: ReturnType, caster: { kind: ZoneCasterKind; id: string }, from: XY): XY | null { const foes = tokens.filter((token) => (caster.kind === "enemy" ? token.kind === "pc" : token.kind === "enemy")); foes.sort((a, b) => chebyshev(from.x, from.y, a.x, a.y) - chebyshev(from.x, from.y, b.x, b.y)); return foes[0] ? { x: foes[0].x, y: foes[0].y } : null; @@ -88,7 +88,7 @@ function inside(point: XY, width: number, height: number): XY | null { // caster, the one nearest the caster: where a weapon that strikes appears // when no square is named (Spiritual Weapon, issue 659), so its first strike // can follow. Null when no foe is in range. -function besideNearestFoe(map: { terrain: string; width: number; height: number }, tokens: ReturnType, caster: { kind: ZoneCasterKind; id: string }, from: XY, rangeTiles: number, only?: string): XY | null { +function besideNearestFoe(map: { terrain: string; width: number; height: number }, tokens: ReturnType, caster: { kind: ZoneCasterKind; id: string }, from: XY, rangeTiles: number, only?: string): XY | null { const taken = new Set(tokens.map((token) => token.y * map.width + token.x)); const foes = tokens .filter((token) => (only ? token.refId === only : caster.kind === "enemy" ? token.kind === "pc" : token.kind === "enemy")) @@ -170,7 +170,7 @@ export function placeSpellZone(campaign: Campaign, cast: ZoneCast): string | nul if (standing) { return `${standing.spell} stays where it is, at (${standing.origin.x},${standing.origin.y}), ${standing.concentration ? `while ${standing.casterName} concentrates` : standing.untilRound === null ? "for the rest of the fight" : `through round ${standing.untilRound}`}.`; } - const tokens = listTokens(map.id); + const tokens = listStandings(map.id); const casterToken = getTokenByRef(map.id, cast.caster.id); const casterAt = casterToken ? { x: casterToken.x, y: casterToken.y } : null; const named = cast.at ? inside(cast.at, map.width, map.height) : null; diff --git a/src/lib/dm/zone-quake.ts b/src/lib/dm/zone-quake.ts index 4382e8cefd..6f3169a6fa 100644 --- a/src/lib/dm/zone-quake.ts +++ b/src/lib/dm/zone-quake.ts @@ -23,7 +23,7 @@ import type { Campaign } from "@/lib/db/campaigns"; import { closeStandInTurn, openStandInTurn, type DmTurn } from "@/lib/db/dm-turns"; -import { listTokens, type BattleMap } from "@/lib/db/battle-maps"; +import { listStandings, type BattleMap } from "@/lib/db/battle-maps"; import { getEnemy, setEnemyConcentration, type Encounter } from "@/lib/db/encounters"; import { getSheetById } from "@/lib/db/sheets"; import { rollExpression } from "@/lib/dice"; @@ -58,7 +58,7 @@ const prone = (conditions: string[]) => conditions.some((entry) => entry.toLower // that is not flying. function groundedIn(map: BattleMap, cells: number[]): BattleToken[] { const inside = new Set(cells); - return listTokens(map.id).filter( + return listStandings(map.id).filter( (token) => (token.kind === "pc" || token.kind === "enemy") && token.movement !== "fly" && inside.has(tileIndex(map.width, token.x, token.y)), ); } diff --git a/src/lib/dm/zone-store.ts b/src/lib/dm/zone-store.ts index 9d128219da..6724a2d0b4 100644 --- a/src/lib/dm/zone-store.ts +++ b/src/lib/dm/zone-store.ts @@ -8,7 +8,7 @@ import { getDatabase, nowIso } from "@/lib/db/core"; import { keepRow } from "@/lib/db/turn-rows"; -import { getBattleMapForEncounter, listTokens, type BattleMap } from "@/lib/db/battle-maps"; +import { getBattleMapForEncounter, listStandings, type BattleMap } from "@/lib/db/battle-maps"; import { getActiveBoard, getEnemy, type Encounter } from "@/lib/db/encounters"; import { getSheetById } from "@/lib/db/sheets"; import { publishEphemeral } from "@/lib/events"; @@ -84,7 +84,7 @@ export function liveZones(map: BattleMap, encounter: Pick | if (holding.length !== map.spellZones.length) { saveZones(map.id, holding); } - return holdGasesBack(withAnchors(holding, listTokens(map.id), map), map.width); + return holdGasesBack(withAnchors(holding, listStandings(map.id), map), map.width); } // A spell's areas end: every one of that spell by that caster (any caster diff --git a/src/lib/dm/zone-triggers.ts b/src/lib/dm/zone-triggers.ts index 2f6f544730..0e61e66c29 100644 --- a/src/lib/dm/zone-triggers.ts +++ b/src/lib/dm/zone-triggers.ts @@ -22,7 +22,7 @@ import { maskKeepsOut } from "@/lib/dm/genre-cc-a-drones"; import { bindsWorthResisting } from "@/lib/dm/legendary-logic"; import type { Campaign } from "@/lib/db/campaigns"; import { closeStandInTurn, openStandInTurn, type DmTurn } from "@/lib/db/dm-turns"; -import { getBattleMap, getBattleMapForEncounter, getTokenByRef, listHiddenRefIds, listTokens, moveToken, type BattleMap } from "@/lib/db/battle-maps"; +import { getBattleMap, getBattleMapForEncounter, getTokenByRef, listHiddenRefIds, listStandings, listTokens, moveToken, type BattleMap } from "@/lib/db/battle-maps"; import type { RollAttacker } from "@/lib/db/rolls"; import { rollCard } from "@/lib/dm/roll-card"; import { spellBombardment } from "@/lib/dm/ar-ws-bombardment"; @@ -407,13 +407,16 @@ function afterFailOnCharacter(campaign: Campaign, turn: DmTurn, map: BattleMap, lines.push(`${sheet.name} spends their action this turn retching.`); } if (trigger.pushFeet) { - const token = listTokens(map.id).find((entry) => entry.refId === sheet.id); + // A character's mount with its rider on it stands on the rider's token + // (getTokenByRef): the push moves the pair, and it is the rider who + // saves to stay on. + const token = getTokenByRef(map.id, sheet.id); const at = token ? pushAlong(map, zone, token, trigger.pushFeet) : null; if (at) { lines.push(`${sheet.name} is pushed to (${at.x},${at.y}).`); // Gust of Wind's push moves a rider's mount against its will: the save // to stay on is asked as the call finishes (mount-moved.ts). - mountMoved(campaign.id, sheet.id); + mountMoved(campaign.id, token?.kind === "pc" ? token.refId : sheet.id); } } return lines; @@ -598,7 +601,7 @@ export function zoneTurnStart(campaign: Campaign, encounter: Encounter, combatan return []; } const zones = liveZones(map, encounter); - const tokens = listTokens(map.id); + const tokens = listStandings(map.id); const lines: string[] = []; for (const zone of zones) { const row = zoneRowFor(zone); @@ -649,7 +652,7 @@ export function zoneTurnEnd(campaign: Campaign, encounterId: string, combatantId return []; } const zones = liveZones(map, encounter); - const lines = momentFor(campaign, encounter, map, zones, listTokens(map.id), combatantIds, "end"); + const lines = momentFor(campaign, encounter, map, zones, listStandings(map.id), combatantIds, "end"); // Earthquake shakes the ground again as its caster's turn ends // (zone-quake.ts): once a turn, an enemy caster's once for each turn begun. let shook = false; @@ -680,11 +683,11 @@ function momentFor( const lines: string[] = []; for (const id of combatantIds) { // A ridden mount stands on its rider's token and suffers the area in its - // own name, on its own turn. Looked up by its own id alone it had no - // token, and its turn began and ended inside an area untouched. - const own = tokens.find((entry) => entry.refId === id); - const token = own ?? (getEnemy(id) ? getTokenByRef(map.id, id) : null); - const victim: Victim | null = own ? victimOf(own) : token ? { kind: "enemy", id } : null; + // own name, on its own turn (listStandings). Looked up among the pieces + // on the board it had none, and its turn began and ended inside an area + // untouched. + const token = tokens.find((entry) => entry.refId === id); + const victim = token ? victimOf(token) : null; if (!token || !victim) { continue; } From 2d254f5c1a9e6dfb4de73d005357a74c23318f1c Mon Sep 17 00:00:00 2001 From: Smoebo Date: Sat, 21 Nov 2026 13:40:04 -0500 Subject: [PATCH 7/7] The check for a named rider drops a map id it never read Co-Authored-By: Claude Fable 5.2 --- src/lib/dm/map-tools.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/lib/dm/map-tools.ts b/src/lib/dm/map-tools.ts index ba2e5dfe56..5b21678f8a 100644 --- a/src/lib/dm/map-tools.ts +++ b/src/lib/dm/map-tools.ts @@ -1042,7 +1042,6 @@ export function handleMoveToken( // that moved its mount a moment ago has already carried it. function riderNamed( campaignId: string, - mapId: string, targetRef: string, shared: BattleToken, at: { x: number; y: number }, @@ -1094,7 +1093,7 @@ export function pushTokenAway( x: target.x + Math.sign(target.x - pusher.x), y: target.y + Math.sign(target.y - pusher.y), }; - const saddle = target.kind === "enemy" ? riderNamed(campaign.id, map.id, targetRef, target, at) : null; + const saddle = target.kind === "enemy" ? riderNamed(campaign.id, targetRef, target, at) : null; if (saddle && "reason" in saddle) { return { moved: false, reason: saddle.reason }; } @@ -1150,7 +1149,7 @@ export function pullTokenToward( x: target.x + Math.sign(puller.x - target.x), y: target.y + Math.sign(puller.y - target.y), }; - const saddle = target.kind === "enemy" ? riderNamed(campaign.id, map.id, targetRef, target, at) : null; + const saddle = target.kind === "enemy" ? riderNamed(campaign.id, targetRef, target, at) : null; if (saddle && "reason" in saddle) { return { moved: false, reason: saddle.reason }; }