V1.21.0: a DM's toolkit: the battle at a glance, subclasses, character state, rolls, XP

Seven steps in one commit, 1.15.0 to 1.21.0. They change the same files
and were not saved apart, so they go in together.

- The battle at a glance (1.15). A strip across the top of an encounter
  lists everyone in turn order and stays in view; a click goes to that
  card. On a wide screen the stat block of whoever is on turn stays
  beside the cards, and Pin keeps anyone else's there. Saving throws,
  every skill and passive Perception, Investigation and Insight are on
  encounter cards and in the character panel, which "Sheet" on a card
  and a button on the party overview open. For the DM, N is Next Turn
  and S opens the sheet of whoever is on turn. The party overview shows
  passive scores and spell save DC.
- Subclasses (1.16). Three per class, picked in the level-up checklist
  at level 2 (cleric, druid, wizard) or 3, shown beside the class
  everywhere, and changed by the DM from the sheet: the old one's lines
  come out of Special Abilities and the new one's go in. Characters
  already at that level keep the path they were on.
- Character state (1.17). Inspiration, exhaustion and conditions on the
  sheet and in the panel, and counters for what a class does a set
  number of times (Rage, Ki, Channel Divinity...), which the player
  spends and a rest gives back. A long rest takes a level of exhaustion
  off. A character's conditions are their own now: they stay from one
  encounter to the next.
- Faster battles (1.18). Up to 20 of a monster added at once, numbered.
  One button rolls initiative for the monsters and NPCs. A condition can
  be given a number of rounds and then comes off by itself. Hovering
  over a condition shows its rule, and damaging someone who is
  Concentrating shows the save to call for.
- Rolls from the sheet (1.19). A number with a dotted underline rolls
  when clicked, with its bonus: skills, saves, ability checks, attacks,
  damage, spell dice, and a monster's attack, damage and abilities. The
  dice roller has advantage and disadvantage. "Call for a roll" rolls
  one check or save for the whole party. Rolls stay in the browser.
- XP and difficulty (1.20). An encounter shows the DM how hard it is,
  Trivial to Deadly, from the monsters' challenge ratings against the
  characters in it, and what it is worth in XP; one button shares that
  out, once. The sheet and the party overview show XP and when a level
  is due. Levelling up stays the DM's decision.
- Subclasses are optional per campaign (1.21). With "Characters choose a
  subclass" unticked in the campaign's Settings nobody is asked, each
  class follows its first subclass, and none is named.
- Conditions, exhaustion, counters and subclass features are reminders
  for the table: none of them changes a number on the sheet.
- The docs cover all of it, with generated tables of what each subclass
  adds.
- New migrations: a character's subclass; inspiration, exhaustion,
  conditions and spent counters on a character; the rounds left on a
  combatant's conditions; the XP awarded for an encounter; the
  campaign's subclass setting.
