Files
the-sunken-reach/backend/src/game/calculations.js
T
joshuaandClaude Opus 5.5 4a6a09bae8 V1.1.0: gear levels, encounter overhaul, guided builder, trading, docs
Characters
- Builder: pick-then-Next on every step with live preview, Back button,
  plain-language help throughout, and "Suggest for me" for ability scores
- Motivation is picked from a list; new steps for special abilities,
  background and appearance, all composed from fixed lists and DM-only
  to edit afterwards
- Copy a character to another campaign
- Characters can give gold, weapons, items and spells to each other
- Money tracker: gold only changes through a logged ledger
- Fixes: level/XP/location are DM-only, HP stays within 0..max, physical
  dice ability rolls, every die is rolled once

Gear
- DM-managed item pool; weapons, items and spells are handed out by the DM
- Starting-option flag per pool entry
- Gear levels 1-9 per held copy with a damage ladder, growth rate and
  starting level; spells gated by spell level with a fixed damage value
- Spell library carries default damage; damage is picked from a list

Encounters
- Battle and NPC quest modes, turn tracking, scene description, DM notes
- NPCs, richer combatant cards, conditions from a list
- Rewards (gold, weapons, items) lined up and awarded, with gold splitting
- Character HP is shared between the sheet and the encounter
- Monster stat blocks and NPC secrets are never sent to players

Other
- Dice roller on every page
- Docs for characters, weapons, spells, items, encounters, monsters and
  NPCs, with full lists generated from the data (npm run docs:lists)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 16:47:28 +02:00

362 lines
13 KiB
JavaScript

