V1.3.0: Hollowcrown seed, player visibility rules, initiative rolls, number limits, temp HP
- Hollowcrown: The Rift Between Worlds as its own seed (npm run seed:hollowcrown), built from the campaign book: pools, 58 monsters, 57 NPCs, 28 locations, 72 encounters with rewards, and DM notes. Shared seeding logic moved to prisma/seedCampaign.js. - What players can see: only encounters their own character is in; only the pool entries their character holds (plus starting options while building); only locations their character has been to; no invite code; no gold, inventory or money log of other players' characters. Socket events carry ids only and campaign rooms are members-only. - Encounters have a location; while one is in progress its characters are there, and visits are remembered. - Campaign setting to show players a health bar only for monsters and NPCs. - Initiative is entered as the d20 roll (1-20) and the bonus is added; players can enter their own character's roll. - Number fields enforce their limits when typing, and the API enforces the same limits. - Temp HP shows on HP bars and absorbs damage before real HP. - All packages at version 1.3.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,8 +3,10 @@ const { z } = require('zod');
|
||||
const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { loadCampaignMembership } = require('../middleware/campaignAccess');
|
||||
const { computeCharacterSheet, computeWeaponStats, canUseGear, MAX_GEAR_LEVEL } = require('../game/calculations');
|
||||
const { computeCharacterSheet, computeWeaponStats, canUseGear, abilityModifier, MAX_GEAR_LEVEL } = require('../game/calculations');
|
||||
const { adjustGold, giveGear } = require('../utils/grants');
|
||||
const { moveCharacters, visitedLocationIds } = require('../utils/locations');
|
||||
const { absorbDamage } = require('../utils/hp');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -18,9 +20,20 @@ async function requireEncounterAccess(req, res, next) {
|
||||
const membership = await loadCampaignMembership(req.user.id, encounter.campaignId);
|
||||
if (!membership) return res.status(403).json({ error: 'Not a member of this campaign' });
|
||||
|
||||
// A player only gets into a scene one of their own characters is in. To
|
||||
// anyone else it doesn't exist — the name alone can be a spoiler.
|
||||
const isDM = membership.role === 'DM';
|
||||
if (!isDM) {
|
||||
const present = await prisma.encounterParticipant.findFirst({
|
||||
where: { encounterId: encounter.id, character: { userId: req.user.id } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!present) return res.status(404).json({ error: 'Encounter not found' });
|
||||
}
|
||||
|
||||
req.encounter = encounter;
|
||||
req.membership = membership;
|
||||
req.isDM = membership.role === 'DM';
|
||||
req.isDM = isDM;
|
||||
return next();
|
||||
} catch (err) {
|
||||
return next(err);
|
||||
@@ -37,10 +50,24 @@ function clamp(value, min, max) {
|
||||
}
|
||||
|
||||
// Highest initiative first; ties keep the order combatants were added in.
|
||||
// Anyone who has not rolled yet waits at the bottom.
|
||||
function inTurnOrder(participants) {
|
||||
return [...participants].sort((a, b) => b.initiative - a.initiative || (a.id < b.id ? -1 : 1));
|
||||
const rolled = (p) => (p.initiativeRoll == null ? 0 : 1);
|
||||
return [...participants].sort((a, b) => rolled(b) - rolled(a) || b.initiative - a.initiative || (a.id < b.id ? -1 : 1));
|
||||
}
|
||||
|
||||
// What is added to a combatant's d20 for initiative: the sheet's initiative
|
||||
// bonus for a character, the Dexterity modifier for a monster, and nothing for
|
||||
// an NPC (they have no ability scores). Takes a participant with its
|
||||
// character (and proficiencies) and monster loaded.
|
||||
function initiativeBonus({ character, monster }) {
|
||||
if (character) return computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies).initiative;
|
||||
if (monster) return abilityModifier(monster.dexScore);
|
||||
return 0;
|
||||
}
|
||||
|
||||
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
|
||||
// sheet's headline numbers plus the weapons and spells it can actually use —
|
||||
// so the party can plan around each other mid-fight, not only the DM. Uses the
|
||||
@@ -92,10 +119,17 @@ function characterCombatInfo(character) {
|
||||
// The DM gets everything. Players get the scene as their characters see it:
|
||||
// no DM notes, no monster stat blocks, no NPC secrets or stats, and only the
|
||||
// rewards that have actually been handed out.
|
||||
async function serializeEncounter(encounterId, isDM) {
|
||||
//
|
||||
// `viewerId` is the user the payload is for. A player is told where a scene
|
||||
// is once one of their characters has been there, and — when the campaign
|
||||
// hides monster hit points — gets a percentage for the health bar in place of
|
||||
// the numbers for anyone who is not a character.
|
||||
async function serializeEncounter(encounterId, isDM, viewerId) {
|
||||
const encounter = await prisma.encounter.findUnique({
|
||||
where: { id: encounterId },
|
||||
include: {
|
||||
campaign: { select: { showMonsterHp: true } },
|
||||
location: { select: { id: true, name: true, description: true } },
|
||||
participants: {
|
||||
include: {
|
||||
character: {
|
||||
@@ -115,16 +149,20 @@ async function serializeEncounter(encounterId, isDM) {
|
||||
});
|
||||
if (!encounter) return encounter;
|
||||
|
||||
const hideHp = !isDM && !encounter.campaign.showMonsterHp;
|
||||
const participants = inTurnOrder(encounter.participants).map((p) => {
|
||||
const { character, monster, npc, ...row } = p;
|
||||
const out = { ...row, kind: npc || p.npcId ? 'NPC' : p.isMonster ? 'MONSTER' : 'CHARACTER' };
|
||||
// The bonus is part of a monster's stat block, so only the DM gets it for
|
||||
// those; a character's is on their sheet for all to see.
|
||||
const bonus = isDM || character ? { initiativeBonus: initiativeBonus(p) } : {};
|
||||
const out = { ...row, ...bonus, kind: npc || p.npcId ? 'NPC' : p.isMonster ? 'MONSTER' : 'CHARACTER' };
|
||||
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);
|
||||
out.currentHp = character.currentHp;
|
||||
out.maxHp = maxHp;
|
||||
out.character = { id: character.id, name: character.name };
|
||||
out.character = { id: character.id, name: character.name, userId: character.userId };
|
||||
out.characterCombatInfo = combatInfo;
|
||||
}
|
||||
if (monster) out.monster = isDM ? monster : { id: monster.id, name: monster.name };
|
||||
@@ -132,12 +170,21 @@ async function serializeEncounter(encounterId, isDM) {
|
||||
const { dmNotes, ac, maxHp, attackBonus, damageDice, campaignId, createdAt, ...publicNpc } = npc;
|
||||
out.npc = isDM ? { ...publicNpc, dmNotes, ac, maxHp, attackBonus, damageDice } : publicNpc;
|
||||
}
|
||||
if (hideHp && !character) {
|
||||
// Rounded up, so anything still standing shows a sliver of bar.
|
||||
out.hpPercent = p.maxHp > 0 ? Math.ceil((clamp(p.currentHp, 0, p.maxHp) / p.maxHp) * 100) : null;
|
||||
out.currentHp = null;
|
||||
out.maxHp = null;
|
||||
}
|
||||
return out;
|
||||
});
|
||||
|
||||
const { dmNotes, rewards, ...scene } = encounter;
|
||||
const { dmNotes, rewards, campaign, location, ...scene } = encounter;
|
||||
const knowsPlace = isDM || (location && (await visitedLocationIds(prisma, viewerId, encounter.campaignId)).has(location.id));
|
||||
return {
|
||||
...scene,
|
||||
locationId: knowsPlace ? scene.locationId : null,
|
||||
location: knowsPlace ? location : null,
|
||||
...(isDM ? { dmNotes } : {}),
|
||||
participants,
|
||||
rewards: isDM ? rewards : rewards.filter((r) => r.awardedAt),
|
||||
@@ -154,15 +201,31 @@ function emitCharacterUpdated(req, characterId) {
|
||||
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('character:updated', { characterId });
|
||||
}
|
||||
|
||||
// While an encounter with a location is in progress, the characters in it
|
||||
// are at that location: starting it, moving it, or adding someone to it puts
|
||||
// them there, and that goes on their record of places visited.
|
||||
async function syncCharacterLocations(req) {
|
||||
const encounter = await prisma.encounter.findUnique({
|
||||
where: { id: req.encounter.id },
|
||||
include: { participants: { where: { characterId: { not: null } }, include: { character: { select: { id: true, currentLocationId: true } } } } },
|
||||
});
|
||||
if (!encounter || encounter.status !== 'ACTIVE' || !encounter.locationId) return;
|
||||
|
||||
const elsewhere = encounter.participants.map((p) => p.character).filter((c) => c.currentLocationId !== encounter.locationId);
|
||||
await moveCharacters(prisma, elsewhere.map((c) => c.id), encounter.locationId);
|
||||
for (const character of elsewhere) emitCharacterUpdated(req, character.id);
|
||||
}
|
||||
|
||||
async function respondWithEncounter(req, res, status = 200, extra = {}) {
|
||||
const encounter = await serializeEncounter(req.encounter.id, req.isDM);
|
||||
await syncCharacterLocations(req);
|
||||
const encounter = await serializeEncounter(req.encounter.id, req.isDM, req.user.id);
|
||||
emitEncounterUpdated(req);
|
||||
res.status(status).json({ ...extra, encounter });
|
||||
}
|
||||
|
||||
router.get('/:id', requireEncounterAccess, async (req, res, next) => {
|
||||
try {
|
||||
res.json({ encounter: await serializeEncounter(req.encounter.id, req.isDM) });
|
||||
res.json({ encounter: await serializeEncounter(req.encounter.id, req.isDM, req.user.id) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
@@ -174,6 +237,7 @@ const patchEncounterSchema = z.object({
|
||||
name: z.string().min(1).max(120).optional(),
|
||||
description: z.string().max(4000).nullable().optional(),
|
||||
dmNotes: z.string().max(4000).nullable().optional(),
|
||||
locationId: z.string().nullable().optional(),
|
||||
archived: z.boolean().optional(), // put away (true) or bring back (false)
|
||||
});
|
||||
|
||||
@@ -185,6 +249,11 @@ router.patch('/:id', requireEncounterAccess, requireDM, async (req, res, next) =
|
||||
if (archived === true && !req.encounter.archivedAt) data.archivedAt = new Date();
|
||||
if (archived === false) data.archivedAt = null;
|
||||
|
||||
if (data.locationId) {
|
||||
const location = await prisma.location.findFirst({ where: { id: data.locationId, campaignId: req.encounter.campaignId } });
|
||||
if (!location) return res.status(400).json({ error: 'That location is not part of this campaign.' });
|
||||
}
|
||||
|
||||
// Starting a battle puts the first combatant in the initiative order on turn.
|
||||
const mode = data.mode ?? req.encounter.mode;
|
||||
if (data.status === 'ACTIVE' && mode === 'BATTLE' && !req.encounter.activeParticipantId) {
|
||||
@@ -221,7 +290,7 @@ const participantSchema = z
|
||||
monsterId: z.string().optional(),
|
||||
npcId: z.string().optional(),
|
||||
displayName: z.string().min(1).max(80).optional(),
|
||||
initiative: z.number().int().default(0),
|
||||
initiativeRoll: initiativeRollSchema.optional(),
|
||||
})
|
||||
.refine((data) => [data.characterId, data.monsterId, data.npcId].filter(Boolean).length === 1, {
|
||||
message: 'Provide exactly one of characterId, monsterId or npcId',
|
||||
@@ -231,9 +300,10 @@ router.post('/:id/participants', requireEncounterAccess, requireDM, async (req,
|
||||
try {
|
||||
const parsed = participantSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { characterId, monsterId, npcId, displayName, initiative } = parsed.data;
|
||||
const { characterId, monsterId, npcId, displayName, initiativeRoll } = parsed.data;
|
||||
|
||||
let currentHp, maxHp, resolvedName;
|
||||
let bonus = 0;
|
||||
|
||||
if (characterId) {
|
||||
const character = await prisma.character.findUnique({
|
||||
@@ -246,6 +316,7 @@ router.post('/:id/participants', requireEncounterAccess, requireDM, async (req,
|
||||
currentHp = character.currentHp;
|
||||
maxHp = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies).hp.max;
|
||||
resolvedName = displayName || character.name;
|
||||
bonus = initiativeBonus({ character });
|
||||
} else if (monsterId) {
|
||||
const monster = await prisma.monster.findUnique({ where: { id: monsterId } });
|
||||
if (!monster || monster.campaignId !== req.encounter.campaignId) {
|
||||
@@ -254,6 +325,7 @@ router.post('/:id/participants', requireEncounterAccess, requireDM, async (req,
|
||||
currentHp = monster.maxHp;
|
||||
maxHp = monster.maxHp;
|
||||
resolvedName = displayName || monster.name;
|
||||
bonus = initiativeBonus({ monster });
|
||||
} else {
|
||||
const npc = await prisma.npc.findUnique({ where: { id: npcId } });
|
||||
if (!npc || npc.campaignId !== req.encounter.campaignId) {
|
||||
@@ -272,7 +344,8 @@ router.post('/:id/participants', requireEncounterAccess, requireDM, async (req,
|
||||
monsterId: monsterId || null,
|
||||
npcId: npcId || null,
|
||||
displayName: resolvedName,
|
||||
initiative,
|
||||
initiativeRoll: initiativeRoll ?? null,
|
||||
initiative: initiativeRoll == null ? 0 : initiativeRoll + bonus,
|
||||
currentHp,
|
||||
maxHp,
|
||||
isMonster: Boolean(monsterId),
|
||||
@@ -287,34 +360,49 @@ router.post('/:id/participants', requireEncounterAccess, requireDM, async (req,
|
||||
|
||||
const updateParticipantSchema = z.object({
|
||||
currentHp: z.number().int().optional(),
|
||||
maxHp: z.number().int().min(1).optional(),
|
||||
initiative: z.number().int().optional(),
|
||||
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(),
|
||||
displayName: z.string().min(1).max(80).optional(),
|
||||
});
|
||||
|
||||
router.patch('/:id/participants/:participantId', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
// The DM runs every combatant. A player may do one thing here: enter the
|
||||
// initiative roll for their own character.
|
||||
router.patch('/:id/participants/:participantId', requireEncounterAccess, async (req, res, next) => {
|
||||
try {
|
||||
const parsed = updateParticipantSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const existing = await prisma.encounterParticipant.findUnique({
|
||||
where: { id: req.params.participantId },
|
||||
include: { character: { include: { skillProficiencies: true, saveProficiencies: true } } },
|
||||
include: { character: { include: { skillProficiencies: true, saveProficiencies: true } }, monster: true },
|
||||
});
|
||||
if (!existing || existing.encounterId !== req.encounter.id) {
|
||||
return res.status(404).json({ error: 'Combatant not found in this encounter' });
|
||||
}
|
||||
if (!req.isDM) {
|
||||
const onlyTheRoll = Object.keys(parsed.data).every((key) => key === 'initiativeRoll');
|
||||
const ownCharacter = existing.character && existing.character.userId === req.user.id;
|
||||
if (!onlyTheRoll || !ownCharacter) {
|
||||
return res.status(403).json({ error: 'You can only enter the initiative roll for your own character' });
|
||||
}
|
||||
}
|
||||
|
||||
const data = { ...parsed.data };
|
||||
// The roll is what was on the die; the bonus is added here.
|
||||
if (data.initiativeRoll !== undefined) {
|
||||
data.initiative = data.initiativeRoll == null ? 0 : data.initiativeRoll + initiativeBonus(existing);
|
||||
}
|
||||
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.currentHp !== undefined) {
|
||||
data.currentHp = clamp(data.currentHp, 0, maxHp);
|
||||
await prisma.character.update({ where: { id: character.id }, data: { currentHp: data.currentHp } });
|
||||
// Temp HP soaks damage first; what is left lands on the character.
|
||||
const after = absorbDamage(character.currentHp, character.tempHp, data.currentHp);
|
||||
data.currentHp = clamp(after.currentHp, 0, maxHp);
|
||||
await prisma.character.update({ where: { id: character.id }, data: { currentHp: data.currentHp, tempHp: after.tempHp } });
|
||||
emitCharacterUpdated(req, character.id);
|
||||
}
|
||||
} else if (data.currentHp !== undefined) {
|
||||
@@ -389,11 +477,12 @@ router.post('/:id/advance-round', requireEncounterAccess, requireDM, async (req,
|
||||
...(req.encounter.mode === 'BATTLE' ? { activeParticipantId: inTurnOrder(participants)[0]?.id ?? null } : {}),
|
||||
},
|
||||
});
|
||||
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) });
|
||||
res.json({ encounter: await serializeEncounter(updated.id, req.isDM, req.user.id) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
@@ -404,18 +493,18 @@ router.post('/:id/advance-round', requireEncounterAccess, requireDM, async (req,
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const rewardSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('GOLD'), gold: z.number().int().min(1), note: z.string().trim().max(200).optional().nullable() }),
|
||||
z.object({ type: z.literal('GOLD'), gold: z.number().int().min(1).max(1000000), note: z.string().trim().max(200).optional().nullable() }),
|
||||
z.object({
|
||||
type: z.literal('WEAPON'),
|
||||
weaponId: z.string(),
|
||||
quantity: z.number().int().min(1).default(1),
|
||||
quantity: z.number().int().min(1).max(999).default(1),
|
||||
level: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
|
||||
note: z.string().trim().max(200).optional().nullable(),
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal('ITEM'),
|
||||
itemId: z.string(),
|
||||
quantity: z.number().int().min(1).default(1),
|
||||
quantity: z.number().int().min(1).max(999).default(1),
|
||||
level: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
|
||||
note: z.string().trim().max(200).optional().nullable(),
|
||||
}),
|
||||
|
||||
Reference in New Issue
Block a user