dsh-dungeon-master 0.5.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/CHANGELOG.md +24 -2
  2. package/CHANGELOG_EN.md +24 -2
  3. package/README.md +203 -198
  4. package/README_EN.md +203 -198
  5. package/cordis.patch.yml +32 -32
  6. package/cordis.yml +112 -112
  7. package/dist/commands/dnd.d.ts.map +1 -1
  8. package/dist/commands/dnd.js +4 -3
  9. package/dist/commands/dnd.js.map +1 -1
  10. package/dist/config.d.ts +2 -0
  11. package/dist/config.d.ts.map +1 -1
  12. package/dist/config.js +2 -0
  13. package/dist/config.js.map +1 -1
  14. package/dist/dnd/battle-image.d.ts +11 -4
  15. package/dist/dnd/battle-image.d.ts.map +1 -1
  16. package/dist/dnd/battle-image.js +86 -7
  17. package/dist/dnd/battle-image.js.map +1 -1
  18. package/dist/dnd/battlefield.d.ts +39 -3
  19. package/dist/dnd/battlefield.d.ts.map +1 -1
  20. package/dist/dnd/battlefield.js +378 -88
  21. package/dist/dnd/battlefield.js.map +1 -1
  22. package/dist/dnd/campaign.d.ts +192 -16
  23. package/dist/dnd/campaign.d.ts.map +1 -1
  24. package/dist/dnd/campaign.js +645 -92
  25. package/dist/dnd/campaign.js.map +1 -1
  26. package/dist/dnd/combat-agent.d.ts +53 -5
  27. package/dist/dnd/combat-agent.d.ts.map +1 -1
  28. package/dist/dnd/combat-agent.js +612 -62
  29. package/dist/dnd/combat-agent.js.map +1 -1
  30. package/dist/dnd/combat-context.d.ts +74 -2
  31. package/dist/dnd/combat-context.d.ts.map +1 -1
  32. package/dist/dnd/combat-context.js +62 -21
  33. package/dist/dnd/combat-context.js.map +1 -1
  34. package/dist/dnd/conditions.d.ts +217 -0
  35. package/dist/dnd/conditions.d.ts.map +1 -0
  36. package/dist/dnd/conditions.js +1216 -0
  37. package/dist/dnd/conditions.js.map +1 -0
  38. package/dist/dnd/custom-effects.d.ts +121 -0
  39. package/dist/dnd/custom-effects.d.ts.map +1 -0
  40. package/dist/dnd/custom-effects.js +446 -0
  41. package/dist/dnd/custom-effects.js.map +1 -0
  42. package/dist/dnd/dice.d.ts +5 -1
  43. package/dist/dnd/dice.d.ts.map +1 -1
  44. package/dist/dnd/dice.js +4 -3
  45. package/dist/dnd/dice.js.map +1 -1
  46. package/dist/dnd/dnd-service.d.ts +8 -6
  47. package/dist/dnd/dnd-service.d.ts.map +1 -1
  48. package/dist/dnd/dnd-service.js +43 -7
  49. package/dist/dnd/dnd-service.js.map +1 -1
  50. package/dist/dnd/dnd-tools.d.ts.map +1 -1
  51. package/dist/dnd/dnd-tools.js +2 -0
  52. package/dist/dnd/dnd-tools.js.map +1 -1
  53. package/dist/dnd/formula.d.ts +40 -0
  54. package/dist/dnd/formula.d.ts.map +1 -0
  55. package/dist/dnd/formula.js +219 -0
  56. package/dist/dnd/formula.js.map +1 -0
  57. package/dist/dnd/map-view.d.ts +3 -1
  58. package/dist/dnd/map-view.d.ts.map +1 -1
  59. package/dist/dnd/map-view.js +33 -10
  60. package/dist/dnd/map-view.js.map +1 -1
  61. package/dist/dnd/movement.d.ts +3 -3
  62. package/dist/dnd/movement.d.ts.map +1 -1
  63. package/dist/dnd/movement.js +14 -8
  64. package/dist/dnd/movement.js.map +1 -1
  65. package/dist/dnd/pending-attack.d.ts +23 -13
  66. package/dist/dnd/pending-attack.d.ts.map +1 -1
  67. package/dist/dnd/pending-attack.js +198 -27
  68. package/dist/dnd/pending-attack.js.map +1 -1
  69. package/dist/dnd/save-effect.d.ts +12 -0
  70. package/dist/dnd/save-effect.d.ts.map +1 -1
  71. package/dist/dnd/save-effect.js +72 -8
  72. package/dist/dnd/save-effect.js.map +1 -1
  73. package/dist/dnd/spell-links.d.ts +32 -11
  74. package/dist/dnd/spell-links.d.ts.map +1 -1
  75. package/dist/dnd/spell-links.js +105 -20
  76. package/dist/dnd/spell-links.js.map +1 -1
  77. package/dist/dnd/srd-lookup.d.ts.map +1 -1
  78. package/dist/dnd/srd-lookup.js +23 -0
  79. package/dist/dnd/srd-lookup.js.map +1 -1
  80. package/dist/dnd/terrain.d.ts +8 -2
  81. package/dist/dnd/terrain.d.ts.map +1 -1
  82. package/dist/dnd/terrain.js +13 -8
  83. package/dist/dnd/terrain.js.map +1 -1
  84. package/dist/dnd/tool-scope.d.ts.map +1 -1
  85. package/dist/dnd/tool-scope.js +1 -1
  86. package/dist/dnd/tool-scope.js.map +1 -1
  87. package/dist/dnd/tool-views.js +4 -4
  88. package/dist/dnd/tool-views.js.map +1 -1
  89. package/dist/dnd/tools/character.d.ts.map +1 -1
  90. package/dist/dnd/tools/character.js +223 -21
  91. package/dist/dnd/tools/character.js.map +1 -1
  92. package/dist/dnd/tools/combat.d.ts.map +1 -1
  93. package/dist/dnd/tools/combat.js +222 -32
  94. package/dist/dnd/tools/combat.js.map +1 -1
  95. package/dist/dnd/tools/dice.d.ts.map +1 -1
  96. package/dist/dnd/tools/dice.js +406 -53
  97. package/dist/dnd/tools/dice.js.map +1 -1
  98. package/dist/dnd/tools/explore.d.ts.map +1 -1
  99. package/dist/dnd/tools/explore.js +3 -2
  100. package/dist/dnd/tools/explore.js.map +1 -1
  101. package/dist/dnd/tools/rules.d.ts +3 -0
  102. package/dist/dnd/tools/rules.d.ts.map +1 -0
  103. package/dist/dnd/tools/rules.js +190 -0
  104. package/dist/dnd/tools/rules.js.map +1 -0
  105. package/dist/dnd/tools/saves.d.ts.map +1 -1
  106. package/dist/dnd/tools/saves.js +23 -6
  107. package/dist/dnd/tools/saves.js.map +1 -1
  108. package/dist/dnd/tools/shared.d.ts +8 -2
  109. package/dist/dnd/tools/shared.d.ts.map +1 -1
  110. package/dist/dnd/tools/shared.js +239 -39
  111. package/dist/dnd/tools/shared.js.map +1 -1
  112. package/dist/dnd/turn-buttons.d.ts +4 -0
  113. package/dist/dnd/turn-buttons.d.ts.map +1 -1
  114. package/dist/dnd/turn-buttons.js +49 -25
  115. package/dist/dnd/turn-buttons.js.map +1 -1
  116. package/dist/dnd/zones.d.ts +123 -0
  117. package/dist/dnd/zones.d.ts.map +1 -0
  118. package/dist/dnd/zones.js +545 -0
  119. package/dist/dnd/zones.js.map +1 -0
  120. package/dist/features/button-utils.d.ts +2 -1
  121. package/dist/features/button-utils.d.ts.map +1 -1
  122. package/dist/features/button-utils.js.map +1 -1
  123. package/dist/features/note-judge.d.ts +24 -7
  124. package/dist/features/note-judge.d.ts.map +1 -1
  125. package/dist/features/note-judge.js +112 -24
  126. package/dist/features/note-judge.js.map +1 -1
  127. package/dist/features/reply-judge.d.ts.map +1 -1
  128. package/dist/features/reply-judge.js +22 -4
  129. package/dist/features/reply-judge.js.map +1 -1
  130. package/dist/gateway/bootstrap.d.ts.map +1 -1
  131. package/dist/gateway/bootstrap.js +28 -1
  132. package/dist/gateway/bootstrap.js.map +1 -1
  133. package/dist/gateway/middleware-setup.d.ts +3 -1
  134. package/dist/gateway/middleware-setup.d.ts.map +1 -1
  135. package/dist/gateway/middleware-setup.js +24 -5
  136. package/dist/gateway/middleware-setup.js.map +1 -1
  137. package/dist/middleware/reply-decider.d.ts +8 -1
  138. package/dist/middleware/reply-decider.d.ts.map +1 -1
  139. package/dist/middleware/reply-decider.js +22 -8
  140. package/dist/middleware/reply-decider.js.map +1 -1
  141. package/dist/middleware/serial-merge.d.ts +7 -3
  142. package/dist/middleware/serial-merge.d.ts.map +1 -1
  143. package/dist/middleware/serial-merge.js +125 -9
  144. package/dist/middleware/serial-merge.js.map +1 -1
  145. package/dist/model/status-watch.d.ts +4 -0
  146. package/dist/model/status-watch.d.ts.map +1 -1
  147. package/dist/model/status-watch.js +6 -2
  148. package/dist/model/status-watch.js.map +1 -1
  149. package/dist/session/index.d.ts +1 -1
  150. package/dist/session/index.d.ts.map +1 -1
  151. package/dist/session/index.js.map +1 -1
  152. package/dist/session/session-manager.d.ts +21 -5
  153. package/dist/session/session-manager.d.ts.map +1 -1
  154. package/dist/session/session-manager.js +141 -18
  155. package/dist/session/session-manager.js.map +1 -1
  156. package/dist/session/types.d.ts +8 -0
  157. package/dist/session/types.d.ts.map +1 -1
  158. package/dist/setup/bind-routes.d.ts.map +1 -1
  159. package/dist/setup/bind-routes.js +2 -1
  160. package/dist/setup/bind-routes.js.map +1 -1
  161. package/dist/transport/agent-turn.d.ts +7 -3
  162. package/dist/transport/agent-turn.d.ts.map +1 -1
  163. package/dist/transport/agent-turn.js +20 -2
  164. package/dist/transport/agent-turn.js.map +1 -1
  165. package/dist/transport/events.d.ts +6 -1
  166. package/dist/transport/events.d.ts.map +1 -1
  167. package/dist/transport/events.js +1 -0
  168. package/dist/transport/events.js.map +1 -1
  169. package/dist/transport/inbound.d.ts +6 -0
  170. package/dist/transport/inbound.d.ts.map +1 -1
  171. package/dist/transport/inbound.js +66 -13
  172. package/dist/transport/inbound.js.map +1 -1
  173. package/dist/transport/outbound-buffer.d.ts +6 -0
  174. package/dist/transport/outbound-buffer.d.ts.map +1 -1
  175. package/dist/transport/outbound-buffer.js +13 -0
  176. package/dist/transport/outbound-buffer.js.map +1 -1
  177. package/dist/transport/outbound.d.ts.map +1 -1
  178. package/dist/transport/outbound.js +95 -21
  179. package/dist/transport/outbound.js.map +1 -1
  180. package/dist/transport/turn-steer.d.ts +70 -0
  181. package/dist/transport/turn-steer.d.ts.map +1 -0
  182. package/dist/transport/turn-steer.js +206 -0
  183. package/dist/transport/turn-steer.js.map +1 -0
  184. package/lib/client.js +10 -0
  185. package/lib/client.js.map +1 -1
  186. package/package.json +143 -137
  187. package/skills/dnd-module-authoring/SKILL.md +91 -0
  188. package/skills/dnd-module-authoring/guide.md +76 -47
  189. package/skills/dnd-rule-extension/SKILL.md +126 -0
  190. package/skills/qqbot-sticker-maker/SKILL.md +87 -0
  191. package/skills/qqbot-sticker-maker/references/character-specs.md +94 -0
  192. package/skills/qqbot-sticker-maker/references/meme-adaptation-notes.md +46 -0
  193. package/skills/qqbot-sticker-maker/resources/zipzippipe/sources.json +105 -0
  194. package/skills/qqbot-sticker-maker/scripts/sticker-cli.cjs +1158 -0
  195. package/skills/qqbot-sticker-maker/scripts/sticker-export.cjs +147 -0