// D&D 5e rules calculation engine — the ONLY place these formulas may live.
// See /docs/GAME_RULES_REFERENCE.md for the spec this implements.
// Pure and dependency-free on purpose: no DB calls, no framework imports.
const { SPECIES } = require('./data/species');
const { CLASSES } = require('./data/classes');
const { SKILLS } = require('./data/skills');
const ABILITIES = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA'];
function abilityModifier(score) {
return Math.floor((score - 10) / 2);
}
function proficiencyBonus(level) {
return 2 + Math.floor((level - 1) / 4);
}
// Half-Elf's flexible +1/+1 lands on whichever two abilities the player picked
// (halfElfBonusAbilities), on top of the fixed +2 CHA in the species table.
function speciesAbilityBonus(ability, species, halfElfBonusAbilities = []) {
const speciesData = species ? SPECIES[species] : null;
if (!speciesData) return 0;
let bonus = speciesData.abilityBonuses[ability] || 0;
if (species === 'HALF_ELF' && halfElfBonusAbilities.includes(ability)) {
bonus += 1;
}
return bonus;
}
function finalAbilityScore(rolledScore, ability, species, halfElfBonusAbilities = []) {
return rolledScore + speciesAbilityBonus(ability, species, halfElfBonusAbilities);
}
function speciesSpeed(species) {
return species && SPECIES[species] ? SPECIES[species].speed : 30;
}
function effectiveSpeed(species, speedOverride) {
return speedOverride != null ? speedOverride : speciesSpeed(species);
}
function saveBonus(abilityMod, proficient, profBonus) {
return abilityMod + (proficient ? profBonus : 0);
}
// expertise (e.g. Rogue) doubles the proficiency portion of the bonus.
function skillBonus(abilityMod, proficient, profBonus, expertise = false) {
if (!proficient) return abilityMod;
return abilityMod + profBonus * (expertise ? 2 : 1);
}
function passivePerception(perceptionSkillBonus) {
return 10 + perceptionSkillBonus;
}
function armorClass(dexMod, armorBonus = 0) {
return 10 + dexMod + armorBonus;
}
function initiative(dexMod) {
return dexMod;
}
// Level 1 always uses the maximum possible Hit Die roll; every level after
// that uses the fixed "average" value (floor(hitDieSize / 2) + 1). Do not
// regress this to a flat average-for-all-levels formula — that was a bug
// caught while building the reference Excel calculator.
function hpMax(level, hitDieSize, conMod) {
const base = hitDieSize + conMod;
if (level <= 1) return base;
const perLevelAverage = Math.floor(hitDieSize / 2) + 1;
return base + (level - 1) * (perLevelAverage + conMod);
}
function spellSaveDC(profBonus, spellAbilityMod) {
return 8 + profBonus + spellAbilityMod;
}
function spellAttackBonus(profBonus, spellAbilityMod) {
return profBonus + spellAbilityMod;
}
// attackAbility is "STR" | "DEX" | "FINESSE" (finesse = better of STR/DEX).
function weaponAbilityModifier(attackAbility, strMod, dexMod) {
if (attackAbility === 'STR') return strMod;
if (attackAbility === 'DEX') return dexMod;
if (attackAbility === 'FINESSE') return Math.max(strMod, dexMod);
throw new Error(`Unknown attackAbility: ${attackAbility}`);
}
function weaponAttackBonus({ attackAbility, strMod, dexMod, proficient, profBonus }) {
const abilityMod = weaponAbilityModifier(attackAbility, strMod, dexMod);
return abilityMod + (proficient ? profBonus : 0);
}
function weaponDamageBonus({ attackAbility, strMod, dexMod }) {
return weaponAbilityModifier(attackAbility, strMod, dexMod);
}
function getGoverningAbilityForSkill(skill) {
const data = SKILLS[skill];
if (!data) throw new Error(`Unknown skill: ${skill}`);
return data.ability;
}
// Saving throw proficiencies are fixed per class, not a player choice —
// use this at character-build finalize time to seed CharacterSaveProficiency.
function getClassSaveProficiencies(characterClass) {
const data = characterClass ? CLASSES[characterClass] : null;
return data ? data.saveProficiencies : [];
}
function getClassHitDieSize(characterClass) {
const data = characterClass ? CLASSES[characterClass] : null;
return data ? data.hitDie : 8;
}
function getClassSpellcastingAbility(characterClass) {
const data = characterClass ? CLASSES[characterClass] : null;
return data ? data.spellcastingAbility : null;
}
/**
* Assembles the full derived character sheet from raw stored data. This is
* the single function the API and quick-stats view should call rather than
* re-deriving any of the above by hand.
*
* @param {object} character - rolled scores, species/class, level, armorBonus, etc.
* @param {Array<{skill: string, proficient: boolean, expertise: boolean}>} skillProficiencies
* @param {Array<{ability: string, proficient: boolean}>} saveProficiencies
*/
function computeCharacterSheet(character, skillProficiencies = [], saveProficiencies = []) {
const {
level = 1,
species = null,
characterClass = null,
strScore = 10,
dexScore = 10,
conScore = 10,
intScore = 10,
wisScore = 10,
chaScore = 10,
halfElfBonusAbility1 = null,
halfElfBonusAbility2 = null,
armorBonus = 0,
speedOverride = null,
} = character;
const halfElfBonusAbilities = [halfElfBonusAbility1, halfElfBonusAbility2].filter(Boolean);
const rolled = { STR: strScore, DEX: dexScore, CON: conScore, INT: intScore, WIS: wisScore, CHA: chaScore };
const abilities = {};
for (const ability of ABILITIES) {
const final = finalAbilityScore(rolled[ability], ability, species, halfElfBonusAbilities);
abilities[ability] = {
rolled: rolled[ability],
final,
modifier: abilityModifier(final),
};
}
const profBonus = proficiencyBonus(level);
const saves = {};
for (const ability of ABILITIES) {
const entry = saveProficiencies.find((s) => s.ability === ability);
const proficient = entry ? entry.proficient : false;
saves[ability] = { proficient, bonus: saveBonus(abilities[ability].modifier, proficient, profBonus) };
}
const skills = {};
for (const skillKey of Object.keys(SKILLS)) {
const ability = getGoverningAbilityForSkill(skillKey);
const entry = skillProficiencies.find((s) => s.skill === skillKey);
const proficient = entry ? entry.proficient : false;
const expertise = entry ? Boolean(entry.expertise) : false;
skills[skillKey] = {
ability,
proficient,
expertise,
bonus: skillBonus(abilities[ability].modifier, proficient, profBonus, expertise),
};
}
const hitDieSize = getClassHitDieSize(characterClass);
const spellcastingAbility = getClassSpellcastingAbility(characterClass);
return {
abilities,
proficiencyBonus: profBonus,
armorClass: armorClass(abilities.DEX.modifier, armorBonus),
initiative: initiative(abilities.DEX.modifier),
speed: effectiveSpeed(species, speedOverride),
hp: { max: hpMax(level, hitDieSize, abilities.CON.modifier) },
hitDice: { size: hitDieSize, count: level },
saves,
skills,
passivePerception: passivePerception(skills.PERCEPTION.bonus),
spellcasting: spellcastingAbility
? {
ability: spellcastingAbility,
saveDC: spellSaveDC(profBonus, abilities[spellcastingAbility].modifier),
attackBonus: spellAttackBonus(profBonus, abilities[spellcastingAbility].modifier),
}
: null,
};
}
// ---------------------------------------------------------------------------
// Gear levels (house rule, not SRD). A held weapon or item has its own level,
// 1-9 (the same span as spell levels), and its dice climb a fixed ladder as it
// levels:
//
// 1d4 1d6 1d8 1d10 1d12 2d6 1d6+1d8 2d8 1d8+1d10 2d10 ...
//
// Each rung is the smallest possible step up in average damage: +1, or +0.5
// where the ladder has to add a die (1d12 -> 2d6, 2d12 -> 3d8, ...).
// ---------------------------------------------------------------------------
const MAX_GEAR_LEVEL = 9;
const DIE_SIZES = [4, 6, 8, 10, 12];
// Rungs a piece of gear climbs per level: 1 = standard, 2 = powerful, 3 = legendary.
const MAX_DAMAGE_SCALING = 3;
function formatDice(sizes) {
const counts = new Map();
for (const size of sizes) counts.set(size, (counts.get(size) || 0) + 1);
return [...counts].map(([size, count]) => `${count}d${size}`).join('+');
}
// k dice whose sizes are as even as possible, `steps` die-size steps above k d4s.
function evenDice(k, steps) {
const sizes = [];
for (let i = 0; i < k; i++) {
const share = Math.floor(steps / k) + (i >= k - (steps % k) ? 1 : 0);
sizes.push(DIE_SIZES[share]);
}
return sizes;
}
function buildDamageLadder(rungs) {
const ladder = [];
let k = 1;
let steps = 0;
while (ladder.length < rungs) {
const maxSteps = k * (DIE_SIZES.length - 1);
if (steps > maxSteps) {
// Out of room at this many dice: add one, landing just above the last rung.
const previousAverage = ladder[ladder.length - 1].average;
k += 1;
steps = Math.floor(previousAverage - k * 2.5) + 1;
continue;
}
ladder.push({ dice: formatDice(evenDice(k, steps)), average: k * 2.5 + steps });
steps += 1;
}
return ladder;
}
// Far longer than max level at legendary scaling needs, so heavy base dice
// (a "10d6" item, say) still have room to climb.
const DAMAGE_LADDER = buildDamageLadder(120);
// Average roll of a dice expression like "1d8", "2d6", "1d6+1d8" or "2d4+2".
// Returns null for anything else (free text is allowed in the pool).
function diceAverage(expression) {
if (typeof expression !== 'string' || !expression.trim()) return null;
let total = 0;
for (const term of expression.replace(/\s+/g, '').toLowerCase().replace(/-/g, '+-').split('+')) {
if (!term) continue;
const die = /^(-?)(\d*)d(\d+)$/.exec(term);
if (die) {
total += (die[1] ? -1 : 1) * (Number(die[2]) || 1) * ((Number(die[3]) + 1) / 2);
} else if (/^-?\d+$/.test(term)) {
total += Number(term);
} else {
return null;
}
}
return total;
}
function clampGearLevel(level) {
return Math.min(Math.max(Math.round(Number(level) || 1), 1), MAX_GEAR_LEVEL);
}
// Dice for a piece of gear at a given level. `minLevel` is the level the gear
// starts at (most gear: 1; a greatsword might only exist from level 3). At its
// starting level it is always the base dice exactly as the DM wrote them;
// above that it climbs `scaling` rungs per level, starting from the highest
// rung that doesn't beat the base (so "1d4+1" starts from 1d6, and a flat "1"
// starts below the ladder). Dice the ladder can't read (free text) never scale.
function scaledDamageDice(baseDice, level = 1, scaling = 1, minLevel = 1) {
const levelsGained = clampGearLevel(level) - clampGearLevel(minLevel);
if (levelsGained <= 0) return baseDice;
const baseAverage = diceAverage(baseDice);
if (baseAverage === null) return baseDice;
let baseRung = -1;
while (baseRung + 1 < DAMAGE_LADDER.length && DAMAGE_LADDER[baseRung + 1].average <= baseAverage) baseRung += 1;
const rungsPerLevel = Math.min(Math.max(Math.round(Number(scaling) || 1), 1), MAX_DAMAGE_SCALING);
const rung = Math.min(baseRung + levelsGained * rungsPerLevel, DAMAGE_LADDER.length - 1);
return DAMAGE_LADDER[rung].dice;
}
// A character can use gear and spells of their own level or lower. For
// weapons and items the required level is the held copy's level; for spells
// it is the classic spell level (cantrips, level 0, are open to everyone).
function canUseGear(characterLevel, requiredLevel) {
return characterLevel >= requiredLevel;
}
/**
* Attack/damage bonus for a specific weapon against a character's abilities —
* used by the quick-stats panel and weapon list. `gearLevel` is the level of
* the copy the character holds.
*/
function computeWeaponStats(weapon, abilities, profBonus, proficient = true, gearLevel = 1) {
const strMod = abilities.STR.modifier;
const dexMod = abilities.DEX.modifier;
return {
attackBonus: weaponAttackBonus({ attackAbility: weapon.attackAbility, strMod, dexMod, proficient, profBonus }),
damageBonus: weaponDamageBonus({ attackAbility: weapon.attackAbility, strMod, dexMod }),
damageDice: scaledDamageDice(weapon.damageDice, gearLevel, weapon.damageScaling, weapon.minLevel),
damageType: weapon.damageType,
};
}
module.exports = {
ABILITIES,
abilityModifier,
proficiencyBonus,
speciesAbilityBonus,
finalAbilityScore,
speciesSpeed,
effectiveSpeed,
saveBonus,
skillBonus,
passivePerception,
armorClass,
initiative,
hpMax,
spellSaveDC,
spellAttackBonus,
weaponAbilityModifier,
weaponAttackBonus,
weaponDamageBonus,
getGoverningAbilityForSkill,
getClassSaveProficiencies,
getClassHitDieSize,
getClassSpellcastingAbility,
computeCharacterSheet,
computeWeaponStats,
MAX_GEAR_LEVEL,
MAX_DAMAGE_SCALING,
DAMAGE_LADDER,
diceAverage,
scaledDamageDice,
canUseGear,
};