- All packages at version 1.21.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-10 17:36:27 +02:00
co-authored by Claude Opus 5.5
parent 61221f262c
commit 57fba68a48
50 changed files with 4706 additions and 592 deletions
+373 -4
View File
@@ -1623,6 +1623,38 @@ describe('encounter combat info', () => {
expect(participant.characterCombatInfo.weapons[0].name).toBe('Dagger');
expect(typeof participant.characterCombatInfo.weapons[0].attackBonus).toBe('number');
});
itIfDb('sends saves, skills and passive scores with a combatant, in the character panel and on the party list', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('glance');
const characterId = await buildCharacter(campaign.id, playerAuth, 'Glance');
const { sheet } = (await request(app).get(`/characters/${characterId}`).set(dmAuth)).body.character;
const encounterId = (await request(app).post(`/campaigns/${campaign.id}/encounters`).set(dmAuth).send({ name: 'Glance' })).body.encounter.id;
await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ characterId });
const info = (await request(app).get(`/encounters/${encounterId}`).set(dmAuth)).body.encounter.participants[0].characterCombatInfo;
expect(info.skills).toEqual(sheet.skills);
expect(info.saves).toEqual(sheet.saves);
expect(info.passiveInvestigation).toBe(10 + sheet.skills.INVESTIGATION.bonus);
expect(info.passiveInsight).toBe(10 + sheet.skills.INSIGHT.bonus);
const quick = (await request(app).get(`/characters/${characterId}/quick-stats`).set(dmAuth)).body.quickStats;
expect(quick.skills).toEqual(sheet.skills);
expect(quick.saves).toEqual(sheet.saves);
expect(quick.passiveInsight).toBe(sheet.passiveInsight);
const listed = (await request(app).get(`/campaigns/${campaign.id}/characters`).set(dmAuth)).body.characters.find((c) => c.id === characterId);
expect(listed.passives).toEqual({ perception: sheet.passivePerception, investigation: sheet.passiveInvestigation, insight: sheet.passiveInsight });
expect(listed.spellSaveDC).toBe(sheet.spellcasting ? sheet.spellcasting.saveDC : null);
// And what each rolls with, for a check called for from the whole party.
expect(listed.checks).toEqual({ abilities: sheet.abilities, saves: sheet.saves, skills: sheet.skills });
// A held weapon says what its holder rolls with it.
const weaponId = (await request(app).post(`/campaigns/${campaign.id}/weapons/from-library`).set(dmAuth).send({ key: 'dagger' })).body.weapon.id;
await request(app).post(`/characters/${characterId}/weapons`).set(dmAuth).send({ weaponId });
const held = (await request(app).get(`/characters/${characterId}`).set(dmAuth)).body.character.weapons[0];
const finesse = Math.max(sheet.abilities.STR.modifier, sheet.abilities.DEX.modifier);
expect(held).toMatchObject({ attackBonus: finesse + sheet.proficiencyBonus, damageBonus: finesse });
});
});
describe('changing a password', () => {
@@ -3004,8 +3036,16 @@ describe('levelling up', () => {
expect(character.currentHp).toBe(plan.maxHp.to);
expect(character.specialAbilities).toBe('Action Surge — Once per short rest, take one extra action on your turn.');
// Level 4 grants a Boon, which has to be picked.
await levelUp(dmAuth);
// Level 3 is where a fighter picks a subclass, which has to be one of theirs.
const choice = (await request(app).get(`/characters/${characterId}/level-up`).set(dmAuth)).body.plan.subclass;
expect(choice.options.map((o) => o.key)).toEqual(['CHAMPION', 'BATTLE_MASTER', 'SAMURAI']);
expect((await levelUp(dmAuth)).status).toBe(400);
expect((await levelUp(dmAuth, { subclass: 'LIFE' })).status).toBe(400);
const champion = (await levelUp(dmAuth, { subclass: 'CHAMPION' })).body.character;
expect(champion).toMatchObject({ level: 3, subclass: 'CHAMPION', subclassName: 'Champion' });
// Level 4 grants a Boon, which has to be picked. There is no second subclass to pick.
expect((await levelUp(dmAuth, { boon: 'TOUGHENED', subclass: 'SAMURAI' })).status).toBe(400);
expect((await levelUp(dmAuth)).status).toBe(400);
expect((await levelUp(dmAuth, { boon: 'FLIGHT' })).status).toBe(400);
const toughened = (await levelUp(dmAuth, { boon: 'TOUGHENED' })).body.character;
@@ -3052,9 +3092,11 @@ describe('levelling up', () => {
expect((await levelUp({ weaponId: 'not-held' })).status).toBe(400);
expect((await levelUp({ spellIds: [foreignSpellId] })).status).toBe(400);
// A spell already known is simply kept.
const character = (await levelUp({ weaponId, spellIds: [boltId, wardId] })).body.character;
// A wizard picks a school at level 2. A spell already known is simply kept.
expect(plan.subclass.level).toBe(2);
const character = (await levelUp({ weaponId, spellIds: [boltId, wardId], subclass: 'ILLUSION' })).body.character;
expect(character.level).toBe(2);
expect(character.specialAbilities).toMatch(/^Illusion Savant — School of Illusion/m);
expect(character.weapons[0]).toMatchObject({ weaponId, level: 2, scaledDamageDice: '1d6' });
expect(character.spells.map((s) => s.spell.name).sort()).toEqual(['Test Bolt', 'Test Ward']);
expect(character.sheet.spellSlots.levels).toEqual([{ level: 1, max: 3, used: 0, remaining: 3 }]);
@@ -3075,6 +3117,7 @@ describe('levelling up', () => {
expect(lines[0]).toMatch(/^Sneak Attack — .*2d6/);
expect(lines).toContainEqual(expect.stringMatching(/^Cunning Action — /));
expect(lines).toContainEqual(expect.stringMatching(/^Boon \(level 4\) — Choose one/));
expect(lines).toContainEqual('Subclass — Choose one with your DM: Thief, Assassin, Swashbuckler.');
// Going down takes nothing away, and coming back up adds nothing twice.
await patch({ level: 1 });
@@ -3086,4 +3129,330 @@ describe('levelling up', () => {
await patch({ level: 20 });
expect((await request(app).post(`/characters/${characterId}/level-up`).set(dmAuth).send({})).status).toBe(400);
});
itIfDb('the DM sets and changes a subclass on the sheet; its lines follow', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('subclass');
const characterId = await buildAs(campaign.id, playerAuth, 'Sly', 'ROGUE');
const patch = (auth, body) => request(app).patch(`/characters/${characterId}`).set(auth).send(body);
const names = (res) => res.body.character.specialAbilities.split('\n').map((line) => line.split(' — ')[0]);
// Too early, not theirs, and not the player's to set.
expect((await patch(dmAuth, { subclass: 'THIEF' })).status).toBe(400);
await patch(dmAuth, { level: 3 });
expect((await patch(dmAuth, { subclass: 'CHAMPION' })).status).toBe(400);
expect((await patch(playerAuth, { subclass: 'THIEF' })).status).toBe(403);
const thief = await patch(dmAuth, { subclass: 'THIEF' });
expect(thief.body.character).toMatchObject({ subclass: 'THIEF', subclassName: 'Thief' });
expect(names(thief)).toEqual(['Cunning Action', 'Sneak Attack', 'Fast Hands', 'Second-Story Work']);
// From here the Level field writes the subclass's features too.
expect(names(await patch(dmAuth, { level: 9 }))).toContain('Supreme Sneak');
const assassin = await patch(dmAuth, { subclass: 'ASSASSIN' });
expect(names(assassin)).toEqual(expect.arrayContaining(['Assassinate', 'Tools of the Trade', 'Infiltration Expertise', 'Uncanny Dodge']));
expect(names(assassin)).not.toContain('Fast Hands');
expect(names(assassin)).not.toContain('Supreme Sneak');
// Everyone who can see the character sees the subclass.
const listed = (await request(app).get(`/campaigns/${campaign.id}/characters`).set(playerAuth)).body.characters.find((c) => c.id === characterId);
expect(listed.subclassName).toBe('Assassin');
expect((await request(app).get(`/characters/${characterId}/quick-stats`).set(playerAuth)).body.quickStats.subclassName).toBe('Assassin');
// Cleared, the choice is owed again.
const cleared = await patch(dmAuth, { subclass: null });
expect(cleared.body.character.subclass).toBeNull();
expect(names(cleared)).toContain('Subclass');
expect(names(cleared)).not.toContain('Assassinate');
});
});
describe('character state', () => {
itIfDb('class counters: the player spends, only the DM gives back, and rests refill them', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('counters');
const characterId = await buildAs(campaign.id, playerAuth, 'Brakk', 'FIGHTER', 9);
const resources = (auth, body) => request(app).post(`/characters/${characterId}/resources`).set(auth).send(body);
const left = (res) => Object.fromEntries(res.body.character.sheet.resources.map((r) => [r.key, r.remaining]));
const sheet = (await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character.sheet;
expect(sheet.resources.map((r) => r.key)).toEqual(['SECOND_WIND', 'ACTION_SURGE', 'INDOMITABLE']);
const used = await resources(playerAuth, { action: 'use', key: 'SECOND_WIND' });
expect(used.status).toBe(200);
expect(left(used)).toEqual({ SECOND_WIND: 0, ACTION_SURGE: 1, INDOMITABLE: 1 });
// None left, no such counter, and not the player's to give back.
const again = await resources(playerAuth, { action: 'use', key: 'SECOND_WIND' });
expect(again.status).toBe(400);
expect(again.body.error).toMatch(/short or long rest/);
expect((await resources(playerAuth, { action: 'use', key: 'RAGE' })).status).toBe(400);
expect((await resources(playerAuth, { action: 'set', key: 'SECOND_WIND', used: 0 })).status).toBe(403);
expect((await resources(playerAuth, { action: 'restore' })).status).toBe(403);
await resources(playerAuth, { action: 'use', key: 'INDOMITABLE' });
expect(left(await resources(dmAuth, { action: 'set', key: 'SECOND_WIND', used: 0 }))).toMatchObject({ SECOND_WIND: 1, INDOMITABLE: 0 });
await resources(playerAuth, { action: 'use', key: 'ACTION_SURGE' });
// A short rest gives back Action Surge, not Indomitable; a long rest everything.
const rest = (type) => request(app).post(`/campaigns/${campaign.id}/rest`).set(dmAuth).send({ type, characters: [{ characterId }] });
expect((await rest('SHORT')).body.results[0].notes).toContain('Back: Action Surge.');
const after = (await request(app).get(`/campaigns/${campaign.id}/characters`).set(dmAuth)).body.characters.find((c) => c.id === characterId);
expect(after.resources.find((r) => r.key === 'INDOMITABLE').remaining).toBe(0);
expect((await rest('LONG')).body.results[0].notes).toContain('Back: Indomitable.');
expect(left(await resources(dmAuth, { action: 'restore' }))).toEqual({ SECOND_WIND: 1, ACTION_SURGE: 1, INDOMITABLE: 1 });
// A pool is spent several at a time, never past what is left.
const paladinId = await buildAs(campaign.id, playerAuth, 'Sera', 'PALADIN', 2);
const pool = (body) => request(app).post(`/characters/${paladinId}/resources`).set(playerAuth).send(body);
expect(left(await pool({ action: 'use', key: 'LAY_ON_HANDS', amount: 7 })).LAY_ON_HANDS).toBe(3);
const tooMuch = await pool({ action: 'use', key: 'LAY_ON_HANDS', amount: 4 });
expect(tooMuch.status).toBe(400);
expect(tooMuch.body.error).toMatch(/only 3/);
});
itIfDb('inspiration is given by the DM and spent by the player; exhaustion and conditions are for the DM', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('state');
const characterId = await buildCharacter(campaign.id, playerAuth, 'Aria');
const patch = (auth, body) => request(app).patch(`/characters/${characterId}`).set(auth).send(body);
expect((await patch(playerAuth, { inspiration: true })).status).toBe(403);
expect((await patch(dmAuth, { inspiration: true })).body.character.inspiration).toBe(true);
expect((await patch(playerAuth, { inspiration: false })).body.character.inspiration).toBe(false);
expect((await patch(playerAuth, { exhaustion: 0 })).status).toBe(403);
expect((await patch(playerAuth, { conditions: [] })).status).toBe(403);
expect((await patch(dmAuth, { exhaustion: 7 })).status).toBe(400);
const state = (await patch(dmAuth, { exhaustion: 2, conditions: ['Poisoned', 'Poisoned', 'Prone'] })).body.character;
expect(state).toMatchObject({ exhaustion: 2, conditions: ['Poisoned', 'Prone'] });
// A long rest takes one level of exhaustion off; conditions stay.
await request(app).post(`/campaigns/${campaign.id}/rest`).set(dmAuth).send({ type: 'LONG', characters: [{ characterId }] });
const listed = (await request(app).get(`/campaigns/${campaign.id}/characters`).set(playerAuth)).body.characters.find((c) => c.id === characterId);
expect(listed).toMatchObject({ exhaustion: 1, conditions: ['Poisoned', 'Prone'], inspiration: false });
});
itIfDb('conditions belong to the character: an encounter shows and changes them, and they outlast it', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('conditions');
const characterId = await buildCharacter(campaign.id, playerAuth, 'Aria');
await request(app).patch(`/characters/${characterId}`).set(dmAuth).send({ conditions: ['Poisoned'] });
await request(app).post(`/campaigns/${campaign.id}/monsters/from-library`).set(dmAuth).send({ key: 'kobold' });
const monsterId = (await request(app).get(`/campaigns/${campaign.id}/monsters`).set(dmAuth)).body.monsters[0].id;
const encounterId = (await request(app).post(`/campaigns/${campaign.id}/encounters`).set(dmAuth).send({ name: 'Bog' })).body.encounter.id;
const add = (body) => request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send(body);
const hero = (await add({ characterId })).body.participant;
const kobold = (await add({ monsterId })).body.participant;
const view = async () => (await request(app).get(`/encounters/${encounterId}`).set(playerAuth)).body.encounter.participants;
const find = (list, id) => list.find((p) => p.id === id);
// Poisoned before the fight, poisoned in it.
expect(find(await view(), hero.id).conditions).toEqual(['Poisoned']);
const patch = (id, body) => request(app).patch(`/encounters/${encounterId}/participants/${id}`).set(dmAuth).send(body);
await patch(hero.id, { conditions: ['Poisoned', 'Prone'] });
await patch(kobold.id, { conditions: ['Frightened'] });
const during = await view();
expect(find(during, hero.id).conditions).toEqual(['Poisoned', 'Prone']);
expect(find(during, kobold.id).conditions).toEqual(['Frightened']);
await request(app).delete(`/encounters/${encounterId}`).set(dmAuth);
expect((await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character.conditions).toEqual(['Poisoned', 'Prone']);
});
});
describe('faster battles', () => {
async function scene(prefix) {
const { dmAuth, playerAuth, campaign } = await setupCampaign(prefix);
await request(app).post(`/campaigns/${campaign.id}/monsters/from-library`).set(dmAuth).send({ key: 'kobold' });
const monsterId = (await request(app).get(`/campaigns/${campaign.id}/monsters`).set(dmAuth)).body.monsters[0].id;
const encounterId = (await request(app).post(`/campaigns/${campaign.id}/encounters`).set(dmAuth).send({ name: 'Warren' })).body.encounter.id;
const add = (body) => request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send(body);
return { dmAuth, playerAuth, campaign, monsterId, encounterId, add };
}
itIfDb('adds several of a monster at once, numbered on from those already there', async () => {
const { dmAuth, playerAuth, campaign, monsterId, encounterId, add } = await scene('several');
const first = await add({ monsterId, count: 3 });
expect(first.status).toBe(201);
expect(first.body.participants.map((p) => p.displayName)).toEqual(['Kobold 1', 'Kobold 2', 'Kobold 3']);
expect((await add({ monsterId, count: 2, initiativeRoll: 10 })).body.participants.map((p) => p.displayName)).toEqual(['Kobold 4', 'Kobold 5']);
// One on its own keeps the plain name; more than twenty at once is refused.
expect((await add({ monsterId })).body.participant.displayName).toBe('Kobold');
expect((await add({ monsterId, count: 21 })).status).toBe(400);
// Only monsters come in numbers.
const characterId = await buildCharacter(campaign.id, playerAuth, 'Aria');
expect((await add({ characterId, count: 2 })).status).toBe(400);
expect((await request(app).get(`/encounters/${encounterId}`).set(dmAuth)).body.encounter.participants).toHaveLength(6);
});
itIfDb('rolls initiative for the monsters and NPCs that have not rolled, and leaves the rest alone', async () => {
const { dmAuth, playerAuth, campaign, monsterId, encounterId, add } = await scene('rollall');
const characterId = await buildCharacter(campaign.id, playerAuth, 'Aria');
const hero = (await add({ characterId })).body.participant;
const rolledAlready = (await add({ monsterId, initiativeRoll: 20 })).body.participant;
await add({ monsterId, count: 3 });
const npcId = (await request(app).post(`/campaigns/${campaign.id}/npcs`).set(dmAuth).send({ name: 'Guide' })).body.npc.id;
await add({ npcId });
expect((await request(app).post(`/encounters/${encounterId}/roll-initiative`).set(playerAuth)).status).toBe(403);
const res = await request(app).post(`/encounters/${encounterId}/roll-initiative`).set(dmAuth);
expect(res.status).toBe(200);
expect(res.body.rolled).toBe(4);
for (const p of res.body.encounter.participants) {
if (p.id === hero.id) expect(p.initiativeRoll).toBeNull();
else {
expect(p.initiativeRoll).toBeGreaterThanOrEqual(1);
expect(p.initiativeRoll).toBeLessThanOrEqual(20);
expect(p.initiative).toBe(p.initiativeRoll + p.initiativeBonus);
}
}
expect(res.body.encounter.participants.find((p) => p.id === rolledAlready.id).initiativeRoll).toBe(20);
// Nothing left to roll the second time.
expect((await request(app).post(`/encounters/${encounterId}/roll-initiative`).set(dmAuth)).body.rolled).toBe(0);
});
itIfDb('a condition given for a number of rounds counts down as rounds begin, and wears off', async () => {
const { dmAuth, playerAuth, campaign, monsterId, encounterId, add } = await scene('timed');
const characterId = await buildCharacter(campaign.id, playerAuth, 'Aria');
const hero = (await add({ characterId, initiativeRoll: 15 })).body.participant;
const kobold = (await add({ monsterId, initiativeRoll: 5 })).body.participant;
await request(app).patch(`/encounters/${encounterId}`).set(dmAuth).send({ status: 'ACTIVE' });
const patch = (id, body) => request(app).patch(`/encounters/${encounterId}/participants/${id}`).set(dmAuth).send(body);
const find = (res, id) => res.body.encounter.participants.find((p) => p.id === id);
// The hero is frightened for a round and poisoned until cured; the kobold is prone for two rounds.
const given = await patch(hero.id, { conditions: ['Frightened', 'Poisoned'], conditionRounds: { Frightened: 1, Blinded: 3 } });
expect(find(given, hero.id).conditionRounds).toEqual({ Frightened: 1 }); // no countdown for a condition they are not under
await patch(kobold.id, { conditions: ['Prone'], conditionRounds: { Prone: 2 } });
const turn = () => request(app).post(`/encounters/${encounterId}/next-turn`).set(dmAuth);
// Within the round nothing moves.
const within = await turn();
expect(within.body.expired).toEqual([]);
expect(find(within, kobold.id).conditionRounds).toEqual({ Prone: 2 });
// Round 2 begins: the fright is over, on the sheet too.
const round2 = await turn();
expect(round2.body.encounter.currentRound).toBe(2);
expect(round2.body.expired).toEqual([{ name: 'Aria', condition: 'Frightened' }]);
expect(find(round2, hero.id).conditions).toEqual(['Poisoned']);
expect(find(round2, kobold.id).conditionRounds).toEqual({ Prone: 1 });
expect((await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character.conditions).toEqual(['Poisoned']);
// Skipping to round 3 counts too. Removing a condition by hand drops its countdown.
const round3 = await request(app).post(`/encounters/${encounterId}/advance-round`).set(dmAuth);
expect(round3.body.expired).toEqual([{ name: 'Kobold', condition: 'Prone' }]);
expect(find(round3, kobold.id)).toMatchObject({ conditions: [], conditionRounds: {} });
await patch(kobold.id, { conditions: ['Stunned'], conditionRounds: { Stunned: 4 } });
expect(find(await patch(kobold.id, { conditions: [] }), kobold.id).conditionRounds).toEqual({});
});
});
describe('experience and difficulty', () => {
itIfDb('the DM sees how hard an encounter is, and awards its XP once, in equal shares', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('xp');
await request(app).post(`/campaigns/${campaign.id}/monsters/from-library`).set(dmAuth).send({ key: 'kobold' }); // CR 1/8: 25 XP
const monsterId = (await request(app).get(`/campaigns/${campaign.id}/monsters`).set(dmAuth)).body.monsters[0].id;
const ariaId = await buildCharacter(campaign.id, playerAuth, 'Aria');
const boId = await buildCharacter(campaign.id, playerAuth, 'Bo');
const encounterId = (await request(app).post(`/campaigns/${campaign.id}/encounters`).set(dmAuth).send({ name: 'Warren' })).body.encounter.id;
const add = (body) => request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send(body);
const award = (auth, body = {}) => request(app).post(`/encounters/${encounterId}/award-xp`).set(auth).send(body);
// Nobody to give it to yet.
await add({ monsterId, count: 3 });
expect((await award(dmAuth)).status).toBe(400);
await add({ characterId: ariaId });
await add({ characterId: boId });
// Three kobolds against two level 1 characters: 75 XP, doubled for their number.
const dmView = (await request(app).get(`/encounters/${encounterId}`).set(dmAuth)).body.encounter;
expect(dmView.difficulty).toEqual({
xp: 75,
adjustedXp: 150,
multiplier: 2,
rating: 'HARD',
thresholds: { easy: 50, medium: 100, hard: 150, deadly: 200 },
monsters: 3,
unrated: 0,
});
expect(dmView.xpAwarded).toBeNull();
// It is the DM's to know and to award.
expect((await request(app).get(`/encounters/${encounterId}`).set(playerAuth)).body.encounter.difficulty).toBeUndefined();
expect((await award(playerAuth)).status).toBe(403);
const res = await award(dmAuth);
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ xp: 75, share: 37, awardedTo: ['Aria', 'Bo'] });
expect(res.body.encounter.xpAwarded).toBe(75);
const aria = (await request(app).get(`/characters/${ariaId}`).set(playerAuth)).body.character;
expect(aria).toMatchObject({ xp: 37, level: 1, xpProgress: { nextLevelAt: 300, levelUpDue: false } });
// Once only.
const again = await award(dmAuth, { xp: 500 });
expect(again.status).toBe(400);
expect(again.body.error).toMatch(/already been awarded/);
// The DM can set XP on the sheet; enough of it says a level is due, and changes nothing else.
expect((await request(app).patch(`/characters/${ariaId}`).set(playerAuth).send({ xp: 300 })).status).toBe(403);
const due = (await request(app).patch(`/characters/${ariaId}`).set(dmAuth).send({ xp: 300 })).body.character;
expect(due).toMatchObject({ xp: 300, level: 1, xpProgress: { nextLevelAt: 300, levelUpDue: true } });
const listed = (await request(app).get(`/campaigns/${campaign.id}/characters`).set(playerAuth)).body.characters.find((c) => c.id === ariaId);
expect(listed).toMatchObject({ xp: 300, xpProgress: { levelUpDue: true } });
});
itIfDb('an amount can be typed, for a scene with nothing rated to fight', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('xpquest');
const characterId = await buildCharacter(campaign.id, playerAuth, 'Aria');
const encounterId = (await request(app).post(`/campaigns/${campaign.id}/encounters`).set(dmAuth).send({ name: 'Riddle', mode: 'QUEST' })).body.encounter.id;
await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ characterId });
const award = (body) => request(app).post(`/encounters/${encounterId}/award-xp`).set(dmAuth).send(body);
expect((await request(app).get(`/encounters/${encounterId}`).set(dmAuth)).body.encounter.difficulty).toMatchObject({ xp: 0, rating: null, monsters: 0 });
expect((await award({})).status).toBe(400);
expect((await award({ xp: 0 })).status).toBe(400);
expect((await award({ xp: 120 })).body).toMatchObject({ xp: 120, share: 120 });
expect((await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character.xp).toBe(120);
});
});
describe('a campaign without subclasses', () => {
itIfDb('nobody is asked: each class follows its first subclass, and none is named', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('nosubclass');
expect(campaign.subclassesEnabled).toBe(true);
const settings = await request(app).patch(`/campaigns/${campaign.id}`).set(dmAuth).send({ subclassesEnabled: false });
expect(settings.body.campaign.subclassesEnabled).toBe(false);
expect((await request(app).patch(`/campaigns/${campaign.id}`).set(playerAuth).send({ subclassesEnabled: true })).status).toBe(403);
const characterId = await buildAs(campaign.id, playerAuth, 'Brakk', 'FIGHTER', 2);
const levelUp = (body = {}) => request(app).post(`/characters/${characterId}/level-up`).set(dmAuth).send(body);
const names = (character) => character.specialAbilities.split('\n').map((line) => line.split(' — ')[0]);
// Level 3 asks for no subclass, and writes the Champion's feature all the same.
const plan = (await request(app).get(`/characters/${characterId}/level-up`).set(dmAuth)).body.plan;
expect(plan.subclass).toBeNull();
expect(plan.features.map((f) => f.name)).toEqual(['Improved Critical']);
expect((await levelUp({ subclass: 'SAMURAI' })).status).toBe(400);
const character = (await levelUp()).body.character;
expect(character.level).toBe(3);
expect(names(character)).toEqual(['Improved Critical']);
// Nothing names it or offers a choice, on the sheet, the party list or the panel.
expect(character).toMatchObject({ subclass: null, subclassName: null, subclassLevel: null, subclassOptions: [] });
const listed = (await request(app).get(`/campaigns/${campaign.id}/characters`).set(dmAuth)).body.characters.find((c) => c.id === characterId);
expect(listed.subclassName).toBeNull();
expect((await request(app).get(`/characters/${characterId}/quick-stats`).set(dmAuth)).body.quickStats.subclassName).toBeNull();
expect((await request(app).patch(`/characters/${characterId}`).set(dmAuth).send({ subclass: 'SAMURAI' })).status).toBe(400);
// The Level field does the same, with no line saying a choice is owed.
const rogueId = await buildAs(campaign.id, playerAuth, 'Sly', 'ROGUE');
const rogue = (await request(app).patch(`/characters/${rogueId}`).set(dmAuth).send({ level: 9 })).body.character;
expect(names(rogue)).toEqual(expect.arrayContaining(['Fast Hands', 'Second-Story Work', 'Supreme Sneak']));
expect(names(rogue)).not.toContain('Subclass');
// Switched back on, what they were following shows, and can be changed.
await request(app).patch(`/campaigns/${campaign.id}`).set(dmAuth).send({ subclassesEnabled: true });
const shown = (await request(app).get(`/characters/${characterId}`).set(dmAuth)).body.character;
expect(shown).toMatchObject({ subclass: 'CHAMPION', subclassName: 'Champion', subclassLevel: 3 });
expect((await request(app).patch(`/characters/${characterId}`).set(dmAuth).send({ subclass: 'SAMURAI' })).body.character.subclassName).toBe('Samurai');
});
});
+23 -3
View File
@@ -4,7 +4,7 @@ const prisma = require('../db');
const { requireAuth } = require('../middleware/auth');
const { requireCampaignMember, requireDM } = require('../middleware/campaignAccess');
const { generateInviteCode } = require('../utils/inviteCode');
const { computeCharacterSheet, GEAR_STATS, MAX_DAMAGE_SCALING, MAX_GEAR_LEVEL, MAX_LEVEL } = require('../game/calculations');
const { computeCharacterSheet, xpProgress, GEAR_STATS, MAX_DAMAGE_SCALING, MAX_GEAR_LEVEL, MAX_LEVEL } = require('../game/calculations');
const { rollDie } = require('../game/buildFlow');
const { SHEET_INCLUDE, sheetOf, settleHp } = require('../utils/sheet');
const { WEAPON_LIBRARY, ITEM_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../game/data/library');
@@ -12,6 +12,7 @@ const { visitedLocationIds } = require('../utils/locations');
const { deathSaveInfo, lifeState } = require('../utils/hp');
const { hitDiceProblem, shortRest, longRest } = require('../utils/rest');
const { CURRENCIES } = require('../utils/grants');
const { subclassName } = require('../game/data/subclasses');
const { findSeed, normalizeCode, CODE_LENGTH } = require('../seeds');
const { createCampaignFromSeed } = require('../seeds/createCampaign');
@@ -34,6 +35,7 @@ function campaignSummary(campaign, role) {
areaAttackAcPenalty: campaign.areaAttackAcPenalty,
maxEquipped: campaign.maxEquipped,
maxEquippedWeapons: campaign.maxEquippedWeapons,
subclassesEnabled: campaign.subclassesEnabled,
ownerId: campaign.ownerId,
archivedAt: campaign.archivedAt,
role,
@@ -69,6 +71,8 @@ const createCampaignSchema = z.object({
// they are checked when something is put on.
maxEquipped: z.number().int().min(1).max(20).optional(),
maxEquippedWeapons: z.number().int().min(0).max(20).optional(),
// Off: nobody chooses a subclass, and each class follows its first one.
subclassesEnabled: z.boolean().optional(),
});
// POST /campaigns — create, creator becomes DM/owner
@@ -213,7 +217,8 @@ router.post('/:id/invite', requireCampaignMember(), requireDM(), async (req, res
// Characters within a campaign
// ---------------------------------------------------------------------------
function characterSummary(character) {
// `subclasses` is the campaign's setting: off, no subclass is named.
function characterSummary(character, subclasses = true) {
const sheet = computeCharacterSheet(
character,
character.skillProficiencies || [],
@@ -227,23 +232,38 @@ function characterSummary(character) {
name: character.name,
species: character.species,
characterClass: character.characterClass,
subclassName: subclasses ? subclassName(character.characterClass, character.subclass) : null,
level: character.level,
xp: character.xp,
xpProgress: xpProgress(character.xp, character.level),
buildStage: character.buildStage,
currentHp: character.currentHp,
tempHp: character.tempHp,
deathSaves: deathSaveInfo(character),
inspiration: character.inspiration,
exhaustion: character.exhaustion,
conditions: character.conditions,
gold: character.gold,
silver: character.silver,
copper: character.copper,
cash: character.cash,
maxHp: character.buildStage === 'COMPLETE' ? sheet.hp.max : null,
armorClass: character.buildStage === 'COMPLETE' ? sheet.armorClass : null,
// What the DM reads off without asking for a roll.
passives:
character.buildStage === 'COMPLETE'
? { perception: sheet.passivePerception, investigation: sheet.passiveInvestigation, insight: sheet.passiveInsight }
: null,
spellSaveDC: character.buildStage === 'COMPLETE' && sheet.spellcasting ? sheet.spellcasting.saveDC : null,
// What each rolls with, for a check the DM calls for from the whole party.
checks: character.buildStage === 'COMPLETE' ? { abilities: sheet.abilities, saves: sheet.saves, skills: sheet.skills } : null,
// What is left to spend before the next rest: the slot tracker (null for
// a character with no spell slots) and Hit Dice, with the Constitution
// modifier each die healed is rolled with.
spellSlots: character.buildStage === 'COMPLETE' ? sheet.spellSlots : null,
hitDice: character.buildStage === 'COMPLETE' ? { ...sheet.hitDice, conModifier: sheet.abilities.CON.modifier } : null,
// The class counters (Rage, Ki...), with how many of each are left.
resources: character.buildStage === 'COMPLETE' ? sheet.resources : [],
currentLocationId: character.currentLocationId,
currentLocationName: character.currentLocation ? character.currentLocation.name : null,
};
@@ -256,7 +276,7 @@ router.get('/:id/characters', requireCampaignMember(), async (req, res, next) =>
include: { ...SHEET_INCLUDE, currentLocation: true },
orderBy: { createdAt: 'asc' },
});
const summaries = characters.map(characterSummary);
const summaries = characters.map((character) => characterSummary(character, req.campaign.subclassesEnabled));
if (req.membership.role === 'DM') return res.json({ characters: summaries });
// A player sees the party's headline numbers, but another character's
+155 -20
View File
@@ -12,12 +12,15 @@ const {
scaledDamageDice,
canUseGear,
spellSlotState,
xpProgress,
MAX_GEAR_LEVEL,
MAX_LEVEL,
MAX_SLOT_LEVEL,
ABILITIES,
} = require('../game/calculations');
const { LevelUpError, advance, levelUpPlan } = require('../game/levelUp');
const { LevelUpError, advance, levelUpPlan, switchSubclass, subclassByDefault } = require('../game/levelUp');
const { resourceTally, MAX_EXHAUSTION } = require('../game/classResources');
const { SUBCLASS_LEVEL, subclassesOf, findSubclass, subclassName } = require('../game/data/subclasses');
const {
rollDie,
rollAbilityScore,
@@ -52,10 +55,15 @@ async function loadFullCharacter(id) {
weapons: { include: { weapon: true } },
spells: { include: { spell: true } },
currentLocation: true,
campaign: { select: { subclassesEnabled: true } },
},
});
}
// Whether a character's campaign uses subclasses. Takes a character loaded
// with its campaign (loadFullCharacter).
const usesSubclasses = (character) => !character.campaign || character.campaign.subclassesEnabled;
// privateNotes is a real privacy boundary, not a UI hide — it's only ever
// included in the payload for the character's own owning player.
//
@@ -67,6 +75,8 @@ async function loadFullCharacter(id) {
function serializeCharacter(character, isOwner, isDM = true) {
const restricted = !isOwner && !isDM;
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
// With subclasses switched off for the campaign, none is named or offered.
const subclasses = usesSubclasses(character);
return {
id: character.id,
campaignId: character.campaignId,
@@ -75,8 +85,14 @@ function serializeCharacter(character, isOwner, isDM = true) {
name: character.name,
species: character.species,
characterClass: character.characterClass,
subclass: subclasses ? character.subclass : null,
subclassName: subclasses ? subclassName(character.characterClass, character.subclass) : null,
// What the class can choose from, and the level it chooses at.
subclassLevel: subclasses ? (SUBCLASS_LEVEL[character.characterClass] ?? null) : null,
subclassOptions: subclasses ? subclassesOf(character.characterClass).map(({ key, name, summary }) => ({ key, name, summary })) : [],
level: character.level,
xp: character.xp,
xpProgress: xpProgress(character.xp, character.level),
motivation: character.motivation,
halfElfBonusAbility1: character.halfElfBonusAbility1,
halfElfBonusAbility2: character.halfElfBonusAbility2,
@@ -91,6 +107,9 @@ function serializeCharacter(character, isOwner, isDM = true) {
currentHp: character.currentHp,
tempHp: character.tempHp,
deathSaves: deathSaveInfo(character),
inspiration: character.inspiration,
exhaustion: character.exhaustion,
conditions: character.conditions,
armorBonus: character.armorBonus,
specialAbilities: character.specialAbilities,
background: character.background,
@@ -117,11 +136,17 @@ function serializeCharacter(character, isOwner, isDM = true) {
: null,
usable: canUseGear(character.level, ii.level),
})),
weapons: character.weapons.map((cw) => ({
...cw,
scaledDamageDice: scaledDamageDice(cw.weapon.damageDice, cw.level, cw.weapon.damageScaling, cw.weapon.minLevel),
usable: canUseGear(character.level, cw.level),
})),
weapons: character.weapons.map((cw) => {
// What this character rolls with it: to hit, and on top of its dice.
const { attackBonus, damageBonus } = computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true, cw.level);
return {
...cw,
scaledDamageDice: scaledDamageDice(cw.weapon.damageDice, cw.level, cw.weapon.damageScaling, cw.weapon.minLevel),
attackBonus,
damageBonus,
usable: canUseGear(character.level, cw.level),
};
}),
spells: character.spells.map((cs) => ({ ...cs, usable: canUseGear(character.level, cs.spell.level) })),
sheet: character.buildStage === 'COMPLETE' ? sheet : null,
};
@@ -163,8 +188,12 @@ const patchCharacterSchema = z.object({
privateNotes: z.string().max(4000).nullable().optional(),
currentLocationId: z.string().nullable().optional(),
level: z.number().int().min(1).max(MAX_LEVEL).optional(),
xp: z.number().int().min(0).optional(),
subclass: z.string().max(40).nullable().optional(), // a key from game/data/subclasses.js; null clears it
xp: z.number().int().min(0).max(10000000).optional(),
hitDiceUsed: z.number().int().min(0).max(MAX_LEVEL).optional(),
inspiration: z.boolean().optional(),
exhaustion: z.number().int().min(0).max(MAX_EXHAUSTION).optional(),
conditions: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
});
// Progression and placement are the DM's call, and so is rewriting what the
@@ -174,8 +203,10 @@ const patchCharacterSchema = z.object({
// edit the rest of their own sheet. Gold is not patchable at all — it only
// moves through the ledger (POST /:id/gold). The armor bonus is the DM's
// adjustment on top of what equipped gear gives, so it is the DM's too. Hit
// Dice are spent on a rest, which the DM runs.
const DM_ONLY_PATCH_FIELDS = ['currentHp', 'tempHp', 'level', 'xp', 'currentLocationId', 'speedOverride', 'armorBonus', 'specialAbilities', 'background', 'appearance', 'hitDiceUsed'];
// Dice are spent on a rest, which the DM runs. Exhaustion and conditions are
// the DM's to give and take away. Inspiration is the DM's to give; the player
// may spend it (checked below).
const DM_ONLY_PATCH_FIELDS = ['currentHp', 'tempHp', 'level', 'subclass', 'xp', 'currentLocationId', 'speedOverride', 'armorBonus', 'specialAbilities', 'background', 'appearance', 'hitDiceUsed', 'exhaustion', 'conditions'];
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
@@ -190,8 +221,12 @@ router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, n
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
if (!req.isDM && DM_ONLY_PATCH_FIELDS.some((field) => parsed.data[field] !== undefined)) {
return res.status(403).json({ error: 'Only the DM can change HP, temp HP, Hit Dice, level, XP, speed, armor bonus, location, special abilities, background or appearance.' });
return res.status(403).json({ error: 'Only the DM can change HP, temp HP, Hit Dice, level, subclass, XP, speed, armor bonus, location, exhaustion, conditions, special abilities, background or appearance.' });
}
if (!req.isDM && parsed.data.inspiration === true) {
return res.status(403).json({ error: 'Only the DM can give inspiration. You can spend it.' });
}
if (parsed.data.conditions) parsed.data.conditions = [...new Set(parsed.data.conditions)];
const newLevel = parsed.data.level ?? req.character.level;
if (parsed.data.level !== undefined || parsed.data.hitDiceUsed !== undefined) {
@@ -205,15 +240,37 @@ router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, n
for (const slot of slots ? slots.levels : []) tally[slot.level - 1] = slot.used;
parsed.data.spellSlotsUsed = Array.from(tally, (used) => used || 0);
}
if (req.character.buildStage === 'COMPLETE' && newLevel > req.character.level && parsed.data.specialAbilities === undefined) {
// Setting a higher level by hand still writes down what the class gains
// on the way there. A Boon is left as a line saying one is owed: picking
// it is part of levelling up properly (POST /:id/level-up).
let abilities = req.character.specialAbilities;
const characterClass = req.character.characterClass;
const askedSubclass = parsed.data.subclass; // before a level change may take one by default
let abilities = parsed.data.specialAbilities === undefined ? req.character.specialAbilities : null;
const writesAbilities = req.character.buildStage === 'COMPLETE' && parsed.data.specialAbilities === undefined;
if (writesAbilities && newLevel > req.character.level) {
// Setting a higher level by hand still writes down what the class and
// subclass give on the way there. A Boon, and a subclass not yet picked,
// are left as a line saying one is owed: picking them is part of
// levelling up properly (POST /:id/level-up).
let key = req.character.subclass;
for (let level = req.character.level + 1; level <= newLevel; level++) {
abilities = advance(abilities, req.character.characterClass, level).specialAbilities;
// With subclasses switched off, the class's first one is taken at the
// level it would have been chosen.
const taken = req.campaign.subclassesEnabled ? null : subclassByDefault(characterClass, level, key);
abilities = advance(abilities, characterClass, level, undefined, taken ? { key: taken, chosen: true } : { key }).specialAbilities;
if (taken) key = taken;
}
parsed.data.specialAbilities = abilities;
if (key !== req.character.subclass && askedSubclass === undefined) parsed.data.subclass = key;
}
if (askedSubclass !== undefined && askedSubclass !== req.character.subclass) {
if (!req.campaign.subclassesEnabled) return res.status(400).json({ error: 'Subclasses are switched off for this campaign.' });
const picked = askedSubclass;
if (picked !== null) {
if (!findSubclass(characterClass, picked)) return res.status(400).json({ error: 'That is not a subclass of this character\'s class.' });
if (newLevel < SUBCLASS_LEVEL[characterClass]) {
return res.status(400).json({ error: `${req.character.name} chooses a subclass at level ${SUBCLASS_LEVEL[characterClass]}.` });
}
}
// The old subclass's lines come off the sheet and the new one's go on.
if (writesAbilities) parsed.data.specialAbilities = switchSubclass(abilities, characterClass, newLevel, req.character.subclass, picked);
}
// Damage is soaked by temp HP before it reaches real HP — unless this
@@ -401,6 +458,65 @@ router.post('/:id/spell-slots', requireCharacterAccess({ write: true }), async (
}
});
// ---------------------------------------------------------------------------
// Class counters — Rage, Ki, Channel Divinity and the like. Which a character
// has, and how many, comes from class, subclass and level
// (game/classResources.js); the character row keeps how many are spent.
// ---------------------------------------------------------------------------
const resourceKey = z.string().min(1).max(40);
const resourceSchema = z.discriminatedUnion('action', [
// Using it: one is spent, or `amount` from a pool (Lay on Hands, Ki).
z.object({ action: z.literal('use'), key: resourceKey, amount: z.number().int().min(1).max(999).default(1) }),
// The DM setting how many are spent: giving some back, or fixing a mistake.
z.object({ action: z.literal('set'), key: resourceKey, used: z.number().int().min(0).max(999) }),
// The DM giving every counter back.
z.object({ action: z.literal('restore') }),
]);
// The owning player spends their own. Getting any back is the DM's: by hand
// here, or for everyone with a rest (POST /campaigns/:id/rest).
router.post('/:id/resources', requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
const parsed = resourceSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
if (req.character.buildStage !== 'COMPLETE') return res.status(400).json({ error: 'Character build is not finished yet.' });
const input = parsed.data;
if (input.action !== 'use' && !req.isDM) return res.status(403).json({ error: 'Only the DM can give a use back.' });
const character = await loadFullCharacter(req.character.id);
const resources = sheetOf(character).resources;
if (input.action === 'restore') {
for (const resource of resources) resource.used = 0;
} else {
const resource = resources.find((r) => r.key === input.key);
if (!resource) return res.status(400).json({ error: `${character.name} has no such counter.` });
if (input.action === 'use') {
if (input.amount > resource.remaining) {
const back = resource.restoresOn === 'SHORT' ? 'short or long' : 'long';
return res.status(400).json({
error:
resource.remaining === 0
? `${character.name} has no ${resource.name} left. It comes back on a ${back} rest.`
: `${character.name} has only ${resource.remaining} ${resource.name} left.`,
});
}
resource.used += input.amount;
} else {
resource.used = Math.min(input.used, resource.max);
}
}
await prisma.character.update({ where: { id: character.id }, data: { resourcesUsed: resourceTally(resources) } });
const full = await loadFullCharacter(character.id);
emitCharacterUpdated(req);
res.json({ character: serializeCharacter(full, req.isOwner) });
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Levelling up — one level at a time, with the checklist that goes with it
// (game/levelUp.js): the new level, full HP, the class's new special
@@ -423,7 +539,7 @@ router.get('/:id/level-up', requireCharacterAccess(), async (req, res, next) =>
try {
const character = await loadFullCharacter(req.character.id);
if (!canLevelUp(req, res, character)) return;
const plan = levelUpPlan(character);
const plan = levelUpPlan(character, { subclasses: usesSubclasses(character) });
const after = sheetOf({ ...character, level: plan.toLevel, spellSlotsUsed: [] });
res.json({ plan: { ...plan, maxHp: { from: sheetOf(character).hp.max, to: after.hp.max }, spellSlots: after.spellSlots } });
} catch (err) {
@@ -432,6 +548,7 @@ router.get('/:id/level-up', requireCharacterAccess(), async (req, res, next) =>
});
const levelUpSchema = z.object({
subclass: z.string().optional(), // which subclass, at the level the class chooses one
boon: z.string().optional(), // which Boon, at a level that grants one
weaponId: z.string().nullable().optional(), // the weapon that gets the free upgrade
spellIds: z.array(z.string()).max(50).default([]), // spells newly granted
@@ -441,11 +558,16 @@ router.post('/:id/level-up', requireCharacterAccess({ write: true }), async (req
try {
const parsed = levelUpSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { boon, weaponId, spellIds } = parsed.data;
const { subclass, boon, weaponId, spellIds } = parsed.data;
const character = await loadFullCharacter(req.character.id);
if (!canLevelUp(req, res, character)) return;
const plan = levelUpPlan(character);
const plan = levelUpPlan(character, { subclasses: usesSubclasses(character) });
if (plan.subclass && !subclass) return res.status(400).json({ error: `Level ${plan.toLevel} needs a subclass: pick one.` });
if (!plan.subclass && subclass) return res.status(400).json({ error: `There is no subclass to pick at level ${plan.toLevel}.` });
if (subclass && !plan.subclass.options.some((option) => option.key === subclass)) {
return res.status(400).json({ error: 'That is not a subclass of this character\'s class.' });
}
if (plan.boon && !boon) return res.status(400).json({ error: `Level ${plan.toLevel} grants a Boon: pick one.` });
if (!plan.boon && boon) return res.status(400).json({ error: `Level ${plan.toLevel} does not grant a Boon.` });
if (weaponId && !plan.weapons.some((w) => w.weaponId === weaponId)) {
@@ -458,7 +580,9 @@ router.post('/:id/level-up', requireCharacterAccess({ write: true }), async (req
let gained;
try {
gained = advance(character.specialAbilities, character.characterClass, plan.toLevel, boon);
// The subclass picked, or the one taken for them where the campaign has no choosing.
const newSubclass = subclass || plan.subclassTaken;
gained = advance(character.specialAbilities, character.characterClass, plan.toLevel, boon, newSubclass ? { key: newSubclass, chosen: true } : { key: character.subclass });
} catch (err) {
if (!(err instanceof LevelUpError)) throw err;
return res.status(400).json({ error: err.message });
@@ -478,6 +602,7 @@ router.post('/:id/level-up', requireCharacterAccess({ write: true }), async (req
where: { id: character.id },
data: {
level: plan.toLevel,
...(subclass || plan.subclassTaken ? { subclass: subclass || plan.subclassTaken } : {}),
specialAbilities: gained.specialAbilities,
armorBonus,
tempHp: Math.max(character.tempHp, gained.tempHp),
@@ -603,6 +728,7 @@ router.post('/:id/copy', requireCharacterAccess(), async (req, res, next) => {
name: source.name,
species: source.species,
characterClass: source.characterClass,
subclass: source.subclass,
level: source.level,
xp: source.xp,
motivation: source.motivation,
@@ -1135,6 +1261,7 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
level: character.level,
species: character.species,
characterClass: character.characterClass,
subclassName: usesSubclasses(character) ? subclassName(character.characterClass, character.subclass) : null,
currentHp: character.currentHp,
maxHp: sheet.hp.max,
tempHp: character.tempHp,
@@ -1146,8 +1273,16 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
spellcasting: sheet.spellcasting,
spellSlots: sheet.spellSlots,
hitDice: sheet.hitDice,
resources: sheet.resources,
inspiration: character.inspiration,
exhaustion: character.exhaustion,
conditions: character.conditions,
passivePerception: sheet.passivePerception,
passiveInvestigation: sheet.passiveInvestigation,
passiveInsight: sheet.passiveInsight,
abilities: sheet.abilities,
saves: sheet.saves,
skills: sheet.skills,
specialAbilities: character.specialAbilities,
// What equipped gear is adding and taking away, and what else it does.
gear: sheet.gear,
+177 -24
View File
@@ -1,13 +1,15 @@
const crypto = require('crypto');
const express = require('express');
const { z } = require('zod');
const prisma = require('../db');
const { requireAuth } = require('../middleware/auth');
const { loadCampaignMembership } = require('../middleware/campaignAccess');
const { computeCharacterSheet, computeWeaponStats, scaledDamageDice, canUseGear, abilityModifier, MAX_GEAR_LEVEL } = require('../game/calculations');
const { computeCharacterSheet, computeWeaponStats, scaledDamageDice, canUseGear, abilityModifier, encounterDifficulty, MAX_GEAR_LEVEL } = require('../game/calculations');
const { CURRENCIES, InsufficientGoldError, adjustGold, spendCoins, giveGear } = require('../utils/grants');
const { moveCharacters, visitedLocationIds } = require('../utils/locations');
const { SHEET_INCLUDE } = require('../utils/sheet');
const { NO_DEATH_SAVES, lifeState, deathSaveInfo, changeHp } = require('../utils/hp');
const { subclassName } = require('../game/data/subclasses');
const router = express.Router();
@@ -104,6 +106,41 @@ function revivalSpell(character) {
return character.spells.map((cs) => cs.spell).find((spell) => spell.revives && canUseGear(character.level, spell.level));
}
// The rounds left on a combatant's timed conditions, squared up with the
// conditions they are actually under: { condition: rounds }.
function roundsFor(conditionRounds, conditions) {
const rounds = conditionRounds && typeof conditionRounds === 'object' ? conditionRounds : {};
return Object.fromEntries(conditions.filter((condition) => Number.isInteger(rounds[condition]) && rounds[condition] > 0).map((condition) => [condition, rounds[condition]]));
}
// A new round: every timed condition has one round less to run, and those
// that run out are removed (from the character too, when it is a character's).
// Returns what wore off, as [{ name, condition }], for the DM to read out.
async function tickConditions(req) {
const participants = await prisma.encounterParticipant.findMany({
where: { encounterId: req.encounter.id },
include: { character: { select: { id: true, conditions: true } } },
});
const expired = [];
for (const p of participants) {
const conditions = p.character ? p.character.conditions : p.conditions;
const before = roundsFor(p.conditionRounds, conditions);
if (Object.keys(before).length === 0) continue;
const after = {};
for (const [condition, rounds] of Object.entries(before)) {
if (rounds > 1) after[condition] = rounds - 1;
else expired.push({ name: p.displayName, condition });
}
const left = conditions.filter((condition) => before[condition] === undefined || after[condition] !== undefined);
await prisma.encounterParticipant.update({ where: { id: p.id }, data: { conditionRounds: after, conditions: left } });
if (p.character && left.length !== conditions.length) {
await prisma.character.update({ where: { id: p.character.id }, data: { conditions: left } });
emitCharacterUpdated(req, p.character.id);
}
}
return expired;
}
const initiativeRollSchema = z.number().int().min(1, 'An initiative roll is a d20: 1 to 20').max(20, 'An initiative roll is a d20: 1 to 20');
// What every campaign member sees about a character in an encounter: the
@@ -113,7 +150,7 @@ const initiativeRollSchema = z.number().int().min(1, 'An initiative roll is a d2
// used; what is still in the pack is in the character panel, for the
// character's own player and the DM. Uses the
// same calculation-engine functions as the sheet, never re-deriving formulas.
function characterCombatInfo(character) {
function characterCombatInfo(character, subclasses = true) {
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
// Gear and spells above the character's level are held but can't be used,
// so they stay out of the fight; so does anything not equipped.
@@ -149,6 +186,7 @@ function characterCombatInfo(character) {
level: character.level,
species: character.species,
characterClass: character.characterClass,
subclassName: subclasses ? subclassName(character.characterClass, character.subclass) : null,
armorClass: sheet.armorClass,
maxHp: sheet.hp.max,
tempHp: character.tempHp,
@@ -157,9 +195,16 @@ function characterCombatInfo(character) {
speed: sheet.speed,
initiativeBonus: sheet.initiative,
passivePerception: sheet.passivePerception,
passiveInvestigation: sheet.passiveInvestigation,
passiveInsight: sheet.passiveInsight,
proficiencyBonus: sheet.proficiencyBonus,
abilities: sheet.abilities,
saves: sheet.saves,
skills: sheet.skills,
spellSlots: sheet.spellSlots,
resources: sheet.resources,
inspiration: character.inspiration,
exhaustion: character.exhaustion,
specialAbilities: character.specialAbilities,
// What equipped gear is adding and taking away. The numbers above already include it.
gear: sheet.gear,
@@ -170,6 +215,16 @@ function characterCombatInfo(character) {
};
}
// How hard the scene is for the characters in it, and what its monsters are
// worth: every monster counts, standing or not. Takes the encounter's
// participants with their characters and monsters loaded.
function difficultyOf(participants) {
return encounterDifficulty(
participants.filter((p) => p.character).map((p) => p.character.level),
participants.filter((p) => p.monster).map((p) => p.monster.challengeRating)
);
}
// What is for sale, oldest first, with the weapon or item itself.
const WARES = { include: { weapon: true, item: true }, orderBy: { createdAt: 'asc' } };
@@ -189,7 +244,7 @@ async function serializeEncounter(encounterId, isDM, viewerId) {
const encounter = await prisma.encounter.findUnique({
where: { id: encounterId },
include: {
campaign: { select: { showMonsterHp: true } },
campaign: { select: { showMonsterHp: true, subclassesEnabled: true } },
location: { select: { id: true, name: true, description: true } },
participants: {
include: {
@@ -224,12 +279,15 @@ async function serializeEncounter(encounterId, isDM, viewerId) {
if (character) {
// A character combatant's HP is the character's own HP, not a
// per-encounter copy, so the tracker and the sheet can never disagree.
const { maxHp, ...combatInfo } = characterCombatInfo(character);
const { maxHp, ...combatInfo } = characterCombatInfo(character, encounter.campaign.subclassesEnabled);
out.currentHp = character.currentHp;
out.maxHp = maxHp;
// Likewise their conditions: the character's own, which outlast the scene.
out.conditions = character.conditions;
out.character = { id: character.id, name: character.name, userId: character.userId };
out.characterCombatInfo = combatInfo;
}
out.conditionRounds = roundsFor(p.conditionRounds, out.conditions);
if (monster) out.monster = isDM ? monster : { id: monster.id, name: monster.name };
if (npc) {
const { dmNotes, ac, maxHp, attackBonus, damageDice, campaignId, createdAt, ...publicNpc } = npc;
@@ -250,7 +308,7 @@ async function serializeEncounter(encounterId, isDM, viewerId) {
...scene,
locationId: knowsPlace ? scene.locationId : null,
location: knowsPlace ? location : null,
...(isDM ? { dmNotes } : {}),
...(isDM ? { dmNotes, difficulty: difficultyOf(encounter.participants) } : {}),
// A player is not told that someone they cannot see is being targeted.
targetParticipantIds: isDM ? scene.targetParticipantIds : scene.targetParticipantIds.filter((id) => !hiddenIds.has(id)),
participants,
@@ -361,16 +419,19 @@ const participantSchema = z
npcId: z.string().optional(),
displayName: z.string().min(1).max(80).optional(),
initiativeRoll: initiativeRollSchema.optional(),
// Several of one monster at once: "Goblin 1" to "Goblin 4".
count: z.number().int().min(1).max(20).default(1),
})
.refine((data) => [data.characterId, data.monsterId, data.npcId].filter(Boolean).length === 1, {
message: 'Provide exactly one of characterId, monsterId or npcId',
});
})
.refine((data) => data.count === 1 || Boolean(data.monsterId), { message: 'Only monsters can be added several at a time' });
router.post('/:id/participants', requireEncounterAccess, requireDM, async (req, res, next) => {
try {
const parsed = participantSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { characterId, monsterId, npcId, displayName, initiativeRoll } = parsed.data;
const { characterId, monsterId, npcId, displayName, initiativeRoll, count } = parsed.data;
let currentHp, maxHp, resolvedName;
let bonus = 0;
@@ -411,22 +472,40 @@ router.post('/:id/participants', requireEncounterAccess, requireDM, async (req,
resolvedName = displayName || npc.name;
}
const participant = await prisma.encounterParticipant.create({
data: {
encounterId: req.encounter.id,
characterId: characterId || null,
monsterId: monsterId || null,
npcId: npcId || null,
displayName: resolvedName,
initiativeRoll: initiativeRoll ?? null,
initiative: initiativeRoll == null ? 0 : initiativeRoll + bonus,
currentHp,
maxHp,
isMonster: Boolean(monsterId),
},
});
// Several at once are numbered, carrying on from any of that name already
// in the scene ("Goblin 3" after "Goblin 1" and "Goblin 2").
let names = [resolvedName];
if (count > 1) {
const present = await prisma.encounterParticipant.findMany({ where: { encounterId: req.encounter.id }, select: { displayName: true } });
const numbered = present
.filter((p) => p.displayName.startsWith(`${resolvedName} `))
.map((p) => Number(p.displayName.slice(resolvedName.length + 1)))
.filter((n) => Number.isInteger(n) && n > 0);
const from = Math.max(0, ...numbered);
names = Array.from({ length: count }, (_, i) => `${resolvedName} ${from + i + 1}`.slice(-80));
}
await respondWithEncounter(req, res, 201, { participant });
const participants = [];
for (const name of names) {
participants.push(
await prisma.encounterParticipant.create({
data: {
encounterId: req.encounter.id,
characterId: characterId || null,
monsterId: monsterId || null,
npcId: npcId || null,
displayName: name,
initiativeRoll: initiativeRoll ?? null,
initiative: initiativeRoll == null ? 0 : initiativeRoll + bonus,
currentHp,
maxHp,
isMonster: Boolean(monsterId),
},
})
);
}
await respondWithEncounter(req, res, 201, { participant: participants[0], participants });
} catch (err) {
next(err);
}
@@ -437,6 +516,9 @@ const updateParticipantSchema = z.object({
maxHp: z.number().int().min(1).max(100000).optional(),
initiativeRoll: initiativeRollSchema.nullable().optional(), // null clears the roll
conditions: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
// Rounds left on the conditions that wear off by themselves; one left out
// lasts until the DM removes it.
conditionRounds: z.record(z.string().max(40), z.number().int().min(1).max(100)).optional(),
displayName: z.string().min(1).max(80).optional(),
});
@@ -467,11 +549,22 @@ router.patch('/:id/participants/:participantId', requireEncounterAccess, async (
if (data.initiativeRoll !== undefined) {
data.initiative = data.initiativeRoll == null ? 0 : data.initiativeRoll + initiativeBonus(existing);
}
if (data.conditions) data.conditions = [...new Set(data.conditions)];
if (data.conditions !== undefined || data.conditionRounds !== undefined) {
// A condition that goes takes its countdown with it.
const conditions = data.conditions ?? (existing.character ? existing.character.conditions : existing.conditions);
data.conditionRounds = roundsFor(data.conditionRounds ?? existing.conditionRounds, conditions);
}
if (existing.character) {
// Max HP comes from the sheet, and damage/healing lands on the character.
const { character } = existing;
const maxHp = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies).hp.max;
data.maxHp = maxHp;
if (data.conditions !== undefined) {
// So do conditions: they are the character's, and stay after the scene.
await prisma.character.update({ where: { id: character.id }, data: { conditions: data.conditions } });
emitCharacterUpdated(req, character.id);
}
if (data.currentHp !== undefined) {
if (lifeState(character) === 'DEAD' && data.currentHp > 0) {
return res.status(400).json({ error: `${character.name} is dead. Revive them before healing.` });
@@ -563,6 +656,25 @@ router.post('/:id/participants/:participantId/revive', requireEncounterAccess, a
}
});
// Rolls initiative for every monster and NPC that has no roll yet: a d20 each,
// with their bonus added as when a roll is typed in. Characters are left to
// their players.
router.post('/:id/roll-initiative', requireEncounterAccess, requireDM, async (req, res, next) => {
try {
const waiting = await prisma.encounterParticipant.findMany({
where: { encounterId: req.encounter.id, characterId: null, initiativeRoll: null },
include: { monster: true },
});
for (const p of waiting) {
const roll = crypto.randomInt(1, 21);
await prisma.encounterParticipant.update({ where: { id: p.id }, data: { initiativeRoll: roll, initiative: roll + initiativeBonus(p) } });
}
await respondWithEncounter(req, res, 200, { rolled: waiting.length });
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Targets — who the combatant on turn is going for
// ---------------------------------------------------------------------------
@@ -635,7 +747,9 @@ router.post('/:id/next-turn', requireEncounterAccess, requireDM, async (req, res
...(wrapped ? { currentRound: { increment: 1 } } : {}),
},
});
await respondWithEncounter(req, res);
// What wore off as the new round began, for the DM to read out.
const expired = wrapped ? await tickConditions(req) : [];
await respondWithEncounter(req, res, 200, { expired });
} catch (err) {
next(err);
}
@@ -654,12 +768,51 @@ router.post('/:id/advance-round', requireEncounterAccess, requireDM, async (req,
...(req.encounter.mode === 'BATTLE' ? { activeParticipantId: standingFrom(order, 0)?.id ?? null } : {}),
},
});
const expired = await tickConditions(req);
await syncCharacterLocations(req);
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('encounter:round-advanced', {
encounterId: updated.id,
currentRound: updated.currentRound,
});
res.json({ encounter: await serializeEncounter(updated.id, req.isDM, req.user.id) });
res.json({ expired, encounter: await serializeEncounter(updated.id, req.isDM, req.user.id) });
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Experience — awarded once, shared evenly between the characters in the scene
// ---------------------------------------------------------------------------
const awardXpSchema = z.object({ xp: z.number().int().min(1).max(10000000).optional() });
// The DM hands out the encounter's XP: what its monsters are worth unless
// another amount is given, in equal shares (rounded down) to every character
// in the scene. Nobody levels up by it; the sheet says when a level is due.
router.post('/:id/award-xp', requireEncounterAccess, requireDM, async (req, res, next) => {
try {
const parsed = awardXpSchema.safeParse(req.body || {});
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
if (req.encounter.xpAwarded != null) {
return res.status(400).json({ error: `XP has already been awarded for this encounter (${req.encounter.xpAwarded}). Change a character's XP on their sheet.` });
}
const participants = await prisma.encounterParticipant.findMany({
where: { encounterId: req.encounter.id },
include: { character: { select: { id: true, name: true, level: true } }, monster: { select: { challengeRating: true } } },
});
const characters = participants.filter((p) => p.character).map((p) => p.character);
if (characters.length === 0) return res.status(400).json({ error: 'There are no characters in this encounter to award XP to.' });
const xp = parsed.data.xp ?? difficultyOf(participants).xp;
if (!(xp > 0)) return res.status(400).json({ error: 'There is no XP to award: no monster here has a challenge rating. Type an amount.' });
const share = Math.floor(xp / characters.length);
await prisma.$transaction([
prisma.character.updateMany({ where: { id: { in: characters.map((c) => c.id) } }, data: { xp: { increment: share } } }),
prisma.encounter.update({ where: { id: req.encounter.id }, data: { xpAwarded: xp } }),
]);
for (const character of characters) emitCharacterUpdated(req, character.id);
await respondWithEncounter(req, res, 200, { xp, share, awardedTo: characters.map((c) => c.name) });
} catch (err) {
next(err);
}