import { useEffect, useState } from 'react'; import { fmtMod } from '../lib/format'; const DICE = [4, 6, 8, 10, 12, 20, 100]; const MAX_DICE = 20; const HISTORY_LENGTH = 8; interface Roll { id: number; sides: number; modifier: number; dice: number[]; total: number; } // One fair roll of an n-sided die. Uses the browser's cryptographic random // source, discarding values that would make some faces slightly likelier. function rollDie(sides: number): number { const limit = Math.floor(0x100000000 / sides) * sides; const buffer = new Uint32Array(1); do { crypto.getRandomValues(buffer); } while (buffer[0] >= limit); return (buffer[0] % sides) + 1; } function notation(count: number, sides: number, modifier: number): string { return `${count}d${sides}${modifier ? fmtMod(modifier) : ''}`; } // A table-side dice roller, reachable from every page. These rolls are for // the player's own use at the table: they are not sent to the server and do // not feed the character builder, whose dice stay locked in server-side. export function DiceRoller() { const [open, setOpen] = useState(false); const [sides, setSides] = useState(20); const [count, setCount] = useState(1); const [modifier, setModifier] = useState(0); const [history, setHistory] = useState([]); useEffect(() => { if (!open) return; const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false); window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); }, [open]); const latest = history[0]; function roll() { const dice = Array.from({ length: count }, () => rollDie(sides)); const total = dice.reduce((sum, d) => sum + d, 0) + modifier; setHistory((prev) => [{ id: (prev[0]?.id ?? 0) + 1, sides, modifier, dice, total }, ...prev].slice(0, HISTORY_LENGTH)); } // The natural 20 and natural 1 only mean something on a single d20. const natural = latest && latest.sides === 20 && latest.dice.length === 1 ? latest.dice[0] : null; return ( <> {open && (
Roll Dice
{DICE.map((d) => ( ))}
Dice {count}
{latest ? ( <> {/* Keyed on the roll so the pop animation replays every time, even on a repeat result. */}
{latest.total}
{natural === 20 &&
Natural 20!
} {natural === 1 &&
Natural 1
} {(latest.dice.length > 1 || latest.modifier !== 0) && (
{latest.dice.join(' + ')} {latest.modifier !== 0 && ` ${latest.modifier > 0 ? '+' : '−'} ${Math.abs(latest.modifier)}`} = {latest.total}
)} ) : (

Pick a die and roll.

)}
{history.length > 1 && ( <>
Earlier rolls
{history.slice(1).map((r) => (
{notation(r.dice.length, r.sides, r.modifier)} {r.dice.length > 1 && ({r.dice.join(', ')})} {r.total}
))} )}
)} ); }