V1.26.0: dice that tumble, rolled by the server, seen by the DM

- Each die is drawn as its own shape, tumbles in and lands on its result;
  a natural 20 glows, a natural 1 shakes; respects reduced motion
- In a campaign the server makes every digital roll and keeps it
- The DM sees each roll as it lands: an "Everyone's rolls" tab in the
  roller, a pop-up beside the dice button, and a list on the encounter page
- Players see everyone's rolls or only their own, by the campaign setting;
  the DM can roll hidden
- Physical dice are typed in, one box per die, and checked; with "both",
  each person chooses in the roller
- game/dice.js: parsing, rolling, checking typed dice, critical damage

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 08:46:22 +02:00
co-authored by Claude Opus 5.5
parent c3f2b0dfa7
commit 8811f14732
22 changed files with 1345 additions and 167 deletions
+125
View File
@@ -14,6 +14,7 @@ const { hitDiceProblem, shortRest, longRest } = require('../utils/rest');
const { CURRENCIES } = require('../utils/grants');
const { subclassName } = require('../game/data/subclasses');
const { classLevels } = require('../game/multiclass');
const { parseDice, diceOf, validValues, rollExpression, rollD20, d20Count, D20_MODES, MAX_DICE } = require('../game/dice');
const { findSeed, normalizeCode, CODE_LENGTH } = require('../seeds');
const { createCampaignFromSeed } = require('../seeds/createCampaign');
@@ -1243,4 +1244,128 @@ router.post('/:id/monsters/from-library', requireCampaignMember(), requireDM(),
}
});
// ---------------------------------------------------------------------------
// Dice rolls — the table's dice roller (game/dice.js). A digital roll is made
// here, never taken from the client; a physical one is typed in and checked
// against its dice. Every roll is kept and announced, so the table (and above
// all the DM) sees it.
// ---------------------------------------------------------------------------
const rollSchema = z
.object({
label: z.string().max(120).optional().nullable(),
// A d20 plus `modifier` (a check, a save, an attack), or a dice expression (damage).
kind: z.enum(['check', 'dice']),
modifier: z.number().int().min(-99).max(99).default(0),
mode: z.enum(D20_MODES).default('NORMAL'),
expression: z.string().max(60).optional(),
// Dice rolled at the table: what each showed, in order. Left out, the dice are rolled here.
values: z.array(z.number().int().min(1).max(1000)).max(MAX_DICE).optional(),
hidden: z.boolean().default(false), // the DM's alone
encounterId: z.string().optional().nullable(),
})
.refine((roll) => roll.kind === 'check' || roll.expression, { message: 'A dice roll needs its dice, like "2d6+3".' });
// Rolls older than this are cleared away as new ones come in.
const ROLL_KEEP_DAYS = 14;
const publicRoll = ({ id, userId, rollerName, label, notation, dice, modifier, total, natural, mode, physical, hidden, encounterId, createdAt }) => ({
id,
userId,
rollerName,
label,
notation,
dice,
modifier,
total,
natural,
mode,
physical,
hidden,
encounterId,
createdAt,
});
// Which rolls a member may see: the DM every one; a player their own, and
// everyone's (but the DM's hidden ones) where the campaign shows all rolls.
function visibleRolls(req) {
if (req.membership.role === 'DM') return {};
if (req.campaign.rollVisibility === 'OWN') return { userId: req.user.id };
return { OR: [{ userId: req.user.id }, { hidden: false }] };
}
router.post('/:id/rolls', requireCampaignMember(), async (req, res, next) => {
try {
const parsed = rollSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { label, kind, modifier, mode, expression, values, encounterId } = parsed.data;
const isDM = req.membership.role === 'DM';
// The campaign's dice decide whether a roll is made here or typed in.
const diceMode = req.campaign.diceMode;
if (values && diceMode === 'DIGITAL') return res.status(400).json({ error: 'This campaign plays with digital dice: the app rolls.' });
if (!values && diceMode === 'PHYSICAL') return res.status(400).json({ error: 'This campaign plays with physical dice: roll at the table and enter what the dice show.' });
let rolled;
let notation;
if (kind === 'check') {
const dice = Array.from({ length: d20Count(mode) }, () => ({ sides: 20 }));
if (values && !validValues(dice, values)) {
return res.status(400).json({ error: `Enter ${dice.length === 1 ? 'the d20' : 'both d20s'} you rolled: whole numbers from 1 to 20.` });
}
rolled = rollD20(modifier, mode, { values });
notation = `1d20${modifier ? (modifier > 0 ? `+${modifier}` : `${modifier}`) : ''}`;
} else {
const dice = parseDice(expression);
if (!dice) return res.status(400).json({ error: 'Those dice cannot be read. Write them like "2d6+3".' });
if (values && !validValues(diceOf(dice), values)) {
return res.status(400).json({ error: 'Enter what each die showed, in order, each within its die.' });
}
rolled = { ...rollExpression(dice, { values }), natural: null };
notation = expression.replace(/\s+/g, '');
}
const [roll] = await prisma.$transaction([
prisma.diceRoll.create({
data: {
campaignId: req.campaign.id,
userId: req.user.id,
rollerName: req.user.displayName || 'Someone',
label: label || null,
notation,
dice: rolled.dice,
modifier: rolled.modifier,
total: rolled.total,
natural: rolled.natural,
mode: kind === 'check' ? mode : 'NORMAL',
physical: Boolean(values),
hidden: isDM && parsed.data.hidden, // only the DM rolls behind the screen
encounterId: encounterId || null,
},
}),
prisma.diceRoll.deleteMany({ where: { campaignId: req.campaign.id, createdAt: { lt: new Date(Date.now() - ROLL_KEEP_DAYS * 24 * 60 * 60 * 1000) } } }),
]);
// Ids only: each member's page asks for the roll and gets it only if it is theirs to see.
req.app.get('io').to(`campaign:${req.campaign.id}`).emit('roll:created', { rollId: roll.id, userId: roll.userId });
res.status(201).json({ roll: publicRoll(roll) });
} catch (err) {
next(err);
}
});
// GET /campaigns/:id/rolls — the latest rolls this member may see, newest first.
router.get('/:id/rolls', requireCampaignMember(), async (req, res, next) => {
try {
const limit = Math.min(Math.max(Number(req.query.limit) || 30, 1), 100);
const rolls = await prisma.diceRoll.findMany({
where: { campaignId: req.campaign.id, ...visibleRolls(req) },
orderBy: { createdAt: 'desc' },
take: limit,
});
res.json({ rolls: rolls.map(publicRoll) });
} catch (err) {
next(err);
}
});
module.exports = router;