@@ -15,8 +15,11 @@ import { findSite, isHub, roomGraph, siteOfRoom } from "./adventure.js";
15
15
  import { exitBetween, exitKey, exitsOf, findRoom, } from "./dungeon.js";
16
16
  import { ABILITIES, abilityModifier, parseAbility, parseSkill, proficiencyBonus, SKILLS } from "./rules.js";
17
17
  import { battleGridLines, battleLines, canReact, cellOf, distancesFrom, hiddenFromPlayers } from "./battlefield.js";
18
+ import { INCAPACITATING_CONDITIONS, ZERO_SPEED_CONDITIONS, actionRestriction, breakConcentration, computeDefenseStateMod, concentratingOn, effectiveMaxHp, effectiveStates, exhaustionLevel, hasCondition, isIncapacitated, normalizeCondition, removeActiveState, stateAcBonus, tickActiveStatesOnTurnChange, upsertActiveState, } from "./conditions.js";
18
19
  import { pendingSummaryLine } from "./pending-attack.js";
20
+ import { DEFENSE_NAMES } from "./save-effect.js";
19
21
  import { afterChange, describeCondition, evalCondition, locationKnown, roomView, storySummaryLines } from "./story.js";
22
+ import { settleTurnBoundaryHazards } from "./zones.js";
20
23
  /**
21
24
  * 没写 reactions 的旧角色卡从备注认这几个常见能力,旧存档不用先补卡就有反应窗口。
22
25
  * 新卡用 dnd_character reactions 明写,写了就不再猜(空数组 = 明确没有)。
@@ -25,16 +28,42 @@ const INFERRED_REACTIONS = [
25
28
  { pattern: /尖刻言语|Cutting Words/i, def: { name: '尖刻言语', when: 'foe_attacks', resource: '诗人激励', range: 60 } },
26
29
  { pattern: /护盾术/, def: { name: '护盾术', when: 'attacked' } },
27
30
  { pattern: /导引打击|Guided Strike/i, def: { name: '导引打击', when: 'attacking', resource: '引导神力' } },
31
+ // 时间变幻平时不每刀都弹,敌人重击时自动挂起防秒杀;普通检定/豁免仍由 DM 用 hold_for 挂起
32
+ { pattern: /时间变幻|Chronal Shift/i, def: { name: '时间变幻', when: 'enemy_crit', resource: '时间变幻', range: 30 } },
33
+ { pattern: /迷雾逃生|Misty Escape/i, def: { name: '迷雾逃生', when: 'damaged', resource: '迷雾逃生' } },
34
+ { pattern: /炼狱叱喝|Hellish Rebuke/i, def: { name: '炼狱叱喝', when: 'damaged', range: 60 } },
35
+ { pattern: /吸收元素|Absorb Elements/i, def: { name: '吸收元素', when: 'damaged' } },
36
+ { pattern: /直觉闪避|Uncanny Dodge/i, def: { name: '直觉闪避', when: 'damaged' } },
28
37
  // 哨兵:5 尺内有人打别人时反打一记。是不算命中与否的新攻击,所以不看 hit
29
38
  { pattern: /哨兵|Sentinel/i, def: { name: '哨兵', when: 'foe_attacks', range: 5, counter: true } },
30
39
  // 长柄大师:拿着长柄武器时,敌人「进入」触及范围就借机(不是离开)
31
40
  { pattern: /长柄大师|Polearm Master/i, def: { name: '长柄大师', when: 'foe_attacks', enter: true, range: 10 } },
32
41
  ];
42
+ function hasPositiveReactionMention(notes, pattern) {
43
+ const cleanPattern = new RegExp(pattern.source, pattern.flags.replace('g', ''));
44
+ for (const sub of notes.split(/[,,。\n;;!!]+/)) {
45
+ const m = cleanPattern.exec(sub);
46
+ if (m === null)
47
+ continue;
48
+ const pre = sub.slice(0, m.index);
49
+ const post = sub.slice(m.index + m[0].length);
50
+ if (/(?:移除|取消|失去|没有|不含|未学|作废|放弃|删去)|(?:^|[^不])无\s*$/.test(pre))
51
+ continue;
52
+ if (/^原/.test(pre.trim()) && /(?:移除|取消|失去|作废|洗点|重修|改为)/.test(sub))
53
+ continue;
54
+ if (/^[^((]*?(?:已移除|被移除|移除|已取消|取消|已失去|失去|作废|已删)/.test(post))
55
+ continue;
56
+ return true;
57
+ }
58
+ return false;
59
+ }
33
60
  export function reactionsOf(ch) {
34
61
  if (ch.reactions !== undefined)
35
62
  return ch.reactions;
36
63
  const notes = ch.notes ?? '';
37
- return INFERRED_REACTIONS.filter(({ pattern }) => pattern.test(notes)).map(({ def }) => def);
64
+ if (!notes)
65
+ return [];
66
+ return INFERRED_REACTIONS.filter(({ pattern }) => hasPositiveReactionMention(notes, pattern)).map(({ def }) => def);
38
67
  }
39
68
  export function reactionWindow(c) {
40
69
  return c?.initiative?.pending ?? c?.initiative?.movement;
@@ -49,6 +78,7 @@ export function describePending(p) {
49
78
  return p.attacker === who ? `${who} 的${p.label}` : `${p.attacker} 的效果(${who} ${p.label})`;
50
79
  }
51
80
  const MAX_LOG = 30;
81
+ const MAX_COMBAT_LEDGER = 200;
52
82
  const MAX_SNAPSHOTS = 40;
53
83
  const MAX_SUMMARIES = 10;
54
84
  /** 一条进度/结团摘要的上限:每次开团都整条注入 */
@@ -126,10 +156,19 @@ export function parseCampaign(json) {
126
156
  announced: [],
127
157
  };
128
158
  }
159
+ export function pushCombatLedger(c, text, seq) {
160
+ if (c.initiative === undefined)
161
+ return;
162
+ const ledger = (c.initiative.ledger ??= []);
163
+ ledger.push({ round: c.initiative.round, ...(seq !== undefined ? { seq } : {}), text });
164
+ if (ledger.length > MAX_COMBAT_LEDGER)
165
+ ledger.splice(0, ledger.length - MAX_COMBAT_LEDGER);
166
+ }
129
167
  export function pushLog(c, line) {
130
168
  c.log.push(line);
131
169
  if (c.log.length > MAX_LOG)
132
170
  c.log.splice(0, c.log.length - MAX_LOG);
171
+ pushCombatLedger(c, line);
133
172
  }
