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:
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user