Implement D&D 5e death-save state machine and cleanup combat ordering
- Add status-driven death-save model: - status: conscious | dying | stable | dead - deathSaveSuccesses/deathSaveFailures as display counters - remove old death-save fields as source of truth - Add death-save actions: - success, fail, nat1, nat20 - stabilize participant - revive dead participant to 0 HP, stable, unconscious - Apply 5e HP transition rules: - characters and NPCs at 0 HP become dying - stable/dying participants gain unconscious condition - healing clears death saves and returns conscious - massive damage kills - non-NPC monsters at 0 HP become dead and inactive - Split NPCs from monsters with type="npc": - NPCs use death saves like characters - NPCs remain DM-controlled/monster-colored in UI - new NPCs no longer persist isNpc flag - Keep dead PCs/NPCs in encounter and initiative until DM removes or deactivates - Allow DM active/inactive toggle for dead participants - Hide inactive participants from player display - Improve DM and player death-state UI: - show Dying/Dead/Unconscious states consistently - add revive button for dead participants - distinguish dead visual from inactive visual in DM view - Fix initiative drag/reorder behavior: - downward drag now changes order instead of no-op - paused combat can reorder across current turn pointer - turnOrderIds stay synced to participants order - Persist campaign collapse state in localStorage - Update death-save docs and encounter builder docs - Add/expand tests for: - death saves and HP transitions - dead/active/inactive behavior - NPC death-save behavior - player display visibility - drag reorder semantics - logging expectations Tests: - npm run test:all - app: 94 passed - shared: 158 passed, 5 skipped - server: 32 passed
This commit is contained in:
@@ -35,6 +35,7 @@ function createMockStorage() {
|
||||
// filters
|
||||
updatesFor(prefix) { return calls.filter(c => c.fn === 'updateDoc' && c.path.startsWith(prefix)); },
|
||||
logs() { return calls.filter(c => c.fn === 'addDoc').map(c => c.data); },
|
||||
getLogs() { return calls.filter(c => c.fn === 'addDoc').map(c => c.data); },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -63,8 +64,8 @@ function readyEnc(opts = {}) {
|
||||
currentTurnParticipantId: null,
|
||||
turnOrderIds: [],
|
||||
participants: opts.participants || [
|
||||
{ id: 'p1', name: 'Bob', type: 'character', initiative: 10, maxHp: 10, currentHp: 10, isActive: true, conditions: [], deathSaves: 0, deathFails: 0, isStable: false, isDying: false },
|
||||
{ id: 'p2', name: 'Mob', type: 'monster', initiative: 5, maxHp: 10, currentHp: 10, isActive: true, conditions: [], deathSaves: 0, deathFails: 0, isStable: false, isDying: false },
|
||||
{ id: 'p1', name: 'Bob', type: 'character', initiative: 10, maxHp: 10, currentHp: 10, isActive: true, conditions: [], status: 'conscious', deathSaveSuccesses: 0, deathSaveFailures: 0 },
|
||||
{ id: 'p2', name: 'Mob', type: 'monster', initiative: 5, maxHp: 10, currentHp: 10, isActive: true, conditions: [], status: 'conscious', deathSaveSuccesses: 0, deathSaveFailures: 0 },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -245,27 +245,26 @@ describe('applyHpChange', () => {
|
||||
expect(newEnc.participants[0].currentHp).toBe(10);
|
||||
});
|
||||
|
||||
test('damage to 0 deactivates + keeps turn order (unified)', async () => {
|
||||
// Unified: death flips isActive=false (removed from active rotation).
|
||||
// turnOrderIds unchanged (no turn-order patch on death).
|
||||
test('damage to 0 marks dying, keeps active, keeps turn order', async () => {
|
||||
const { storage, ctx } = mockCtx();
|
||||
const ps = [p('a', 10, { currentHp: 3 }), p('b', 5)];
|
||||
const ps = [p('a', 10, { type: 'character', currentHp: 3 }), p('b', 5)];
|
||||
const e = enc(ps, { isStarted: true, turnOrderIds: ['a', 'b'], currentTurnParticipantId: 'a' });
|
||||
const newEnc = await applyHpChange(e, 'a', 'damage', 5, ctx);
|
||||
expect(newEnc.participants[0].currentHp).toBe(0);
|
||||
expect(newEnc.participants[0].isActive).toBe(false);
|
||||
expect(newEnc.participants[0].status).toBe('dying');
|
||||
expect(newEnc.participants[0].isActive).not.toBe(false);
|
||||
expect(lastPatch(storage).turnOrderIds).toBeUndefined();
|
||||
expect(lastPatch(storage).currentTurnParticipantId).toBeUndefined();
|
||||
});
|
||||
|
||||
test('heal above 0 reactivates + resets death saves (unified)', async () => {
|
||||
// Unified: revive from 0 flips isActive=true, deathSaves reset.
|
||||
test('heal from dying makes conscious and resets death-save counters', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [p('a', 10, { currentHp: 0, isActive: false, deathSaves: 2 })];
|
||||
const ps = [p('a', 10, { currentHp: 0, status: 'dying', deathSaveSuccesses: 2, deathSaveFailures: 1 })];
|
||||
const newEnc = await applyHpChange(enc(ps), 'a', 'heal', 5, ctx);
|
||||
expect(newEnc.participants[0].currentHp).toBe(5);
|
||||
expect(newEnc.participants[0].isActive).toBe(true);
|
||||
expect(newEnc.participants[0].deathSaves).toBe(0);
|
||||
expect(newEnc.participants[0].status).toBe('conscious');
|
||||
expect(newEnc.participants[0].deathSaveSuccesses).toBe(0);
|
||||
expect(newEnc.participants[0].deathSaveFailures).toBe(0);
|
||||
});
|
||||
|
||||
test('heal clamps to maxHp', async () => {
|
||||
@@ -285,27 +284,21 @@ describe('applyHpChange', () => {
|
||||
});
|
||||
|
||||
describe('deathSave', () => {
|
||||
test('increments fails', async () => {
|
||||
test('fail increments failure counter while dying', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [p('a', 10, { currentHp: 0, deathFails: 0 })];
|
||||
const { enc: newEnc } = await deathSave(enc(ps), 'a', 'fail', 1, ctx);
|
||||
expect(newEnc.participants[0].deathFails).toBe(1);
|
||||
const ps = [p('a', 10, { currentHp: 0, status: 'dying', deathSaveFailures: 0, deathSaveSuccesses: 0 })];
|
||||
const { enc: newEnc, status } = await deathSave(enc(ps), 'a', 'fail', ctx);
|
||||
expect(status).toBe('dying');
|
||||
expect(newEnc.participants[0].deathSaveFailures).toBe(1);
|
||||
});
|
||||
|
||||
test('clicking same fail decrements (toggle)', async () => {
|
||||
test('third fail makes dead and resets counters', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [p('a', 10, { currentHp: 0, deathFails: 2 })];
|
||||
const { enc: newEnc } = await deathSave(enc(ps), 'a', 'fail', 2, ctx);
|
||||
expect(newEnc.participants[0].deathFails).toBe(1);
|
||||
});
|
||||
|
||||
test('third fail sets isDying', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [p('a', 10, { currentHp: 0, deathFails: 2 })];
|
||||
const { enc: newEnc, isDying } = await deathSave(enc(ps), 'a', 'fail', 3, ctx);
|
||||
expect(newEnc.participants[0].deathFails).toBe(3);
|
||||
expect(newEnc.participants[0].isDying).toBe(true);
|
||||
expect(isDying).toBe(true);
|
||||
const ps = [p('a', 10, { currentHp: 0, status: 'dying', deathSaveFailures: 2, deathSaveSuccesses: 0 })];
|
||||
const { enc: newEnc, status } = await deathSave(enc(ps), 'a', 'fail', ctx);
|
||||
expect(status).toBe('dead');
|
||||
expect(newEnc.participants[0].status).toBe('dead');
|
||||
expect(newEnc.participants[0].deathSaveFailures).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -326,12 +319,12 @@ describe('toggleCondition', () => {
|
||||
});
|
||||
|
||||
describe('reorderParticipants', () => {
|
||||
test('drag before target (same-init tie)', async () => {
|
||||
test('drag downward onto target moves after target (same-init tie)', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [p('a', 10), p('b', 10), p('c', 10)];
|
||||
const newEnc = await reorderParticipants(enc(ps), 'a', 'c', ctx);
|
||||
// drag a before c: remove a → [b,c], insert before c → [b,a,c]
|
||||
expect(newEnc.participants.map(x => x.id)).toEqual(['b', 'a', 'c']);
|
||||
// drag a downward onto c: remove a → [b,c], insert after c → [b,c,a]
|
||||
expect(newEnc.participants.map(x => x.id)).toEqual(['b', 'c', 'a']);
|
||||
});
|
||||
|
||||
test('cross-init drag blocked (no-op)', async () => {
|
||||
|
||||
@@ -56,7 +56,7 @@ function setupEncounter() {
|
||||
buildMonsterParticipant({ name:'Goblin2', maxHp:100, initMod:2 }).participant,
|
||||
buildMonsterParticipant({ name:'OrcBoss', maxHp:500, initMod:1 }).participant,
|
||||
buildMonsterParticipant({ name:'Wolf', maxHp:120, initMod:3 }).participant,
|
||||
buildMonsterParticipant({ name:'Merchant', maxHp:150, initMod:0, isNpc:true }).participant,
|
||||
buildMonsterParticipant({ name:'Merchant', maxHp:150, initMod:0, asNpc:true }).participant,
|
||||
];
|
||||
// give deterministic ids to monsters for assertions
|
||||
const idMap = { Goblin1:'m1', Goblin2:'m2', OrcBoss:'m3', Wolf:'m4', Merchant:'n1' };
|
||||
@@ -163,12 +163,12 @@ describe('combat integrity (100 rounds, full op coverage)', () => {
|
||||
}
|
||||
}
|
||||
// 5. deathSave
|
||||
if (actor && actor.currentHp <= 0 && !actor.isNpc) {
|
||||
try { const r = await deathSave(e, actor.id, 'fail', 1, ctx); e = r.enc; } catch (err) {}
|
||||
if (actor && actor.status === 'dying' && actor.type !== 'npc') {
|
||||
try { const r = await deathSave(e, actor.id, 'fail', ctx); e = r.enc; } catch (err) {}
|
||||
}
|
||||
// 6. removeParticipant
|
||||
// 6. removeParticipant (monsters/NPC only; dead PCs stay until DM removes manually)
|
||||
if (totalTurns % 5 === 0) {
|
||||
const dead = e.participants.find(part => (part.isDying || part.currentHp <= 0) && (part.isNpc || part.name.startsWith('Goblin') || part.name === 'OrcBoss' || part.name === 'Wolf'));
|
||||
const dead = e.participants.find(part => (part.status === 'dead' || part.currentHp <= 0) && (part.type === 'npc' || part.name.startsWith('Goblin') || part.name === 'OrcBoss' || part.name === 'Wolf'));
|
||||
if (dead) { try { e = await removeParticipant(e, dead.id, ctx); } catch (err) {} }
|
||||
}
|
||||
// 7. addParticipant
|
||||
|
||||
@@ -1,28 +1,17 @@
|
||||
// Unified behavior (App main): death flips isActive=false, dead participant
|
||||
// removed from active rotation, skipped by nextTurn. deathSave is a manual
|
||||
// DM action (button), not tied to rotation. turnOrderIds unchanged on death
|
||||
// (only isActive flag flips). Revive (heal from 0) reactivates.
|
||||
//
|
||||
// Previous "M4: dead stays in rotation" concept reversed by unification.
|
||||
//
|
||||
// New API: mutating funcs are async, take ctx last, write encounter + log
|
||||
// internally, return newEnc. Chained calls become `e = await fn(e, ctx)`.
|
||||
'use strict';
|
||||
|
||||
const shared = require('@ttrpg/shared');
|
||||
const { makeParticipant, startEncounter, nextTurn, applyHpChange, deathSave } = shared;
|
||||
const { mockCtx } = require('./_helpers');
|
||||
|
||||
function p(id, init, extra = {}) {
|
||||
return makeParticipant({
|
||||
id, name: id, type: 'monster',
|
||||
initiative: init, maxHp: 100, currentHp: 100,
|
||||
...extra,
|
||||
});
|
||||
}
|
||||
function pc(id, init, extra = {}) {
|
||||
return makeParticipant({
|
||||
id, name: id, type: 'character',
|
||||
initiative: init, maxHp: 100, currentHp: 100,
|
||||
id,
|
||||
name: id,
|
||||
type: 'character',
|
||||
initiative: init,
|
||||
maxHp: 100,
|
||||
currentHp: 100,
|
||||
...extra,
|
||||
});
|
||||
}
|
||||
@@ -30,69 +19,67 @@ function enc(ps) {
|
||||
return { name:'t', participants:ps, isStarted:false, isPaused:false,
|
||||
round:0, currentTurnParticipantId:null, turnOrderIds:[] };
|
||||
}
|
||||
const byId = (e, id) => e.participants.find(p => p.id === id);
|
||||
|
||||
describe('unified: death deactivates, dead skipped in rotation', () => {
|
||||
test('dead PC not removed from turnOrderIds (stays in list, inactive)', async () => {
|
||||
describe('death state: participant remains in initiative and encounter', () => {
|
||||
test('dropping to 0 keeps PC active, in participants, and in turnOrderIds', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [pc('a', 20), pc('b', 15), pc('c', 10)];
|
||||
let e = enc(ps);
|
||||
let e = enc([pc('a', 20), pc('b', 15), pc('c', 10)]);
|
||||
e = await startEncounter(e, ctx);
|
||||
const orderBefore = e.turnOrderIds.slice();
|
||||
// kill b
|
||||
|
||||
e = await applyHpChange(e, 'b', 'damage', 100, ctx);
|
||||
|
||||
expect(byId(e, 'b').status).toBe('dying');
|
||||
expect(byId(e, 'b').isActive).not.toBe(false);
|
||||
expect(e.participants.map(p => p.id)).toContain('b');
|
||||
expect(e.turnOrderIds).toEqual(orderBefore);
|
||||
});
|
||||
|
||||
test('dead PC skipped by nextTurn (isActive=false)', async () => {
|
||||
test('dead PC remains in participants and turnOrderIds after three failures', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [pc('a', 20), pc('b', 15), pc('c', 10)];
|
||||
let e = enc(ps);
|
||||
let e = enc([pc('a', 20), pc('b', 15), pc('c', 10)]);
|
||||
e = await startEncounter(e, ctx);
|
||||
// kill b
|
||||
const orderBefore = e.turnOrderIds.slice();
|
||||
e = await applyHpChange(e, 'b', 'damage', 100, ctx);
|
||||
// advance: a→c (b skipped, inactive)
|
||||
|
||||
e = (await deathSave(e, 'b', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'b', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'b', 'fail', ctx)).enc;
|
||||
|
||||
expect(byId(e, 'b').status).toBe('dead');
|
||||
expect(byId(e, 'b').isActive).not.toBe(false);
|
||||
expect(e.participants.map(p => p.id)).toContain('b');
|
||||
expect(e.turnOrderIds).toEqual(orderBefore);
|
||||
});
|
||||
|
||||
test('nextTurn may still land on dead PC because DM/tool events may matter', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
let e = enc([pc('a', 20), pc('b', 15), pc('c', 10)]);
|
||||
e = await startEncounter(e, ctx);
|
||||
e = await applyHpChange(e, 'b', 'damage', 100, ctx);
|
||||
e = (await deathSave(e, 'b', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'b', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'b', 'fail', ctx)).enc;
|
||||
|
||||
e = await nextTurn(e, ctx);
|
||||
expect(e.currentTurnParticipantId).toBe('c');
|
||||
|
||||
expect(e.currentTurnParticipantId).toBe('b');
|
||||
expect(byId(e, 'b').status).toBe('dead');
|
||||
});
|
||||
|
||||
test('dead PC deathSave fires on manual call (not via rotation)', async () => {
|
||||
test('deathSave rejected/no-op once dead', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [pc('a', 20), pc('b', 15)];
|
||||
let e = enc(ps);
|
||||
let e = enc([pc('a', 20), pc('b', 15)]);
|
||||
e = await startEncounter(e, ctx);
|
||||
// kill b (current = a)
|
||||
e = await applyHpChange(e, 'b', 'damage', 100, ctx);
|
||||
// b is dead: DM can still fire deathSave (manual action)
|
||||
const { enc: newEnc } = await deathSave(e, 'b', 'fail', 1, ctx);
|
||||
const b = newEnc.participants.find(x => x.id === 'b');
|
||||
expect(b.deathFails).toBe(1);
|
||||
});
|
||||
e = (await deathSave(e, 'b', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'b', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'b', 'fail', ctx)).enc;
|
||||
const before = byId(e, 'b');
|
||||
|
||||
// D1 unification: shared now matches App main — death flips isActive=false.
|
||||
// Dead participant removed from active rotation (skipped by nextTurn).
|
||||
test('dead PC auto-set isActive=false by applyHpChange', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [pc('a', 20), pc('b', 15)];
|
||||
let e = enc(ps);
|
||||
e = await startEncounter(e, ctx);
|
||||
e = await applyHpChange(e, 'b', 'damage', 100, ctx);
|
||||
const b = e.participants.find(x => x.id === 'b');
|
||||
expect(b.isActive).toBe(false);
|
||||
});
|
||||
try { e = (await deathSave(e, 'b', 'fail', ctx)).enc; } catch (err) {}
|
||||
|
||||
test('revive (heal from 0) reactivates participant', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [pc('a', 20), pc('b', 15)];
|
||||
let e = enc(ps);
|
||||
e = await startEncounter(e, ctx);
|
||||
e = await applyHpChange(e, 'b', 'damage', 100, ctx);
|
||||
const dead = e.participants.find(x => x.id === 'b');
|
||||
expect(dead.isActive).toBe(false);
|
||||
// heal b back up
|
||||
e = await applyHpChange(e, 'b', 'heal', 50, ctx);
|
||||
const revived = e.participants.find(x => x.id === 'b');
|
||||
expect(revived.isActive).toBe(true);
|
||||
expect(revived.currentHp).toBe(50);
|
||||
expect(revived.deathSaves).toBe(0);
|
||||
expect(byId(e, 'b')).toMatchObject(before);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,92 +1,334 @@
|
||||
// Death saves: broken model. Current = single counter, 3=dying. D&D 5e needs
|
||||
// separate success/fail tracking:
|
||||
// 3 successes = stable (0hp unconscious, safe until healed)
|
||||
// 3 failures = dead
|
||||
// Current tracks "saves" (really fails via red X UI), no successes at all.
|
||||
// "Stable" state doesn't exist.
|
||||
//
|
||||
// RED was: prove current can't model 3-success stability.
|
||||
//
|
||||
// New API: deathSave is async, takes ctx, returns { enc, status, isDying }.
|
||||
// applyHpChange + startEncounter are async, take ctx, return newEnc.
|
||||
|
||||
'use strict';
|
||||
|
||||
const { makeParticipant, startEncounter, applyHpChange, deathSave } = require('@ttrpg/shared');
|
||||
const {
|
||||
makeParticipant,
|
||||
startEncounter,
|
||||
applyHpChange,
|
||||
deathSave,
|
||||
stabilizeParticipant,
|
||||
reviveParticipant,
|
||||
} = require('@ttrpg/shared');
|
||||
const { mockCtx } = require('./_helpers');
|
||||
|
||||
function p(id) {
|
||||
return makeParticipant({ id, name: id, type: 'character',
|
||||
initiative: 10, maxHp: 100, currentHp: 100 });
|
||||
function pc(id, extra = {}) {
|
||||
return makeParticipant({
|
||||
id,
|
||||
name: id,
|
||||
type: 'character',
|
||||
initiative: 10,
|
||||
maxHp: 100,
|
||||
currentHp: 100,
|
||||
...extra,
|
||||
});
|
||||
}
|
||||
function enc(ps, extra = {}) {
|
||||
return { name:'t', participants:ps, isStarted:false, isPaused:false,
|
||||
round:0, currentTurnParticipantId:null, turnOrderIds:[], ...extra };
|
||||
function monster(id, extra = {}) {
|
||||
return makeParticipant({
|
||||
id,
|
||||
name: id,
|
||||
type: 'monster',
|
||||
initiative: 10,
|
||||
maxHp: 100,
|
||||
currentHp: 100,
|
||||
...extra,
|
||||
});
|
||||
}
|
||||
|
||||
describe('death saves: missing success/stable model', () => {
|
||||
test('3 successes makes character stable (not dead, not dying)', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
// Character at 0hp. Roll 3 successful death saves.
|
||||
let e = enc([p('a')]);
|
||||
e = await startEncounter(e, ctx);
|
||||
e = await applyHpChange(e, 'a', 'damage', 100, ctx); // 0hp
|
||||
expect(e.participants[0].currentHp).toBe(0);
|
||||
function enc(participants, extra = {}) {
|
||||
return {
|
||||
id: 'e1',
|
||||
name: 'death-save-test',
|
||||
participants,
|
||||
isStarted: false,
|
||||
isPaused: false,
|
||||
round: 0,
|
||||
currentTurnParticipantId: null,
|
||||
turnOrderIds: [],
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
// Roll 3 successful saves. Should mark stable.
|
||||
let res;
|
||||
res = await deathSave(e, 'a', 'success', 1, ctx); e = res.enc;
|
||||
res = await deathSave(e, 'a', 'success', 2, ctx); e = res.enc;
|
||||
res = await deathSave(e, 'a', 'success', 3, ctx); e = res.enc;
|
||||
async function startedAtZero() {
|
||||
const { ctx } = mockCtx();
|
||||
let e = enc([pc('a')]);
|
||||
e = await startEncounter(e, ctx);
|
||||
const originalTurnOrderIds = [...e.turnOrderIds];
|
||||
e = await applyHpChange(e, 'a', 'damage', 100, ctx);
|
||||
return { e, ctx, originalTurnOrderIds };
|
||||
}
|
||||
|
||||
expect(res.status).toBe('stable');
|
||||
expect(e.participants[0].isDying).toBe(false);
|
||||
expect(e.participants[0].isStable).toBe(true);
|
||||
expect(e.participants[0].deathFails).toBe(0);
|
||||
const part = e => e.participants.find(p => p.id === 'a');
|
||||
|
||||
describe('death saves: D&D 5e status state machine', () => {
|
||||
test('damage drops character to dying without removal or deactivation', async () => {
|
||||
const { e, originalTurnOrderIds } = await startedAtZero();
|
||||
const p = part(e);
|
||||
|
||||
expect(p.currentHp).toBe(0);
|
||||
expect(p.status).toBe('dying');
|
||||
expect(p.deathSaveSuccesses).toBe(0);
|
||||
expect(p.deathSaveFailures).toBe(0);
|
||||
expect(p.isActive).not.toBe(false);
|
||||
expect(e.participants.map(x => x.id)).toContain('a');
|
||||
expect(e.turnOrderIds).toEqual(originalTurnOrderIds);
|
||||
});
|
||||
|
||||
test('3 failures makes character dead (isDying for removal)', async () => {
|
||||
test('damage drops non-NPC monster to dead/inactive, not dying', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
let e = enc([p('a')]);
|
||||
let e = enc([monster('a')]);
|
||||
e = await startEncounter(e, ctx);
|
||||
const orderBefore = [...e.turnOrderIds];
|
||||
|
||||
e = await applyHpChange(e, 'a', 'damage', 100, ctx);
|
||||
|
||||
let res;
|
||||
res = await deathSave(e, 'a', 'fail', 1, ctx); e = res.enc;
|
||||
res = await deathSave(e, 'a', 'fail', 2, ctx); e = res.enc;
|
||||
res = await deathSave(e, 'a', 'fail', 3, ctx); e = res.enc;
|
||||
expect(part(e).status).toBe('dead');
|
||||
expect(part(e).deathSaveSuccesses).toBe(0);
|
||||
expect(part(e).deathSaveFailures).toBe(0);
|
||||
expect(part(e).conditions).not.toContain('unconscious');
|
||||
expect(part(e).isActive).toBe(false);
|
||||
expect(e.turnOrderIds).toEqual(orderBefore);
|
||||
});
|
||||
|
||||
test('dead non-NPC monster with stale active flag repairs to inactive', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
let e = enc([monster('a', { currentHp: 0, status: 'dead', isActive: true })]);
|
||||
e = await startEncounter(e, ctx);
|
||||
|
||||
e = await applyHpChange(e, 'a', 'damage', 1, ctx);
|
||||
|
||||
expect(part(e).status).toBe('dead');
|
||||
expect(part(e).isActive).toBe(false);
|
||||
});
|
||||
|
||||
test('damage drops NPC to dying', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
let e = enc([monster('a', { type: 'npc' })]);
|
||||
e = await startEncounter(e, ctx);
|
||||
|
||||
e = await applyHpChange(e, 'a', 'damage', 100, ctx);
|
||||
|
||||
expect(part(e).type).toBe('npc');
|
||||
expect(part(e).status).toBe('dying');
|
||||
expect(part(e).conditions).toContain('unconscious');
|
||||
});
|
||||
|
||||
test('three failures immediately makes dead, resets counters, keeps participant and turn order', async () => {
|
||||
let { e, ctx, originalTurnOrderIds } = await startedAtZero();
|
||||
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
expect(part(e).status).toBe('dying');
|
||||
expect(part(e).deathSaveFailures).toBe(1);
|
||||
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
expect(part(e).status).toBe('dying');
|
||||
expect(part(e).deathSaveFailures).toBe(2);
|
||||
|
||||
const res = await deathSave(e, 'a', 'fail', ctx);
|
||||
e = res.enc;
|
||||
expect(res.status).toBe('dead');
|
||||
expect(e.participants[0].isDying).toBe(true);
|
||||
expect(e.participants[0].deathFails).toBe(3);
|
||||
expect(part(e).status).toBe('dead');
|
||||
expect(part(e).currentHp).toBe(0);
|
||||
expect(part(e).deathSaveSuccesses).toBe(0);
|
||||
expect(part(e).deathSaveFailures).toBe(0);
|
||||
expect(part(e).isActive).not.toBe(false);
|
||||
expect(e.participants.map(x => x.id)).toContain('a');
|
||||
expect(e.turnOrderIds).toEqual(originalTurnOrderIds);
|
||||
});
|
||||
|
||||
test('successes and fails tracked independently', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
// Mixed: 1 success, 2 fails, then 2 more successes = stable.
|
||||
let e = enc([p('a')]);
|
||||
e = await startEncounter(e, ctx);
|
||||
e = await applyHpChange(e, 'a', 'damage', 100, ctx);
|
||||
test('three successes immediately makes stable and resets counters', async () => {
|
||||
let { e, ctx } = await startedAtZero();
|
||||
|
||||
let res;
|
||||
res = await deathSave(e, 'a', 'success', 1, ctx); e = res.enc;
|
||||
expect(e.participants[0].deathSaves).toBe(1);
|
||||
expect(e.participants[0].deathFails).toBe(0);
|
||||
e = (await deathSave(e, 'a', 'success', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'success', ctx)).enc;
|
||||
const res = await deathSave(e, 'a', 'success', ctx);
|
||||
e = res.enc;
|
||||
|
||||
res = await deathSave(e, 'a', 'fail', 1, ctx); e = res.enc;
|
||||
res = await deathSave(e, 'a', 'fail', 2, ctx); e = res.enc;
|
||||
expect(e.participants[0].deathSaves).toBe(1);
|
||||
expect(e.participants[0].deathFails).toBe(2);
|
||||
|
||||
// 2 more successes → total 3 successes → stable
|
||||
res = await deathSave(e, 'a', 'success', 2, ctx); e = res.enc;
|
||||
res = await deathSave(e, 'a', 'success', 3, ctx);
|
||||
expect(res.status).toBe('stable');
|
||||
expect(e.participants[0].deathFails).toBe(2); // fails unchanged
|
||||
expect(part(e).status).toBe('stable');
|
||||
expect(part(e).currentHp).toBe(0);
|
||||
expect(part(e).deathSaveSuccesses).toBe(0);
|
||||
expect(part(e).deathSaveFailures).toBe(0);
|
||||
});
|
||||
|
||||
test('deathSave signature: (enc, id, type, n)', async () => {
|
||||
// type = 'success' | 'fail'. n = 1|2|3. ctx appended by async refactor.
|
||||
expect(deathSave.length).toBe(5);
|
||||
test('successes and failures are independent before terminal transition', async () => {
|
||||
let { e, ctx } = await startedAtZero();
|
||||
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'success', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'success', ctx)).enc;
|
||||
|
||||
expect(part(e).status).toBe('dying');
|
||||
expect(part(e).deathSaveFailures).toBe(2);
|
||||
expect(part(e).deathSaveSuccesses).toBe(2);
|
||||
|
||||
e = (await deathSave(e, 'a', 'success', ctx)).enc;
|
||||
expect(part(e).status).toBe('stable');
|
||||
expect(part(e).deathSaveFailures).toBe(0);
|
||||
expect(part(e).deathSaveSuccesses).toBe(0);
|
||||
});
|
||||
|
||||
test('nat1 adds two failures and can kill', async () => {
|
||||
let { e, ctx } = await startedAtZero();
|
||||
|
||||
e = (await deathSave(e, 'a', 'nat1', ctx)).enc;
|
||||
expect(part(e).status).toBe('dying');
|
||||
expect(part(e).deathSaveFailures).toBe(2);
|
||||
|
||||
e = (await deathSave(e, 'a', 'nat1', ctx)).enc;
|
||||
expect(part(e).status).toBe('dead');
|
||||
expect(part(e).deathSaveFailures).toBe(0);
|
||||
});
|
||||
|
||||
test('nat1 at one failure immediately kills', async () => {
|
||||
let { e, ctx } = await startedAtZero();
|
||||
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'nat1', ctx)).enc;
|
||||
|
||||
expect(part(e).status).toBe('dead');
|
||||
expect(part(e).deathSaveFailures).toBe(0);
|
||||
});
|
||||
|
||||
test('nat20 restores to 1 HP conscious and resets counters', async () => {
|
||||
let { e, ctx } = await startedAtZero();
|
||||
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'success', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'nat20', ctx)).enc;
|
||||
|
||||
expect(part(e).status).toBe('conscious');
|
||||
expect(part(e).currentHp).toBe(1);
|
||||
expect(part(e).deathSaveSuccesses).toBe(0);
|
||||
expect(part(e).deathSaveFailures).toBe(0);
|
||||
});
|
||||
|
||||
test('damage while dying adds one failure', async () => {
|
||||
let { e, ctx } = await startedAtZero();
|
||||
|
||||
e = await applyHpChange(e, 'a', 'damage', 1, ctx);
|
||||
|
||||
expect(part(e).status).toBe('dying');
|
||||
expect(part(e).deathSaveFailures).toBe(1);
|
||||
});
|
||||
|
||||
test('critical damage while dying adds two failures', async () => {
|
||||
let { e, ctx } = await startedAtZero();
|
||||
|
||||
e = await applyHpChange(e, 'a', 'damage', 1, { isCriticalHit: true }, ctx);
|
||||
|
||||
expect(part(e).status).toBe('dying');
|
||||
expect(part(e).deathSaveFailures).toBe(2);
|
||||
});
|
||||
|
||||
test('damage while stable returns to dying and applies failure', async () => {
|
||||
let { e, ctx } = await startedAtZero();
|
||||
|
||||
e = (await deathSave(e, 'a', 'success', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'success', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'success', ctx)).enc;
|
||||
expect(part(e).status).toBe('stable');
|
||||
|
||||
e = await applyHpChange(e, 'a', 'damage', 1, ctx);
|
||||
|
||||
expect(part(e).status).toBe('dying');
|
||||
expect(part(e).deathSaveSuccesses).toBe(0);
|
||||
expect(part(e).deathSaveFailures).toBe(1);
|
||||
});
|
||||
|
||||
test('healing while dying or stable makes conscious and clears counters', async () => {
|
||||
let { e, ctx } = await startedAtZero();
|
||||
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
e = await applyHpChange(e, 'a', 'heal', 10, ctx);
|
||||
expect(part(e).status).toBe('conscious');
|
||||
expect(part(e).currentHp).toBe(10);
|
||||
expect(part(e).deathSaveFailures).toBe(0);
|
||||
|
||||
e = await applyHpChange(e, 'a', 'damage', 10, ctx);
|
||||
e = (await deathSave(e, 'a', 'success', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'success', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'success', ctx)).enc;
|
||||
expect(part(e).status).toBe('stable');
|
||||
|
||||
e = await applyHpChange(e, 'a', 'heal', 5, ctx);
|
||||
expect(part(e).status).toBe('conscious');
|
||||
expect(part(e).currentHp).toBe(5);
|
||||
expect(part(e).deathSaveSuccesses).toBe(0);
|
||||
expect(part(e).deathSaveFailures).toBe(0);
|
||||
});
|
||||
|
||||
test('normal healing does not revive dead', async () => {
|
||||
let { e, ctx } = await startedAtZero();
|
||||
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
expect(part(e).status).toBe('dead');
|
||||
|
||||
try { e = await applyHpChange(e, 'a', 'heal', 10, ctx); } catch (err) {}
|
||||
|
||||
expect(part(e).status).toBe('dead');
|
||||
expect(part(e).currentHp).toBe(0);
|
||||
});
|
||||
|
||||
test('stabilize sets stable, hp zero, counters zero', async () => {
|
||||
let { e, ctx } = await startedAtZero();
|
||||
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
e = await stabilizeParticipant(e, 'a', ctx);
|
||||
|
||||
expect(part(e).status).toBe('stable');
|
||||
expect(part(e).currentHp).toBe(0);
|
||||
expect(part(e).deathSaveSuccesses).toBe(0);
|
||||
expect(part(e).deathSaveFailures).toBe(0);
|
||||
});
|
||||
|
||||
test('negative heal acts as damage and can drop to dying', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
let e = enc([pc('a', { currentHp: 1 })]);
|
||||
e = await startEncounter(e, ctx);
|
||||
|
||||
e = await applyHpChange(e, 'a', 'heal', -1, ctx);
|
||||
|
||||
expect(part(e).currentHp).toBe(0);
|
||||
expect(part(e).status).toBe('dying');
|
||||
});
|
||||
|
||||
test('negative damage acts as healing', async () => {
|
||||
let { e, ctx } = await startedAtZero();
|
||||
|
||||
e = await applyHpChange(e, 'a', 'damage', -5, ctx);
|
||||
|
||||
expect(part(e).currentHp).toBe(5);
|
||||
expect(part(e).status).toBe('conscious');
|
||||
});
|
||||
|
||||
test('revive moves dead participant to 0 HP stable/unconscious', async () => {
|
||||
let { e, ctx } = await startedAtZero();
|
||||
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
e = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||
expect(part(e).status).toBe('dead');
|
||||
|
||||
e = await reviveParticipant(e, 'a', ctx);
|
||||
|
||||
expect(part(e).currentHp).toBe(0);
|
||||
expect(part(e).status).toBe('stable');
|
||||
expect(part(e).deathSaveSuccesses).toBe(0);
|
||||
expect(part(e).deathSaveFailures).toBe(0);
|
||||
expect(part(e).conditions).toContain('unconscious');
|
||||
expect(part(e).isActive).toBe(true);
|
||||
});
|
||||
|
||||
test('death save outside dying state is rejected or no-op', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
let e = enc([pc('a')]);
|
||||
e = await startEncounter(e, ctx);
|
||||
|
||||
try { e = (await deathSave(e, 'a', 'fail', ctx)).enc; } catch (err) {}
|
||||
|
||||
expect(part(e).status).toBe('conscious');
|
||||
expect(part(e).deathSaveFailures).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -21,9 +21,9 @@ const {
|
||||
reorderParticipants, endEncounter,
|
||||
} = shared;
|
||||
|
||||
function p(id, init) {
|
||||
function p(id, init, extra = {}) {
|
||||
return makeParticipant({ id, name: id, type: 'monster',
|
||||
initiative: init, maxHp: 100, currentHp: 100 });
|
||||
initiative: init, maxHp: 100, currentHp: 100, ...extra });
|
||||
}
|
||||
function enc(ps, extra = {}) {
|
||||
return { name:'t', participants:ps, isStarted:false, isPaused:false,
|
||||
@@ -105,11 +105,11 @@ describe('Logging contract: mutating ops', () => {
|
||||
});
|
||||
|
||||
test('deathSave logs', async () => {
|
||||
const e = enc([p('a', 10), p('b', 7), p('c', 3)]);
|
||||
const e = enc([p('a', 10), p('b', 7, { type: 'character' }), p('c', 3)]);
|
||||
const started = await startEncounter(e, ctx); // 1 log
|
||||
const dying = await applyHpChange(started, 'b', 'damage', 100, ctx); // 2 logs
|
||||
const r = await deathSave(dying, 'b', 'fail', 1, ctx); // 3 logs
|
||||
expect(r.status).toBe('pending');
|
||||
const r = await deathSave(dying, 'b', 'fail', ctx); // 3 logs
|
||||
expect(r.status).toBe('dying');
|
||||
expect(storage.logs()).toHaveLength(3);
|
||||
expectLastLogged(storage);
|
||||
});
|
||||
|
||||
@@ -23,15 +23,24 @@ function enc(ps) {
|
||||
}
|
||||
|
||||
describe('reorderParticipants', () => {
|
||||
test('drag before target (1-list model, pre-combat)', async () => {
|
||||
test('drag upward inserts before target (1-list model, pre-combat)', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [p('a', 10), p('b', 20), p('c', 20)]; // b,c tie
|
||||
let e = enc(ps); // pre-combat, no pointer
|
||||
const newEnc = await reorderParticipants(e, 'c', 'b', ctx);
|
||||
// drag c before b: remove c → [a,b], insert before b → [a,c,b]
|
||||
// drag c upward onto b: insert before b → [a,c,b]
|
||||
expect(newEnc.participants.map(p => p.id)).toEqual(['a', 'c', 'b']);
|
||||
});
|
||||
|
||||
test('drag downward inserts after target (1-list model, pre-combat)', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [p('a', 20), p('b', 20), p('c', 10)]; // a,b tie
|
||||
let e = enc(ps); // pre-combat, no pointer
|
||||
const newEnc = await reorderParticipants(e, 'a', 'b', ctx);
|
||||
// drag a downward onto b: insert after b → [b,a,c]
|
||||
expect(newEnc.participants.map(p => p.id)).toEqual(['b', 'a', 'c']);
|
||||
});
|
||||
|
||||
test('cross-init drag blocked (no-op)', async () => {
|
||||
const { storage, ctx } = mockCtx();
|
||||
const ps = [p('a', 10), p('b', 20)];
|
||||
@@ -51,6 +60,19 @@ describe('reorderParticipants', () => {
|
||||
await expect(reorderParticipants(e, 'a', 'zzz', ctx)).rejects.toThrow();
|
||||
});
|
||||
|
||||
test('paused combat allows reorder across current-turn pointer', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [p('a', 20), p('b', 20), p('c', 20), p('d', 20)];
|
||||
let e = await startEncounter(enc(ps), ctx); // current=a
|
||||
e = { ...e, isPaused: true };
|
||||
|
||||
const newEnc = await reorderParticipants(e, 'd', 'a', ctx);
|
||||
|
||||
expect(newEnc).not.toBe(e);
|
||||
expect(newEnc.participants.map(p => p.id)).toEqual(['d', 'a', 'b', 'c']);
|
||||
expect(newEnc.turnOrderIds).toEqual(['d', 'a', 'b', 'c']);
|
||||
});
|
||||
|
||||
test('syncs turnOrderIds = participants order (1-list, fixes BUG-6)', async () => {
|
||||
const { ctx } = mockCtx();
|
||||
const ps = [p('a', 10), p('b', 20), p('c', 20)];
|
||||
|
||||
@@ -33,7 +33,7 @@ function setup(ctx) {
|
||||
buildMonsterParticipant({ name: 'Goblin2', maxHp: 100, initMod: 2 }).participant,
|
||||
buildMonsterParticipant({ name: 'OrcBoss', maxHp: 500, initMod: 1 }).participant,
|
||||
buildMonsterParticipant({ name: 'Wolf', maxHp: 120, initMod: 3 }).participant,
|
||||
buildMonsterParticipant({ name: 'Merchant', maxHp: 150, initMod: 0, isNpc: true }).participant,
|
||||
buildMonsterParticipant({ name: 'Merchant', maxHp: 150, initMod: 0, asNpc: true }).participant,
|
||||
];
|
||||
let e = {
|
||||
name: 't', participants: ps, isStarted: false, isPaused: false,
|
||||
|
||||
+195
-64
@@ -52,6 +52,18 @@ function slotIndexForInit(list, init) {
|
||||
return list.length;
|
||||
}
|
||||
|
||||
function withDeathStatusConditions(participant, updates) {
|
||||
const status = updates.status !== undefined ? updates.status : participant.status;
|
||||
const current = participant.conditions || [];
|
||||
let conditions = current;
|
||||
if (status === 'dying' || status === 'stable') {
|
||||
conditions = current.includes('unconscious') ? current : [...current, 'unconscious'];
|
||||
} else if (status === 'conscious' || status === 'dead') {
|
||||
conditions = current.filter(c => c !== 'unconscious');
|
||||
}
|
||||
return { ...updates, conditions };
|
||||
}
|
||||
|
||||
const syncTurnOrder = (participants) => ({
|
||||
turnOrderIds: participants.map(p => p.id),
|
||||
});
|
||||
@@ -282,13 +294,11 @@ function makeParticipant(opts) {
|
||||
initiative: opts.initiative,
|
||||
maxHp: opts.maxHp,
|
||||
currentHp: opts.currentHp,
|
||||
isNpc: opts.isNpc || false,
|
||||
conditions: opts.conditions || [],
|
||||
isActive: opts.isActive !== undefined ? opts.isActive : true,
|
||||
deathSaves: opts.deathSaves || 0,
|
||||
deathFails: opts.deathFails || 0,
|
||||
isStable: opts.isStable || false,
|
||||
isDying: opts.isDying || false,
|
||||
status: opts.status || (opts.currentHp === 0 ? 'dying' : 'conscious'),
|
||||
deathSaveSuccesses: opts.deathSaveSuccesses || 0,
|
||||
deathSaveFailures: opts.deathSaveFailures || 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -305,13 +315,12 @@ function buildCharacterParticipant(character) {
|
||||
initiative: finalInitiative,
|
||||
maxHp,
|
||||
currentHp: maxHp,
|
||||
isNpc: false,
|
||||
}),
|
||||
roll: { roll: initiativeRoll, mod: modifier, total: finalInitiative },
|
||||
};
|
||||
}
|
||||
|
||||
function buildMonsterParticipant({ name, maxHp, initMod, isNpc }) {
|
||||
function buildMonsterParticipant({ name, maxHp, initMod, asNpc }) {
|
||||
const initiativeRoll = rollD20();
|
||||
const modifier = initMod !== undefined ? initMod : MONSTER_DEFAULT_INIT_MOD;
|
||||
const finalInitiative = initiativeRoll + modifier;
|
||||
@@ -319,11 +328,10 @@ function buildMonsterParticipant({ name, maxHp, initMod, isNpc }) {
|
||||
return {
|
||||
participant: makeParticipant({
|
||||
name,
|
||||
type: 'monster',
|
||||
type: asNpc ? 'npc' : 'monster',
|
||||
initiative: finalInitiative,
|
||||
maxHp: hp,
|
||||
currentHp: hp,
|
||||
isNpc: isNpc || false,
|
||||
}),
|
||||
roll: { roll: initiativeRoll, mod: modifier, total: finalInitiative },
|
||||
};
|
||||
@@ -519,85 +527,145 @@ async function toggleParticipantActive(encounter, participantId, ctx) {
|
||||
return commit(encounter, patch, log, ctx);
|
||||
}
|
||||
|
||||
async function applyHpChange(encounter, participantId, changeType, amount, ctx) {
|
||||
async function applyHpChange(encounter, participantId, changeType, amount, optionsOrCtx, maybeCtx) {
|
||||
const ctx = maybeCtx || optionsOrCtx;
|
||||
const options = maybeCtx ? (optionsOrCtx || {}) : {};
|
||||
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
||||
if (!participant) throw new Error('Participant not found.');
|
||||
if (isNaN(amount) || amount === 0) return encounter; // no-op, no write
|
||||
let newHp = participant.currentHp;
|
||||
if (changeType === 'damage') newHp = Math.max(0, participant.currentHp - amount);
|
||||
else if (changeType === 'heal') newHp = Math.min(participant.maxHp, participant.currentHp + amount);
|
||||
const wasDead = participant.currentHp === 0;
|
||||
const isDead = newHp === 0;
|
||||
const wasResurrected = wasDead && newHp > 0;
|
||||
const updatedParticipants = (encounter.participants || []).map(p => {
|
||||
if (p.id !== participantId) return p;
|
||||
const updates = { ...p, currentHp: newHp };
|
||||
if (isDead && !wasDead) {
|
||||
updates.isActive = false;
|
||||
updates.deathSaves = p.deathSaves || 0;
|
||||
updates.isDying = false;
|
||||
if (isNaN(amount) || amount === 0) return encounter;
|
||||
if (amount < 0) {
|
||||
amount = Math.abs(amount);
|
||||
changeType = changeType === 'damage' ? 'heal' : 'damage';
|
||||
}
|
||||
|
||||
const oldValues = {
|
||||
currentHp: participant.currentHp,
|
||||
status: participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious'),
|
||||
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||
isActive: participant.isActive,
|
||||
};
|
||||
|
||||
let updates = {};
|
||||
let message = '';
|
||||
let logDelta = { amount, from: participant.currentHp };
|
||||
const status = oldValues.status;
|
||||
|
||||
if (changeType === 'damage') {
|
||||
if (participant.currentHp === 0) {
|
||||
if (status === 'dead') {
|
||||
if (participant.type === 'monster' && participant.isActive !== false) {
|
||||
const updatedParticipants = (encounter.participants || []).map(p =>
|
||||
p.id === participantId ? { ...p, isActive: false } : p
|
||||
);
|
||||
const patch = { participants: updatedParticipants };
|
||||
const log = {
|
||||
type: 'deactivate_dead_monster',
|
||||
participantId,
|
||||
participantName: participant.name,
|
||||
message: `${participant.name} marked inactive (dead monster)`,
|
||||
delta: { status: 'dead', isActive: false },
|
||||
undo: { oldValues },
|
||||
};
|
||||
return commit(encounter, patch, log, ctx);
|
||||
}
|
||||
return encounter;
|
||||
}
|
||||
const add = options.isCriticalHit ? 2 : 1;
|
||||
const failures = (status === 'stable' ? 0 : (participant.deathSaveFailures || 0)) + add;
|
||||
if (failures >= 3) {
|
||||
updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0, ...(participant.type === 'monster' ? { isActive: false } : {}) };
|
||||
} else {
|
||||
updates = { currentHp: 0, status: 'dying', deathSaveSuccesses: 0, deathSaveFailures: failures };
|
||||
}
|
||||
message = `${participant.name} took ${amount} damage while ${status === 'stable' ? 'stable' : 'dying'}`;
|
||||
logDelta = { ...logDelta, to: 0, status: updates.status, deathSaveFailures: updates.deathSaveFailures };
|
||||
} else if (amount >= participant.currentHp + participant.maxHp) {
|
||||
updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0, ...(participant.type === 'monster' ? { isActive: false } : {}) };
|
||||
message = `Massive damage! ${participant.name} instantly killed`;
|
||||
logDelta = { ...logDelta, to: 0, status: 'dead', massive: true };
|
||||
} else {
|
||||
const newHp = Math.max(0, participant.currentHp - amount);
|
||||
if (newHp === 0) {
|
||||
const zeroStatus = participant.type === 'monster' ? 'dead' : 'dying';
|
||||
updates = { currentHp: 0, status: zeroStatus, deathSaveSuccesses: 0, deathSaveFailures: 0, ...(zeroStatus === 'dead' ? { isActive: false } : {}) };
|
||||
} else {
|
||||
updates = { currentHp: newHp, status: 'conscious' };
|
||||
}
|
||||
message = `${participant.name} took ${amount} damage (${participant.currentHp} → ${newHp} HP)`;
|
||||
logDelta = { ...logDelta, to: newHp, status: updates.status };
|
||||
}
|
||||
if (wasResurrected) {
|
||||
updates.isActive = true;
|
||||
updates.deathSaves = 0;
|
||||
updates.isDying = false;
|
||||
}
|
||||
return updates;
|
||||
});
|
||||
const hpLine = `${participant.currentHp} → ${newHp} HP`;
|
||||
const deathSuffix = (isDead && !wasDead) ? (participant.type === 'character' ? ' — Unconscious' : ' — Defeated') : '';
|
||||
const resurSuffix = wasResurrected ? ' — Revived' : '';
|
||||
const message = changeType === 'damage'
|
||||
? `${participant.name} took ${amount} damage (${hpLine})${deathSuffix}`
|
||||
: `${participant.name} healed for ${amount} (${hpLine})${resurSuffix}`;
|
||||
} else if (changeType === 'heal') {
|
||||
if (status === 'dead') return encounter;
|
||||
const newHp = Math.min(participant.maxHp, Math.max(1, participant.currentHp + amount));
|
||||
updates = { currentHp: newHp, status: 'conscious', deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
||||
message = `${participant.name} healed for ${amount} (${participant.currentHp} → ${newHp} HP)`;
|
||||
logDelta = { ...logDelta, to: newHp, status: 'conscious', deathSavesCleared: true };
|
||||
} else {
|
||||
throw new Error(`Unknown HP change type: ${changeType}`);
|
||||
}
|
||||
|
||||
const updatedParticipants = (encounter.participants || []).map(p =>
|
||||
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p
|
||||
);
|
||||
const patch = { participants: updatedParticipants };
|
||||
// undo: inverse amount (damage→heal, heal→damage). expandUndo uses sign.
|
||||
const undoAmount = changeType === 'damage' ? amount : -amount;
|
||||
const log = {
|
||||
type: changeType,
|
||||
participantId, participantName: participant.name,
|
||||
message,
|
||||
delta: { amount, from: participant.currentHp, to: newHp },
|
||||
undo: { amount: undoAmount },
|
||||
delta: logDelta,
|
||||
undo: { amount: undoAmount, oldValues },
|
||||
};
|
||||
return commit(encounter, patch, log, ctx);
|
||||
}
|
||||
|
||||
// DEATH_SAVE — returns { enc, status, isDying } so caller knows terminal state.
|
||||
async function deathSave(encounter, participantId, type, n, ctx) {
|
||||
async function deathSave(encounter, participantId, outcome, ctx) {
|
||||
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
||||
if (!participant) throw new Error('Participant not found.');
|
||||
if (type !== 'success' && type !== 'fail') {
|
||||
throw new Error(`deathSave type must be 'success' or 'fail', got "${type}".`);
|
||||
const statusBefore = participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious');
|
||||
if (statusBefore !== 'dying') throw new Error('Death saves only apply while dying.');
|
||||
if (!['success', 'fail', 'nat1', 'nat20'].includes(outcome)) {
|
||||
throw new Error(`deathSave outcome must be success, fail, nat1, or nat20; got "${outcome}".`);
|
||||
}
|
||||
|
||||
const oldValues = {
|
||||
currentHp: participant.currentHp,
|
||||
status: statusBefore,
|
||||
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||
};
|
||||
|
||||
let updates;
|
||||
if (outcome === 'nat20') {
|
||||
updates = { currentHp: 1, status: 'conscious', deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
||||
} else {
|
||||
const successes = (participant.deathSaveSuccesses || 0) + (outcome === 'success' ? 1 : 0);
|
||||
const failures = (participant.deathSaveFailures || 0) + (outcome === 'fail' ? 1 : outcome === 'nat1' ? 2 : 0);
|
||||
if (failures >= 3) updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
||||
else if (successes >= 3) updates = { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
||||
else updates = { currentHp: 0, status: 'dying', deathSaveSuccesses: successes, deathSaveFailures: failures };
|
||||
}
|
||||
|
||||
const name = participant.name;
|
||||
const current = type === 'success' ? (participant.deathSaves || 0) : (participant.deathFails || 0);
|
||||
const next = current === n ? n - 1 : n;
|
||||
const field = type === 'success' ? 'deathSaves' : 'deathFails';
|
||||
const updates = { [field]: next };
|
||||
let status = 'pending';
|
||||
const newSuccesses = type === 'success' ? next : (participant.deathSaves || 0);
|
||||
const newFails = type === 'fail' ? next : (participant.deathFails || 0);
|
||||
if (newSuccesses >= 3) { updates.isStable = true; updates.isDying = false; status = 'stable'; }
|
||||
else if (newFails >= 3) { updates.isStable = false; updates.isDying = true; status = 'dead'; }
|
||||
else { updates.isStable = false; updates.isDying = false; }
|
||||
const message = outcome === 'nat20' ? `Nat 20! ${name} restored to 1 HP, conscious`
|
||||
: outcome === 'nat1' ? `Nat 1! ${name} takes 2 death save failures`
|
||||
: updates.status === 'stable' ? `${name} stabilized (3 death saves)`
|
||||
: updates.status === 'dead' ? `${name} failed 3 death saves — dead`
|
||||
: `${name} death save ${outcome}`;
|
||||
const updatedParticipants = (encounter.participants || []).map(p =>
|
||||
p.id === participantId ? { ...p, ...updates } : p
|
||||
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p
|
||||
);
|
||||
const message = status === 'stable' ? `${name} stabilized (3 death saves)`
|
||||
: status === 'dead' ? `${name} failed 3 death saves — dead`
|
||||
: `${name} death ${type}: ${next}/3`;
|
||||
const patch = { participants: updatedParticipants };
|
||||
const oldValues = { [field]: participant[field] || 0, isStable: participant.isStable || false, isDying: participant.isDying || false };
|
||||
const log = {
|
||||
type: 'death_save',
|
||||
participantId, participantName: name,
|
||||
message,
|
||||
delta: { type, count: next, status },
|
||||
delta: { outcome, status: updates.status, deathSaveSuccesses: updates.deathSaveSuccesses, deathSaveFailures: updates.deathSaveFailures },
|
||||
undo: { oldValues },
|
||||
};
|
||||
const enc = await commit(encounter, patch, log, ctx);
|
||||
return { enc, status, isDying: status === 'dead' };
|
||||
return { enc, status: updates.status };
|
||||
}
|
||||
|
||||
async function toggleCondition(encounter, participantId, conditionId, ctx) {
|
||||
@@ -621,6 +689,67 @@ async function toggleCondition(encounter, participantId, conditionId, ctx) {
|
||||
return commit(encounter, patch, log, ctx);
|
||||
}
|
||||
|
||||
async function stabilizeParticipant(encounter, participantId, ctx) {
|
||||
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
||||
if (!participant) throw new Error('Participant not found.');
|
||||
const status = participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious');
|
||||
if (status === 'conscious' || participant.currentHp > 0) throw new Error('Cannot stabilize conscious participant.');
|
||||
if (status === 'dead') throw new Error('Cannot stabilize dead participant.');
|
||||
if (status === 'stable') return encounter;
|
||||
|
||||
const updates = { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
||||
const updatedParticipants = (encounter.participants || []).map(p =>
|
||||
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p
|
||||
);
|
||||
|
||||
const patch = { participants: updatedParticipants };
|
||||
const oldValues = {
|
||||
currentHp: participant.currentHp,
|
||||
status,
|
||||
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||
};
|
||||
const log = {
|
||||
type: 'stabilize',
|
||||
participantId,
|
||||
participantName: participant.name,
|
||||
message: `${participant.name} stabilized at 0 HP`,
|
||||
delta: { status: 'stable' },
|
||||
undo: { oldValues },
|
||||
};
|
||||
return commit(encounter, patch, log, ctx);
|
||||
}
|
||||
|
||||
async function reviveParticipant(encounter, participantId, ctx) {
|
||||
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
||||
if (!participant) throw new Error('Participant not found.');
|
||||
const status = participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious');
|
||||
if (status !== 'dead') return encounter;
|
||||
|
||||
const updates = { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0, isActive: true };
|
||||
const updatedParticipants = (encounter.participants || []).map(p =>
|
||||
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p
|
||||
);
|
||||
|
||||
const patch = { participants: updatedParticipants };
|
||||
const oldValues = {
|
||||
currentHp: participant.currentHp,
|
||||
status,
|
||||
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||
isActive: participant.isActive,
|
||||
};
|
||||
const log = {
|
||||
type: 'revive',
|
||||
participantId,
|
||||
participantName: participant.name,
|
||||
message: `${participant.name} revived to 0 HP (stable, unconscious)`,
|
||||
delta: { status: 'stable', currentHp: 0 },
|
||||
undo: { oldValues },
|
||||
};
|
||||
return commit(encounter, patch, log, ctx);
|
||||
}
|
||||
|
||||
async function reorderParticipants(encounter, draggedId, targetId, ctx) {
|
||||
const participants = [...(encounter.participants || [])];
|
||||
const dragged = participants.find(p => p.id === draggedId);
|
||||
@@ -629,7 +758,7 @@ async function reorderParticipants(encounter, draggedId, targetId, ctx) {
|
||||
if (draggedId === targetId) return encounter; // no-op, no write
|
||||
if (dragged.initiative !== target.initiative) return encounter; // cross-init blocked
|
||||
const draggedIndex = participants.findIndex(p => p.id === draggedId);
|
||||
if (encounter.isStarted && encounter.currentTurnParticipantId) {
|
||||
if (encounter.isStarted && !encounter.isPaused && encounter.currentTurnParticipantId) {
|
||||
const pointerIdx = participants.findIndex(p => p.id === encounter.currentTurnParticipantId);
|
||||
const targetIdx0 = participants.findIndex(p => p.id === targetId);
|
||||
if (pointerIdx >= 0) {
|
||||
@@ -637,9 +766,11 @@ async function reorderParticipants(encounter, draggedId, targetId, ctx) {
|
||||
if (crosses(draggedIndex, targetIdx0)) return encounter; // cross-pointer blocked
|
||||
}
|
||||
}
|
||||
const targetIndex = participants.findIndex(p => p.id === targetId);
|
||||
const [removedItem] = participants.splice(draggedIndex, 1);
|
||||
const newTargetIndex = participants.findIndex(p => p.id === targetId);
|
||||
participants.splice(newTargetIndex, 0, removedItem);
|
||||
const insertIndex = draggedIndex < targetIndex ? newTargetIndex + 1 : newTargetIndex;
|
||||
participants.splice(insertIndex, 0, removedItem);
|
||||
const patch = { participants, ...syncTurnOrder(participants) };
|
||||
const log = {
|
||||
type: 'reorder',
|
||||
@@ -687,7 +818,7 @@ module.exports = {
|
||||
makeParticipant, buildCharacterParticipant, buildMonsterParticipant,
|
||||
startEncounter, nextTurn, togglePause,
|
||||
addParticipant, addParticipants, updateParticipant, removeParticipant,
|
||||
toggleParticipantActive, applyHpChange, deathSave, toggleCondition,
|
||||
toggleParticipantActive, applyHpChange, deathSave, stabilizeParticipant, reviveParticipant, toggleCondition,
|
||||
reorderParticipants, endEncounter,
|
||||
activateDisplay, clearDisplay, toggleHidePlayerHp,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user