134
173
  export function findCharacter(c, name) {
135
174
  const q = name.trim();
@@ -214,6 +253,19 @@ export function upsertCharacter(c, input) {
214
253
  next.initBonus = Math.trunc(input.initBonus);
215
254
  if (input.speed !== undefined)
216
255
  next.speed = clampInt(input.speed, 0, 300);
256
+ if (input.flySpeed !== undefined) {
257
+ const fs = clampInt(input.flySpeed, 0, 300);
258
+ if (fs > 0)
259
+ next.flySpeed = fs;
260
+ else
261
+ delete next.flySpeed;
262
+ }
263
+ if (input.hover !== undefined) {
264
+ if (input.hover)
265
+ next.hover = true;
266
+ else
267
+ delete next.hover;
268
+ }
217
269
  if (input.reactions !== undefined)
218
270
  next.reactions = input.reactions;
219
271
  if (input.weapons !== undefined)
@@ -246,6 +298,11 @@ export function removeCharacter(c, name) {
246
298
  c.characters = c.characters.filter((x) => x !== ch);
247
299
  if (c.initiative !== undefined)
248
300
  removeFromInitiative(c.initiative, ch.name);
301
+ if (c.hexbladeCurses !== undefined) {
302
+ c.hexbladeCurses = c.hexbladeCurses.filter((x) => x.caster !== ch.name && x.target !== ch.name);
303
+ if (c.hexbladeCurses.length === 0)
304
+ delete c.hexbladeCurses;
305
+ }
249
306
  return ch;
250
307
  }
251
308
  function clampInt(value, min, max) {
@@ -309,7 +366,8 @@ export function applyDamage(c, name, amount, options = {}) {
309
366
  }
310
367
  }
311
368
  if (ch.hp === 0 && rest > 0) {
312
- if (ch.kind !== 'pc' || overflow >= ch.maxHp) {
369
+ const effMax = effectiveMaxHp(ch);
370
+ if (ch.kind !== 'pc' || overflow >= effMax) {
313
371
  if (setCondition(ch, '死亡', true))
314
372
  events.push('死亡');
315
373
  }
@@ -324,24 +382,56 @@ export function applyDamage(c, name, amount, options = {}) {
324
382
  events.push(...addDeathFailures(ch, 1));
325
383
  }
326
384
  }
385
+ if (dmg > 0) {
386
+ if (ch.hp === 0 || isIncapacitated(ch)) {
387
+ events.push(...breakConcentration(c, ch.name, '失去行动能力'));
388
+ }
389
+ else {
390
+ const conc = concentratingOn(c, ch.name);
391
+ if (conc.length > 0) {
392
+ const dc = Math.max(10, Math.floor(dmg / 2));
393
+ const spells = [...new Set(conc.map((x) => x.state.name))].join('、');
394
+ events.push(`专注受击(${spells}):需过体质专注豁免 DC ${dc}`);
395
+ }
396
+ }
397
+ }
327
398
  pushLog(c, `${ch.name} 受到 ${dmg} 点伤害(${hpTrail(ch, before)})${events.length > 0 ? `,${events.join('、')}` : ''}`);
399
+ if (ch.hp === 0 || isIncapacitated(ch)) {
400
+ const crashLines = checkAllAirborneCrashes(c, options.roller ?? cryptoRoller);
401
+ events.push(...crashLines);
402
+ }
403
+ if (events.includes('死亡') && c.hexbladeCurses !== undefined) {
404
+ const triggered = c.hexbladeCurses.filter((x) => x.target === ch.name);
405
+ c.hexbladeCurses = c.hexbladeCurses.filter((x) => x.target !== ch.name);
406
+ if (c.hexbladeCurses.length === 0)
407
+ delete c.hexbladeCurses;
408
+ for (const curse of triggered) {
409
+ const caster = findCharacter(c, curse.caster);
410
+ if (caster !== undefined && !isOut(caster) && caster.hp > 0 && canReact(caster)) {
411
+ const healed = heal(c, caster.name, hexbladeKillHeal(caster));
412
+ const gained = healed.after - healed.before;
413
+ events.push(gained > 0 ? `咒剑诅咒:${caster.name} 恢复 ${gained} HP` : `咒剑诅咒触发(${caster.name} HP 已满)`);
414
+ }
415
+ }
416
+ }
328
417
  return { name: ch.name, before, after: ch.hp, maxHp: ch.maxHp, tempHp: ch.tempHp, absorbed, events, ...woundOf(ch) };
329
418
  }
330
419
  /** 日志里的血量变化:日志会进团况的「最近」,怪物只写伤势词,免得数字被说出去 */
331
420
  function hpTrail(ch, before) {
332
421
  return ch.kind === 'monster' ? woundLabel(ch) : `${before}→${ch.hp}/${ch.maxHp}`;
333
422
  }
334
- /** 治疗:不超过最大 HP;从 0 恢复时清掉昏迷/稳定 */
423
+ /** 治疗:不超过有效最大 HP(力竭 4 级减半);从 0 恢复时清掉昏迷/稳定 */
335
424
  export function heal(c, name, amount) {
336
425
  const ch = requireCharacter(c, name);
337
426
  if (ch.conditions.includes('死亡'))
338
427
  throw new Error(`${ch.name} 已经死亡,普通治疗无效`);
339
428
  const before = ch.hp;
340
- ch.hp = Math.min(ch.maxHp, ch.hp + Math.max(0, Math.trunc(amount)));
429
+ const effMax = effectiveMaxHp(ch);
430
+ ch.hp = Math.min(effMax, ch.hp + Math.max(0, Math.trunc(amount)));
341
431
  const events = [];
342
432
  if (before === 0 && ch.hp > 0) {
343
- setCondition(ch, '昏迷', false);
344
- setCondition(ch, '稳定', false);
433
+ removeActiveState(ch, '昏迷');
434
+ removeActiveState(ch, '稳定');
345
435
  delete ch.deathSaves;
346
436
  events.push('苏醒');
347
437
  }
@@ -354,16 +444,107 @@ export function grantTempHp(c, name, amount) {
354
444
  ch.tempHp = Math.max(ch.tempHp, Math.max(0, Math.trunc(amount)));
355
445
  return { name: ch.name, before: ch.hp, after: ch.hp, maxHp: ch.maxHp, tempHp: ch.tempHp, absorbed: 0, events: [] };
356
446
  }
357
- export function changeCondition(c, name, condition, on) {
447
+ /**
448
+ * 检查单个处于高空(z > 0)的角色是否因陷入倒地/失能/速度归 0 或失去飞行能力而坠机(PHB 高空坠落规则):
449
+ * - 若具备 `hover: true` 或仍维持未死亡的 `飞行术`,可悬浮免于坠落;
450
+ * - 否则 `z` 归 0,每 10 尺掷 1d6(上限 20d6)钝击伤害,若受到至少 1 点坠落伤害则陷入「倒地」。
451
+ */
452
+ export function checkAirborneCrash(c, ch, roller = cryptoRoller, globalEffects) {
453
+ const state = c.initiative;
454
+ if (state === undefined)
455
+ return [];
456
+ const cell = state.positions?.[ch.name];
457
+ if (cell === undefined || cell.room !== roomOf(c, ch) || (cell.z ?? 0) <= 0)
458
+ return [];
459
+ const fallFeet = cell.z;
460
+ if (ch.conditions.includes('死亡')) {
461
+ delete cell.z;
462
+ const msg = `${ch.name} 从 ${fallFeet} 尺高空坠落地面`;
463
+ pushLog(c, msg);
464
+ return [msg];
465
+ }
466
+ const magicalAloft = hasCondition(ch, '飞行术');
467
+ const canHover = ch.hover === true || magicalAloft;
468
+ if (canHover)
469
+ return [];
470
+ const lostFlight = (ch.flySpeed ?? 0) <= 0;
471
+ const incapacitatedOrPinned = hasCondition(ch, '倒地')
472
+ || effectiveStates(ch).some((s) => ZERO_SPEED_CONDITIONS.has(s.name) || INCAPACITATING_CONDITIONS.has(s.name))
473
+ || exhaustionLevel(ch) >= 5;
474
+ if (!lostFlight && !incapacitatedOrPinned)
475
+ return [];
476
+ // 先落地归 0,防止后续 applyDamage 再次触发递归坠机
477
+ delete cell.z;
478
+ const diceCount = Math.min(20, Math.floor(fallFeet / 10));
479
+ if (diceCount <= 0) {
480
+ const msg = `【高空坠落】${ch.name} 从 ${fallFeet} 尺高度坠地(未满 10 尺无坠落伤害)`;
481
+ pushLog(c, msg);
482
+ return [msg];
483
+ }
484
+ const rolled = rollExpression(`${diceCount}d6`, roller);
485
+ const defMod = computeDefenseStateMod(ch, '钝击', undefined, c, globalEffects);
486
+ let finalDmg = rolled.total;
487
+ if (defMod.defense === 'immune')
488
+ finalDmg = 0;
489
+ else if (defMod.defense === 'resistant')
490
+ finalDmg = Math.floor(finalDmg / 2);
491
+ else if (defMod.defense === 'vulnerable')
492
+ finalDmg *= 2;
493
+ let dmgTail = `${rolled.detail}${defMod.defense !== undefined ? `(${DEFENSE_NAMES[defMod.defense]}→${finalDmg})` : ''} 钝击`;
494
+ if (finalDmg > 0) {
495
+ const change = applyDamage(c, ch.name, finalDmg, { damageType: '钝击', roller });
496
+ const trail = ch.kind === 'monster' ? (change.wound ?? woundLabel(ch)) : `HP ${change.before}→${change.after}/${change.maxHp}`;
497
+ dmgTail += `(${trail})`;
498
+ if (!ch.conditions.includes('死亡') && !hasCondition(ch, '倒地')) {
499
+ upsertActiveState(c, ch, { name: '倒地' });
500
+ dmgTail += ',摔成倒地';
501
+ }
502
+ }
503
+ const msg = `【高空坠落】${ch.name} 从 ${fallFeet} 尺高空坠落地面:${dmgTail}`;
504
+ pushCombatLedger(c, msg);
505
+ return [msg];
506
+ }
507
+ export function checkAllAirborneCrashes(c, roller = cryptoRoller, globalEffects) {
508
+ if (c.initiative?.positions === undefined)
509
+ return [];
510
+ const out = [];
511
+ for (const name of Object.keys(c.initiative.positions)) {
512
+ const ch = findCharacter(c, name);
513
+ if (ch !== undefined)
514
+ out.push(...checkAirborneCrash(c, ch, roller, globalEffects));
515
+ }
516
+ return out;
517
+ }
518
+ export function changeCondition(c, name, condition, on, options = {}) {
358
519
  const ch = requireCharacter(c, name);
359
- const value = condition.trim();
360
- if (value.length === 0)
520
+ const norm = normalizeCondition(condition);
521
+ if (norm.length === 0)
361
522
  throw new Error('状态名不能为空');
362
- if (!on && value === '死亡' && ch.conditions.includes('死亡')) {
523
+ if (!on && norm === '死亡' && ch.conditions.includes('死亡')) {
363
524
  throw new Error('不能手动解除「死亡」。判错了要回滚用 dnd_undo;不死坚韧之类的特性工具会自动处理');
364
525
  }
365
- if (setCondition(ch, value, on))
366
- pushLog(c, `${ch.name} ${on ? '获得' : '解除'}状态「${value}」`);
526
+ if (on) {
527
+ const had = ch.conditions.some((x) => normalizeCondition(x) === norm);
528
+ const { broken } = upsertActiveState(c, ch, {
529
+ name: condition,
530
+ ...(norm === '闪避' ? { source: ch.name, expires: 'start_of_source_turn' } : {}),
531
+ ...(options.source !== undefined ? { source: options.source } : {}),
532
+ ...(options.concentration !== undefined ? { concentration: options.concentration } : {}),
533
+ ...(options.roundsLeft !== undefined ? { roundsLeft: options.roundsLeft } : {}),
534
+ ...(options.expires !== undefined ? { expires: options.expires } : {}),
535
+ }, { ...(options.replaceConcentration !== undefined ? { replaceConcentration: options.replaceConcentration } : {}) });
536
+ if (!had)
537
+ pushLog(c, `${ch.name} 获得状态「${norm}」`);
538
+ for (const line of broken)
539
+ pushLog(c, line);
540
+ checkAllAirborneCrashes(c, options.roller ?? cryptoRoller, options.globalEffects);
541
+ }
542
+ else {
543
+ const removed = removeActiveState(ch, condition);
544
+ for (const r of removed)
545
+ pushLog(c, `${ch.name} 解除状态「${r}」`);
546
+ checkAllAirborneCrashes(c, options.roller ?? cryptoRoller, options.globalEffects);
547
+ }
367
548
  return ch;
368
549
  }
369
550
  // ── 死亡豁免 ──
@@ -458,12 +639,7 @@ export function combatants(c, room = c.currentRoom) {
458
639
  export function initBonusOf(ch) {
459
640
  return ch.initBonus ?? abilityModifier(ch.abilities.dex);
460
641
  }
461
- /**
462
- * 为参战者掷先攻并排序;names 省略时取 room(默认队伍主位置)里的 combatants()。
463
- * `bonus` 是开战时就已生效的额外先攻值(灵敏之赐 1d8、警觉 +5、状态加成),按角色名给骰子表达式,
464
- * 由这里掷进去——否则「d20 + 敏调」的半成品会被当成最终结果,玩家事后发现少算了也只能认。
465
- */
466
- export function startInitiative(c, roller = cryptoRoller, names, room, bonus = {}, surprisedNames = []) {
642
+ export function startInitiative(c, roller = cryptoRoller, names, room, bonus = {}, surprisedNames = [], options = {}) {
467
643
  const members = names === undefined || names.length === 0 ? combatants(c, room) : names.map((n) => requireCharacter(c, n));
468
644
  if (members.length === 0)
469
645
  throw new Error('没有可以参战的角色');
@@ -472,6 +648,30 @@ export function startInitiative(c, roller = cryptoRoller, names, room, bonus = {
472
648
  const outsider = surprised.filter((n) => !members.some((m) => m.name === n));
473
649
  if (outsider.length > 0)
474
650
  throw new Error(`surprised 里的 ${outsider.join('、')} 不在参战者里`);
651
+ const rehearsal = options.rehearsal === true;
652
+ if (!rehearsal && (options.rehearsalHp !== undefined || options.temporaryMonsters !== undefined)) {
653
+ throw new Error('rehearsal_hp / temporary_monsters 只在 rehearsal=true 的演练战斗中使用');
654
+ }
655
+ const tempMonsters = rehearsal
656
+ ? [...new Set((options.temporaryMonsters ?? []).map((n) => requireCharacter(c, n).name))]
657
+ : [];
658
+ const hpOverrides = rehearsal && options.rehearsalHp !== undefined
659
+ ? Object.entries(options.rehearsalHp).map(([rawName, hp]) => ({ ch: requireCharacter(c, rawName), hp: clampInt(hp, 1, 999) }))
660
+ : [];
661
+ const rehearsalSnapshot = rehearsal
662
+ ? structuredClone({
663
+ characters: c.characters,
664
+ ...(c.battlemaps !== undefined ? { battlemaps: c.battlemaps } : {}),
665
+ npcs: c.npcs,
666
+ spawned: c.spawned,
667
+ ...(c.enteredFrom !== undefined ? { enteredFrom: c.enteredFrom } : {}),
668
+ ...(tempMonsters.length > 0 ? { temporaryMonsters: tempMonsters } : {}),
669
+ })
670
+ : undefined;
671
+ for (const { ch, hp } of hpOverrides) {
672
+ ch.maxHp = hp;
673
+ ch.hp = hp;
674
+ }
475
675
  const rolls = members.map((ch) => {
476
676
  const r = rollD20(initBonusOf(ch), 'none', roller);
477
677
  const expr = bonus[ch.name];
@@ -485,11 +685,19 @@ export function startInitiative(c, roller = cryptoRoller, names, room, bonus = {
485
685
  };
486
686
  });
487
687
  rolls.sort((a, b) => b.init - a.init || b.tiebreak - a.tiebreak);
488
- c.initiative = { round: 1, turn: 0, order: rolls.map(({ name, init }) => ({ name, init })) };
688
+ c.initiative = {
689
+ round: 1,
690
+ turn: 0,
691
+ order: rolls.map(({ name, init }) => ({ name, init })),
692
+ allParticipants: rolls.map(({ name }) => name),
693
+ ...(rolls[0] !== undefined ? { turnState: { actor: rolls[0].name, attacks: 0 } } : {}),
694
+ ...(rehearsal ? { rehearsal: true, rehearsalSnapshot } : {}),
695
+ };
489
696
  if (surprised.length > 0)
490
697
  c.initiative.surprised = surprised;
491
- c.begun = true;
492
- pushLog(c, `进入战斗:${rolls.map((r) => `${r.name}(${r.init})`).join(' > ')}${surprised.length > 0 ? `;受惊:${surprised.join('、')}` : ''}`);
698
+ if (!rehearsal)
699
+ c.begun = true;
700
+ pushLog(c, `进入${rehearsal ? '演练' : ''}战斗:${rolls.map((r) => `${r.name}(${r.init})`).join(' > ')}${surprised.length > 0 ? `;受惊:${surprised.join('、')}` : ''}`);
493
701
  return rolls.map(({ name, init, detail }) => ({ name, init, detail }));
494
702
  }
495
703
  export function isSurprised(c, name) {
@@ -499,6 +707,9 @@ export function isSurprised(c, name) {
499
707
  export function reactionBlocked(c, name) {
500
708
  if (isSurprised(c, name))
501
709
  return `${name} 受惊,自己第一个回合过去之前不能反应`;
710
+ const ch = findCharacter(c, name);
711
+ if (ch !== undefined && hasCondition(ch, '迟缓术'))
712
+ return `${name} 受迟缓术影响,无法执行反应`;
502
713
  if (c.initiative?.reacted?.includes(name) === true)
503
714
  return `${name} 的反应已经用过了,要到他下个回合开始才恢复`;
504
715
  return undefined;
@@ -515,8 +726,21 @@ export function spendReaction(c, name) {
515
726
  c.initiative.reacted = [...new Set([...(c.initiative.reacted ?? []), ch.name])];
516
727
  c.initiative.rebrief = true;
517
728
  }
518
- export function armorClass(c, ch) {
519
- return ch.ac + (c?.initiative?.shielded?.includes(ch.name) === true ? 5 : 0);
729
+ /** 退回本轮误扣的反应名额(1/1),供改判退费或未最终受伤自动回退使用 */
730
+ export function restoreReaction(c, name) {
731
+ const ch = requireCharacter(c, name);
732
+ if (c.initiative === undefined)
733
+ throw new Error('反应名额只在战斗中记账');
734
+ const had = c.initiative.reacted?.includes(ch.name) === true;
735
+ if (c.initiative.reacted !== undefined) {
736
+ c.initiative.reacted = c.initiative.reacted.filter((n) => n !== ch.name);
737
+ if (c.initiative.reacted.length === 0)
738
+ delete c.initiative.reacted;
739
+ }
740
+ return had;
741
+ }
742
+ export function armorClass(c, ch, globalEffects) {
743
+ return ch.ac + (c?.initiative?.shielded?.includes(ch.name) === true ? 5 : 0) + stateAcBonus(ch, c, globalEffects);
520
744
  }
521
745
  /** 指针往后挪一格;回到表头算新一轮。新一轮开始时突袭已经结束 */
522
746
  function stepTurn(state) {
@@ -549,6 +773,9 @@ export function skipSurprised(c) {
549
773
  }
550
774
  if (skipped.length > 0)
551
775
  pushLog(c, `受惊跳过:${skipped.join('、')}`);
776
+ const active = state.order[state.turn]?.name;
777
+ if (active !== undefined)
778
+ state.turnState = { actor: active, attacks: 0 };
552
779
  return { skipped, newRound };
553
780
  }
554
781
  /**
@@ -556,7 +783,7 @@ export function skipSurprised(c) {
556
783
  * 不重掷别人、不重置轮数——重开一场会把正在进行的回合和整张先攻表都打乱。
557
784
  * 插在当前行动者前面的,本轮已经错过,下一轮才轮到。
558
785
  */
559
- export function joinInitiative(c, names, roller = cryptoRoller) {
786
+ export function joinInitiative(c, names, roller = cryptoRoller, bonus = {}, options = {}) {
560
787
  const state = requireInitiative(c);
561
788
  if (names.length === 0)
562
789
  throw new Error('join 要给 participants');
@@ -564,14 +791,44 @@ export function joinInitiative(c, names, roller = cryptoRoller) {
564
791
  const already = members.filter((ch) => state.order.some((e) => e.name === ch.name));
565
792
  if (already.length > 0)
566
793
  throw new Error(`${already.map((ch) => ch.name).join('、')} 已经在先攻表里了`);
794
+ const rehearsal = state.rehearsal === true;
795
+ if (!rehearsal && (options.rehearsalHp !== undefined || options.temporaryMonsters !== undefined)) {
796
+ throw new Error('rehearsal_hp / temporary_monsters 只在 rehearsal=true 的演练战斗中使用');
797
+ }
798
+ const tempMonsters = rehearsal
799
+ ? [...new Set((options.temporaryMonsters ?? []).map((n) => requireCharacter(c, n).name))]
800
+ : [];
801
+ const hpOverrides = rehearsal && options.rehearsalHp !== undefined
802
+ ? Object.entries(options.rehearsalHp).map(([rawName, hp]) => ({ ch: requireCharacter(c, rawName), hp: clampInt(hp, 1, 999) }))
803
+ : [];
804
+ // 先在活体卡上应用演练临时血量(战前快照 rehearsalSnapshot 保持不变,结束时仍能还原真实状态)
805
+ for (const { ch, hp } of hpOverrides) {
806
+ ch.maxHp = hp;
807
+ ch.hp = hp;
808
+ ch.conditions = ch.conditions.filter((cond) => cond !== '死亡' && cond !== '昏迷');
809
+ }
567
810
  const out = members.filter((ch) => isOut(ch));
568
811
  if (out.length > 0)
569
812
  throw new Error(`${out.map((ch) => ch.name).join('、')} 已经倒下,不能入战`);
813
+ if (rehearsal && tempMonsters.length > 0 && state.rehearsalSnapshot !== undefined) {
814
+ state.rehearsalSnapshot.temporaryMonsters = [
815
+ ...new Set([...(state.rehearsalSnapshot.temporaryMonsters ?? []), ...tempMonsters]),
816
+ ];
817
+ }
570
818
  const rolls = members.map((ch) => {
571
819
  const r = rollD20(initBonusOf(ch), 'none', roller);
572
- return { name: ch.name, init: r.total, detail: r.detail };
820
+ const expr = bonus[ch.name];
821
+ const extra = expr === undefined ? undefined : rollExpression(expr, roller);
822
+ const flat = initBonusOf(ch) + (extra?.total ?? 0);
823
+ return {
824
+ name: ch.name,
825
+ init: r.total + (extra?.total ?? 0),
826
+ detail: extra === undefined ? r.detail : `${r.detail} + ${expr} ${extra.detail}`,
827
+ tiebreak: flat,
828
+ };
573
829
  });
574
- for (const r of rolls) {
830
+ const sorted = [...rolls].sort((a, b) => b.init - a.init || b.tiebreak - a.tiebreak);
831
+ for (const r of sorted) {
575
832
  // 同点数排在已有的人后面:先在场的先动
576
833
  let idx = state.order.findIndex((e) => e.init < r.init);
577
834
  if (idx === -1)
@@ -580,8 +837,9 @@ export function joinInitiative(c, names, roller = cryptoRoller) {
580
837
  if (idx <= state.turn)
581
838
  state.turn++;
582
839
  }
583
- pushLog(c, `加入战斗:${rolls.map((r) => `${r.name}(${r.init})`).join('、')}`);
584
- return rolls;
840
+ state.allParticipants = [...new Set([...(state.allParticipants ?? []), ...state.order.map((e) => e.name)])];
841
+ pushLog(c, `加入${rehearsal ? '演练' : ''}战斗:${sorted.map((r) => `${r.name}(${r.init})`).join('、')}`);
842
+ return sorted.map(({ name, init, detail }) => ({ name, init, detail }));
585
843
  }
586
844
  /**
587
845
  * 角色离开战斗(怪物逃走报信、NPC 退场):移出先攻表但不算击败。
@@ -650,9 +908,10 @@ export function nextRollId(c) {
650
908
  return c.rollSeq;
651
909
  }
652
910
  /** 推进到下一个还能行动的角色(跳过死亡的;昏迷的 PC 保留,要做死亡豁免) */
653
- export function nextTurn(c) {
911
+ export function nextTurn(c, roller = cryptoRoller, globalEffects) {
654
912
  assertNoPending(c, '推进回合');
655
913
  const state = requireInitiative(c);
914
+ let prevActor = state.order[state.turn]?.name;
656
915
  for (const entry of [...state.order]) {
657
916
  const ch = findCharacter(c, entry.name);
658
917
  if (ch === undefined || isOut(ch))
@@ -663,32 +922,121 @@ export function nextTurn(c) {
663
922
  delete state.moved;
664
923
  delete state.dashed;
665
924
  delete state.disengaged;
925
+ delete state.fightingSpirit;
666
926
  delete state.counterAttacks;
667
- let newRound = stepTurn(state);
668
- const skip = skipSurprised(c);
669
- newRound ||= skip.newRound;
670
- // 反应到自己回合开始时恢复
671
- const current = state.order[state.turn];
672
- if (state.shielded !== undefined)
673
- state.shielded = state.shielded.filter((name) => name !== current.name);
674
- if (state.reacted !== undefined) {
675
- state.reacted = state.reacted.filter((n) => n !== current.name);
676
- if (state.reacted.length === 0)
677
- delete state.reacted;
678
- }
679
- return { round: state.round, current, newRound, skipped: skip.skipped };
680
- }
681
- /** 结束战斗:清空先攻,移除已死亡的怪物 */
682
- export function endInitiative(c) {
683
- const rounds = c.initiative?.round ?? 0;
684
- c.initiative = undefined;
927
+ delete state.zoneTriggered;
928
+ delete state.auraTriggered;
929
+ const allSkipped = [];
930
+ const allExpired = [];
931
+ const allHazards = [];
932
+ let newRound = false;
933
+ const maxHops = Math.max(1, state.order.length + 1);
934
+ for (let hop = 0; hop < maxHops; hop++) {
935
+ if (stepTurn(state))
936
+ newRound = true;
937
+ const skip = skipSurprised(c);
938
+ newRound ||= skip.newRound;
939
+ allSkipped.push(...skip.skipped);
940
+ const current = state.order[state.turn];
941
+ if (current === undefined)
942
+ break;
943
+ if (state.shielded !== undefined)
944
+ state.shielded = state.shielded.filter((name) => name !== current.name);
945
+ if (state.reacted !== undefined) {
946
+ state.reacted = state.reacted.filter((n) => n !== current.name);
947
+ if (state.reacted.length === 0)
948
+ delete state.reacted;
949
+ }
950
+ const expired = tickActiveStatesOnTurnChange(c, prevActor, current.name);
951
+ for (const line of expired)
952
+ pushLog(c, line);
953
+ allExpired.push(...expired);
954
+ allHazards.push(...checkAllAirborneCrashes(c, roller, globalEffects));
955
+ allHazards.push(...settleTurnBoundaryHazards(c, prevActor, current.name, roller, globalEffects));
956
+ allHazards.push(...checkAllAirborneCrashes(c, roller, globalEffects));
957
+ const curCh = findCharacter(c, current.name);
958
+ if (curCh !== undefined && !isOut(curCh)) {
959
+ return { round: state.round, current, newRound, skipped: allSkipped, expired: allExpired, hazardNotes: allHazards };
960
+ }
961
+ // 当前行动者在回合开始时被光环/持续地形直接击杀:移出先攻表并顺延到下一名存活角色
962
+ prevActor = undefined;
963
+ removeFromInitiative(state, current.name);
964
+ if (state.order.length === 0)
965
+ break;
966
+ }
967
+ const fallback = state.order[Math.max(0, state.turn)] ?? { name: '(全灭)', init: 0 };
968
+ return { round: state.round, current: fallback, newRound, skipped: allSkipped, expired: allExpired, hazardNotes: allHazards };
969
+ }
970
+ /** 结束战斗:记录本场完整结果与账本,清空先攻,移除已死亡的怪物(演练模式则自动还原战前状态与场地图) */
971
+ export function endInitiative(c, options = {}) {
972
+ const state = c.initiative;
973
+ const rounds = state?.round ?? 0;
974
+ const participants = [...new Set([...(state?.allParticipants ?? []), ...(state?.order.map((e) => e.name) ?? [])])];
975
+ const rooms = fightRooms(c);
685
976
  const dead = c.characters.filter((ch) => ch.kind === 'monster' && isOut(ch));
686
977
  const defeated = dead.map((ch) => ch.name);
978
+ const survivingMonsters = c.characters
979
+ .filter((ch) => ch.kind === 'monster' && !isOut(ch) && (participants.includes(ch.name) || (ch.room !== undefined && rooms.has(ch.room))))
980
+ .map((ch) => ({ name: ch.name, hp: ch.hp, maxHp: ch.maxHp, conditions: [...ch.conditions], wound: woundLabel(ch) }));
981
+ const fallenParty = c.characters
982
+ .filter((ch) => ch.kind !== 'monster' && (ch.hp === 0 || isOut(ch) || ch.conditions.includes('昏迷')) && (participants.includes(ch.name) || rooms.has(roomOf(c, ch) ?? '')))
983
+ .map((ch) => ({ name: ch.name, hp: ch.hp, maxHp: ch.maxHp, conditions: [...ch.conditions] }));
984
+ const rehearsal = state?.rehearsal === true;
985
+ const snap = state?.rehearsalSnapshot;
986
+ const restored = rehearsal && snap !== undefined && options.keepChanges !== true;
987
+ const ledger = [...(state?.ledger ?? [])];
988
+ c.initiative = undefined;
989
+ delete c.hexbladeCurses;
990
+ c.lastCombat = {
991
+ at: Date.now(),
992
+ rounds,
993
+ ...(rehearsal ? { rehearsal: true, restored } : {}),
994
+ participants,
995
+ defeated,
996
+ survivingMonsters,
997
+ fallenParty,
998
+ ledger,
999
+ };
1000
+ if (restored) {
1001
+ const tempSet = new Set(snap.temporaryMonsters ?? []);
1002
+ const participantSet = new Set(participants);
1003
+ c.characters = structuredClone(snap.characters).filter((ch) => {
1004
+ if (tempSet.has(ch.name))
1005
+ return false;
1006
+ if (ch.kind === 'monster' && ch.npcId === undefined && ch.srd === undefined && participantSet.has(ch.name) && /梦境|演练|幻境|幻象|加练/.test(ch.notes ?? ''))
1007
+ return false;
1008
+ return true;
1009
+ });
1010
+ if (snap.battlemaps !== undefined)
1011
+ c.battlemaps = structuredClone(snap.battlemaps);
1012
+ else
1013
+ delete c.battlemaps;
1014
+ c.npcs = structuredClone(snap.npcs);
1015
+ c.spawned = [...snap.spawned];
1016
+ if (snap.enteredFrom !== undefined)
1017
+ c.enteredFrom = structuredClone(snap.enteredFrom);
1018
+ else
1019
+ delete c.enteredFrom;
1020
+ pushLog(c, `演练战斗结束(${rounds} 轮)${defeated.length > 0 ? `,演练击败 ${defeated.join('、')}` : ''},战前角色状态与房间场地图已自动还原`);
1021
+ return { rounds, defeated, survivingMonsters, rehearsal: true, restored: true };
1022
+ }
687
1023
  for (const ch of dead)
688
1024
  recordNpcDeath(c, ch);
689
1025
  c.characters = c.characters.filter((ch) => !(ch.kind === 'monster' && isOut(ch)));
1026
+ for (const ch of c.characters) {
1027
+ if (ch.activeStates !== undefined) {
1028
+ const endNames = ch.activeStates
1029
+ .filter((s) => s.expires === 'end_of_combat' || s.name === '闪避')
1030
+ .map((s) => s.name);
1031
+ for (const name of endNames)
1032
+ removeActiveState(ch, name);
1033
+ }
1034
+ else if (ch.conditions.includes('闪避')) {
1035
+ removeActiveState(ch, '闪避');
1036
+ }
1037
+ }
690
1038
  pushLog(c, `战斗结束(${rounds} 轮)${defeated.length > 0 ? `,击败 ${defeated.join('、')}` : ''}`);
691
- return { rounds, defeated };
1039
+ return { rounds, defeated, survivingMonsters, ...(rehearsal ? { rehearsal: true, restored: false } : {}) };
692
1040
  }
693
1041
  /** 城镇里随便走:同一城镇里玩家知道的其他地点 */
694
1042
  function hubExits(c, adv, roomId) {
@@ -968,6 +1316,11 @@ export function assertDeclaredByOwner(ch, options, what) {
968
1316
  export function assertCanAct(c, ch, options = {}) {
969
1317
  if (options.reaction === true)
970
1318
  return;
1319
+ if (options.ignoreStateMods !== true) {
1320
+ const blocked = actionRestriction(ch);
1321
+ if (blocked !== undefined)
1322
+ throw new Error(`${blocked}(若特殊规则允许请传 ignore_state_mods=true)`);
1323
+ }
971
1324
  // 委托来的行动(玩家自己说「让 Kriv 去谈」)和强制位移不查本人,但仍然只能在轮到他的回合里主动行动
972
1325
  if (options.dmOverride !== true)
973
1326
  assertDeclaredByOwner(ch, options, '行动');
@@ -976,6 +1329,9 @@ export function assertCanAct(c, ch, options = {}) {
976
1329
  return;
977
1330
  const current = state.order[state.turn];
978
1331
  if (current !== undefined && current.name !== ch.name) {
1332
+ if (!inInitiative(c, ch.name)) {
1333
+ throw new Error(`现在是 ${current.name} 的回合,${ch.name} 不能主动行动(且 ${ch.name} 还不在先攻表里:若中途参战请先调用 dnd_initiative action=join participants=["${ch.name}"] 掷先攻并摆位;场外被动/知识检定传 reaction=true)。`);
1334
+ }
979
1335
  throw new Error(`现在是 ${current.name} 的回合,${ch.name} 不能主动行动。${current.name} 行动完先调用 dnd_initiative next;`
980
1336
  + '借机攻击/反应传 reaction=true。');
981
1337
  }
@@ -1007,6 +1363,10 @@ export function gotoTurn(c, name, round) {
1007
1363
  delete state.moved;
1008
1364
  delete state.dashed;
1009
1365
  delete state.disengaged;
1366
+ delete state.fightingSpirit;
1367
+ delete state.zoneTriggered;
1368
+ delete state.auraTriggered;
1369
+ state.turnState = { actor: ch.name, attacks: 0 };
1010
1370
  if (round !== undefined && round >= 1)
1011
1371
  state.round = Math.trunc(round);
1012
1372
  pushLog(c, `先攻指针调整到第 ${state.round} 轮 ${ch.name}`);
@@ -1038,22 +1398,68 @@ export function weaponDamage(ch, weapon) {
1038
1398
  const mod = abilityModifier(ch.abilities[weapon.ability ?? 'str']) + (weapon.magic ?? 0);
1039
1399
  return mod === 0 ? weapon.damage : `${weapon.damage}${mod > 0 ? '+' : '-'}${Math.abs(mod)}`;
1040
1400
  }
1041
- // 战斗风格写进 traits,由工具自动结算;模型不用每次记着手动加 bonus / 重投
1401
+ // 战斗风格与专长写进 traits,由工具自动结算;模型不用每次记着手动加 bonus / 重投
1042
1402
  export const GREAT_WEAPON_FIGHTING = '巨武器战斗';
1043
1403
  export const ARCHERY = '箭术';
1404
+ export const ELVEN_ACCURACY = '精灵精准';
1044
1405
  const TRAIT_ALIASES = {
1045
1406
  'great weapon fighting': GREAT_WEAPON_FIGHTING,
1046
1407
  巨武器: GREAT_WEAPON_FIGHTING,
1408
+ 大武器战斗: GREAT_WEAPON_FIGHTING,
1047
1409
  巨武器战斗风格: GREAT_WEAPON_FIGHTING,
1048
1410
  archery: ARCHERY,
1049
1411
  箭术战斗风格: ARCHERY,
1050
1412
  弓术: ARCHERY,
1413
+ 射击: ARCHERY,
1414
+ 射术: ARCHERY,
1415
+ 'elven accuracy': ELVEN_ACCURACY,
1416
+ 精灵准: ELVEN_ACCURACY,
1417
+ 精灵精准专长: ELVEN_ACCURACY,
1051
1418
  };
1052
1419
  /** 把别名统一成工具认的特性名(「巨武器战斗风格」→「巨武器战斗」) */
1053
1420
  export function normalizeTrait(trait) {
1054
1421
  const t = trait.trim();
1055
1422
  return TRAIT_ALIASES[t.toLowerCase()] ?? t;
1056
1423
  }
1424
+ /** 精灵精准:优先看结构化 traits,旧角色卡未填 traits 时从备注兜底识别 */
1425
+ export function hasElvenAccuracy(ch) {
1426
+ if (ch.traits !== undefined)
1427
+ return ch.traits.includes(ELVEN_ACCURACY);
1428
+ return /精灵精?准|Elven Accuracy/i.test(ch.notes ?? '');
1429
+ }
1430
+ /** 用敏捷/智力/感知/魅力进行的攻击检定具优势时可触发精灵精准(三骰取高) */
1431
+ export function usesElvenAccuracy(ch, ability) {
1432
+ return ability !== undefined && ability !== 'str' && hasElvenAccuracy(ch);
1433
+ }
1434
+ /** 武士「战斗英姿」临时生命值:3/10/15 级战士对应 5/10/15 点(兼职优先按 className 中的战士等级) */
1435
+ export function fightingSpiritTempHp(ch) {
1436
+ const match = /战士(?:[((][^))]*[))])?\s*(\d+)/.exec(ch.className ?? '')
1437
+ ?? /(\d+)\s*级[^\n]*武士/.exec(ch.notes ?? '');
1438
+ const fighterLevel = match !== null ? Number(match[1]) : ch.level;
1439
+ if (fighterLevel >= 15)
1440
+ return 15;
1441
+ if (fighterLevel >= 10)
1442
+ return 10;
1443
+ return 5;
1444
+ }
1445
+ /** 咒剑诅咒:每个施法者同时维持一个诅咒目标 */
1446
+ export function setHexbladeCurse(c, caster, target) {
1447
+ const casterCh = requireCharacter(c, caster);
1448
+ const targetCh = requireCharacter(c, target);
1449
+ const entry = { caster: casterCh.name, target: targetCh.name };
1450
+ c.hexbladeCurses = [...(c.hexbladeCurses ?? []).filter((x) => x.caster !== casterCh.name), entry];
1451
+ return entry;
1452
+ }
1453
+ export function hexbladeCurseOn(c, caster, target) {
1454
+ return c?.hexbladeCurses?.find((x) => x.caster === caster && x.target === target);
1455
+ }
1456
+ /** 咒剑诅咒目标死亡时的治疗量:邪术师等级 + 魅力调整值(至少 1) */
1457
+ export function hexbladeKillHeal(caster) {
1458
+ const match = /邪术师(?:[((][^))]*[))])?\s*(\d+)/.exec(caster.className ?? '')
1459
+ ?? /邪术师\s*(\d+)\s*级/.exec(caster.notes ?? '');
1460
+ const warlockLevel = match !== null ? Number(match[1]) : caster.level;
1461
+ return Math.max(1, warlockLevel + abilityModifier(caster.abilities.cha));
1462
+ }
1057
1463
  export function isRangedWeapon(weapon) {
1058
1464
  return weapon.ranged ?? /弓|弩|bow/i.test(weapon.name);
1059
1465
  }
@@ -1130,6 +1536,7 @@ export function restoreResource(c, name, key, amount) {
1130
1536
  export function rest(c, kind, names, spend = {}, roller = cryptoRoller) {
1131
1537
  if (c.initiative !== undefined)
1132
1538
  throw new Error('战斗中不能休息');
1539
+ delete c.hexbladeCurses;
1133
1540
  const members = names === undefined || names.length === 0
1134
1541
  ? c.characters.filter((ch) => ch.kind !== 'monster' && !isOut(ch))
1135
1542
  : names.map((n) => requireCharacter(c, n));
@@ -1145,6 +1552,11 @@ export function rest(c, kind, names, spend = {}, roller = cryptoRoller) {
1145
1552
  }
1146
1553
  }
1147
1554
  if (kind === 'short') {
1555
+ if (ch.activeStates !== undefined) {
1556
+ const timed = ch.activeStates.filter((s) => s.roundsLeft !== undefined || s.expires !== undefined).map((s) => s.name);
1557
+ for (const t of timed)
1558
+ removeActiveState(ch, t);
1559
+ }
1148
1560
  const dice = Math.max(0, Math.trunc(spendFor.get(ch) ?? 0));
1149
1561
  if (dice > 0) {
1150
1562
  if (ch.hitDie === undefined)
@@ -1166,20 +1578,38 @@ export function rest(c, kind, names, spend = {}, roller = cryptoRoller) {
1166
1578
  }
1167
1579
  ch.hitDiceUsed = (ch.hitDiceUsed ?? 0) + dice;
1168
1580
  const before = ch.hp;
1581
+ const effMax = effectiveMaxHp(ch);
1169
1582
  if (!ch.conditions.includes('死亡'))
1170
- ch.hp = Math.min(ch.maxHp, ch.hp + healed);
1171
- lines.push(`生命骰 ${rolls.join(' ')} = ${healed},HP ${before}→${ch.hp}/${ch.maxHp}(剩 ${ch.level - ch.hitDiceUsed} 颗)`);
1583
+ ch.hp = Math.min(effMax, ch.hp + healed);
1584
+ lines.push(`生命骰 ${rolls.join(' ')} = ${healed},HP ${before}→${ch.hp}/${effMax}(剩 ${ch.level - ch.hitDiceUsed} 颗)`);
1172
1585
  }
1173
1586
  }
1174
1587
  else {
1588
+ if (ch.activeStates !== undefined) {
1589
+ const timed = ch.activeStates.filter((s) => s.roundsLeft !== undefined || s.expires !== undefined).map((s) => s.name);
1590
+ for (const t of timed)
1591
+ removeActiveState(ch, t);
1592
+ }
1593
+ const exh = exhaustionLevel(ch);
1594
+ if (exh > 0) {
1595
+ removeActiveState(ch, '力竭');
1596
+ if (exh > 1) {
1597
+ upsertActiveState(c, ch, { name: `力竭:${exh - 1}` });
1598
+ lines.push(`力竭减轻为 ${exh - 1} 级`);
1599
+ }
1600
+ else {
1601
+ lines.push('解除力竭');
1602
+ }
1603
+ }
1175
1604
  const before = ch.hp;
1176
- ch.hp = ch.maxHp;
1605
+ const effMax = effectiveMaxHp(ch);
1606
+ ch.hp = effMax;
1177
1607
  ch.tempHp = 0;
1178
1608
  delete ch.deathSaves;
1179
- setCondition(ch, '昏迷', false);
1180
- setCondition(ch, '稳定', false);
1181
- if (before < ch.maxHp)
1182
- lines.push(`HP ${before}→${ch.maxHp}`);
1609
+ removeActiveState(ch, '昏迷');
1610
+ removeActiveState(ch, '稳定');
1611
+ if (before < effMax)
1612
+ lines.push(`HP ${before}→${effMax}`);
1183
1613
  if ((ch.hitDiceUsed ?? 0) > 0) {
1184
1614
  const regained = Math.min(ch.hitDiceUsed ?? 0, Math.max(1, Math.floor(ch.level / 2)));
1185
1615
  ch.hitDiceUsed = (ch.hitDiceUsed ?? 0) - regained;
@@ -1219,10 +1649,18 @@ export function changeInventory(c, name, add = [], remove = [], gpDelta = 0) {
1219
1649
  return ch;
1220
1650
  }
1221
1651
  export function resourceTag(ch, c) {
1222
- const parts = Object.entries(ch.resources ?? {}).map(([k, r]) => `${k}${r.current}/${r.max}`);
1652
+ const entries = Object.entries(ch.resources ?? {});
1653
+ const hitDiceKeys = entries.map(([k]) => k).filter((k) => k.startsWith('生命骰'));
1654
+ const preferredHitDieKey = hitDiceKeys.length > 1
1655
+ ? (hitDiceKeys.find((k) => k.length > '生命骰'.length) ?? hitDiceKeys.at(-1))
1656
+ : undefined;
1657
+ const parts = entries
1658
+ .filter(([k]) => preferredHitDieKey === undefined || !k.startsWith('生命骰') || k === preferredHitDieKey)
1659
+ .map(([k, r]) => `${k}${r.current}/${r.max}`);
1223
1660
  if (c?.initiative !== undefined && inInitiative(c, ch.name))
1224
1661
  parts.push(`反应${reactionBlocked(c, ch.name) === undefined && canReact(ch) ? 1 : 0}/1`);
1225
- if (ch.hitDie !== undefined)
1662
+ const hasHitDieResource = hitDiceKeys.length > 0;
1663
+ if (ch.hitDie !== undefined && !hasHitDieResource)
1226
1664
  parts.push(`生命骰${ch.level - (ch.hitDiceUsed ?? 0)}/${ch.level}`);
1227
1665
  return parts.length > 0 ? ` {${parts.join(' ')}}` : '';
1228
1666
  }
@@ -1240,7 +1678,7 @@ export function addSummary(c, text, now = Date.now()) {
1240
1678
  }
1241
1679
  /** 元数据变化不代表剧情推进;备团计划也不能混进已发生事实。 */
1242
1680
  export function campaignState(c) {
1243
- const { summaries, handoff, preparation, active, updatedAt, sessionStartedAt, rollSeq, ...state } = c;
1681
+ const { summaries, handoff, preparation, lastCombat, active, updatedAt, sessionStartedAt, rollSeq, ...state } = c;
1244
1682
  return createHash('sha256').update(JSON.stringify(state)).digest('hex');
1245
1683
  }
1246
1684
  function fitHandoff(lines, budget = 1000) {
@@ -1273,10 +1711,10 @@ export function ensureSessionSummary(c, now = Date.now()) {
1273
1711
  return true;
1274
1712
  }
1275
1713
  // ── 每回合注入的精简摘要 ──
1276
- function hpTag(ch, c) {
1714
+ function hpTag(ch, c, globalEffects) {
1277
1715
  const temp = ch.tempHp > 0 ? `+${ch.tempHp}` : '';
1278
1716
  const cond = ch.conditions.length > 0 ? ` [${ch.conditions.join(',')}]` : '';
1279
- return `${ch.name} ${ch.hp}${temp}/${ch.maxHp} AC${armorClass(c, ch)}${cond}`;
1717
+ return `${ch.name} ${ch.hp}${temp}/${ch.maxHp} AC${armorClass(c, ch, globalEffects)}${cond}`;
1280
1718
  }
1281
1719
  /** 队伍主位置所在的场景,以及这个场景探索了几个房间 */
1282
1720
  export function explored(c, adv) {
@@ -1317,10 +1755,19 @@ export function summarize(c, adv) {
1317
1755
  if (c.initiative !== undefined) {
1318
1756
  const s = c.initiative;
1319
1757
  const order = s.order.map((e, i) => (i === s.turn ? `▶${e.name}(${e.init})` : `${e.name}(${e.init})`)).join(' > ');
1320
- lines.push(`战斗第 ${s.round} 轮:${order}`);
1758
+ lines.push(`${s.rehearsal === true ? '【演练模式·战后自动还原状态与场地图】' : ''}战斗第 ${s.round} 轮:${order}`);
1321
1759
  lines.push(...battleLines(c, (id) => findRoom(graph, id)?.name ?? id));
1322
1760
  if (s.reacted?.length)
1323
1761
  lines.push(`已用反应:${s.reacted.join('、')}`);
1762
+ if (s.fightingSpirit?.length)
1763
+ lines.push(`战斗英姿生效:${s.fightingSpirit.join('、')}(本回合武器攻击自动具优势)`);
1764
+ if (c.hexbladeCurses?.length) {
1765
+ lines.push(`咒剑诅咒生效:${c.hexbladeCurses.map((x) => {
1766
+ const caster = findCharacter(c, x.caster);
1767
+ const bonus = caster === undefined ? 0 : proficiencyBonus(caster.level);
1768
+ return `${x.caster}→${x.target}(19-20 重击,伤害自动 +${bonus},勿在 damage 重复填常数)`;
1769
+ }).join(';')}`);
1770
+ }
1324
1771
  if (s.shielded?.length)
1325
1772
  lines.push(`护盾术生效:${s.shielded.join('、')}(到各自下回合开始)`);
1326
1773
  if (s.disengaged?.length)
@@ -1343,44 +1790,138 @@ export function summarize(c, adv) {
1343
1790
  lines.push(`最近:${c.log.slice(-SUMMARY_LOG_LINES).join(';')}`);
1344
1791
  return lines.join('\n');
1345
1792
  }
1793
+ /** 专用战斗子代理的精简动态战况:只含当前战场、参战生物血量/状态/资源、先攻站位区域与待结算窗口,不含全图出口、场外角色全资源和主线剧情线索。 */
1794
+ export function summarizeCombat(c, adv, globalEffects) {
1795
+ const graph = roomGraph(adv);
1796
+ const room = findRoom(graph, c.currentRoom);
1797
+ const lines = [];
1798
+ lines.push(`当前战场:${room?.name ?? c.currentRoom}(${c.currentRoom})`);
1799
+ const s = c.initiative;
1800
+ const activeRooms = fightRooms(c);
1801
+ if (activeRooms.size === 0)
1802
+ activeRooms.add(c.currentRoom);
1803
+ const participantSet = new Set([
1804
+ ...(s?.order.map((e) => e.name) ?? []),
1805
+ ...(s?.allParticipants ?? []),
1806
+ ]);
1807
+ const party = c.characters.filter((ch) => ch.kind !== 'monster');
1808
+ const combatParty = party.filter((ch) => participantSet.has(ch.name)
1809
+ || (s?.rehearsal !== true && (ch.hp === 0 || ch.conditions.includes('昏迷') || ch.conditions.includes('稳定')) && activeRooms.has(roomOf(c, ch) ?? '')));
1810
+ const bystanders = s?.rehearsal === true
1811
+ ? []
1812
+ : party.filter((ch) => !combatParty.includes(ch) && !isOut(ch) && activeRooms.has(roomOf(c, ch) ?? ''));
1813
+ if (combatParty.length > 0) {
1814
+ lines.push(`参战我方:${combatParty.map((ch) => `${hpTag(ch, c, globalEffects)}${ch.player ? `〈${ch.player}〉` : ''}${resourceTag(ch, c)}`).join(';')}`);
1815
+ }
1816
+ if (bystanders.length > 0) {
1817
+ lines.push(`同房未入战:${bystanders.map((ch) => ch.name).join('、')}(中途入战先 dnd_initiative join)`);
1818
+ }
1819
+ const foes = c.characters.filter((ch) => ch.kind === 'monster'
1820
+ && !isOut(ch)
1821
+ && (inInitiative(c, ch.name) || (s?.rehearsal !== true && activeRooms.has(ch.room ?? ''))));
1822
+ if (foes.length > 0) {
1823
+ lines.push(`敌方:${foes.map((ch) => `${ch.name}${!inInitiative(c, ch.name) ? '(未入先攻)' : ''}${ch.conditions.length > 0 ? ` [${ch.conditions.join(',')}]` : ''} ${woundLabel(ch)}`).join(';')}`);
1824
+ }
1825
+ if (s !== undefined) {
1826
+ const order = s.order.map((e, i) => (i === s.turn ? `▶${e.name}(${e.init})` : `${e.name}(${e.init})`)).join(' > ');
1827
+ lines.push(`${s.rehearsal === true ? '【演练模式·战后自动还原状态与场地图】' : ''}战斗第 ${s.round} 轮:${order}`);
1828
+ lines.push(...battleLines(c, (id) => findRoom(graph, id)?.name ?? id));
1829
+ if (s.reacted?.length)
1830
+ lines.push(`已用反应:${s.reacted.join('、')}`);
1831
+ if (s.fightingSpirit?.length)
1832
+ lines.push(`战斗英姿生效:${s.fightingSpirit.join('、')}(本回合武器攻击自动具优势)`);
1833
+ if (c.hexbladeCurses?.length) {
1834
+ lines.push(`咒剑诅咒生效:${c.hexbladeCurses.map((x) => {
1835
+ const caster = findCharacter(c, x.caster);
1836
+ const bonus = caster === undefined ? 0 : proficiencyBonus(caster.level);
1837
+ return `${x.caster}→${x.target}(19-20 重击,伤害自动 +${bonus},勿在 damage 重复填常数)`;
1838
+ }).join(';')}`);
1839
+ }
1840
+ if (s.shielded?.length)
1841
+ lines.push(`护盾术生效:${s.shielded.join('、')}(到各自下回合开始)`);
1842
+ if (s.disengaged?.length)
1843
+ lines.push(`本回合已撤离:${s.disengaged.join('、')}`);
1844
+ if (s.counterAttacks?.length)
1845
+ lines.push(`待还击(反应已扣):${s.counterAttacks.map((r) => `${r.by}→${r.target}·${r.name}`).join('、')},原攻击落账后 dnd_check attack reaction=true;不再另扣反应。`);
1846
+ if (s.moved && Object.keys(s.moved).length)
1847
+ lines.push(`本回合已移动:${Object.entries(s.moved).map(([name, feet]) => `${name} ${feet}尺`).join('、')}`);
1848
+ if (s.dashed?.length)
1849
+ lines.push(`本回合已冲刺:${s.dashed.join('、')}`);
1850
+ if (s.surprised?.length)
1851
+ lines.push(`受惊:${s.surprised.join('、')}`);
1852
+ if (s.pending !== undefined)
1853
+ lines.push(pendingSummaryLine(s.pending));
1854
+ if (s.movement !== undefined)
1855
+ lines.push(pendingSummaryLine(s.movement));
1856
+ }
1857
+ return lines.filter((l) => l.length > 0).join('\n');
1858
+ }
1346
1859
  /**
1347
1860
  * 给玩家看的团况:PC 的 HP/资源、敌人只给伤势词、先攻顺序、站位;不含 DM 笔记和怪物数值。
1348
1861
  * viewer 是看的人的 openid:战斗中多给一行他的角色到各人的距离。
1349
1862
  * markdown:站位画成代码块里的字符网格(只有 markdown 消息等宽);纯文本消息退回坐标列表。
1350
1863
  * 探索进度、出口这些 /dnd map 已经有的不在这里重复。
1351
1864
  */
1352
- /** format=image:站位已经在战斗图上了,文字里不再列坐标和字符网格 */
1865
+ /** format=image:战斗图下方只保留敌人伤势与先攻(我方血量合在图例里,不刷长串资源与异地角色) */
1353
1866
  export function playerStatus(c, adv, viewer, format = 'text') {
1354
1867
  const lines = [];
1355
1868
  const graph = roomGraph(adv);
1356
- const room = findRoom(graph, c.currentRoom);
1357
- const site = siteOfRoom(adv, c.currentRoom);
1358
- lines.push(`📍 ${adv.sites.length > 1 && site !== undefined ? `${site.name} · ` : ''}${room?.name ?? c.currentRoom}`);
1359
- const positions = partyPositions(c);
1360
- for (const [roomId, members] of positions) {
1361
- const where = positions.size > 1 ? `${findRoom(graph, roomId)?.name ?? roomId}:` : '';
1362
- lines.push(`${where}${members.map((ch) => `${ch.name} ${ch.hp}/${ch.maxHp}${ch.conditions.length > 0 ? `[${ch.conditions.join(',')}]` : ''}${resourceTag(ch)}`).join(';')}`);
1363
- }
1364
- const foes = c.characters.filter((ch) => ch.kind === 'monster' && !isOut(ch) && positions.has(ch.room ?? ''));
1365
- if (foes.length > 0)
1366
- lines.push(`敌人:${foes.map((ch) => `${ch.name}(${woundLabel(ch)}${ch.conditions.length > 0 ? `,${ch.conditions.join(',')}` : ''})`).join('、')}`);
1367
- if (c.initiative !== undefined) {
1869
+ if (format === 'image' && c.initiative !== undefined) {
1368
1870
  const s = c.initiative;
1871
+ const activeRooms = fightRooms(c);
1872
+ if (activeRooms.size === 0)
1873
+ activeRooms.add(c.currentRoom);
1874
+ const foes = c.characters.filter((ch) => ch.kind === 'monster' && !isOut(ch)
1875
+ && (inInitiative(c, ch.name) || (!hiddenFromPlayers(ch) && activeRooms.has(ch.room ?? ''))));
1876
+ if (foes.length > 0) {
1877
+ lines.push(`敌人:${foes.map((ch) => `${ch.name}(${woundLabel(ch)}${ch.conditions.length > 0 ? `,${ch.conditions.join(',')}` : ''})`).join('、')}`);
1878
+ }
1369
1879
  lines.push(`⚔ 第 ${s.round} 轮:${s.order.map((e, i) => (i === s.turn ? `▶${e.name}` : e.name)).join(' → ')}`);
1370
- // 藏起来的怪只是位置保密:名字已经在先攻表里了
1371
- const visible = (ch) => !hiddenFromPlayers(ch);
1372
- const roomName = (id) => findRoom(graph, id)?.name ?? id;
1373
- const grid = format === 'markdown' ? battleGridLines(c, roomName, visible) : undefined;
1374
- if (format !== 'image')
1375
- lines.push(...(grid ?? battleLines(c, roomName, visible)));
1376
- const mine = viewer === undefined ? [] : c.characters.filter((ch) => ch.playerId === viewer && !isOut(ch) && cellOf(c, ch) !== undefined);
1377
- for (const ch of mine)
1378
- lines.push(distancesFrom(c, ch.name, visible));
1379
1880
  if (s.pending !== undefined)
1380
1881
  lines.push(`⏳ ${describePending(s.pending)}还没结算,等反应`);
1381
1882
  if (s.movement !== undefined)
1382
1883
  lines.push(`⏳ ${s.movement.target} 暂停移动,等借机反应`);
1884
+ return lines.join('\n');
1885
+ }
1886
+ const room = findRoom(graph, c.currentRoom);
1887
+ const site = siteOfRoom(adv, c.currentRoom);
1888
+ if (c.initiative === undefined) {
1889
+ lines.push(`📍 ${adv.sites.length > 1 && site !== undefined ? `${site.name} · ` : ''}${room?.name ?? c.currentRoom}`);
1890
+ const positions = partyPositions(c);
1891
+ for (const [roomId, members] of positions) {
1892
+ const where = positions.size > 1 ? `${findRoom(graph, roomId)?.name ?? roomId}:` : '';
1893
+ lines.push(`${where}${members.map((ch) => `${ch.name} ${ch.hp}/${ch.maxHp}${ch.conditions.length > 0 ? `[${ch.conditions.join(',')}]` : ''}${resourceTag(ch)}`).join(';')}`);
1894
+ }
1895
+ const foes = c.characters.filter((ch) => ch.kind === 'monster' && !isOut(ch) && positions.has(ch.room ?? ''));
1896
+ if (foes.length > 0)
1897
+ lines.push(`敌人:${foes.map((ch) => `${ch.name}(${woundLabel(ch)}${ch.conditions.length > 0 ? `,${ch.conditions.join(',')}` : ''})`).join('、')}`);
1898
+ return lines.join('\n');
1899
+ }
1900
+ const s = c.initiative;
1901
+ const activeRooms = fightRooms(c);
1902
+ if (activeRooms.size === 0)
1903
+ activeRooms.add(c.currentRoom);
1904
+ const combatAllies = c.characters.filter((ch) => ch.kind !== 'monster' && (inInitiative(c, ch.name) || activeRooms.has(roomOf(c, ch) ?? '')));
1905
+ if (combatAllies.length > 0) {
1906
+ lines.push(`我方:${combatAllies.map((ch) => `${ch.name} ${ch.hp}/${ch.maxHp}${(ch.tempHp ?? 0) > 0 ? `(+${ch.tempHp})` : ''}`).join('、')}`);
1383
1907
  }
1908
+ const foes = c.characters.filter((ch) => ch.kind === 'monster' && !isOut(ch)
1909
+ && (inInitiative(c, ch.name) || (!hiddenFromPlayers(ch) && activeRooms.has(ch.room ?? ''))));
1910
+ if (foes.length > 0)
1911
+ lines.push(`敌人:${foes.map((ch) => `${ch.name}(${woundLabel(ch)}${ch.conditions.length > 0 ? `,${ch.conditions.join(',')}` : ''})`).join('、')}`);
1912
+ lines.push(`⚔ 第 ${s.round} 轮:${s.order.map((e, i) => (i === s.turn ? `▶${e.name}` : e.name)).join(' → ')}`);
1913
+ // 藏起来的怪只是位置保密:名字已经在先攻表里了
1914
+ const visible = (ch) => !hiddenFromPlayers(ch);
1915
+ const roomName = (id) => findRoom(graph, id)?.name ?? id;
1916
+ const grid = format === 'markdown' ? battleGridLines(c, roomName, visible) : undefined;
1917
+ lines.push(...(grid ?? battleLines(c, roomName, visible)));
1918
+ const mine = viewer === undefined ? [] : c.characters.filter((ch) => ch.playerId === viewer && !isOut(ch) && cellOf(c, ch) !== undefined);
1919
+ for (const ch of mine)
1920
+ lines.push(distancesFrom(c, ch.name, visible));
1921
+ if (s.pending !== undefined)
1922
+ lines.push(`⏳ ${describePending(s.pending)}还没结算,等反应`);
1923
+ if (s.movement !== undefined)
1924
+ lines.push(`⏳ ${s.movement.target} 暂停移动,等借机反应`);
1384
1925
  return lines.join('\n');
1385
1926
  }
1386
1927
  function safeFileName(key) {
@@ -1440,10 +1981,11 @@ export class CampaignStore {
1440
1981
  const seqBefore = c.rollSeq;
1441
1982
  const result = fn(c);
1442
1983
  if (JSON.stringify(c) !== before) {
1443
- // 只多掷了一骰(没有后果的检定)不占快照:快照有上限,别让它挤掉真正能撤的改动
1984
+ // 只多掷了一骰(没有后果的检定)或纯反应窗口去重记录不占快照:快照有上限,别让它挤掉真正能撤的改动
1444
1985
  const onlyCounter = JSON.stringify({ ...c, rollSeq: seqBefore }) === before;
1445
- if (!onlyCounter)
1446
- this.pushSnapshot(key, { at: Date.now(), label: typeof label === 'function' ? label() : label, state: before });
1986
+ if (!onlyCounter && options.recordHistory !== false) {
1987
+ this.pushSnapshot(key, { at: Date.now(), label: typeof label === 'function' ? label() : label, state: before }, c.initiative !== undefined);
1988
+ }
1447
1989
  this.save(c);
1448
1990
  }
1449
1991
  return result;
@@ -1462,11 +2004,22 @@ export class CampaignStore {
1462
2004
  return [];
1463
2005
  }
1464
2006
  }
1465
- pushSnapshot(key, snapshot) {
2007
+ pushSnapshot(key, snapshot, inCombat = false) {
1466
2008
  const list = this.snapshots(key);
1467
2009
  list.push(snapshot);
1468
- if (list.length > MAX_SNAPSHOTS)
1469
- list.splice(0, list.length - MAX_SNAPSHOTS);
2010
+ while (list.length > MAX_SNAPSHOTS) {
2011
+ // 战斗进行中保留最近一次开战前的基线快照,避免长战斗超过 40 步后丢掉开战前状态
2012
+ let pinned = -1;
2013
+ if (inCombat) {
2014
+ for (let i = list.length - 1; i >= 0; i--) {
2015
+ if (/^dnd_initiative\b.*\baction=start\b/.test(list[i].label)) {
2016
+ pinned = i;
2017
+ break;
2018
+ }
2019
+ }
2020
+ }
2021
+ list.splice(pinned === 0 ? 1 : 0, 1);
2022
+ }
1470
2023
  this.writeSnapshots(key, list);
1471
2024
  }
1472
2025
  writeSnapshots(key, list) {
@@ -1497,8 +2050,8 @@ export class CampaignStore {
1497
2050
  export function snapshotRolls(label) {
1498
2051
  return [...label.matchAll(/#R(\d+)\b/g)].map((m) => Number(m[1]));
1499
2052
  }
1500
- /** 这些改动推进过回合:按骰子撤销越过它们时要 DM 再确认一次 */
2053
+ /** 这些改动推进过回合、有人中途入战/换房间,或已经结过下一轮检定:按骰子撤销越过它们时要 DM 再确认一次 */
1501
2054
  export function crossesTurn(label) {
1502
- return /^dnd_initiative .*action=(next|goto|end)\b|^按钮 结束回合/.test(label);
2055
+ return /^dnd_initiative .*action=(next|goto|end|join|start)\b|^按钮 结束回合|^dnd_move\b|^dnd_check\b/.test(label);
1503
2056
  }
1504
2057
  //# sourceMappingURL=campaign.js.map