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>
This commit is contained in:
2026-10-05 16:47:28 +02:00
co-authored by Claude Opus 5.5
parent 94067f1268
commit 4a6a09bae8
44 changed files with 9405 additions and 700 deletions
+59 -10
View File
@@ -4,6 +4,7 @@
const crypto = require('crypto');
const { SPECIES } = require('./data/species');
const { CLASSES } = require('./data/classes');
const { SPECIES_TRAITS, CLASS_FEATURES, TALENTS, TALENT_PICKS } = require('./data/characterOptions');
const ALL_SPECIES = Object.keys(SPECIES);
const ALL_CLASSES = Object.keys(CLASSES);
@@ -28,15 +29,6 @@ const CLASS_ROLL_TABLE = {
8: 'WILDCARD',
};
const MOTIVATION_TABLE = {
1: 'Revenge for a past wrong',
2: 'Seeking fortune or wealth',
3: 'Protecting someone they love',
4: 'Redemption for a past mistake',
5: 'Driven by curiosity or knowledge',
6: 'Duty or oath to a cause or order',
};
function rollDie(sides) {
return crypto.randomInt(1, sides + 1);
}
@@ -87,6 +79,60 @@ function validateManualRoll(sides, value) {
return Number.isInteger(value) && value >= 1 && value <= sides;
}
// ---------------------------------------------------------------------------
// Story steps: background, appearance and special abilities are composed from
// picks out of fixed lists, never typed in.
// ---------------------------------------------------------------------------
// `picks` maps each group's key to the option keys chosen in it. Returns a
// message describing the first problem, or null if the picks are valid.
function validatePicks(groups, picks) {
for (const group of groups) {
const chosen = picks[group.key] || [];
if (!Array.isArray(chosen) || new Set(chosen).size !== chosen.length) return `${group.label}: pick each option once.`;
if (chosen.some((key) => !group.options.some((o) => o.key === key))) return `${group.label}: that is not one of the options.`;
if (chosen.length < group.min || chosen.length > group.max) {
const range = group.min === group.max ? `${group.min}` : `${group.min} to ${group.max}`;
return `${group.label}: pick ${range}.`;
}
}
return null;
}
// One line per group, in the groups' order: "Upbringing: Soldier — Served in
// an army…" or, for several picks, "Personality: Brave, Curious".
function composeFromPicks(groups, picks) {
const lines = [];
for (const group of groups) {
const chosen = group.options.filter((o) => (picks[group.key] || []).includes(o.key));
if (chosen.length === 0) continue;
const detail = chosen.length === 1 && chosen[0].text ? ` — ${chosen[0].text}` : '';
lines.push(`${group.label}: ${chosen.map((o) => o.label).join(', ')}${detail}`);
}
return lines.join('\n');
}
function validateTalents(talentKeys) {
const valid = new Set(talentKeys).size === talentKeys.length && talentKeys.every((key) => TALENTS.some((t) => t.key === key));
return valid && talentKeys.length === TALENT_PICKS ? null : `Pick ${TALENT_PICKS} different talents from the list.`;
}
// Everything a new character can do beyond the numbers: what its species and
// class grant automatically, then the talents the player picked.
function composeSpecialAbilities(species, characterClass, talentKeys = []) {
const abilities = [
...(SPECIES_TRAITS[species] || []),
...(CLASS_FEATURES[characterClass] || []),
...TALENTS.filter((t) => talentKeys.includes(t.key)),
];
// A trait granted twice over (two sources of Darkvision, say) is listed once.
const seen = new Set();
return abilities
.filter((a) => !seen.has(a.name) && seen.add(a.name))
.map((a) => `${a.name} — ${a.text}`)
.join('\n');
}
function speciesChoicesForRoll(roll) {
const entry = SPECIES_ROLL_TABLE[roll];
if (entry === 'WILDCARD') return { type: 'wildcard', options: ALL_SPECIES };
@@ -103,7 +149,6 @@ function classChoicesForRoll(roll) {
module.exports = {
SPECIES_ROLL_TABLE,
CLASS_ROLL_TABLE,
MOTIVATION_TABLE,
ALL_SPECIES,
ALL_CLASSES,
rollDie,
@@ -114,4 +159,8 @@ module.exports = {
randomSample,
autoSelectSkills,
validateManualRoll,
validatePicks,
composeFromPicks,
validateTalents,
composeSpecialAbilities,
};
+114 -3
View File
@@ -207,17 +207,122 @@ function computeCharacterSheet(character, skillProficiencies = [], saveProficien
};
}
// ---------------------------------------------------------------------------
// 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.
* 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) {
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: weapon.damageDice,
damageDice: scaledDamageDice(weapon.damageDice, gearLevel, weapon.damageScaling, weapon.minLevel),
damageType: weapon.damageType,
};
}
@@ -247,4 +352,10 @@ module.exports = {
getClassSpellcastingAbility,
computeCharacterSheet,
computeWeaponStats,
MAX_GEAR_LEVEL,
MAX_DAMAGE_SCALING,
DAMAGE_LADDER,
diceAverage,
scaledDamageDice,
canUseGear,
};
+110
View File
@@ -14,6 +14,10 @@ const {
weaponDamageBonus,
computeCharacterSheet,
computeWeaponStats,
DAMAGE_LADDER,
diceAverage,
scaledDamageDice,
canUseGear,
} = require('./calculations');
describe('abilityModifier', () => {
@@ -211,4 +215,110 @@ describe('computeWeaponStats', () => {
expect(stats.damageBonus).toBe(sheet.abilities.STR.modifier);
expect(stats.damageDice).toBe('1d8');
});
test('uses the dice for the level of the copy the character holds', () => {
const sheet = computeCharacterSheet({ level: 5, strScore: 16 });
const spear = { attackAbility: 'STR', damageDice: '1d6', damageType: 'piercing', damageScaling: 1 };
expect(computeWeaponStats(spear, sheet.abilities, sheet.proficiencyBonus, true, 3).damageDice).toBe('1d10');
// The level changes the dice only, never the bonuses.
expect(computeWeaponStats(spear, sheet.abilities, sheet.proficiencyBonus, true, 3).damageBonus).toBe(sheet.abilities.STR.modifier);
});
});
describe('gear levels — the damage ladder', () => {
test('starts with single dice, then pairs, in the smallest possible steps', () => {
expect(DAMAGE_LADDER.slice(0, 13).map((r) => r.dice)).toEqual([
'1d4', '1d6', '1d8', '1d10', '1d12',
'2d6', '1d6+1d8', '2d8', '1d8+1d10', '2d10', '1d10+1d12', '2d12',
'3d8',
]);
});
test('every rung is stronger than the last by 1 average damage, or 0.5 where a die is added', () => {
for (let i = 1; i < DAMAGE_LADDER.length; i++) {
const step = DAMAGE_LADDER[i].average - DAMAGE_LADDER[i - 1].average;
expect([0.5, 1]).toContain(step);
// The stated average really is the average of the dice shown.
expect(diceAverage(DAMAGE_LADDER[i].dice)).toBe(DAMAGE_LADDER[i].average);
}
});
test('diceAverage reads the expressions DMs type, and rejects free text', () => {
expect(diceAverage('1d8')).toBe(4.5);
expect(diceAverage('d8')).toBe(4.5);
expect(diceAverage('2d6')).toBe(7);
expect(diceAverage('1d6 + 1d8')).toBe(8);
expect(diceAverage('2d4+2')).toBe(7);
expect(diceAverage('1d6-1')).toBe(2.5);
expect(diceAverage('3')).toBe(3);
expect(diceAverage('special')).toBeNull();
expect(diceAverage('')).toBeNull();
expect(diceAverage(null)).toBeNull();
});
});
describe('scaledDamageDice', () => {
const byLevel = (base, scaling, levels) => levels.map((level) => scaledDamageDice(base, level, scaling));
test('standard gear climbs one rung per level', () => {
expect(byLevel('1d4', 1, [1, 2, 3, 4, 5, 6])).toEqual(['1d4', '1d6', '1d8', '1d10', '1d12', '2d6']);
expect(byLevel('1d8', 1, [1, 2, 3])).toEqual(['1d8', '1d10', '1d12']);
});
test('powerful and legendary gear climb two and three rungs per level', () => {
expect(byLevel('1d6', 2, [1, 2, 3, 4])).toEqual(['1d6', '1d10', '2d6', '2d8']);
expect(byLevel('1d8', 3, [1, 2, 3])).toEqual(['1d8', '2d6', '1d8+1d10']);
});
test('level 1 is always the base dice exactly as written', () => {
expect(scaledDamageDice('2d4+2', 1, 1)).toBe('2d4+2');
expect(scaledDamageDice('special', 1, 3)).toBe('special');
});
test('dice that are not on the ladder start from the highest rung that does not beat them', () => {
expect(scaledDamageDice('2d4+2', 2, 1)).toBe('1d6+1d8'); // avg 7 sits on 2d6
expect(scaledDamageDice('1d4+1', 2, 1)).toBe('1d8'); // avg 3.5 sits on 1d6
expect(scaledDamageDice('1', 2, 1)).toBe('1d4'); // below the ladder
});
test('free text never scales, and levels and scaling are clamped to their ranges', () => {
expect(scaledDamageDice('special', 9, 3)).toBe('special');
expect(scaledDamageDice('1d4', 99, 1)).toBe(scaledDamageDice('1d4', 9, 1));
expect(scaledDamageDice('1d4', 9, 1)).toBe('1d8+1d10');
expect(scaledDamageDice('1d4', 0, 1)).toBe('1d4');
expect(scaledDamageDice('1d4', 2, 99)).toBe(scaledDamageDice('1d4', 2, 3));
expect(scaledDamageDice('1d4', 2, undefined)).toBe('1d6');
});
test('gear with a starting level shows its base dice there and climbs from it', () => {
// A greatsword that only exists from level 3: 2d6 at 3, then one rung per level.
expect([3, 4, 5].map((level) => scaledDamageDice('2d6', level, 1, 3))).toEqual(['2d6', '1d6+1d8', '2d8']);
expect(scaledDamageDice('2d6', 1, 1, 3)).toBe('2d6'); // never below its base
expect(scaledDamageDice('2d4+2', 3, 2, 3)).toBe('2d4+2'); // as written at its starting level
const sheet = computeCharacterSheet({ level: 5, strScore: 16 });
const greatsword = { attackAbility: 'STR', damageDice: '2d6', damageType: 'slashing', damageScaling: 1, minLevel: 3 };
expect(computeWeaponStats(greatsword, sheet.abilities, sheet.proficiencyBonus, true, 4).damageDice).toBe('1d6+1d8');
});
test('a higher level is never weaker', () => {
for (const base of ['1d4', '1d12', '2d6', '2d4+2']) {
for (const scaling of [1, 2, 3]) {
for (let level = 2; level <= 9; level++) {
expect(diceAverage(scaledDamageDice(base, level, scaling))).toBeGreaterThan(
diceAverage(scaledDamageDice(base, level - 1, scaling))
);
}
}
}
});
});
describe('canUseGear', () => {
test('a character can use gear of their own level or lower', () => {
expect(canUseGear(1, 1)).toBe(true);
expect(canUseGear(3, 1)).toBe(true);
expect(canUseGear(3, 3)).toBe(true);
expect(canUseGear(2, 3)).toBe(false);
expect(canUseGear(1, 0)).toBe(true); // cantrips
});
});
+375
View File
@@ -0,0 +1,375 @@
// What a player picks from in the story steps of the character builder:
// motivation, special abilities, background and appearance. A character's
// text for these is always composed from the entries below (see buildFlow.js),
// never typed freely, so the builder page fetches this file's contents rather
// than keeping its own copy.
//
// None of this feeds the calculation engine. Special abilities are written as
// table rules for the DM to apply, in plain words.
const MOTIVATIONS = [
{ key: 1, label: 'Revenge for a past wrong' },
{ key: 2, label: 'Seeking fortune or wealth' },
{ key: 3, label: 'Protecting someone they love' },
{ key: 4, label: 'Redemption for a past mistake' },
{ key: 5, label: 'Driven by curiosity or knowledge' },
{ key: 6, label: 'Duty or oath to a cause or order' },
];
// ---------------------------------------------------------------------------
// Special abilities
// ---------------------------------------------------------------------------
// Granted automatically by species.
const SPECIES_TRAITS = {
HUMAN: [{ name: 'Versatile', text: 'Once per day, reroll one skill check you just failed and keep the new result.' }],
HALF_ELF: [
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
{ name: 'Fey Ancestry', text: 'Advantage on saves against being charmed, and magic cannot put you to sleep.' },
],
ELF: [
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
{ name: 'Fey Ancestry', text: 'Advantage on saves against being charmed, and magic cannot put you to sleep.' },
{ name: 'Trance', text: 'You do not sleep. Four hours of meditation rests you as well as a full night.' },
],
GNOME: [
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
{ name: 'Gnome Cunning', text: 'Advantage on Intelligence, Wisdom and Charisma saves against magic.' },
],
DWARF: [
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
{ name: 'Dwarven Resilience', text: 'Advantage on saves against poison, and poison damage against you is halved.' },
],
HALFLING: [
{ name: 'Lucky', text: 'When you roll a 1 on a d20 for an attack, check or save, reroll it and use the new roll.' },
{ name: 'Brave', text: 'Advantage on saves against being frightened.' },
],
DRAGONBORN: [
{ name: 'Breath Weapon', text: 'Once per rest, exhale destructive energy: creatures in a 15-foot cone take 2d6 damage (Dexterity save for half).' },
{ name: 'Draconic Resistance', text: 'Damage of your breath weapon’s type against you is halved.' },
],
TIEFLING: [
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
{ name: 'Hellish Resistance', text: 'Fire damage against you is halved.' },
],
HALF_ORC: [
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
{ name: 'Relentless Endurance', text: 'Once per day, when you would drop to 0 hit points, drop to 1 instead.' },
],
ORC: [
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
{ name: 'Aggressive', text: 'As a bonus action, move up to your speed toward an enemy you can see.' },
],
};
// Granted automatically by class, at level 1.
const CLASS_FEATURES = {
FIGHTER: [
{ name: 'Second Wind', text: 'Once per rest, as a bonus action, recover 1d10 + your level hit points.' },
{ name: 'Fighting Style', text: 'Choose one with your DM: +2 to ranged attacks, +1 AC in armor, or +2 damage with a one-handed weapon.' },
],
BARBARIAN: [
{ name: 'Rage', text: 'Twice per day, for one minute: +2 melee damage, advantage on Strength checks and saves, and physical damage against you is halved.' },
{ name: 'Unarmored Defense', text: 'Without armor, add your Constitution modifier to your AC (ask your DM to set your armor bonus).' },
],
ROGUE: [
{ name: 'Sneak Attack', text: 'Once per turn, deal an extra 1d6 damage to a target you have advantage against, or that has one of your allies next to it.' },
{ name: 'Thieves’ Cant', text: 'You know the secret slang and signs of the criminal underworld.' },
],
RANGER: [
{ name: 'Favored Enemy', text: 'Choose a kind of creature with your DM. Advantage on checks to track them and to recall what you know about them.' },
{ name: 'Natural Explorer', text: 'In the wild you cannot get lost, you find twice as much food, and difficult terrain does not slow your group.' },
],
WIZARD: [
{ name: 'Spellbook', text: 'Your spells are written in a book. You can copy new spells into it when you find them.' },
{ name: 'Arcane Recovery', text: 'Once per day, after a short rest, regain some of your spent magic.' },
],
SORCERER: [
{ name: 'Innate Magic', text: 'Your magic comes from within: you need no spellbook and no prayers.' },
{ name: 'Wild Talent', text: 'Once per day, reroll the damage dice of one spell and keep the better result.' },
],
CLERIC: [
{ name: 'Divine Domain', text: 'Choose with your DM what your god stands for (life, light, war, knowledge…). It shapes the favours you can ask.' },
{ name: 'Healing Hands', text: 'Once per rest, touch a creature to restore 1d8 + your Wisdom modifier hit points.' },
],
PALADIN: [
{ name: 'Divine Sense', text: 'A few times per day, sense any celestial, fiend or undead within 60 feet.' },
{ name: 'Lay on Hands', text: 'A pool of healing equal to 5 × your level per day, spent by touch however you like.' },
],
BARD: [
{ name: 'Bardic Inspiration', text: 'A few times per day, as a bonus action, give an ally a d6 to add to one attack, check or save.' },
{ name: 'Jack of Many Tales', text: 'You have heard a story about nearly everything: ask your DM for one useful rumour per session.' },
],
WARLOCK: [
{ name: 'Otherworldly Patron', text: 'Choose with your DM who granted your power, and what they want in return.' },
{ name: 'Pact Magic', text: 'Your magic returns after a short rest, not only a long one.' },
],
DRUID: [
{ name: 'Druidic', text: 'You know the secret language of druids and can leave hidden messages in it.' },
{ name: 'Nature’s Voice', text: 'You can calm and make simple requests of ordinary animals.' },
],
MONK: [
{ name: 'Martial Arts', text: 'Your unarmed strikes deal 1d4 damage and can use Dexterity. After attacking, make one unarmed strike as a bonus action.' },
{ name: 'Unarmored Defense', text: 'Without armor, add your Wisdom modifier to your AC (ask your DM to set your armor bonus).' },
],
};
// The player picks TALENT_PICKS of these.
const TALENT_PICKS = 2;
const TALENTS = [
{ key: 'ALERT', name: 'Alert', text: 'You cannot be surprised while you are awake.' },
{ key: 'KEEN_EYE', name: 'Keen Eye', text: 'Advantage on checks to spot hidden doors, traps and things out of place.' },
{ key: 'SILVER_TONGUE', name: 'Silver Tongue', text: 'Once per day, reroll a Persuasion or Deception check and keep the better result.' },
{ key: 'LIGHT_SLEEPER', name: 'Light Sleeper', text: 'You wake at the slightest sound, and keeping watch does not tire you.' },
{ key: 'IRON_STOMACH', name: 'Iron Stomach', text: 'Advantage on saves against spoiled food, strong drink and swallowed poisons.' },
{ key: 'ANIMAL_FRIEND', name: 'Animal Friend', text: 'Ordinary animals are calm around you unless provoked.' },
{ key: 'QUICK_HANDS', name: 'Quick Hands', text: 'Once per turn, draw, stow or pick up an object without using your action.' },
{ key: 'SURE_FOOTED', name: 'Sure-Footed', text: 'Advantage on checks to keep your balance or avoid being knocked down.' },
{ key: 'LINGUIST', name: 'Linguist', text: 'You speak two extra languages of your choice, agreed with your DM.' },
{ key: 'FIELD_MEDIC', name: 'Field Medic', text: 'Steadying a dying creature is automatic for you; no roll needed.' },
{ key: 'STRONG_BACK', name: 'Strong Back', text: 'You can carry, lift and drag twice as much as your size suggests.' },
{ key: 'GOOD_MEMORY', name: 'Good Memory', text: 'You recall exactly anything you have seen or heard in the last month.' },
{ key: 'STREETWISE', name: 'Streetwise', text: 'In any town you can find a place to sleep, a rumour, and someone who buys things without asking questions.' },
{ key: 'TOUGH_AS_NAILS', name: 'Tough as Nails', text: 'Once per day, shrug off a blow: reduce one instance of damage by 1d6.' },
];
// ---------------------------------------------------------------------------
// Background and appearance — groups of options. `min`/`max` say how many a
// player picks in each group.
// ---------------------------------------------------------------------------
const BACKGROUND_GROUPS = [
{
key: 'upbringing',
label: 'Upbringing',
prompt: 'What were you before you became an adventurer?',
min: 1,
max: 1,
options: [
{ key: 'SOLDIER', label: 'Soldier', text: 'Served in an army or militia, and still thinks in terms of orders and watches.' },
{ key: 'ACOLYTE', label: 'Acolyte', text: 'Raised in a temple, tending shrines and copying scripture.' },
{ key: 'CRIMINAL', label: 'Criminal', text: 'Made a living outside the law, and knows who to ask for what.' },
{ key: 'NOBLE', label: 'Noble', text: 'Born to wealth and a family name that opens doors — and makes enemies.' },
{ key: 'SCHOLAR', label: 'Scholar', text: 'Spent years among books, chasing answers to old questions.' },
{ key: 'FARMER', label: 'Farmer', text: 'Worked the land from dawn to dusk, and knows the value of a good harvest.' },
{ key: 'SAILOR', label: 'Sailor', text: 'Grew up on deck, at home with rope, salt and bad weather.' },
{ key: 'ARTISAN', label: 'Guild artisan', text: 'Learned a craft in a workshop and takes pride in good work.' },
{ key: 'ENTERTAINER', label: 'Entertainer', text: 'Sang, juggled or acted for coin in taverns and market squares.' },
{ key: 'OUTLANDER', label: 'Outlander', text: 'Raised far from towns, among hunters, herders or nomads.' },
{ key: 'URCHIN', label: 'Urchin', text: 'Grew up alone on city streets, surviving on wits and quick feet.' },
{ key: 'HERMIT', label: 'Hermit', text: 'Lived apart from the world for years, with only thoughts for company.' },
{ key: 'MERCHANT', label: 'Merchant', text: 'Travelled the trade roads buying low and selling high.' },
{ key: 'HEALER', label: 'Village healer', text: 'Set bones, brewed remedies and sat with the sick.' },
],
},
{
key: 'home',
label: 'Home',
prompt: 'Where did you grow up?',
min: 1,
max: 1,
options: [
{ key: 'CITY', label: 'A crowded city', text: 'Noise, alleys and a thousand strangers.' },
{ key: 'VILLAGE', label: 'A small village', text: 'Everyone knew everyone, and nothing stayed secret.' },
{ key: 'PORT', label: 'A harbour town', text: 'Ships, gulls and news from far away.' },
{ key: 'MOUNTAIN', label: 'A mountain hold', text: 'Thin air, stone halls and long winters.' },
{ key: 'FOREST', label: 'Deep in the forest', text: 'Under old trees, far from any road.' },
{ key: 'FRONTIER', label: 'A frontier fort', text: 'The last wall before the wild.' },
{ key: 'ROAD', label: 'On the road', text: 'Never in one place long enough to call it home.' },
{ key: 'MONASTERY', label: 'A remote monastery', text: 'Bells, silence and routine.' },
],
},
{
key: 'turningPoint',
label: 'Turning point',
prompt: 'What set you on the road?',
min: 1,
max: 1,
options: [
{ key: 'LOSS', label: 'Lost someone dear', text: 'And have not been the same since.' },
{ key: 'BETRAYED', label: 'Was betrayed', text: 'By someone they trusted completely.' },
{ key: 'DISASTER', label: 'Survived a disaster', text: 'Fire, flood, plague or war — and walked away when others did not.' },
{ key: 'SECRET', label: 'Found a secret', text: 'Something they were never meant to see.' },
{ key: 'DEBT', label: 'Owes a debt', text: 'One that cannot be repaid by staying home.' },
{ key: 'EXILED', label: 'Was cast out', text: 'Rightly or wrongly, there is no going back.' },
{ key: 'RESCUED', label: 'Was saved by a stranger', text: 'And means to pass the favour on.' },
{ key: 'CALLING', label: 'Heard a calling', text: 'A dream, a sign or a voice that would not let them rest.' },
{ key: 'BOREDOM', label: 'Could not stand the quiet', text: 'An ordinary life was never going to be enough.' },
],
},
{
key: 'personality',
label: 'Personality',
prompt: 'How do others describe you? Pick one or two.',
min: 1,
max: 2,
options: [
{ key: 'BRAVE', label: 'Brave' },
{ key: 'CAUTIOUS', label: 'Cautious' },
{ key: 'CURIOUS', label: 'Curious' },
{ key: 'KIND', label: 'Kind' },
{ key: 'HOT_HEADED', label: 'Hot-headed' },
{ key: 'SARCASTIC', label: 'Sarcastic' },
{ key: 'LOYAL', label: 'Loyal' },
{ key: 'HONEST', label: 'Honest to a fault' },
{ key: 'CHEERFUL', label: 'Cheerful' },
{ key: 'QUIET', label: 'Quiet' },
{ key: 'PROUD', label: 'Proud' },
{ key: 'SUPERSTITIOUS', label: 'Superstitious' },
{ key: 'GENEROUS', label: 'Generous' },
{ key: 'STUBBORN', label: 'Stubborn' },
],
},
{
key: 'flaw',
label: 'Flaw',
prompt: 'What gets you into trouble?',
min: 1,
max: 1,
options: [
{ key: 'GREEDY', label: 'Greedy', text: 'Cannot walk past treasure.' },
{ key: 'RECKLESS', label: 'Reckless', text: 'Acts first and thinks later.' },
{ key: 'VENGEFUL', label: 'Holds grudges', text: 'Never forgets a slight.' },
{ key: 'GULLIBLE', label: 'Too trusting', text: 'Believes a good story.' },
{ key: 'COWARDLY', label: 'Loses their nerve', text: 'When it matters most.' },
{ key: 'BOASTFUL', label: 'Boastful', text: 'Promises more than they can deliver.' },
{ key: 'SECRETIVE', label: 'Secretive', text: 'Keeps things even from friends.' },
{ key: 'SOFT_HEARTED', label: 'Soft-hearted', text: 'Cannot refuse someone in need.' },
{ key: 'TEMPER', label: 'Short temper', text: 'Easily provoked.' },
],
},
];
const APPEARANCE_GROUPS = [
{
key: 'build',
label: 'Build',
prompt: 'What shape are you?',
min: 1,
max: 1,
options: [
{ key: 'SLIGHT', label: 'Slight' },
{ key: 'LEAN', label: 'Lean' },
{ key: 'AVERAGE', label: 'Average' },
{ key: 'STOCKY', label: 'Stocky' },
{ key: 'MUSCULAR', label: 'Muscular' },
{ key: 'HEAVYSET', label: 'Heavyset' },
],
},
{
key: 'height',
label: 'Height',
prompt: 'For your species, are you…',
min: 1,
max: 1,
options: [
{ key: 'SHORT', label: 'Short' },
{ key: 'AVERAGE', label: 'Average height' },
{ key: 'TALL', label: 'Tall' },
{ key: 'TOWERING', label: 'Towering' },
],
},
{
key: 'hair',
label: 'Hair',
prompt: 'Hair (or what you have instead).',
min: 1,
max: 1,
options: [
{ key: 'BLACK', label: 'Black' },
{ key: 'BROWN', label: 'Brown' },
{ key: 'BLONDE', label: 'Blonde' },
{ key: 'RED', label: 'Red' },
{ key: 'GREY', label: 'Grey' },
{ key: 'WHITE', label: 'White' },
{ key: 'UNUSUAL', label: 'An unusual colour' },
{ key: 'BALD', label: 'Bald' },
{ key: 'NONE', label: 'None — scales, horns or crest' },
],
},
{
key: 'eyes',
label: 'Eyes',
prompt: 'Eye colour.',
min: 1,
max: 1,
options: [
{ key: 'BROWN', label: 'Brown' },
{ key: 'BLUE', label: 'Blue' },
{ key: 'GREEN', label: 'Green' },
{ key: 'GREY', label: 'Grey' },
{ key: 'AMBER', label: 'Amber' },
{ key: 'BLACK', label: 'Black' },
{ key: 'VIOLET', label: 'Violet' },
{ key: 'MISMATCHED', label: 'Mismatched' },
],
},
{
key: 'complexion',
label: 'Skin',
prompt: 'Skin or scales.',
min: 1,
max: 1,
options: [
{ key: 'PALE', label: 'Pale' },
{ key: 'FAIR', label: 'Fair' },
{ key: 'TANNED', label: 'Tanned' },
{ key: 'BROWN', label: 'Brown' },
{ key: 'DARK', label: 'Dark' },
{ key: 'WEATHERED', label: 'Weathered' },
{ key: 'ASHEN', label: 'Ashen grey' },
{ key: 'GREEN', label: 'Green-tinged' },
{ key: 'RED', label: 'Deep red' },
{ key: 'SCALED', label: 'Scaled' },
],
},
{
key: 'features',
label: 'Distinguishing features',
prompt: 'What would a stranger remember? Pick up to two, or none.',
min: 0,
max: 2,
options: [
{ key: 'SCAR', label: 'A scar across the face' },
{ key: 'TATTOO', label: 'A tattoo' },
{ key: 'FRECKLES', label: 'Freckles' },
{ key: 'BROKEN_NOSE', label: 'A broken nose' },
{ key: 'EYEPATCH', label: 'An eyepatch' },
{ key: 'BEARD', label: 'A braided beard' },
{ key: 'PIERCINGS', label: 'Piercings' },
{ key: 'BIRTHMARK', label: 'A birthmark' },
{ key: 'BURN', label: 'An old burn' },
{ key: 'MISSING_FINGER', label: 'A missing finger' },
{ key: 'LIMP', label: 'A slight limp' },
{ key: 'BIG_GRIN', label: 'An easy grin' },
],
},
{
key: 'style',
label: 'Usually wears',
prompt: 'What are you usually seen in?',
min: 1,
max: 1,
options: [
{ key: 'LEATHERS', label: 'Travel-worn leathers' },
{ key: 'ARMOR', label: 'Well-kept armor' },
{ key: 'CLOAK', label: 'A hooded cloak' },
{ key: 'FINE', label: 'Fine clothes' },
{ key: 'PATCHED', label: 'Patched and mended clothes' },
{ key: 'ROBES', label: 'Long robes' },
{ key: 'FURS', label: 'Furs and hides' },
{ key: 'BRIGHT', label: 'Bright colours' },
{ key: 'PLAIN', label: 'Plain, practical clothes' },
],
},
];
module.exports = {
MOTIVATIONS,
SPECIES_TRAITS,
CLASS_FEATURES,
TALENT_PICKS,
TALENTS,
BACKGROUND_GROUPS,
APPEARANCE_GROUPS,
};
+41 -35
View File
@@ -3,16 +3,22 @@
// isn't hand-typing spells from scratch. Shape matches the `Spell` Prisma
// model minus `id`/`campaignId`, plus a stable `key` for "add to campaign"
// lookups and a `classes` tag array the library picker can filter by.
//
// `level` is the classic spell level, which in this app is also the character
// level needed to use the spell. `damageDice` is a default for spells that
// deal damage — the dice at the spell's own level, per the SRD (per ray for
// Scorching Ray, total for Magic Missile's three darts). Spells that only
// heal, protect or control have none. A DM can change either after adding.
const SPELL_LIBRARY = [
// ---- Cantrips (level 0) ----
{ key: 'acid-splash', name: 'Acid Splash', level: 0, school: 'Conjuration', castingTime: '1 action', range: '60 feet', duration: 'Instantaneous', description: 'Hurl a bubble of acid at one or two creatures within 5 feet of each other.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'acid-splash', name: 'Acid Splash', level: 0, school: 'Conjuration', castingTime: '1 action', range: '60 feet', duration: 'Instantaneous', description: 'Hurl a bubble of acid at one or two creatures within 5 feet of each other.', damageDice: '1d6', classes: ['SORCERER', 'WIZARD'] },
{ key: 'blade-ward', name: 'Blade Ward', level: 0, school: 'Abjuration', castingTime: '1 action', range: 'Self', duration: '1 round', description: 'Resist bludgeoning, piercing, and slashing damage until your next turn.', classes: ['BARD', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'chill-touch', name: 'Chill Touch', level: 0, school: 'Necromancy', castingTime: '1 action', range: '120 feet', duration: '1 round', description: 'A ghostly hand deals necrotic damage and prevents healing.', classes: ['SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'chill-touch', name: 'Chill Touch', level: 0, school: 'Necromancy', castingTime: '1 action', range: '120 feet', duration: '1 round', description: 'A ghostly hand deals necrotic damage and prevents healing.', damageDice: '1d8', classes: ['SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'dancing-lights', name: 'Dancing Lights', level: 0, school: 'Illusion', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 1 minute', description: 'Create up to four torch-sized lights that you can move.', classes: ['BARD', 'SORCERER', 'WIZARD'] },
{ key: 'druidcraft', name: 'Druidcraft', level: 0, school: 'Transmutation', castingTime: '1 action', range: '30 feet', duration: 'Instantaneous', description: 'A small, harmless nature-flavored effect: predict weather, sprout a seedling, and the like.', classes: ['DRUID'] },
{ key: 'eldritch-blast', name: 'Eldritch Blast', level: 0, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: 'Instantaneous', description: 'A beam of crackling energy strikes one creature for force damage.', classes: ['WARLOCK'] },
{ key: 'fire-bolt', name: 'Fire Bolt', level: 0, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: 'Instantaneous', description: 'Hurl a mote of fire that deals fire damage on a hit.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'eldritch-blast', name: 'Eldritch Blast', level: 0, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: 'Instantaneous', description: 'A beam of crackling energy strikes one creature for force damage.', damageDice: '1d10', classes: ['WARLOCK'] },
{ key: 'fire-bolt', name: 'Fire Bolt', level: 0, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: 'Instantaneous', description: 'Hurl a mote of fire that deals fire damage on a hit.', damageDice: '1d10', classes: ['SORCERER', 'WIZARD'] },
{ key: 'friends', name: 'Friends', level: 0, school: 'Enchantment', castingTime: '1 action', range: 'Self', duration: 'Concentration, up to 1 minute', description: 'Advantage on Charisma checks against one creature for the duration.', classes: ['BARD', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'guidance', name: 'Guidance', level: 0, school: 'Divination', castingTime: '1 action', range: 'Touch', duration: 'Concentration, up to 1 minute', description: 'Add 1d4 to one ability check of your choice.', classes: ['CLERIC', 'DRUID'] },
{ key: 'light', name: 'Light', level: 0, school: 'Evocation', castingTime: '1 action', range: 'Touch', duration: '1 hour', description: 'An object sheds bright light in a 20-foot radius.', classes: ['BARD', 'CLERIC', 'SORCERER', 'WIZARD'] },
@@ -20,25 +26,25 @@ const SPELL_LIBRARY = [
{ key: 'mending', name: 'Mending', level: 0, school: 'Transmutation', castingTime: '1 minute', range: 'Touch', duration: 'Instantaneous', description: 'Repairs a single break or tear in an object.', classes: ['BARD', 'CLERIC', 'DRUID', 'SORCERER', 'WIZARD'] },
{ key: 'message', name: 'Message', level: 0, school: 'Transmutation', castingTime: '1 action', range: '120 feet', duration: '1 round', description: 'Whisper a message to a target that only they can hear, with a whispered reply.', classes: ['BARD', 'SORCERER', 'WIZARD'] },
{ key: 'minor-illusion', name: 'Minor Illusion', level: 0, school: 'Illusion', castingTime: '1 action', range: '30 feet', duration: '1 minute', description: 'Create a sound or an image of an object for the duration.', classes: ['BARD', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'poison-spray', name: 'Poison Spray', level: 0, school: 'Conjuration', castingTime: '1 action', range: '10 feet', duration: 'Instantaneous', description: 'Project a puff of noxious gas that deals poison damage.', classes: ['DRUID', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'poison-spray', name: 'Poison Spray', level: 0, school: 'Conjuration', castingTime: '1 action', range: '10 feet', duration: 'Instantaneous', description: 'Project a puff of noxious gas that deals poison damage.', damageDice: '1d12', classes: ['DRUID', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'prestidigitation', name: 'Prestidigitation', level: 0, school: 'Transmutation', castingTime: '1 action', range: '10 feet', duration: 'Up to 1 hour', description: 'A minor magical trick — light a candle, clean an object, chill or warm food, and the like.', classes: ['BARD', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'produce-flame', name: 'Produce Flame', level: 0, school: 'Conjuration', castingTime: '1 action', range: 'Self', duration: '10 minutes', description: 'A flickering flame in your hand sheds light and can be hurled for fire damage.', classes: ['DRUID'] },
{ key: 'ray-of-frost', name: 'Ray of Frost', level: 0, school: 'Evocation', castingTime: '1 action', range: '60 feet', duration: 'Instantaneous', description: 'A ray of freezing energy deals cold damage and slows the target.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'produce-flame', name: 'Produce Flame', level: 0, school: 'Conjuration', castingTime: '1 action', range: 'Self', duration: '10 minutes', description: 'A flickering flame in your hand sheds light and can be hurled for fire damage.', damageDice: '1d8', classes: ['DRUID'] },
{ key: 'ray-of-frost', name: 'Ray of Frost', level: 0, school: 'Evocation', castingTime: '1 action', range: '60 feet', duration: 'Instantaneous', description: 'A ray of freezing energy deals cold damage and slows the target.', damageDice: '1d8', classes: ['SORCERER', 'WIZARD'] },
{ key: 'resistance', name: 'Resistance', level: 0, school: 'Abjuration', castingTime: '1 action', range: 'Touch', duration: 'Concentration, up to 1 minute', description: 'The target adds 1d4 to one saving throw of its choice.', classes: ['CLERIC', 'DRUID'] },
{ key: 'sacred-flame', name: 'Sacred Flame', level: 0, school: 'Evocation', castingTime: '1 action', range: '60 feet', duration: 'Instantaneous', description: 'Radiant flame descends on a creature that must succeed a Dexterity save or take damage.', classes: ['CLERIC'] },
{ key: 'sacred-flame', name: 'Sacred Flame', level: 0, school: 'Evocation', castingTime: '1 action', range: '60 feet', duration: 'Instantaneous', description: 'Radiant flame descends on a creature that must succeed a Dexterity save or take damage.', damageDice: '1d8', classes: ['CLERIC'] },
{ key: 'shillelagh', name: 'Shillelagh', level: 0, school: 'Transmutation', castingTime: '1 bonus action', range: 'Touch', duration: '1 minute', description: 'Imbue a club or quarterstaff with magic, using Wisdom for its attack and damage.', classes: ['DRUID'] },
{ key: 'shocking-grasp', name: 'Shocking Grasp', level: 0, school: 'Evocation', castingTime: '1 action', range: 'Touch', duration: 'Instantaneous', description: 'Lightning springs from your hand, dealing damage and preventing reactions.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'shocking-grasp', name: 'Shocking Grasp', level: 0, school: 'Evocation', castingTime: '1 action', range: 'Touch', duration: 'Instantaneous', description: 'Lightning springs from your hand, dealing damage and preventing reactions.', damageDice: '1d8', classes: ['SORCERER', 'WIZARD'] },
{ key: 'spare-the-dying', name: 'Spare the Dying', level: 0, school: 'Necromancy', castingTime: '1 action', range: 'Touch', duration: 'Instantaneous', description: 'A creature you touch that has 0 hit points becomes stable.', classes: ['CLERIC'] },
{ key: 'thorn-whip', name: 'Thorn Whip', level: 0, school: 'Transmutation', castingTime: '1 action', range: '30 feet', duration: 'Instantaneous', description: 'A vine-like whip deals damage and drags the target closer.', classes: ['DRUID'] },
{ key: 'thorn-whip', name: 'Thorn Whip', level: 0, school: 'Transmutation', castingTime: '1 action', range: '30 feet', duration: 'Instantaneous', description: 'A vine-like whip deals damage and drags the target closer.', damageDice: '1d6', classes: ['DRUID'] },
{ key: 'true-strike', name: 'True Strike', level: 0, school: 'Divination', castingTime: '1 action', range: '30 feet', duration: 'Concentration, up to 1 round', description: 'Gain advantage on your next attack roll against the target.', classes: ['BARD', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'vicious-mockery', name: 'Vicious Mockery', level: 0, school: 'Enchantment', castingTime: '1 action', range: '60 feet', duration: 'Instantaneous', description: 'A string of insults deals psychic damage and imposes disadvantage on the target’s next attack.', classes: ['BARD'] },
{ key: 'vicious-mockery', name: 'Vicious Mockery', level: 0, school: 'Enchantment', castingTime: '1 action', range: '60 feet', duration: 'Instantaneous', description: 'A string of insults deals psychic damage and imposes disadvantage on the target’s next attack.', damageDice: '1d4', classes: ['BARD'] },
// ---- Level 1 ----
{ key: 'alarm', name: 'Alarm', level: 1, school: 'Abjuration', castingTime: '1 minute', range: '30 feet', duration: '8 hours', description: 'Set an audible or mental alarm against intruders.', classes: ['RANGER', 'WIZARD'] },
{ key: 'animal-friendship', name: 'Animal Friendship', level: 1, school: 'Enchantment', castingTime: '1 action', range: '30 feet', duration: '24 hours', description: 'Convince a beast that you mean it no harm.', classes: ['BARD', 'DRUID', 'RANGER'] },
{ key: 'bane', name: 'Bane', level: 1, school: 'Enchantment', castingTime: '1 action', range: '30 feet', duration: 'Concentration, up to 1 minute', description: 'Up to three creatures subtract 1d4 from attack rolls and saves.', classes: ['BARD', 'CLERIC'] },
{ key: 'bless', name: 'Bless', level: 1, school: 'Enchantment', castingTime: '1 action', range: '30 feet', duration: 'Concentration, up to 1 minute', description: 'Up to three creatures add 1d4 to attack rolls and saves.', classes: ['CLERIC', 'PALADIN'] },
{ key: 'burning-hands', name: 'Burning Hands', level: 1, school: 'Evocation', castingTime: '1 action', range: 'Self (15-foot cone)', duration: 'Instantaneous', description: 'A thin sheet of flame sweeps out from your hands.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'burning-hands', name: 'Burning Hands', level: 1, school: 'Evocation', castingTime: '1 action', range: 'Self (15-foot cone)', duration: 'Instantaneous', description: 'A thin sheet of flame sweeps out from your hands.', damageDice: '3d6', classes: ['SORCERER', 'WIZARD'] },
{ key: 'charm-person', name: 'Charm Person', level: 1, school: 'Enchantment', castingTime: '1 action', range: '30 feet', duration: '1 hour', description: 'A humanoid you can see regards you as a friendly acquaintance.', classes: ['BARD', 'DRUID', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'color-spray', name: 'Color Spray', level: 1, school: 'Illusion', castingTime: '1 action', range: 'Self (15-foot cone)', duration: '1 round', description: 'A dazzling array of flashing colors can blind weak creatures.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'command', name: 'Command', level: 1, school: 'Enchantment', castingTime: '1 action', range: '60 feet', duration: '1 round', description: 'Speak a one-word command a creature must obey.', classes: ['CLERIC', 'PALADIN'] },
@@ -50,20 +56,20 @@ const SPELL_LIBRARY = [
{ key: 'faerie-fire', name: 'Faerie Fire', level: 1, school: 'Evocation', castingTime: '1 action', range: '60 feet', duration: 'Concentration, up to 1 minute', description: 'Objects in a 20-foot cube are outlined in light, granting attackers advantage.', classes: ['DRUID'] },
{ key: 'feather-fall', name: 'Feather Fall', level: 1, school: 'Transmutation', castingTime: '1 reaction', range: '60 feet', duration: '1 minute', description: 'Falling creatures slow to a gentle descent.', classes: ['BARD', 'SORCERER', 'WIZARD'] },
{ key: 'fog-cloud', name: 'Fog Cloud', level: 1, school: 'Conjuration', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 1 hour', description: 'A 20-foot-radius sphere of fog heavily obscures the area.', classes: ['DRUID', 'RANGER', 'SORCERER', 'WIZARD'] },
{ key: 'guiding-bolt', name: 'Guiding Bolt', level: 1, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: '1 round', description: 'A flash of light streaks to a target, dealing radiant damage.', classes: ['CLERIC'] },
{ key: 'guiding-bolt', name: 'Guiding Bolt', level: 1, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: '1 round', description: 'A flash of light streaks to a target, dealing radiant damage.', damageDice: '4d6', classes: ['CLERIC'] },
{ key: 'healing-word', name: 'Healing Word', level: 1, school: 'Evocation', castingTime: '1 bonus action', range: '60 feet', duration: 'Instantaneous', description: 'A creature you can see regains hit points.', classes: ['BARD', 'CLERIC', 'DRUID'] },
{ key: 'hunters-mark', name: "Hunter's Mark", level: 1, school: 'Divination', castingTime: '1 bonus action', range: '90 feet', duration: 'Concentration, up to 1 hour', description: 'Deal extra damage to a marked target and track it magically.', classes: ['RANGER'] },
{ key: 'hunters-mark', name: "Hunter's Mark", level: 1, school: 'Divination', castingTime: '1 bonus action', range: '90 feet', duration: 'Concentration, up to 1 hour', description: 'Deal extra damage to a marked target and track it magically.', damageDice: '1d6', classes: ['RANGER'] },
{ key: 'identify', name: 'Identify', level: 1, school: 'Divination', castingTime: '1 minute', range: 'Touch', duration: 'Instantaneous', description: 'Learn the properties of a magic item or the nature of a spell affecting a creature.', classes: ['BARD', 'WIZARD'] },
{ key: 'jump', name: 'Jump', level: 1, school: 'Transmutation', castingTime: '1 action', range: 'Touch', duration: '1 minute', description: "A creature's jump distance triples.", classes: ['DRUID', 'RANGER', 'SORCERER', 'WIZARD'] },
{ key: 'longstrider', name: 'Longstrider', level: 1, school: 'Transmutation', castingTime: '1 action', range: 'Touch', duration: '1 hour', description: "A creature's speed increases by 10 feet.", classes: ['BARD', 'DRUID', 'RANGER', 'WIZARD'] },
{ key: 'mage-armor', name: 'Mage Armor', level: 1, school: 'Abjuration', castingTime: '1 action', range: 'Touch', duration: '8 hours', description: "A protective magical force gives the target a base AC of 13 + Dex modifier.", classes: ['SORCERER', 'WIZARD'] },
{ key: 'magic-missile', name: 'Magic Missile', level: 1, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: 'Instantaneous', description: 'Three darts of magical force each strike a target unerringly.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'magic-missile', name: 'Magic Missile', level: 1, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: 'Instantaneous', description: 'Three darts of magical force each strike a target unerringly.', damageDice: '3d4+3', classes: ['SORCERER', 'WIZARD'] },
{ key: 'protection-from-evil-and-good', name: 'Protection from Evil and Good', level: 1, school: 'Abjuration', castingTime: '1 action', range: 'Touch', duration: 'Concentration, up to 10 minutes', description: 'Protect a creature from aberrations, celestials, elementals, fey, fiends, and undead.', classes: ['CLERIC', 'PALADIN', 'WARLOCK', 'WIZARD'] },
{ key: 'shield', name: 'Shield', level: 1, school: 'Abjuration', castingTime: '1 reaction', range: 'Self', duration: '1 round', description: 'An invisible barrier grants +5 AC until the start of your next turn.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'sleep', name: 'Sleep', level: 1, school: 'Enchantment', castingTime: '1 action', range: '90 feet', duration: '1 minute', description: 'Creatures in a 20-foot radius fall unconscious, weakest hit points first.', classes: ['BARD', 'SORCERER', 'WIZARD'] },
{ key: 'speak-with-animals', name: 'Speak with Animals', level: 1, school: 'Divination', castingTime: '1 action', range: 'Self', duration: '10 minutes', description: 'Comprehend and verbally communicate with beasts.', classes: ['BARD', 'DRUID', 'RANGER'] },
{ key: 'thunderwave', name: 'Thunderwave', level: 1, school: 'Evocation', castingTime: '1 action', range: 'Self (15-foot cube)', duration: 'Instantaneous', description: 'A wave of thunderous force sweeps out, damaging and pushing creatures.', classes: ['BARD', 'DRUID', 'SORCERER', 'WIZARD'] },
{ key: 'witch-bolt', name: 'Witch Bolt', level: 1, school: 'Evocation', castingTime: '1 action', range: '30 feet', duration: 'Concentration, up to 1 minute', description: 'A beam of lightning forms a sustained arc that damages the target each turn.', classes: ['SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'thunderwave', name: 'Thunderwave', level: 1, school: 'Evocation', castingTime: '1 action', range: 'Self (15-foot cube)', duration: 'Instantaneous', description: 'A wave of thunderous force sweeps out, damaging and pushing creatures.', damageDice: '2d8', classes: ['BARD', 'DRUID', 'SORCERER', 'WIZARD'] },
{ key: 'witch-bolt', name: 'Witch Bolt', level: 1, school: 'Evocation', castingTime: '1 action', range: '30 feet', duration: 'Concentration, up to 1 minute', description: 'A beam of lightning forms a sustained arc that damages the target each turn.', damageDice: '1d12', classes: ['SORCERER', 'WARLOCK', 'WIZARD'] },
// ---- Level 2 ----
{ key: 'aid', name: 'Aid', level: 2, school: 'Abjuration', castingTime: '1 action', range: '30 feet', duration: '8 hours', description: 'Bolster allies with additional hit points.', classes: ['CLERIC', 'PALADIN'] },
@@ -74,7 +80,7 @@ const SPELL_LIBRARY = [
{ key: 'darkvision', name: 'Darkvision', level: 2, school: 'Transmutation', castingTime: '1 action', range: 'Touch', duration: '8 hours', description: 'Grant a creature darkvision out to 60 feet.', classes: ['DRUID', 'RANGER', 'SORCERER', 'WIZARD'] },
{ key: 'enhance-ability', name: 'Enhance Ability', level: 2, school: 'Transmutation', castingTime: '1 action', range: 'Touch', duration: 'Concentration, up to 1 hour', description: 'Grant advantage on checks with one chosen ability.', classes: ['BARD', 'CLERIC', 'DRUID', 'SORCERER'] },
{ key: 'enlarge-reduce', name: 'Enlarge/Reduce', level: 2, school: 'Transmutation', castingTime: '1 action', range: '30 feet', duration: 'Concentration, up to 1 minute', description: 'A creature or object doubles or halves in size.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'flaming-sphere', name: 'Flaming Sphere', level: 2, school: 'Conjuration', castingTime: '1 action', range: '60 feet', duration: 'Concentration, up to 1 minute', description: 'A 5-foot-diameter sphere of fire rolls where you direct it.', classes: ['DRUID', 'WIZARD'] },
{ key: 'flaming-sphere', name: 'Flaming Sphere', level: 2, school: 'Conjuration', castingTime: '1 action', range: '60 feet', duration: 'Concentration, up to 1 minute', description: 'A 5-foot-diameter sphere of fire rolls where you direct it.', damageDice: '2d6', classes: ['DRUID', 'WIZARD'] },
{ key: 'gust-of-wind', name: 'Gust of Wind', level: 2, school: 'Evocation', castingTime: '1 action', range: 'Self (60-foot line)', duration: 'Concentration, up to 1 minute', description: 'A line of strong wind pushes creatures and extinguishes flames.', classes: ['DRUID', 'SORCERER', 'WIZARD'] },
{ key: 'hold-person', name: 'Hold Person', level: 2, school: 'Enchantment', castingTime: '1 action', range: '60 feet', duration: 'Concentration, up to 1 minute', description: 'Paralyze a humanoid that fails a Wisdom save.', classes: ['BARD', 'CLERIC', 'DRUID', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'invisibility', name: 'Invisibility', level: 2, school: 'Illusion', castingTime: '1 action', range: 'Touch', duration: 'Concentration, up to 1 hour', description: 'A creature you touch becomes invisible.', classes: ['BARD', 'SORCERER', 'WARLOCK', 'WIZARD'] },
@@ -82,13 +88,13 @@ const SPELL_LIBRARY = [
{ key: 'levitate', name: 'Levitate', level: 2, school: 'Transmutation', castingTime: '1 action', range: '60 feet', duration: 'Concentration, up to 10 minutes', description: 'A creature or object rises vertically and can be moved.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'mirror-image', name: 'Mirror Image', level: 2, school: 'Illusion', castingTime: '1 action', range: 'Self', duration: '1 minute', description: 'Three illusory duplicates of yourself spring into being.', classes: ['SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'misty-step', name: 'Misty Step', level: 2, school: 'Conjuration', castingTime: '1 bonus action', range: 'Self', duration: 'Instantaneous', description: 'Teleport up to 30 feet in a burst of silvery mist.', classes: ['SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'moonbeam', name: 'Moonbeam', level: 2, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 1 minute', description: 'A silvery beam of pale light shines down in a 5-foot-radius cylinder.', classes: ['DRUID'] },
{ key: 'moonbeam', name: 'Moonbeam', level: 2, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 1 minute', description: 'A silvery beam of pale light shines down in a 5-foot-radius cylinder.', damageDice: '2d10', classes: ['DRUID'] },
{ key: 'pass-without-trace', name: 'Pass without Trace', level: 2, school: 'Abjuration', castingTime: '1 action', range: 'Self', duration: 'Concentration, up to 1 hour', description: 'The party becomes exceptionally difficult to track.', classes: ['DRUID', 'RANGER'] },
{ key: 'scorching-ray', name: 'Scorching Ray', level: 2, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: 'Instantaneous', description: 'Three rays of fire streak toward targets within range.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'shatter', name: 'Shatter', level: 2, school: 'Evocation', castingTime: '1 action', range: '60 feet', duration: 'Instantaneous', description: 'A sudden loud ringing noise deals thunder damage in a 10-foot-radius sphere.', classes: ['BARD', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'scorching-ray', name: 'Scorching Ray', level: 2, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: 'Instantaneous', description: 'Three rays of fire streak toward targets within range.', damageDice: '2d6', classes: ['SORCERER', 'WIZARD'] },
{ key: 'shatter', name: 'Shatter', level: 2, school: 'Evocation', castingTime: '1 action', range: '60 feet', duration: 'Instantaneous', description: 'A sudden loud ringing noise deals thunder damage in a 10-foot-radius sphere.', damageDice: '3d8', classes: ['BARD', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'silence', name: 'Silence', level: 2, school: 'Illusion', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 10 minutes', description: 'No sound can be created within or pass through a 20-foot-radius sphere.', classes: ['BARD', 'CLERIC', 'RANGER'] },
{ key: 'spider-climb', name: 'Spider Climb', level: 2, school: 'Transmutation', castingTime: '1 action', range: 'Touch', duration: 'Concentration, up to 1 hour', description: 'A creature gains the ability to move on vertical surfaces and ceilings.', classes: ['SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'spiritual-weapon', name: 'Spiritual Weapon', level: 2, school: 'Evocation', castingTime: '1 bonus action', range: '60 feet', duration: '1 minute', description: 'A spectral weapon attacks a target and can be moved each turn.', classes: ['CLERIC'] },
{ key: 'spiritual-weapon', name: 'Spiritual Weapon', level: 2, school: 'Evocation', castingTime: '1 bonus action', range: '60 feet', duration: '1 minute', description: 'A spectral weapon attacks a target and can be moved each turn.', damageDice: '1d8', classes: ['CLERIC'] },
{ key: 'suggestion', name: 'Suggestion', level: 2, school: 'Enchantment', castingTime: '1 action', range: '30 feet', duration: 'Concentration, up to 8 hours', description: 'Plant a reasonable-sounding suggestion in a creature’s mind.', classes: ['BARD', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'web', name: 'Web', level: 2, school: 'Conjuration', castingTime: '1 action', range: '60 feet', duration: 'Concentration, up to 1 hour', description: 'Thick, sticky webs fill a 20-foot cube.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'zone-of-truth', name: 'Zone of Truth', level: 2, school: 'Enchantment', castingTime: '1 action', range: '60 feet', duration: '10 minutes', description: 'Creatures in a 15-foot-radius sphere can’t speak a deliberate lie.', classes: ['BARD', 'CLERIC', 'PALADIN'] },
@@ -96,15 +102,15 @@ const SPELL_LIBRARY = [
// ---- Level 3 ----
{ key: 'animate-dead', name: 'Animate Dead', level: 3, school: 'Necromancy', castingTime: '1 minute', range: '10 feet', duration: 'Instantaneous', description: 'Raise a skeleton or zombie from a corpse to fight for you.', classes: ['CLERIC', 'WIZARD'] },
{ key: 'beacon-of-hope', name: 'Beacon of Hope', level: 3, school: 'Abjuration', castingTime: '1 action', range: '30 feet', duration: 'Concentration, up to 1 minute', description: 'Bolster creatures against despair, granting advantage on saves and max healing.', classes: ['CLERIC'] },
{ key: 'call-lightning', name: 'Call Lightning', level: 3, school: 'Conjuration', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 10 minutes', description: 'A storm cloud forms and you can call down bolts of lightning.', classes: ['DRUID'] },
{ key: 'call-lightning', name: 'Call Lightning', level: 3, school: 'Conjuration', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 10 minutes', description: 'A storm cloud forms and you can call down bolts of lightning.', damageDice: '3d10', classes: ['DRUID'] },
{ key: 'counterspell', name: 'Counterspell', level: 3, school: 'Abjuration', castingTime: '1 reaction', range: '60 feet', duration: 'Instantaneous', description: 'Interrupt a creature casting a spell.', classes: ['SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'daylight', name: 'Daylight', level: 3, school: 'Evocation', castingTime: '1 action', range: '60 feet', duration: '1 hour', description: 'A 60-foot-radius sphere of bright light spreads out.', classes: ['CLERIC', 'DRUID', 'PALADIN', 'RANGER', 'SORCERER'] },
{ key: 'dispel-magic', name: 'Dispel Magic', level: 3, school: 'Abjuration', castingTime: '1 action', range: '120 feet', duration: 'Instantaneous', description: 'End one active spell affecting a creature, object, or effect.', classes: ['BARD', 'CLERIC', 'DRUID', 'PALADIN', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'fear', name: 'Fear', level: 3, school: 'Illusion', castingTime: '1 action', range: 'Self (30-foot cone)', duration: 'Concentration, up to 1 minute', description: 'Creatures in the cone become frightened and drop what they’re holding.', classes: ['BARD', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'fireball', name: 'Fireball', level: 3, school: 'Evocation', castingTime: '1 action', range: '150 feet', duration: 'Instantaneous', description: 'A bright streak explodes into flame, dealing fire damage in a 20-foot radius.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'fireball', name: 'Fireball', level: 3, school: 'Evocation', castingTime: '1 action', range: '150 feet', duration: 'Instantaneous', description: 'A bright streak explodes into flame, dealing fire damage in a 20-foot radius.', damageDice: '8d6', classes: ['SORCERER', 'WIZARD'] },
{ key: 'fly', name: 'Fly', level: 3, school: 'Transmutation', castingTime: '1 action', range: 'Touch', duration: 'Concentration, up to 10 minutes', description: 'The target gains a flying speed of 60 feet.', classes: ['SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'haste', name: 'Haste', level: 3, school: 'Transmutation', castingTime: '1 action', range: '30 feet', duration: 'Concentration, up to 1 minute', description: 'Double the target’s speed and grant an extra action.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'lightning-bolt', name: 'Lightning Bolt', level: 3, school: 'Evocation', castingTime: '1 action', range: 'Self (100-foot line)', duration: 'Instantaneous', description: 'A stroke of lightning blasts out in a line, dealing lightning damage.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'lightning-bolt', name: 'Lightning Bolt', level: 3, school: 'Evocation', castingTime: '1 action', range: 'Self (100-foot line)', duration: 'Instantaneous', description: 'A stroke of lightning blasts out in a line, dealing lightning damage.', damageDice: '8d6', classes: ['SORCERER', 'WIZARD'] },
{ key: 'mass-healing-word', name: 'Mass Healing Word', level: 3, school: 'Evocation', castingTime: '1 bonus action', range: '60 feet', duration: 'Instantaneous', description: 'Up to six creatures you can see regain hit points.', classes: ['CLERIC'] },
{ key: 'nondetection', name: 'Nondetection', level: 3, school: 'Abjuration', castingTime: '1 action', range: 'Touch', duration: '8 hours', description: 'Hide a target from divination magic.', classes: ['BARD', 'RANGER', 'WIZARD'] },
{ key: 'protection-from-energy', name: 'Protection from Energy', level: 3, school: 'Abjuration', castingTime: '1 action', range: 'Touch', duration: 'Concentration, up to 1 hour', description: 'Resistance to one damage type of your choice.', classes: ['CLERIC', 'DRUID', 'RANGER', 'SORCERER', 'WIZARD'] },
@@ -112,36 +118,36 @@ const SPELL_LIBRARY = [
{ key: 'revivify', name: 'Revivify', level: 3, school: 'Necromancy', castingTime: '1 action', range: 'Touch', duration: 'Instantaneous', description: 'A creature that died within the last minute returns to life with 1 hit point.', classes: ['CLERIC', 'PALADIN'] },
{ key: 'sleet-storm', name: 'Sleet Storm', level: 3, school: 'Conjuration', castingTime: '1 action', range: '150 feet', duration: 'Concentration, up to 1 minute', description: 'Freezing rain falls in a 40-foot-radius cylinder, icing the ground.', classes: ['DRUID', 'SORCERER', 'WIZARD'] },
{ key: 'slow', name: 'Slow', level: 3, school: 'Transmutation', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 1 minute', description: 'Up to six creatures are hindered, halving their speed and worse.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'spirit-guardians', name: 'Spirit Guardians', level: 3, school: 'Conjuration', castingTime: '1 action', range: 'Self (15-foot radius)', duration: 'Concentration, up to 10 minutes', description: 'Protective spirits swirl around you, damaging enemies that enter.', classes: ['CLERIC'] },
{ key: 'spirit-guardians', name: 'Spirit Guardians', level: 3, school: 'Conjuration', castingTime: '1 action', range: 'Self (15-foot radius)', duration: 'Concentration, up to 10 minutes', description: 'Protective spirits swirl around you, damaging enemies that enter.', damageDice: '3d8', classes: ['CLERIC'] },
{ key: 'stinking-cloud', name: 'Stinking Cloud', level: 3, school: 'Conjuration', castingTime: '1 action', range: '90 feet', duration: 'Concentration, up to 1 minute', description: 'A 20-foot-radius sphere of yellow, nauseating gas spreads out.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'water-breathing', name: 'Water Breathing', level: 3, school: 'Transmutation', castingTime: '1 action', range: '30 feet', duration: '24 hours', description: 'Up to ten creatures can breathe underwater.', classes: ['DRUID', 'RANGER', 'SORCERER', 'WIZARD'] },
// ---- Level 4 ----
{ key: 'banishment', name: 'Banishment', level: 4, school: 'Abjuration', castingTime: '1 action', range: '60 feet', duration: 'Concentration, up to 1 minute', description: 'Send a creature to a harmless demiplane.', classes: ['CLERIC', 'PALADIN', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'blight', name: 'Blight', level: 4, school: 'Necromancy', castingTime: '1 action', range: '30 feet', duration: 'Instantaneous', description: 'Necromantic energy withers a creature, dealing necrotic damage.', classes: ['DRUID', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'blight', name: 'Blight', level: 4, school: 'Necromancy', castingTime: '1 action', range: '30 feet', duration: 'Instantaneous', description: 'Necromantic energy withers a creature, dealing necrotic damage.', damageDice: '8d8', classes: ['DRUID', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'confusion', name: 'Confusion', level: 4, school: 'Enchantment', castingTime: '1 action', range: '90 feet', duration: 'Concentration, up to 1 minute', description: 'Creatures in a 10-foot-radius sphere act randomly.', classes: ['BARD', 'DRUID', 'SORCERER', 'WIZARD'] },
{ key: 'dimension-door', name: 'Dimension Door', level: 4, school: 'Conjuration', castingTime: '1 action', range: '500 feet', duration: 'Instantaneous', description: 'Teleport yourself (and possibly a companion) to a spot you can visualize.', classes: ['BARD', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'fire-shield', name: 'Fire Shield', level: 4, school: 'Evocation', castingTime: '1 action', range: 'Self', duration: '10 minutes', description: 'Wreathe yourself in flame that damages attackers and grants resistance.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'fire-shield', name: 'Fire Shield', level: 4, school: 'Evocation', castingTime: '1 action', range: 'Self', duration: '10 minutes', description: 'Wreathe yourself in flame that damages attackers and grants resistance.', damageDice: '2d8', classes: ['SORCERER', 'WIZARD'] },
{ key: 'freedom-of-movement', name: 'Freedom of Movement', level: 4, school: 'Abjuration', castingTime: '1 action', range: 'Touch', duration: '1 hour', description: 'The target’s movement is unaffected by difficult terrain and restraints.', classes: ['BARD', 'CLERIC', 'DRUID', 'RANGER'] },
{ key: 'greater-invisibility', name: 'Greater Invisibility', level: 4, school: 'Illusion', castingTime: '1 action', range: 'Touch', duration: 'Concentration, up to 1 minute', description: 'The target becomes invisible even while attacking.', classes: ['BARD', 'SORCERER', 'WIZARD'] },
{ key: 'guardian-of-faith', name: 'Guardian of Faith', level: 4, school: 'Conjuration', castingTime: '1 action', range: '30 feet', duration: '8 hours', description: 'A Large spectral guardian appears and attacks enemies near it.', classes: ['CLERIC'] },
{ key: 'ice-storm', name: 'Ice Storm', level: 4, school: 'Evocation', castingTime: '1 action', range: '300 feet', duration: 'Instantaneous', description: 'Hail hammers a 20-foot-radius cylinder, dealing bludgeoning and cold damage.', classes: ['DRUID', 'SORCERER', 'WIZARD'] },
{ key: 'guardian-of-faith', name: 'Guardian of Faith', level: 4, school: 'Conjuration', castingTime: '1 action', range: '30 feet', duration: '8 hours', description: 'A Large spectral guardian appears and attacks enemies near it.', damageDice: '20', classes: ['CLERIC'] },
{ key: 'ice-storm', name: 'Ice Storm', level: 4, school: 'Evocation', castingTime: '1 action', range: '300 feet', duration: 'Instantaneous', description: 'Hail hammers a 20-foot-radius cylinder, dealing bludgeoning and cold damage.', damageDice: '2d8+4d6', classes: ['DRUID', 'SORCERER', 'WIZARD'] },
{ key: 'polymorph', name: 'Polymorph', level: 4, school: 'Transmutation', castingTime: '1 action', range: '60 feet', duration: 'Concentration, up to 1 hour', description: 'Transform a creature into a new form.', classes: ['BARD', 'DRUID', 'SORCERER', 'WIZARD'] },
{ key: 'stone-shape', name: 'Stone Shape', level: 4, school: 'Transmutation', castingTime: '1 action', range: 'Touch', duration: 'Instantaneous', description: 'Reshape a chunk of stone into a form you desire.', classes: ['CLERIC', 'DRUID', 'WIZARD'] },
{ key: 'stoneskin', name: 'Stoneskin', level: 4, school: 'Abjuration', castingTime: '1 action', range: 'Touch', duration: 'Concentration, up to 1 hour', description: 'The target gains resistance to nonmagical bludgeoning, piercing, and slashing damage.', classes: ['DRUID', 'RANGER', 'SORCERER', 'WIZARD'] },
{ key: 'wall-of-fire', name: 'Wall of Fire', level: 4, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 1 minute', description: 'Conjure a wall of fire that damages creatures passing through it.', classes: ['DRUID', 'SORCERER', 'WIZARD'] },
{ key: 'wall-of-fire', name: 'Wall of Fire', level: 4, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 1 minute', description: 'Conjure a wall of fire that damages creatures passing through it.', damageDice: '5d8', classes: ['DRUID', 'SORCERER', 'WIZARD'] },
// ---- Level 5 ----
{ key: 'animate-objects', name: 'Animate Objects', level: 5, school: 'Transmutation', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 1 minute', description: 'Up to ten nonmagical objects animate and fight for you.', classes: ['BARD', 'SORCERER', 'WIZARD'] },
{ key: 'cloudkill', name: 'Cloudkill', level: 5, school: 'Conjuration', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 10 minutes', description: 'A 20-foot-radius sphere of poisonous, yellow-green fog billows out.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'cone-of-cold', name: 'Cone of Cold', level: 5, school: 'Evocation', castingTime: '1 action', range: 'Self (60-foot cone)', duration: 'Instantaneous', description: 'A blast of cold air deals cold damage to everything in the cone.', classes: ['SORCERER', 'WIZARD'] },
{ key: 'cloudkill', name: 'Cloudkill', level: 5, school: 'Conjuration', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 10 minutes', description: 'A 20-foot-radius sphere of poisonous, yellow-green fog billows out.', damageDice: '5d8', classes: ['SORCERER', 'WIZARD'] },
{ key: 'cone-of-cold', name: 'Cone of Cold', level: 5, school: 'Evocation', castingTime: '1 action', range: 'Self (60-foot cone)', duration: 'Instantaneous', description: 'A blast of cold air deals cold damage to everything in the cone.', damageDice: '8d8', classes: ['SORCERER', 'WIZARD'] },
{ key: 'contagion', name: 'Contagion', level: 5, school: 'Necromancy', castingTime: '1 action', range: 'Touch', duration: '7 days', description: 'Infect a creature with a magical disease.', classes: ['CLERIC', 'DRUID'] },
{ key: 'dispel-evil-and-good', name: 'Dispel Evil and Good', level: 5, school: 'Abjuration', castingTime: '1 action', range: 'Self', duration: 'Concentration, up to 1 minute', description: 'Protection and the ability to banish otherworldly creatures.', classes: ['CLERIC', 'PALADIN'] },
{ key: 'dominate-person', name: 'Dominate Person', level: 5, school: 'Enchantment', castingTime: '1 action', range: '60 feet', duration: 'Concentration, up to 1 minute', description: 'Attempt to beguile a humanoid and control its actions.', classes: ['BARD', 'SORCERER', 'WIZARD'] },
{ key: 'flame-strike', name: 'Flame Strike', level: 5, school: 'Evocation', castingTime: '1 action', range: '60 feet', duration: 'Instantaneous', description: 'A column of divine fire roars down, dealing fire and radiant damage.', classes: ['CLERIC'] },
{ key: 'flame-strike', name: 'Flame Strike', level: 5, school: 'Evocation', castingTime: '1 action', range: '60 feet', duration: 'Instantaneous', description: 'A column of divine fire roars down, dealing fire and radiant damage.', damageDice: '8d6', classes: ['CLERIC'] },
{ key: 'greater-restoration', name: 'Greater Restoration', level: 5, school: 'Abjuration', castingTime: '1 action', range: 'Touch', duration: 'Instantaneous', description: 'Undo a debilitating effect: reduced ability score, exhaustion, or curse.', classes: ['BARD', 'CLERIC', 'DRUID'] },
{ key: 'hold-monster', name: 'Hold Monster', level: 5, school: 'Enchantment', castingTime: '1 action', range: '90 feet', duration: 'Concentration, up to 1 minute', description: 'Paralyze one creature that fails a Wisdom save.', classes: ['BARD', 'SORCERER', 'WARLOCK', 'WIZARD'] },
{ key: 'insect-plague', name: 'Insect Plague', level: 5, school: 'Conjuration', castingTime: '1 action', range: '300 feet', duration: 'Concentration, up to 10 minutes', description: 'A swarm of biting, stinging insects fills a 20-foot-radius sphere.', classes: ['CLERIC', 'DRUID', 'SORCERER'] },
{ key: 'insect-plague', name: 'Insect Plague', level: 5, school: 'Conjuration', castingTime: '1 action', range: '300 feet', duration: 'Concentration, up to 10 minutes', description: 'A swarm of biting, stinging insects fills a 20-foot-radius sphere.', damageDice: '4d10', classes: ['CLERIC', 'DRUID', 'SORCERER'] },
{ key: 'legend-lore', name: 'Legend Lore', level: 5, school: 'Divination', castingTime: '10 minutes', range: 'Self', duration: 'Instantaneous', description: 'Learn what you know, or have heard, about a name, place, or object.', classes: ['BARD', 'CLERIC', 'WIZARD'] },
{ key: 'mass-cure-wounds', name: 'Mass Cure Wounds', level: 5, school: 'Evocation', castingTime: '1 action', range: '60 feet', duration: 'Instantaneous', description: 'Up to six creatures in a 30-foot-radius sphere regain hit points.', classes: ['BARD', 'CLERIC', 'DRUID'] },
{ key: 'raise-dead', name: 'Raise Dead', level: 5, school: 'Necromancy', castingTime: '1 hour', range: 'Touch', duration: 'Instantaneous', description: 'Return a dead creature to life, as long as its body is mostly intact.', classes: ['BARD', 'CLERIC', 'PALADIN'] },
File diff suppressed because it is too large Load Diff
+213 -16
View File
@@ -4,7 +4,7 @@ const prisma = require('../db');
const { requireAuth } = require('../middleware/auth');
const { requireCampaignMember, requireDM } = require('../middleware/campaignAccess');
const { generateInviteCode } = require('../utils/inviteCode');
const { computeCharacterSheet } = require('../game/calculations');
const { computeCharacterSheet, MAX_DAMAGE_SCALING, MAX_GEAR_LEVEL } = require('../game/calculations');
const { WEAPON_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../game/data/library');
const router = express.Router();
@@ -167,6 +167,7 @@ function characterSummary(character) {
buildStage: character.buildStage,
currentHp: character.currentHp,
tempHp: character.tempHp,
gold: character.gold,
maxHp: character.buildStage === 'COMPLETE' ? sheet.hp.max : null,
armorClass: character.buildStage === 'COMPLETE' ? sheet.armorClass : null,
currentLocationId: character.currentLocationId,
@@ -210,6 +211,7 @@ router.post('/:id/characters', requireCampaignMember(), async (req, res, next) =
targetUserId = parsed.data.userId;
}
const startingGold = req.campaign.startingGold;
const character = await prisma.character.create({
data: {
campaignId: req.campaign.id,
@@ -217,7 +219,13 @@ router.post('/:id/characters', requireCampaignMember(), async (req, res, next) =
createdById: req.user.id,
name: parsed.data.name,
buildStage: 'ROLLING_SPECIES',
gold: req.campaign.startingGold,
gold: startingGold,
goldTransactions: {
create:
startingGold > 0
? [{ amount: startingGold, balanceAfter: startingGold, reason: 'Starting gold', createdById: req.user.id }]
: [],
},
},
});
@@ -249,8 +257,35 @@ const weaponSchema = z.object({
properties: z.array(z.string()).default([]),
rangeNormal: z.number().int().positive().optional().nullable(),
rangeLong: z.number().int().positive().optional().nullable(),
damageScaling: z.number().int().min(1).max(MAX_DAMAGE_SCALING).optional(),
minLevel: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
isStartingOption: z.boolean().optional(),
});
// Raising a pool entry's starting level lifts every held copy that is now
// below it. A lifted copy comes off, since its holder may no longer be high
// enough level to use it.
async function liftHeldCopies(heldModel, poolKey, poolId, minLevel) {
if (minLevel === undefined) return;
await prisma[heldModel].updateMany({
where: { [poolKey]: poolId, level: { lt: minLevel } },
data: { level: minLevel, equipped: false },
});
}
// Pool entries are addressed by their own id, so every edit/delete is scoped
// to the campaign in the URL — a DM of one campaign can't reach into another.
// Returns the updated row, or null if it isn't in this campaign.
async function updatePoolEntry(model, id, campaignId, data) {
const { count } = await prisma[model].updateMany({ where: { id, campaignId }, data });
return count === 0 ? null : prisma[model].findUnique({ where: { id } });
}
async function deletePoolEntry(model, id, campaignId) {
const { count } = await prisma[model].deleteMany({ where: { id, campaignId } });
return count > 0;
}
router.post('/:id/weapons', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = weaponSchema.safeParse(req.body);
@@ -266,10 +301,9 @@ router.patch('/:id/weapons/:weaponId', requireCampaignMember(), requireDM(), asy
try {
const parsed = weaponSchema.partial().safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const weapon = await prisma.weapon.update({
where: { id: req.params.weaponId },
data: parsed.data,
});
const weapon = await updatePoolEntry('weapon', req.params.weaponId, req.campaign.id, parsed.data);
if (!weapon) return res.status(404).json({ error: 'Weapon not found in this campaign' });
await liftHeldCopies('characterWeapon', 'weaponId', weapon.id, parsed.data.minLevel);
res.json({ weapon });
} catch (err) {
next(err);
@@ -278,7 +312,9 @@ router.patch('/:id/weapons/:weaponId', requireCampaignMember(), requireDM(), asy
router.delete('/:id/weapons/:weaponId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
await prisma.weapon.delete({ where: { id: req.params.weaponId } });
if (!(await deletePoolEntry('weapon', req.params.weaponId, req.campaign.id))) {
return res.status(404).json({ error: 'Weapon not found in this campaign' });
}
res.status(204).end();
} catch (err) {
next(err);
@@ -306,6 +342,8 @@ const spellSchema = z.object({
range: z.string().max(60).optional().nullable(),
duration: z.string().max(60).optional().nullable(),
description: z.string().max(4000).optional().nullable(),
damageDice: z.string().max(20).optional().nullable(),
isStartingOption: z.boolean().optional(),
});
router.post('/:id/spells', requireCampaignMember(), requireDM(), async (req, res, next) => {
@@ -319,11 +357,92 @@ router.post('/:id/spells', requireCampaignMember(), requireDM(), async (req, res
}
});
router.patch('/:id/spells/:spellId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = spellSchema.partial().safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const spell = await updatePoolEntry('spell', req.params.spellId, req.campaign.id, parsed.data);
if (!spell) return res.status(404).json({ error: 'Spell not found in this campaign' });
res.json({ spell });
} catch (err) {
next(err);
}
});
router.delete('/:id/spells/:spellId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
if (!(await deletePoolEntry('spell', req.params.spellId, req.campaign.id))) {
return res.status(404).json({ error: 'Spell not found in this campaign' });
}
res.status(204).end();
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Monsters (DM only, campaign-scoped)
// Items (campaign-level pool; DM manages and hands them out to characters)
// ---------------------------------------------------------------------------
router.get('/:id/monsters', requireCampaignMember(), async (req, res, next) => {
router.get('/:id/items', requireCampaignMember(), async (req, res, next) => {
try {
const items = await prisma.item.findMany({ where: { campaignId: req.campaign.id }, orderBy: { name: 'asc' } });
res.json({ items });
} catch (err) {
next(err);
}
});
const itemSchema = z.object({
name: z.string().min(1).max(120),
description: z.string().max(2000).optional().nullable(),
damageDice: z.string().max(20).optional().nullable(),
damageScaling: z.number().int().min(1).max(MAX_DAMAGE_SCALING).optional(),
minLevel: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
isStartingOption: z.boolean().optional(),
});
router.post('/:id/items', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = itemSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const item = await prisma.item.create({ data: { ...parsed.data, campaignId: req.campaign.id } });
res.status(201).json({ item });
} catch (err) {
next(err);
}
});
router.patch('/:id/items/:itemId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = itemSchema.partial().safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const item = await updatePoolEntry('item', req.params.itemId, req.campaign.id, parsed.data);
if (!item) return res.status(404).json({ error: 'Item not found in this campaign' });
await liftHeldCopies('inventoryItem', 'itemId', item.id, parsed.data.minLevel);
res.json({ item });
} catch (err) {
next(err);
}
});
router.delete('/:id/items/:itemId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
if (!(await deletePoolEntry('item', req.params.itemId, req.campaign.id))) {
return res.status(404).json({ error: 'Item not found in this campaign' });
}
res.status(204).end();
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Monsters (DM only, campaign-scoped — stat blocks are the DM's; players see
// a monster only as a name and a health bar in an encounter)
// ---------------------------------------------------------------------------
router.get('/:id/monsters', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const monsters = await prisma.monster.findMany({ where: { campaignId: req.campaign.id }, orderBy: { name: 'asc' } });
res.json({ monsters });
@@ -365,7 +484,8 @@ router.patch('/:id/monsters/:monsterId', requireCampaignMember(), requireDM(), a
try {
const parsed = monsterSchema.partial().safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const monster = await prisma.monster.update({ where: { id: req.params.monsterId }, data: parsed.data });
const monster = await updatePoolEntry('monster', req.params.monsterId, req.campaign.id, parsed.data);
if (!monster) return res.status(404).json({ error: 'Monster not found in this campaign' });
res.json({ monster });
} catch (err) {
next(err);
@@ -374,7 +494,9 @@ router.patch('/:id/monsters/:monsterId', requireCampaignMember(), requireDM(), a
router.delete('/:id/monsters/:monsterId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
await prisma.monster.delete({ where: { id: req.params.monsterId } });
if (!(await deletePoolEntry('monster', req.params.monsterId, req.campaign.id))) {
return res.status(404).json({ error: 'Monster not found in this campaign' });
}
res.status(204).end();
} catch (err) {
next(err);
@@ -387,27 +509,99 @@ router.delete('/:id/monsters/:monsterId', requireCampaignMember(), requireDM(),
router.get('/:id/encounters', requireCampaignMember(), async (req, res, next) => {
try {
const isDM = req.membership.role === 'DM';
const encounters = await prisma.encounter.findMany({
where: { campaignId: req.campaign.id },
orderBy: { createdAt: 'desc' },
});
res.json({ encounters });
// dmNotes never leaves the server for a player.
res.json({ encounters: isDM ? encounters : encounters.map(({ dmNotes, ...encounter }) => encounter) });
} catch (err) {
next(err);
}
});
const createEncounterSchema = z.object({
name: z.string().min(1).max(120),
mode: z.enum(['BATTLE', 'QUEST']).optional(),
description: z.string().max(4000).optional().nullable(),
});
router.post('/:id/encounters', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = z.object({ name: z.string().min(1).max(120) }).safeParse(req.body);
const parsed = createEncounterSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const encounter = await prisma.encounter.create({ data: { campaignId: req.campaign.id, name: parsed.data.name } });
const encounter = await prisma.encounter.create({ data: { ...parsed.data, campaignId: req.campaign.id } });
res.status(201).json({ encounter });
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// NPCs (DM only — players meet them through encounters, without the DM's
// notes or stats)
// ---------------------------------------------------------------------------
router.get('/:id/npcs', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const npcs = await prisma.npc.findMany({ where: { campaignId: req.campaign.id }, orderBy: { name: 'asc' } });
res.json({ npcs });
} catch (err) {
next(err);
}
});
const npcSchema = z.object({
name: z.string().min(1).max(80),
role: z.string().max(80).optional().nullable(),
disposition: z.enum(['FRIENDLY', 'NEUTRAL', 'HOSTILE']).optional(),
description: z.string().max(2000).optional().nullable(),
dmNotes: z.string().max(4000).optional().nullable(),
ac: z.number().int().min(0).optional().nullable(),
maxHp: z.number().int().min(1).optional().nullable(),
attackBonus: z.number().int().optional().nullable(),
damageDice: z.string().max(20).optional().nullable(),
});
router.post('/:id/npcs', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = npcSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const npc = await prisma.npc.create({ data: { ...parsed.data, campaignId: req.campaign.id } });
res.status(201).json({ npc });
} catch (err) {
next(err);
}
});
router.patch('/:id/npcs/:npcId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = npcSchema.partial().safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const npc = await updatePoolEntry('npc', req.params.npcId, req.campaign.id, parsed.data);
if (!npc) return res.status(404).json({ error: 'NPC not found in this campaign' });
res.json({ npc });
} catch (err) {
next(err);
}
});
router.delete('/:id/npcs/:npcId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const npc = await prisma.npc.findFirst({ where: { id: req.params.npcId, campaignId: req.campaign.id } });
if (!npc) return res.status(404).json({ error: 'NPC not found in this campaign' });
// An NPC that no longer exists leaves the scenes it was in.
await prisma.$transaction([
prisma.encounterParticipant.deleteMany({ where: { npcId: npc.id } }),
prisma.npc.delete({ where: { id: npc.id } }),
]);
res.status(204).end();
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Notes
// ---------------------------------------------------------------------------
@@ -462,7 +656,8 @@ router.patch('/:id/locations/:locationId', requireCampaignMember(), requireDM(),
try {
const parsed = locationSchema.partial().safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const location = await prisma.location.update({ where: { id: req.params.locationId }, data: parsed.data });
const location = await updatePoolEntry('location', req.params.locationId, req.campaign.id, parsed.data);
if (!location) return res.status(404).json({ error: 'Location not found in this campaign' });
res.json({ location });
} catch (err) {
next(err);
@@ -471,7 +666,9 @@ router.patch('/:id/locations/:locationId', requireCampaignMember(), requireDM(),
router.delete('/:id/locations/:locationId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
await prisma.location.delete({ where: { id: req.params.locationId } });
if (!(await deletePoolEntry('location', req.params.locationId, req.campaign.id))) {
return res.status(404).json({ error: 'Location not found in this campaign' });
}
res.status(204).end();
} catch (err) {
next(err);
+581 -136
View File
@@ -3,23 +3,33 @@ const { z } = require('zod');
const prisma = require('../db');
const { requireAuth } = require('../middleware/auth');
const { requireCharacterAccess } = require('../middleware/characterAccess');
const { loadCampaignMembership } = require('../middleware/campaignAccess');
const {
computeCharacterSheet,
computeWeaponStats,
getClassSaveProficiencies,
getClassSpellcastingAbility,
scaledDamageDice,
canUseGear,
MAX_GEAR_LEVEL,
ABILITIES,
} = require('../game/calculations');
const {
rollDie,
rollAbilityScore,
abilityScoreFromDice,
speciesChoicesForRoll,
classChoicesForRoll,
autoSelectSkills,
validateManualRoll,
MOTIVATION_TABLE,
validatePicks,
composeFromPicks,
validateTalents,
composeSpecialAbilities,
} = require('../game/buildFlow');
const characterOptions = require('../game/data/characterOptions');
const { SKILLS } = require('../game/data/skills');
const { InsufficientGoldError, adjustGold, giveGear } = require('../utils/grants');
const router = express.Router();
@@ -31,7 +41,7 @@ async function loadFullCharacter(id) {
include: {
skillProficiencies: true,
saveProficiencies: true,
inventoryItems: true,
inventoryItems: { include: { item: true } },
weapons: { include: { weapon: true } },
spells: { include: { spell: true } },
currentLocation: true,
@@ -79,13 +89,40 @@ function serializeCharacter(character, isOwner) {
buildState: character.buildStage === 'COMPLETE' ? null : character.buildState,
skillProficiencies: character.skillProficiencies,
saveProficiencies: character.saveProficiencies,
inventoryItems: character.inventoryItems,
weapons: character.weapons,
spells: character.spells,
// Each held entry carries what its level works out to: the dice at that
// level, and whether this character is high enough level to use it.
inventoryItems: character.inventoryItems.map((ii) => ({
...ii,
scaledDamageDice: ii.item.damageDice
? scaledDamageDice(ii.item.damageDice, ii.level, ii.item.damageScaling, ii.item.minLevel)
: null,
usable: canUseGear(character.level, ii.level),
})),
weapons: character.weapons.map((cw) => ({
...cw,
scaledDamageDice: scaledDamageDice(cw.weapon.damageDice, cw.level, cw.weapon.damageScaling, cw.weapon.minLevel),
usable: canUseGear(character.level, cw.level),
})),
spells: character.spells.map((cs) => ({ ...cs, usable: canUseGear(character.level, cs.spell.level) })),
sheet: character.buildStage === 'COMPLETE' ? sheet : null,
};
}
// The lists the builder's story steps are made of. Static, and the same for
// everyone; the page fetches them rather than keeping a second copy.
router.get('/build/options', (req, res) => {
const { MOTIVATIONS, SPECIES_TRAITS, CLASS_FEATURES, TALENTS, TALENT_PICKS, BACKGROUND_GROUPS, APPEARANCE_GROUPS } = characterOptions;
res.json({
motivations: MOTIVATIONS,
speciesTraits: SPECIES_TRAITS,
classFeatures: CLASS_FEATURES,
talents: TALENTS,
talentPicks: TALENT_PICKS,
background: BACKGROUND_GROUPS,
appearance: APPEARANCE_GROUPS,
});
});
router.get('/:id', requireCharacterAccess(), async (req, res, next) => {
try {
const character = await loadFullCharacter(req.character.id);
@@ -106,16 +143,39 @@ const patchCharacterSchema = z.object({
appearance: z.string().max(4000).nullable().optional(),
privateNotes: z.string().max(4000).nullable().optional(),
currentLocationId: z.string().nullable().optional(),
gold: z.number().int().min(0).optional(),
level: z.number().int().min(1).max(20).optional(),
xp: z.number().int().min(0).optional(),
});
// Progression and placement are the DM's call, and so is rewriting what the
// builder composed (special abilities, background, appearance): a player
// picks those from lists and cannot type their own. The owning player can
// edit the rest of their own sheet. Gold is not patchable at all — it only
// moves through the ledger (POST /:id/gold).
const DM_ONLY_PATCH_FIELDS = ['level', 'xp', 'currentLocationId', 'speedOverride', 'specialAbilities', 'background', 'appearance'];
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
if (req.body && req.body.gold !== undefined) {
return res.status(400).json({ error: 'Gold changes go through the money tracker.' });
}
const parsed = patchCharacterSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
if (!req.isDM && DM_ONLY_PATCH_FIELDS.some((field) => parsed.data[field] !== undefined)) {
return res.status(403).json({ error: 'Only the DM can change level, XP, speed, location, special abilities, background or appearance.' });
}
// Current HP stays within 0..max, including when a level change moves max.
if (req.character.buildStage === 'COMPLETE' && (parsed.data.currentHp !== undefined || parsed.data.level !== undefined)) {
const maxHp = computeCharacterSheet({ ...req.character, ...parsed.data }).hp.max;
parsed.data.currentHp = clamp(parsed.data.currentHp ?? req.character.currentHp, 0, maxHp);
}
// privateNotes is for the owning player only — a DM editing someone
// else's character (or another player, though write access already
// blocks that) should never be able to set it through this route.
@@ -131,6 +191,16 @@ router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, n
}
const updated = await prisma.character.update({ where: { id: req.character.id }, data: parsed.data });
if (updated.level < req.character.level) {
// Dropping a level can put equipped gear and prepared spells out of reach.
const tooHigh = { characterId: updated.id, level: { gt: updated.level } };
await prisma.characterWeapon.updateMany({ where: tooHigh, data: { equipped: false } });
await prisma.inventoryItem.updateMany({ where: tooHigh, data: { equipped: false } });
await prisma.characterSpell.updateMany({
where: { characterId: updated.id, spell: { level: { gt: updated.level } } },
data: { prepared: false },
});
}
const full = await loadFullCharacter(updated.id);
// Broadcast payload never includes privateNotes — a socket room has
@@ -153,6 +223,154 @@ router.delete('/:id', requireCharacterAccess(), async (req, res, next) => {
}
});
// ---------------------------------------------------------------------------
// Copy to another campaign
// ---------------------------------------------------------------------------
// Weapons, spells and items are per-campaign rows, so a copied character's gear
// is re-pointed at the target campaign's entry of the same name
// (case-insensitive), creating that entry from the source row when the target
// doesn't have one. A created entry is never a starting option — that stays
// the target DM's decision.
// Returns source id -> the target pool row.
async function mapPoolByName(tx, model, sourceRows, targetCampaignId) {
const existing = await tx[model].findMany({ where: { campaignId: targetCampaignId } });
const byName = new Map(existing.map((row) => [row.name.toLowerCase(), row]));
const idMap = new Map();
for (const { id, campaignId, createdAt, ...fields } of sourceRows) {
const key = fields.name.toLowerCase();
if (!byName.has(key)) {
const created = await tx[model].create({
data: { ...fields, isStartingOption: false, campaignId: targetCampaignId },
});
byName.set(key, created);
}
idMap.set(id, byName.get(key));
}
return idMap;
}
// The copy is an independent character owned by whoever made it: the original
// is untouched and the two never sync. Campaign-bound state (location, notes,
// encounter entries) stays behind, and the copy arrives at full HP.
router.post('/:id/copy', requireCharacterAccess(), async (req, res, next) => {
try {
const parsed = z.object({ targetCampaignId: z.string().min(1) }).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { targetCampaignId } = parsed.data;
if (!req.isDM && !req.isOwner) {
return res.status(403).json({ error: 'You can only copy your own character' });
}
if (req.character.buildStage !== 'COMPLETE') {
return res.status(400).json({ error: 'Finish building this character before copying it.' });
}
if (targetCampaignId === req.character.campaignId) {
return res.status(400).json({ error: 'Pick a different campaign to copy this character into.' });
}
const targetMembership = await loadCampaignMembership(req.user.id, targetCampaignId);
if (!targetMembership) return res.status(403).json({ error: 'Not a member of the target campaign' });
const source = await loadFullCharacter(req.character.id);
const sheet = computeCharacterSheet(source, source.skillProficiencies, source.saveProficiencies);
const copyId = await prisma.$transaction(async (tx) => {
const targetWeapons = await mapPoolByName(tx, 'weapon', source.weapons.map((cw) => cw.weapon), targetCampaignId);
const targetSpells = await mapPoolByName(tx, 'spell', source.spells.map((cs) => cs.spell), targetCampaignId);
const targetItems = await mapPoolByName(tx, 'item', source.inventoryItems.map((ii) => ii.item), targetCampaignId);
// Two source entries that differ only by case land on one target row.
const items = new Map();
for (const ii of source.inventoryItems) {
const target = targetItems.get(ii.itemId);
const itemId = target.id;
const prev = items.get(itemId);
items.set(itemId, {
itemId,
quantity: (prev ? prev.quantity : 0) + ii.quantity,
equipped: Boolean(prev && prev.equipped) || ii.equipped,
// The target campaign's entry may start at a higher level than the source's.
level: Math.max(prev ? prev.level : 1, ii.level, target.minLevel),
});
}
const weapons = new Map();
for (const cw of source.weapons) {
const target = targetWeapons.get(cw.weaponId);
const weaponId = target.id;
const prev = weapons.get(weaponId);
weapons.set(weaponId, {
weaponId,
quantity: (prev ? prev.quantity : 0) + cw.quantity,
equipped: Boolean(prev && prev.equipped) || cw.equipped,
level: Math.max(prev ? prev.level : 1, cw.level, target.minLevel),
});
}
const spells = new Map();
for (const cs of source.spells) {
const spellId = targetSpells.get(cs.spellId).id;
const prev = spells.get(spellId);
spells.set(spellId, { spellId, prepared: Boolean(prev && prev.prepared) || cs.prepared });
}
const created = await tx.character.create({
data: {
campaignId: targetCampaignId,
userId: req.user.id,
createdById: req.user.id,
name: source.name,
species: source.species,
characterClass: source.characterClass,
level: source.level,
xp: source.xp,
motivation: source.motivation,
strScore: source.strScore,
dexScore: source.dexScore,
conScore: source.conScore,
intScore: source.intScore,
wisScore: source.wisScore,
chaScore: source.chaScore,
halfElfBonusAbility1: source.halfElfBonusAbility1,
halfElfBonusAbility2: source.halfElfBonusAbility2,
currentHp: sheet.hp.max,
armorBonus: source.armorBonus,
speedOverride: source.speedOverride,
specialAbilities: source.specialAbilities,
gold: source.gold,
background: source.background,
appearance: source.appearance,
// Same privacy boundary as serializeCharacter: a DM copying a
// player's character never carries the player's private notes along.
privateNotes: req.isOwner ? source.privateNotes : null,
diceMode: source.diceMode,
buildStage: 'COMPLETE',
skillProficiencies: {
create: source.skillProficiencies.map(({ skill, proficient, expertise }) => ({ skill, proficient, expertise })),
},
saveProficiencies: {
create: source.saveProficiencies.map(({ ability, proficient }) => ({ ability, proficient })),
},
inventoryItems: { create: [...items.values()] },
goldTransactions: {
create:
source.gold > 0
? [{ amount: source.gold, balanceAfter: source.gold, reason: 'Carried over from another campaign', createdById: req.user.id }]
: [],
},
weapons: { create: [...weapons.values()] },
spells: { create: [...spells.values()] },
},
});
return created.id;
});
const full = await loadFullCharacter(copyId);
req.app.get('io').to(`campaign:${targetCampaignId}`).emit('character:created', { character: serializeCharacter(full, false) });
res.status(201).json({ character: serializeCharacter(full, true) });
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Roll-Your-Character build flow — docs/ROLL_YOUR_CHARACTER.md
// ---------------------------------------------------------------------------
@@ -212,12 +430,15 @@ router.post('/:id/build/roll', requireCharacterAccess({ write: true }), async (r
const buildState = { ...(character.buildState || {}) };
try {
// Every die is rolled once. Going back to a step shows the roll that was
// already made; it never hands out a fresh one.
if (stage === 'ROLLING_SPECIES') {
if (buildState.speciesRoll) {
return res.status(400).json({ error: 'Species die already rolled for this character — choose from what it offered.' });
}
const roll = resolveSingleRoll(character, req.body, 6);
buildState.speciesRoll = roll;
buildState.speciesChoices = speciesChoicesForRoll(roll);
delete buildState.species;
delete buildState.halfElfBonusAbilities;
} else if (stage === 'ROLLING_CLASS') {
const alreadyRolled = buildState.classChoices && buildState.classChoices.type !== 'reroll';
if (alreadyRolled) {
@@ -227,10 +448,6 @@ router.post('/:id/build/roll', requireCharacterAccess({ write: true }), async (r
buildState.classRoll = roll;
buildState.classChoices = classChoicesForRoll(roll);
delete buildState.characterClass;
} else if (stage === 'ROLLING_MOTIVATION') {
const roll = resolveSingleRoll(character, req.body, 6);
buildState.motivationRoll = roll;
buildState.motivationText = MOTIVATION_TABLE[roll];
} else if (stage === 'ASSIGNING_SCORES') {
if (buildState.abilityRolls) {
return res.status(400).json({ error: 'Ability scores were already rolled for this character.' });
@@ -258,7 +475,9 @@ const chooseSchemas = {
halfElfBonusAbilities: z.array(z.enum(HALF_ELF_ELIGIBLE_ABILITIES)).length(2).optional(),
}),
ROLLING_CLASS: z.object({ characterClass: z.string() }),
ROLLING_MOTIVATION: z.object({ motivation: z.string().max(500).optional() }),
// Motivation is story only, so it is simply picked from the list (the stage
// keeps its old name from when it was a die roll).
ROLLING_MOTIVATION: z.object({ motivation: z.number().int() }),
ASSIGNING_SCORES: z.object({
assignments: z.object({
STR: z.number().int().min(0).max(5),
@@ -283,18 +502,35 @@ const chooseSchemas = {
)
.optional(),
}),
CHOOSING_ABILITIES: z.object({ talents: z.array(z.string()) }),
CHOOSING_BACKGROUND: z.object({ picks: z.record(z.array(z.string())) }),
CHOOSING_APPEARANCE: z.object({ picks: z.record(z.array(z.string())) }),
CHOOSING_EQUIPMENT: z.object({
weaponIds: z.array(z.string()).default([]),
itemIds: z.array(z.string()).default([]),
spellIds: z.array(z.string()).default([]),
}),
};
// Every id must be a distinct entry in this campaign's pool that the DM has
// marked as a starting option. `reach` narrows that to entries a character of
// this level can already use (gear by its starting level, spells by their level).
async function allStartingOptions(model, ids, campaignId, reach) {
if (new Set(ids).size !== ids.length) return false;
if (ids.length === 0) return true;
const count = await prisma[model].count({ where: { id: { in: ids }, campaignId, isStartingOption: true, ...reach } });
return count === ids.length;
}
const STAGE_ORDER = [
'ROLLING_SPECIES',
'ROLLING_CLASS',
'ROLLING_MOTIVATION',
'ASSIGNING_SCORES',
'ASSIGNING_PROFICIENCIES',
'CHOOSING_ABILITIES',
'CHOOSING_BACKGROUND',
'CHOOSING_APPEARANCE',
'CHOOSING_EQUIPMENT',
'COMPLETE',
];
@@ -351,8 +587,10 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
buildState.motivationText = null;
}
} else if (stage === 'ROLLING_MOTIVATION') {
if (!buildState.motivationRoll) return res.status(400).json({ error: 'Roll for motivation first.' });
if (parsed.data.motivation) buildState.motivationText = parsed.data.motivation;
const motivation = characterOptions.MOTIVATIONS.find((m) => m.key === parsed.data.motivation);
if (!motivation) return res.status(400).json({ error: 'Pick a motivation from the list.' });
buildState.motivationChoice = motivation.key;
buildState.motivationText = motivation.label;
} else if (stage === 'ASSIGNING_SCORES') {
if (!buildState.abilityRolls) return res.status(400).json({ error: 'Roll ability scores first.' });
const { assignments } = parsed.data;
@@ -364,20 +602,41 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
buildState.abilityAssignments = assignments;
// Skill proficiencies are auto-generated per the class's SRD "choose N"
// rule the moment ability scores are locked in, so the next step has
// something to show immediately rather than an empty picker.
buildState.skillProficiencies = autoSelectSkills(buildState.characterClass);
// something to show immediately rather than an empty picker. They are
// generated once per class and remembered: stepping back and forward
// again (or switching class and switching back) never re-rolls them.
const cls = buildState.characterClass;
if (buildState.skillsForClass !== cls) {
buildState.autoSkills = { ...(buildState.autoSkills || {}) };
buildState.autoSkills[cls] = buildState.autoSkills[cls] || autoSelectSkills(cls);
buildState.skillProficiencies = buildState.autoSkills[cls];
buildState.skillsForClass = cls;
}
} else if (stage === 'ASSIGNING_PROFICIENCIES') {
// Optional DM override of the auto-generated picks; if omitted, the
// auto-generated set from the previous step stands as-is.
if (parsed.data.skillProficiencies) {
buildState.skillProficiencies = parsed.data.skillProficiencies;
}
} else if (stage === 'CHOOSING_ABILITIES') {
const problem = validateTalents(parsed.data.talents);
if (problem) return res.status(400).json({ error: problem });
buildState.talents = parsed.data.talents;
} else if (stage === 'CHOOSING_BACKGROUND' || stage === 'CHOOSING_APPEARANCE') {
const isBackground = stage === 'CHOOSING_BACKGROUND';
const groups = isBackground ? characterOptions.BACKGROUND_GROUPS : characterOptions.APPEARANCE_GROUPS;
const problem = validatePicks(groups, parsed.data.picks);
if (problem) return res.status(400).json({ error: problem });
// Keep only the groups that exist, so nothing else rides along in the build state.
const picks = Object.fromEntries(groups.map((g) => [g.key, parsed.data.picks[g.key] || []]));
buildState[isBackground ? 'backgroundPicks' : 'appearancePicks'] = picks;
} else if (stage === 'CHOOSING_EQUIPMENT') {
const { weaponIds, spellIds } = parsed.data;
const { weaponIds, itemIds, spellIds } = parsed.data;
const maxItems = req.campaign.startingItemCount;
const maxSpells = req.campaign.startingSpellCount;
if (weaponIds.length > maxItems) {
return res.status(400).json({ error: `This campaign allows at most ${maxItems} starting item(s).` });
// Weapons and items share the one "starting items" allowance.
if (weaponIds.length + itemIds.length > maxItems) {
return res.status(400).json({ error: `This campaign allows at most ${maxItems} starting item(s), weapons included.` });
}
const hasSpellcasting = Boolean(getClassSpellcastingAbility(buildState.characterClass));
if (spellIds.length > 0 && !hasSpellcasting) {
@@ -386,7 +645,18 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
if (spellIds.length > maxSpells) {
return res.status(400).json({ error: `This campaign allows at most ${maxSpells} starting spell(s).` });
}
buildState.equipment = { weaponIds, spellIds };
// A new character can only start with what it can already use.
const gearInReach = { minLevel: { lte: character.level } };
const allOffered =
(await allStartingOptions('weapon', weaponIds, req.campaign.id, gearInReach)) &&
(await allStartingOptions('item', itemIds, req.campaign.id, gearInReach)) &&
(await allStartingOptions('spell', spellIds, req.campaign.id, { level: { lte: character.level } }));
if (!allOffered) {
return res.status(400).json({
error: `Pick only from the starting options the DM has made available for a level ${character.level} character.`,
});
}
buildState.equipment = { weaponIds, itemIds, spellIds };
advanceTo = 'CHOOSING_EQUIPMENT'; // stay here; POST /build/finalize completes the character
}
@@ -400,6 +670,40 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
}
});
// Steps back to the previous step so its choice can be changed. Dice are
// never re-rolled: the earlier step comes back with the same roll, the same
// options and the previous pick still in place. The only thing dropped is the
// equipment selection, which is re-confirmed on the way forward (a change of
// class can change which starting spells are allowed).
router.post('/:id/build/back', requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
const character = req.character;
const stage = character.buildStage;
const buildState = { ...(character.buildState || {}) };
let backTo;
if (stage === 'CHOOSING_EQUIPMENT' && buildState.equipment) {
backTo = 'CHOOSING_EQUIPMENT'; // from the finalize prompt back to picking equipment
} else {
const idx = STAGE_ORDER.indexOf(stage);
if (idx <= 0 || stage === 'COMPLETE') {
return res.status(400).json({ error: 'There is no earlier step to go back to.' });
}
backTo = STAGE_ORDER[idx - 1];
if (backTo === 'ROLLING_MOTIVATION' && req.campaign.skipMotivationRoll) backTo = 'ROLLING_CLASS';
}
delete buildState.equipment;
const updated = await prisma.character.update({
where: { id: character.id },
data: { buildState, buildStage: backTo },
});
res.json({ buildStage: updated.buildStage, buildState: updated.buildState });
} catch (err) {
next(err);
}
});
router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
const character = req.character;
@@ -430,6 +734,11 @@ router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), asyn
species: bs.species,
characterClass: bs.characterClass,
motivation: bs.motivationText || null,
// Composed here, from the picks, so the text can only ever say what
// the lists allow.
specialAbilities: composeSpecialAbilities(bs.species, bs.characterClass, bs.talents || []),
background: bs.backgroundPicks ? composeFromPicks(characterOptions.BACKGROUND_GROUPS, bs.backgroundPicks) : null,
appearance: bs.appearancePicks ? composeFromPicks(characterOptions.APPEARANCE_GROUPS, bs.appearancePicks) : null,
strScore: rolledScores.STR,
dexScore: rolledScores.DEX,
conScore: rolledScores.CON,
@@ -453,6 +762,9 @@ router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), asyn
weapons: {
create: (bs.equipment.weaponIds || []).map((weaponId) => ({ weaponId, quantity: 1, equipped: false })),
},
inventoryItems: {
create: (bs.equipment.itemIds || []).map((itemId) => ({ itemId, quantity: 1, equipped: false })),
},
spells: {
create: (bs.equipment.spellIds || []).map((spellId) => ({ spellId, prepared: false })),
},
@@ -488,14 +800,17 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
}
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
const weapons = character.weapons.map((cw) => ({
characterWeaponId: cw.id,
weaponId: cw.weaponId,
name: cw.weapon.name,
equipped: cw.equipped,
quantity: cw.quantity,
...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true),
}));
const weapons = character.weapons
.filter((cw) => canUseGear(character.level, cw.level))
.map((cw) => ({
characterWeaponId: cw.id,
weaponId: cw.weaponId,
name: cw.weapon.name,
level: cw.level,
equipped: cw.equipped,
quantity: cw.quantity,
...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true, cw.level),
}));
res.json({
quickStats: {
@@ -518,137 +833,267 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
});
// ---------------------------------------------------------------------------
// Weapons assigned to this character
// Money tracker — the gold balance only ever changes through this ledger
// ---------------------------------------------------------------------------
router.post('/:id/weapons', requireCharacterAccess({ write: true }), async (req, res, next) => {
const GOLD_TRANSACTION_INCLUDE = { createdBy: { select: { displayName: true } } };
router.get('/:id/gold', requireCharacterAccess(), async (req, res, next) => {
try {
const parsed = z.object({ weaponId: z.string(), quantity: z.number().int().min(1).default(1) }).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const weapon = await prisma.weapon.findUnique({ where: { id: parsed.data.weaponId } });
if (!weapon || weapon.campaignId !== req.character.campaignId) {
return res.status(400).json({ error: 'That weapon is not part of this campaign.' });
}
const characterWeapon = await prisma.characterWeapon.upsert({
where: { characterId_weaponId: { characterId: req.character.id, weaponId: parsed.data.weaponId } },
create: { characterId: req.character.id, weaponId: parsed.data.weaponId, quantity: parsed.data.quantity },
update: { quantity: { increment: parsed.data.quantity } },
include: { weapon: true },
const transactions = await prisma.goldTransaction.findMany({
where: { characterId: req.character.id },
include: GOLD_TRANSACTION_INCLUDE,
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
});
res.status(201).json({ characterWeapon });
res.json({ gold: req.character.gold, transactions });
} catch (err) {
next(err);
}
});
router.patch('/:id/weapons/:weaponId', requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
const parsed = z
.object({ quantity: z.number().int().min(0).optional(), equipped: z.boolean().optional() })
.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const characterWeapon = await prisma.characterWeapon.update({
where: { characterId_weaponId: { characterId: req.character.id, weaponId: req.params.weaponId } },
data: parsed.data,
include: { weapon: true },
});
res.json({ characterWeapon });
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Inventory
// ---------------------------------------------------------------------------
router.post('/:id/inventory', requireCharacterAccess({ write: true }), async (req, res, next) => {
// amount is signed: positive = gained, negative = spent. The owning player
// and the DM can both record entries; each one is stamped with who made it.
router.post('/:id/gold', requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
const parsed = z
.object({
name: z.string().min(1).max(120),
description: z.string().max(2000).optional().nullable(),
quantity: z.number().int().min(1).default(1),
equipped: z.boolean().default(false),
amount: z.number().int().refine((n) => n !== 0, 'Amount cannot be zero'),
reason: z.string().trim().max(200).optional().nullable(),
})
.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { amount, reason } = parsed.data;
const item = await prisma.inventoryItem.create({ data: { ...parsed.data, characterId: req.character.id } });
res.status(201).json({ item });
} catch (err) {
next(err);
}
});
router.patch('/:id/inventory/:itemId', requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
const parsed = z
.object({
name: z.string().min(1).max(120).optional(),
description: z.string().max(2000).nullable().optional(),
quantity: z.number().int().min(0).optional(),
equipped: z.boolean().optional(),
})
.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const item = await prisma.inventoryItem.update({ where: { id: req.params.itemId }, data: parsed.data });
res.json({ item });
} catch (err) {
next(err);
}
});
router.delete('/:id/inventory/:itemId', requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
await prisma.inventoryItem.delete({ where: { id: req.params.itemId } });
res.status(204).end();
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Spells known by this character
// ---------------------------------------------------------------------------
router.post('/:id/spells', requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
const parsed = z.object({ spellId: z.string(), prepared: z.boolean().default(false) }).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const spell = await prisma.spell.findUnique({ where: { id: parsed.data.spellId } });
if (!spell || spell.campaignId !== req.character.campaignId) {
return res.status(400).json({ error: 'That spell is not part of this campaign.' });
let transaction;
try {
// Throwing inside the transaction rolls the balance change back.
transaction = await prisma.$transaction((tx) =>
adjustGold(tx, { characterId: req.character.id, amount, reason, userId: req.user.id, include: GOLD_TRANSACTION_INCLUDE })
);
} catch (err) {
if (!(err instanceof InsufficientGoldError)) throw err;
return res.status(400).json({ error: `Not enough gold — the balance is ${req.character.gold}.` });
}
const characterSpell = await prisma.characterSpell.upsert({
where: { characterId_spellId: { characterId: req.character.id, spellId: parsed.data.spellId } },
create: { characterId: req.character.id, spellId: parsed.data.spellId, prepared: parsed.data.prepared },
update: { prepared: parsed.data.prepared },
include: { spell: true },
});
res.status(201).json({ characterSpell });
emitCharacterUpdated(req);
res.status(201).json({ gold: transaction.balanceAfter, transaction });
} catch (err) {
next(err);
}
});
router.patch('/:id/spells/:spellId', requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
const parsed = z.object({ prepared: z.boolean() }).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
// ---------------------------------------------------------------------------
// Gear held by this character — weapons, items and spells all come from the
// campaign's DM-managed pools. Only the DM hands them out, changes quantities
// or levels, or takes them away; the owning player can toggle equipped /
// prepared — but only on gear the character is high enough level to use.
// ---------------------------------------------------------------------------
const characterSpell = await prisma.characterSpell.update({
where: { characterId_spellId: { characterId: req.character.id, spellId: req.params.spellId } },
data: parsed.data,
include: { spell: true },
});
res.json({ characterSpell });
function requireDmForGear(req, res) {
if (req.isDM) return true;
res.status(403).json({ error: 'Only the DM can give, remove, re-count or level up gear.' });
return false;
}
function emitCharacterUpdated(req) {
req.app.get('io').to(`campaign:${req.character.campaignId}`).emit('character:updated', { characterId: req.character.id });
}
// One set of routes per kind of gear. `key` is the pool-entry id column on the
// join row (also the route param), `flag` the boolean the owner may toggle.
// A held weapon or item (`ownLevel`) has a quantity and its own level; a spell
// has neither, and the level a character needs is the spell's classic level.
const GEAR = [
{ path: 'weapons', pool: 'weapon', held: 'characterWeapon', key: 'weaponId', flag: 'equipped', ownLevel: true, label: 'weapon' },
{ path: 'inventory', pool: 'item', held: 'inventoryItem', key: 'itemId', flag: 'equipped', ownLevel: true, label: 'item' },
{ path: 'spells', pool: 'spell', held: 'characterSpell', key: 'spellId', flag: 'prepared', ownLevel: false, label: 'spell' },
];
const gearLevelSchema = z.number().int().min(1).max(MAX_GEAR_LEVEL);
for (const gear of GEAR) {
const uniqueKey = `characterId_${gear.key}`;
const whereHeld = (req) => ({ [uniqueKey]: { characterId: req.character.id, [gear.key]: req.params.poolId } });
const include = { [gear.pool]: true };
const requiredLevel = (row, poolEntry) => (gear.ownLevel ? row.level : poolEntry.level);
const tooHighMessage = (level) =>
`Requires character level ${level} to ${gear.flag === 'prepared' ? 'prepare' : 'equip'} this ${gear.label}.`;
const belowStartMessage = (entry) => `${entry.name} starts at level ${entry.minLevel} and can't go below it.`;
const assignSchema = z.object({
[gear.key]: z.string(),
...(gear.ownLevel ? { quantity: z.number().int().min(1).default(1), level: gearLevelSchema.optional() } : {}),
[gear.flag]: z.boolean().default(false),
});
router.post(`/:id/${gear.path}`, requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
if (!requireDmForGear(req, res)) return;
const parsed = assignSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const poolId = parsed.data[gear.key];
const entry = await prisma[gear.pool].findUnique({ where: { id: poolId } });
if (!entry || entry.campaignId !== req.character.campaignId) {
return res.status(400).json({ error: `That ${gear.label} is not part of this campaign.` });
}
if (gear.ownLevel) {
// Given at the entry's starting level unless the DM picks a higher one.
parsed.data.level = parsed.data.level ?? entry.minLevel;
if (parsed.data.level < entry.minLevel) return res.status(400).json({ error: belowStartMessage(entry) });
}
if (parsed.data[gear.flag] && !canUseGear(req.character.level, requiredLevel(parsed.data, entry))) {
return res.status(400).json({ error: tooHighMessage(requiredLevel(parsed.data, entry)) });
}
// Giving something the character already holds adds to the stack (the
// stack keeps the level it has).
const row = await prisma[gear.held].upsert({
where: { [uniqueKey]: { characterId: req.character.id, [gear.key]: poolId } },
create: { characterId: req.character.id, ...parsed.data },
update: gear.ownLevel ? { quantity: { increment: parsed.data.quantity } } : { [gear.flag]: parsed.data[gear.flag] },
include,
});
emitCharacterUpdated(req);
res.status(201).json({ [gear.held]: row });
} catch (err) {
next(err);
}
});
const patchSchema = z.object({
...(gear.ownLevel ? { quantity: z.number().int().min(1).optional(), level: gearLevelSchema.optional() } : {}),
[gear.flag]: z.boolean().optional(),
});
router.patch(`/:id/${gear.path}/:poolId`, requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
const parsed = patchSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const dmOnlyChange = parsed.data.quantity !== undefined || parsed.data.level !== undefined;
if (dmOnlyChange && !requireDmForGear(req, res)) return;
const existing = await prisma[gear.held].findUnique({ where: whereHeld(req), include });
if (!existing) return res.status(404).json({ error: `This character doesn't have that ${gear.label}.` });
const data = { ...parsed.data };
if (data.level !== undefined && data.level < existing[gear.pool].minLevel) {
return res.status(400).json({ error: belowStartMessage(existing[gear.pool]) });
}
const needed = requiredLevel({ ...existing, ...data }, existing[gear.pool]);
if (!canUseGear(req.character.level, needed)) {
if (data[gear.flag]) return res.status(400).json({ error: tooHighMessage(needed) });
data[gear.flag] = false; // levelled past its holder: it comes off
}
const row = await prisma[gear.held].update({ where: whereHeld(req), data, include });
emitCharacterUpdated(req);
res.json({ [gear.held]: row });
} catch (err) {
next(err);
}
});
router.delete(`/:id/${gear.path}/:poolId`, requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
if (!requireDmForGear(req, res)) return;
const { count } = await prisma[gear.held].deleteMany({
where: { characterId: req.character.id, [gear.key]: req.params.poolId },
});
if (count === 0) return res.status(404).json({ error: `This character doesn't have that ${gear.label}.` });
emitCharacterUpdated(req);
res.status(204).end();
} catch (err) {
next(err);
}
});
}
// ---------------------------------------------------------------------------
// Giving to another character — a player (or the DM) hands something this
// character holds to another character in the same campaign. It always moves:
// whatever is given leaves the giver. That keeps the DM in control of how much
// gear, gold and magic exists, while letting the party share it out.
// ---------------------------------------------------------------------------
const giveSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('gold'), toCharacterId: z.string(), amount: z.number().int().min(1) }),
z.object({ kind: z.literal('weapon'), toCharacterId: z.string(), id: z.string(), quantity: z.number().int().min(1).default(1) }),
z.object({ kind: z.literal('item'), toCharacterId: z.string(), id: z.string(), quantity: z.number().int().min(1).default(1) }),
z.object({ kind: z.literal('spell'), toCharacterId: z.string(), id: z.string() }),
]);
class GiveError extends Error {}
router.post('/:id/give', requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
const parsed = giveSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const give = parsed.data;
const giver = req.character;
const recipient = await prisma.character.findUnique({ where: { id: give.toCharacterId } });
if (!recipient || recipient.campaignId !== giver.campaignId) {
return res.status(400).json({ error: 'That character is not part of this campaign.' });
}
if (recipient.id === giver.id) return res.status(400).json({ error: 'Pick a different character to give it to.' });
if (giver.buildStage !== 'COMPLETE' || recipient.buildStage !== 'COMPLETE') {
return res.status(400).json({ error: 'Both characters must be finished before they can trade.' });
}
try {
await prisma.$transaction(async (tx) => {
if (give.kind === 'gold') {
await adjustGold(tx, { characterId: giver.id, amount: -give.amount, reason: `Gave to ${recipient.name}`, userId: req.user.id });
await adjustGold(tx, { characterId: recipient.id, amount: give.amount, reason: `Received from ${giver.name}`, userId: req.user.id });
return;
}
if (give.kind === 'spell') {
const key = { characterId_spellId: { characterId: giver.id, spellId: give.id } };
const known = await tx.characterSpell.findUnique({ where: key, include: { spell: true } });
if (!known) throw new GiveError(`${giver.name} doesn't know that spell.`);
const already = await tx.characterSpell.findUnique({
where: { characterId_spellId: { characterId: recipient.id, spellId: give.id } },
});
if (already) throw new GiveError(`${recipient.name} already knows ${known.spell.name}.`);
await tx.characterSpell.delete({ where: key });
await tx.characterSpell.create({ data: { characterId: recipient.id, spellId: give.id } });
return;
}
// Weapons and items: take from the giver's stack, add to the
// recipient's. A new stack arrives at the giver's level, unequipped; an
// existing one just grows and keeps its own level.
const model = give.kind === 'weapon' ? 'characterWeapon' : 'inventoryItem';
const poolKey = `${give.kind}Id`;
const key = { [`characterId_${poolKey}`]: { characterId: giver.id, [poolKey]: give.id } };
const held = await tx[model].findUnique({ where: key, include: { [give.kind]: true } });
if (!held) throw new GiveError(`${giver.name} doesn't have that ${give.kind}.`);
if (give.quantity > held.quantity) {
throw new GiveError(`${giver.name} only has ${held.quantity} of ${held[give.kind].name}.`);
}
if (give.quantity === held.quantity) await tx[model].delete({ where: key });
else await tx[model].update({ where: key, data: { quantity: { decrement: give.quantity } } });
await giveGear(tx, give.kind, { characterId: recipient.id, entry: held[give.kind], quantity: give.quantity, level: held.level });
});
} catch (err) {
if (err instanceof InsufficientGoldError) {
return res.status(400).json({ error: `Not enough gold — ${giver.name} has ${giver.gold}.` });
}
if (err instanceof GiveError) return res.status(400).json({ error: err.message });
throw err;
}
const io = req.app.get('io');
for (const characterId of [giver.id, recipient.id]) {
io.to(`campaign:${giver.campaignId}`).emit('character:updated', { characterId });
}
const full = await loadFullCharacter(giver.id);
res.json({ character: serializeCharacter(full, req.isOwner) });
} catch (err) {
next(err);
}
+367 -77
View File
@@ -3,7 +3,8 @@ const { z } = require('zod');
const prisma = require('../db');
const { requireAuth } = require('../middleware/auth');
const { loadCampaignMembership } = require('../middleware/campaignAccess');
const { computeCharacterSheet, computeWeaponStats } = require('../game/calculations');
const { computeCharacterSheet, computeWeaponStats, canUseGear, MAX_GEAR_LEVEL } = require('../game/calculations');
const { adjustGold, giveGear } = require('../utils/grants');
const router = express.Router();
@@ -26,30 +27,72 @@ async function requireEncounterAccess(req, res, next) {
}
}
// Every campaign member looking at an encounter can see a character
// combatant's equipped weapons and known spells (attack/damage bonus, save
// DC) — not just HP/AC — so the party can plan around each other mid-fight,
// not only the DM. Uses the same calculation-engine functions the
// quick-stats panel already uses, never re-deriving the formulas.
function characterCombatInfo(character) {
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
const weapons = character.weapons.map((cw) => ({
characterWeaponId: cw.id,
name: cw.weapon.name,
equipped: cw.equipped,
quantity: cw.quantity,
...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true),
}));
const spells = character.spells.map((cs) => ({
characterSpellId: cs.id,
name: cs.spell.name,
level: cs.spell.level,
prepared: cs.prepared,
}));
return { armorClass: sheet.armorClass, weapons, spells, spellcasting: sheet.spellcasting };
function requireDM(req, res, next) {
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
return next();
}
async function serializeEncounter(encounterId) {
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
// Highest initiative first; ties keep the order combatants were added in.
function inTurnOrder(participants) {
return [...participants].sort((a, b) => b.initiative - a.initiative || (a.id < b.id ? -1 : 1));
}
// 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
// same calculation-engine functions as the sheet, never re-deriving formulas.
function characterCombatInfo(character) {
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
// Gear and spells above the character's level are held but can't be used,
// so they stay out of the fight.
const weapons = character.weapons
.filter((cw) => canUseGear(character.level, cw.level))
.map((cw) => ({
characterWeaponId: cw.id,
name: cw.weapon.name,
level: cw.level,
equipped: cw.equipped,
quantity: cw.quantity,
...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true, cw.level),
}));
const spells = character.spells
.filter((cs) => canUseGear(character.level, cs.spell.level))
.map((cs) => ({
characterSpellId: cs.id,
name: cs.spell.name,
level: cs.spell.level,
description: cs.spell.description,
damageDice: cs.spell.damageDice,
prepared: cs.prepared,
}));
return {
level: character.level,
species: character.species,
characterClass: character.characterClass,
armorClass: sheet.armorClass,
maxHp: sheet.hp.max,
tempHp: character.tempHp,
speed: sheet.speed,
initiativeBonus: sheet.initiative,
passivePerception: sheet.passivePerception,
proficiencyBonus: sheet.proficiencyBonus,
abilities: sheet.abilities,
saves: sheet.saves,
specialAbilities: character.specialAbilities,
weapons,
spells,
spellcasting: sheet.spellcasting,
};
}
// 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) {
const encounter = await prisma.encounter.findUnique({
where: { id: encounterId },
include: {
@@ -63,69 +106,132 @@ async function serializeEncounter(encounterId) {
spells: { include: { spell: true } },
},
},
monster: { select: { id: true, name: true } },
monster: true,
npc: true,
},
orderBy: { initiative: 'desc' },
},
rewards: { include: { weapon: true, item: true }, orderBy: { createdAt: 'asc' } },
},
});
if (!encounter) return encounter;
encounter.participants = encounter.participants.map((p) => {
if (!p.character) return p;
return {
...p,
character: { id: p.character.id, name: p.character.name },
characterCombatInfo: characterCombatInfo(p.character),
};
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' };
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.characterCombatInfo = combatInfo;
}
if (monster) out.monster = isDM ? monster : { id: monster.id, name: monster.name };
if (npc) {
const { dmNotes, ac, maxHp, attackBonus, damageDice, campaignId, createdAt, ...publicNpc } = npc;
out.npc = isDM ? { ...publicNpc, dmNotes, ac, maxHp, attackBonus, damageDice } : publicNpc;
}
return out;
});
return encounter;
const { dmNotes, rewards, ...scene } = encounter;
return {
...scene,
...(isDM ? { dmNotes } : {}),
participants,
rewards: isDM ? rewards : rewards.filter((r) => r.awardedAt),
};
}
// Every open tab refetches its own view of the encounter (the payload differs
// between the DM and players, so it is never pushed over the shared room).
function emitEncounterUpdated(req) {
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('encounter:participant-updated', { encounterId: req.encounter.id });
}
function emitCharacterUpdated(req, characterId) {
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('character:updated', { characterId });
}
async function respondWithEncounter(req, res, status = 200, extra = {}) {
const encounter = await serializeEncounter(req.encounter.id, req.isDM);
emitEncounterUpdated(req);
res.status(status).json({ ...extra, encounter });
}
router.get('/:id', requireEncounterAccess, async (req, res, next) => {
try {
const encounter = await serializeEncounter(req.encounter.id);
res.json({ encounter });
res.json({ encounter: await serializeEncounter(req.encounter.id, req.isDM) });
} catch (err) {
next(err);
}
});
const patchEncounterSchema = z.object({
status: z.enum(['PLANNING', 'ACTIVE', 'COMPLETE']).optional(),
mode: z.enum(['BATTLE', 'QUEST']).optional(),
name: z.string().min(1).max(120).optional(),
description: z.string().max(4000).nullable().optional(),
dmNotes: z.string().max(4000).nullable().optional(),
});
router.patch('/:id', requireEncounterAccess, requireDM, async (req, res, next) => {
try {
const parsed = patchEncounterSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const data = { ...parsed.data };
// 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) {
const participants = await prisma.encounterParticipant.findMany({ where: { encounterId: req.encounter.id } });
data.activeParticipantId = inTurnOrder(participants)[0]?.id ?? null;
}
await prisma.encounter.update({ where: { id: req.encounter.id }, data });
await respondWithEncounter(req, res);
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Combatants
// ---------------------------------------------------------------------------
const participantSchema = z
.object({
characterId: z.string().optional(),
monsterId: z.string().optional(),
npcId: z.string().optional(),
displayName: z.string().min(1).max(80).optional(),
initiative: z.number().int().default(0),
})
.refine((data) => Boolean(data.characterId) !== Boolean(data.monsterId), {
message: 'Provide exactly one of characterId or monsterId',
.refine((data) => [data.characterId, data.monsterId, data.npcId].filter(Boolean).length === 1, {
message: 'Provide exactly one of characterId, monsterId or npcId',
});
router.post('/:id/participants', requireEncounterAccess, async (req, res, next) => {
router.post('/:id/participants', requireEncounterAccess, requireDM, async (req, res, next) => {
try {
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
const parsed = participantSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { characterId, monsterId, displayName, initiative } = parsed.data;
const { characterId, monsterId, npcId, displayName, initiative } = parsed.data;
let currentHp, maxHp, resolvedName, isMonster;
let currentHp, maxHp, resolvedName;
if (characterId) {
const character = await prisma.character.findUnique({ where: { id: characterId } });
if (!character || character.campaignId !== req.encounter.campaignId) {
return res.status(400).json({ error: 'That character is not part of this campaign.' });
}
const full = await prisma.character.findUnique({
const character = await prisma.character.findUnique({
where: { id: characterId },
include: { skillProficiencies: true, saveProficiencies: true },
});
const sheet = computeCharacterSheet(full, full.skillProficiencies, full.saveProficiencies);
if (!character || character.campaignId !== req.encounter.campaignId) {
return res.status(400).json({ error: 'That character is not part of this campaign.' });
}
currentHp = character.currentHp;
maxHp = sheet.hp.max;
maxHp = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies).hp.max;
resolvedName = displayName || character.name;
isMonster = false;
} else {
} else if (monsterId) {
const monster = await prisma.monster.findUnique({ where: { id: monsterId } });
if (!monster || monster.campaignId !== req.encounter.campaignId) {
return res.status(400).json({ error: 'That monster is not part of this campaign.' });
@@ -133,7 +239,15 @@ router.post('/:id/participants', requireEncounterAccess, async (req, res, next)
currentHp = monster.maxHp;
maxHp = monster.maxHp;
resolvedName = displayName || monster.name;
isMonster = true;
} else {
const npc = await prisma.npc.findUnique({ where: { id: npcId } });
if (!npc || npc.campaignId !== req.encounter.campaignId) {
return res.status(400).json({ error: 'That NPC is not part of this campaign.' });
}
// An NPC with no combat stats takes part with no hit points to track.
currentHp = npc.maxHp ?? 0;
maxHp = npc.maxHp ?? 0;
resolvedName = displayName || npc.name;
}
const participant = await prisma.encounterParticipant.create({
@@ -141,17 +255,16 @@ router.post('/:id/participants', requireEncounterAccess, async (req, res, next)
encounterId: req.encounter.id,
characterId: characterId || null,
monsterId: monsterId || null,
npcId: npcId || null,
displayName: resolvedName,
initiative,
currentHp,
maxHp,
isMonster,
isMonster: Boolean(monsterId),
},
});
const encounter = await serializeEncounter(req.encounter.id);
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('encounter:participant-updated', { encounter });
res.status(201).json({ participant, encounter });
await respondWithEncounter(req, res, 201, { participant });
} catch (err) {
next(err);
}
@@ -161,65 +274,242 @@ const updateParticipantSchema = z.object({
currentHp: z.number().int().optional(),
maxHp: z.number().int().min(1).optional(),
initiative: z.number().int().optional(),
conditions: z.array(z.string()).optional(),
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, async (req, res, next) => {
router.patch('/:id/participants/:participantId', requireEncounterAccess, requireDM, async (req, res, next) => {
try {
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
const parsed = updateParticipantSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const participant = await prisma.encounterParticipant.update({
const existing = await prisma.encounterParticipant.findUnique({
where: { id: req.params.participantId },
data: parsed.data,
include: { character: { include: { skillProficiencies: true, saveProficiencies: true } } },
});
if (!existing || existing.encounterId !== req.encounter.id) {
return res.status(404).json({ error: 'Combatant not found in this encounter' });
}
const encounter = await serializeEncounter(req.encounter.id);
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('encounter:participant-updated', { encounter });
res.json({ participant, encounter });
const data = { ...parsed.data };
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 } });
emitCharacterUpdated(req, character.id);
}
} else if (data.currentHp !== undefined) {
data.currentHp = clamp(data.currentHp, 0, data.maxHp ?? existing.maxHp);
} else if (data.maxHp !== undefined) {
data.currentHp = Math.min(existing.currentHp, data.maxHp);
}
const participant = await prisma.encounterParticipant.update({ where: { id: existing.id }, data });
await respondWithEncounter(req, res, 200, { participant });
} catch (err) {
next(err);
}
});
router.delete('/:id/participants/:participantId', requireEncounterAccess, async (req, res, next) => {
router.delete('/:id/participants/:participantId', requireEncounterAccess, requireDM, async (req, res, next) => {
try {
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
const participants = await prisma.encounterParticipant.findMany({ where: { encounterId: req.encounter.id } });
const order = inTurnOrder(participants);
const index = order.findIndex((p) => p.id === req.params.participantId);
if (index === -1) return res.status(404).json({ error: 'Combatant not found in this encounter' });
// Removing whoever is on turn passes the turn to the next combatant.
if (req.encounter.activeParticipantId === req.params.participantId) {
const next = order.length > 1 ? order[(index + 1) % order.length] : null;
await prisma.encounter.update({ where: { id: req.encounter.id }, data: { activeParticipantId: next ? next.id : null } });
}
await prisma.encounterParticipant.delete({ where: { id: req.params.participantId } });
const encounter = await serializeEncounter(req.encounter.id);
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('encounter:participant-updated', { encounter });
res.json({ encounter });
await respondWithEncounter(req, res);
} catch (err) {
next(err);
}
});
router.post('/:id/advance-round', requireEncounterAccess, async (req, res, next) => {
// ---------------------------------------------------------------------------
// Turns and rounds
// ---------------------------------------------------------------------------
// Passes the turn down the initiative order; going past the last combatant
// starts the next round.
router.post('/:id/next-turn', requireEncounterAccess, requireDM, async (req, res, next) => {
try {
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
const participants = await prisma.encounterParticipant.findMany({ where: { encounterId: req.encounter.id } });
const order = inTurnOrder(participants);
if (order.length === 0) return res.status(400).json({ error: 'Add combatants before taking turns.' });
const index = order.findIndex((p) => p.id === req.encounter.activeParticipantId);
const wrapped = index === order.length - 1;
await prisma.encounter.update({
where: { id: req.encounter.id },
data: {
status: 'ACTIVE',
activeParticipantId: order[wrapped || index === -1 ? 0 : index + 1].id,
...(wrapped ? { currentRound: { increment: 1 } } : {}),
},
});
await respondWithEncounter(req, res);
} catch (err) {
next(err);
}
});
router.post('/:id/advance-round', requireEncounterAccess, requireDM, async (req, res, next) => {
try {
const participants = await prisma.encounterParticipant.findMany({ where: { encounterId: req.encounter.id } });
const updated = await prisma.encounter.update({
where: { id: req.encounter.id },
data: { currentRound: { increment: 1 }, status: 'ACTIVE' },
data: {
currentRound: { increment: 1 },
status: 'ACTIVE',
// A new round starts back at the top of the initiative order.
...(req.encounter.mode === 'BATTLE' ? { activeParticipantId: inTurnOrder(participants)[0]?.id ?? null } : {}),
},
});
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('encounter:round-advanced', {
encounterId: updated.id,
currentRound: updated.currentRound,
});
res.json({ encounter: updated });
res.json({ encounter: await serializeEncounter(updated.id, req.isDM) });
} catch (err) {
next(err);
}
});
router.patch('/:id', requireEncounterAccess, async (req, res, next) => {
// ---------------------------------------------------------------------------
// Rewards — loot the DM lines up, then hands to a character
// ---------------------------------------------------------------------------
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('WEAPON'),
weaponId: z.string(),
quantity: z.number().int().min(1).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),
level: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
note: z.string().trim().max(200).optional().nullable(),
}),
]);
router.post('/:id/rewards', requireEncounterAccess, requireDM, async (req, res, next) => {
try {
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
const parsed = z.object({ status: z.enum(['PLANNING', 'ACTIVE', 'COMPLETE']).optional(), name: z.string().min(1).max(120).optional() }).safeParse(req.body);
const parsed = rewardSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const updated = await prisma.encounter.update({ where: { id: req.encounter.id }, data: parsed.data });
res.json({ encounter: updated });
const data = { ...parsed.data, note: parsed.data.note || null };
if (data.type !== 'GOLD') {
const pool = data.type === 'WEAPON' ? 'weapon' : 'item';
const entry = await prisma[pool].findUnique({ where: { id: data[`${pool}Id`] } });
if (!entry || entry.campaignId !== req.encounter.campaignId) {
return res.status(400).json({ error: `That ${pool} is not part of this campaign.` });
}
data.level = data.level ?? entry.minLevel;
if (data.level < entry.minLevel) {
return res.status(400).json({ error: `${entry.name} starts at level ${entry.minLevel} and can't go below it.` });
}
}
const reward = await prisma.encounterReward.create({ data: { ...data, encounterId: req.encounter.id } });
await respondWithEncounter(req, res, 201, { reward });
} catch (err) {
next(err);
}
});
// Removing a reward only takes it off the list — anything already handed out
// stays with the character.
router.delete('/:id/rewards/:rewardId', requireEncounterAccess, requireDM, async (req, res, next) => {
try {
const { count } = await prisma.encounterReward.deleteMany({
where: { id: req.params.rewardId, encounterId: req.encounter.id },
});
if (count === 0) return res.status(404).json({ error: 'Reward not found in this encounter' });
await respondWithEncounter(req, res);
} catch (err) {
next(err);
}
});
const awardSchema = z.union([z.object({ characterId: z.string() }), z.object({ split: z.literal(true) })]);
// Hands a reward over, once. `characterId` gives all of it to one character;
// `split` (gold only) shares it evenly between the characters in the
// encounter, any remainder going one gold each down the initiative order.
router.post('/:id/rewards/:rewardId/award', requireEncounterAccess, requireDM, async (req, res, next) => {
try {
const parsed = awardSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const reward = await prisma.encounterReward.findUnique({
where: { id: req.params.rewardId },
include: { weapon: true, item: true },
});
if (!reward || reward.encounterId !== req.encounter.id) {
return res.status(404).json({ error: 'Reward not found in this encounter' });
}
if (reward.awardedAt) return res.status(400).json({ error: `Already awarded to ${reward.awardedTo}.` });
let recipients;
if (parsed.data.split) {
if (reward.type !== 'GOLD') return res.status(400).json({ error: 'Only gold can be split.' });
const participants = await prisma.encounterParticipant.findMany({
where: { encounterId: req.encounter.id, characterId: { not: null } },
include: { character: true },
});
recipients = inTurnOrder(participants).map((p) => p.character);
if (recipients.length === 0) return res.status(400).json({ error: 'There are no characters in this encounter to split it between.' });
} else {
const character = await prisma.character.findUnique({ where: { id: parsed.data.characterId } });
if (!character || character.campaignId !== req.encounter.campaignId) {
return res.status(400).json({ error: 'That character is not part of this campaign.' });
}
recipients = [character];
}
const reason = `Reward: ${req.encounter.name}`;
await prisma.$transaction(async (tx) => {
// Claim the reward first so two clicks can't hand it out twice.
const claimed = await tx.encounterReward.updateMany({
where: { id: reward.id, awardedAt: null },
data: { awardedAt: new Date(), awardedTo: recipients.map((c) => c.name).join(', ') },
});
if (claimed.count === 0) return;
if (reward.type === 'GOLD') {
const share = Math.floor(reward.gold / recipients.length);
const remainder = reward.gold % recipients.length;
for (const [i, character] of recipients.entries()) {
const amount = share + (i < remainder ? 1 : 0);
if (amount > 0) await adjustGold(tx, { characterId: character.id, amount, reason, userId: req.user.id });
}
} else {
const kind = reward.type === 'WEAPON' ? 'weapon' : 'item';
await giveGear(tx, kind, {
characterId: recipients[0].id,
entry: reward[kind],
quantity: reward.quantity,
level: reward.level,
});
}
});
for (const character of recipients) emitCharacterUpdated(req, character.id);
await respondWithEncounter(req, res);
} catch (err) {
next(err);
}
+40
View File
@@ -0,0 +1,40 @@
// The two ways a character's belongings change: gold through the ledger, and
// gear from the campaign pools. Shared by the character sheet routes and by
// encounter rewards so both follow the same rules. Every function takes a
// Prisma client or transaction client as `db`.
class InsufficientGoldError extends Error {}
// amount is signed: positive = gained, negative = spent. Writes the ledger row
// and returns it; throws InsufficientGoldError if the balance would go below 0
// (inside a transaction, that rolls the whole thing back).
async function adjustGold(db, { characterId, amount, reason, userId, include }) {
// The atomic increment is the balance check: two spends racing each other
// can't both pass a stale read.
const updated = await db.character.update({ where: { id: characterId }, data: { gold: { increment: amount } } });
if (updated.gold < 0) throw new InsufficientGoldError();
return db.goldTransaction.create({
data: { characterId, amount, balanceAfter: updated.gold, reason: reason || null, createdById: userId },
include,
});
}
const HELD = {
weapon: { model: 'characterWeapon', key: 'weaponId' },
item: { model: 'inventoryItem', key: 'itemId' },
};
// Gives `quantity` of a pool weapon/item to a character. Something they
// already hold stacks (and keeps the level the stack has); otherwise it
// arrives at `level`, never below the entry's starting level.
async function giveGear(db, kind, { characterId, entry, quantity = 1, level, equipped = false }) {
const { model, key } = HELD[kind];
return db[model].upsert({
where: { [`characterId_${key}`]: { characterId, [key]: entry.id } },
create: { characterId, [key]: entry.id, quantity, equipped, level: Math.max(level ?? entry.minLevel, entry.minLevel) },
update: { quantity: { increment: quantity } },
include: { [kind]: true },
});
}
module.exports = { InsufficientGoldError, adjustGold, giveGear };