// Dice: reading an expression ("2d6+3"), rolling it, and checking dice that // were rolled at the table and typed in. Used by the table's dice roller // (POST /campaigns/:id/rolls) and by attacks in an encounter (game/combat.js). // Pure but for the random source, which can be passed in for tests. const crypto = require('crypto'); const rollDie = (sides) => crypto.randomInt(1, sides + 1); const MAX_DICE = 100; const MAX_SIDES = 1000; // Reads the dice expressions the app writes: "1d8", "2d6", "1d6+1d8", // "2d4+2", "1d8 - 1". Returns { dice: [{ count, sides, sign }], flat }, or null // for anything else (free text is allowed where a DM types dice) and for // something too big to be a real roll. Mirrors parseDice in the frontend's // lib/diceRoller.ts. function parseDice(expression) { const terms = String(expression || '') .replace(/\s+/g, '') .replace(/[−–]/g, '-') .toLowerCase() .replace(/-/g, '+-') .split('+') .filter(Boolean); if (terms.length === 0) return null; const parsed = { dice: [], flat: 0 }; let total = 0; for (const term of terms) { const die = /^(-?)(\d*)d(\d+)$/.exec(term); if (die) { const count = Number(die[2]) || 1; const sides = Number(die[3]); total += count; if (total > MAX_DICE || sides < 2 || sides > MAX_SIDES) return null; parsed.dice.push({ count, sides, sign: die[1] ? -1 : 1 }); } else if (/^-?\d+$/.test(term)) { parsed.flat += Number(term); } else { return null; } } return parsed.dice.length > 0 ? parsed : null; } // The dice at the start of a line of text that says more: "2d8+3" from // "2d8+3 fire". Null when it does not start with dice. function leadingDice(text) { const match = /^\s*((?:\d*d\d+|\d+)(?:\s*[+\-−–]\s*(?:\d*d\d+|\d+))*)/i.exec(String(text || '')); return match && parseDice(match[1]) ? match[1].replace(/\s+/g, '') : null; } // Every die of a parsed expression, one entry each, in order: [{ sides, sign }]. function diceOf(parsed) { return parsed.dice.flatMap((term) => Array.from({ length: term.count }, () => ({ sides: term.sides, sign: term.sign }))); } // Whether `values` could be what these dice showed: one whole number per die, // each on its die. function validValues(dice, values) { return Array.isArray(values) && values.length === dice.length && dice.every((die, i) => Number.isInteger(values[i]) && values[i] >= 1 && values[i] <= die.sides); } // Rolls a parsed expression, or takes `values` (dice rolled at the table, // already checked with validValues) in place of rolling. Returns // { dice: [{ sides, value, kept, sign }], modifier, total }. function rollExpression(parsed, { values = null, roll = rollDie } = {}) { const dice = diceOf(parsed).map((die, i) => ({ sides: die.sides, value: values ? values[i] : roll(die.sides), kept: true, sign: die.sign })); return { dice, modifier: parsed.flat, total: dice.reduce((sum, die) => sum + die.sign * die.value, 0) + parsed.flat }; } const D20_MODES = ['NORMAL', 'ADVANTAGE', 'DISADVANTAGE']; // How many d20s a mode rolls: two with advantage or disadvantage. const d20Count = (mode) => (mode === 'NORMAL' ? 1 : 2); // A d20 plus a modifier, as the mode has it: one die, or two with the higher // (advantage) or lower (disadvantage) kept. `values` as in rollExpression. // Returns { dice, modifier, total, natural }: `natural` is the d20 that counted. function rollD20(modifier = 0, mode = 'NORMAL', { values = null, roll = rollDie } = {}) { const rolled = Array.from({ length: d20Count(mode) }, (_, i) => (values ? values[i] : roll(20))); const natural = mode === 'ADVANTAGE' ? Math.max(...rolled) : mode === 'DISADVANTAGE' ? Math.min(...rolled) : rolled[0]; // Of two equal dice only the first is marked as the one kept. const keptIndex = rolled.indexOf(natural); return { dice: rolled.map((value, i) => ({ sides: 20, value, kept: i === keptIndex, sign: 1 })), modifier, total: natural + modifier, natural, }; } // What a critical hit does to damage dice (Campaign.critRule). DOUBLE_DICE: // every die is rolled twice. MAX_PLUS_ROLL: every die counts at its maximum, // and is rolled once more on top. Takes and returns a parsed expression's // roll; the flat modifier is never doubled. function rollCritical(parsed, critRule = 'DOUBLE_DICE', { roll = rollDie } = {}) { const base = diceOf(parsed); const first = base.map((die) => ({ sides: die.sides, value: critRule === 'MAX_PLUS_ROLL' ? die.sides : roll(die.sides), kept: true, sign: die.sign, maxed: critRule === 'MAX_PLUS_ROLL' })); const second = base.map((die) => ({ sides: die.sides, value: roll(die.sides), kept: true, sign: die.sign })); const dice = [...first, ...second]; return { dice, modifier: parsed.flat, total: dice.reduce((sum, die) => sum + die.sign * die.value, 0) + parsed.flat }; } module.exports = { rollDie, parseDice, leadingDice, diceOf, validValues, rollExpression, rollD20, d20Count, rollCritical, D20_MODES, MAX_DICE };