From 4a6a09bae8da2fea18f9d844671873a35aae29cb Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Mon, 5 Oct 2026 16:47:28 +0200 Subject: [PATCH] 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 --- README.md | 22 +- backend/package.json | 1 + .../migration.sql | 95 ++ .../20261005150000_gear_levels/migration.sql | 21 + .../migration.sql | 7 + .../migration.sql | 69 ++ .../migration.sql | 4 + backend/prisma/schema.prisma | 155 ++- backend/prisma/seed.js | 2 +- backend/scripts/generate-doc-lists.js | 117 ++ backend/src/game/buildFlow.js | 69 +- backend/src/game/calculations.js | 117 +- backend/src/game/calculations.test.js | 110 ++ backend/src/game/data/characterOptions.js | 375 ++++++ backend/src/game/data/spellsLibrary.js | 76 +- backend/src/routes/api.integration.test.js | 1073 ++++++++++++++++- backend/src/routes/campaigns.routes.js | 229 +++- backend/src/routes/characters.routes.js | 717 ++++++++--- backend/src/routes/encounters.routes.js | 444 +++++-- backend/src/utils/grants.js | 40 + docs/Aldenfell - Full Campaign Book.docx | Bin 79809 -> 0 bytes docs/CHARACTERS.md | 961 +++++++++++++++ docs/ENCOUNTERS.md | 215 ++++ docs/ITEMS.md | 151 +++ docs/MONSTERS.md | 170 +++ docs/NPCS.md | 123 ++ docs/SPELLS.md | 387 ++++++ docs/WEAPONS.md | 280 +++++ frontend/src/api/queries.ts | 262 +++- frontend/src/api/types.ts | 144 ++- frontend/src/components/DiceRoller.tsx | 166 +++ frontend/src/components/InfoTip.tsx | 16 +- frontend/src/components/Layout.tsx | 2 + frontend/src/components/QuickStatsDrawer.tsx | 2 +- frontend/src/hooks/useCampaignSocket.ts | 1 + frontend/src/index.css | 453 +++++++ frontend/src/lib/format.ts | 21 + frontend/src/lib/guide.ts | 229 ++++ frontend/src/lib/previewCalc.ts | 67 + frontend/src/pages/CampaignHomePage.tsx | 433 ++++++- frontend/src/pages/CharacterBuilderPage.tsx | 863 +++++++++++-- frontend/src/pages/CharacterSheetPage.tsx | 541 +++++++-- frontend/src/pages/EncounterPage.tsx | 873 +++++++++++--- frontend/src/pages/PartyOverviewPage.tsx | 2 + 44 files changed, 9405 insertions(+), 700 deletions(-) create mode 100644 backend/prisma/migrations/20261005130000_item_pool_starting_options_gold_ledger/migration.sql create mode 100644 backend/prisma/migrations/20261005150000_gear_levels/migration.sql create mode 100644 backend/prisma/migrations/20261005170000_gear_starting_level/migration.sql create mode 100644 backend/prisma/migrations/20261005180000_encounter_modes_npcs_rewards/migration.sql create mode 100644 backend/prisma/migrations/20261005200000_builder_story_steps/migration.sql create mode 100644 backend/scripts/generate-doc-lists.js create mode 100644 backend/src/game/data/characterOptions.js create mode 100644 backend/src/utils/grants.js delete mode 100644 docs/Aldenfell - Full Campaign Book.docx create mode 100644 docs/CHARACTERS.md create mode 100644 docs/ENCOUNTERS.md create mode 100644 docs/ITEMS.md create mode 100644 docs/MONSTERS.md create mode 100644 docs/NPCS.md create mode 100644 docs/SPELLS.md create mode 100644 docs/WEAPONS.md create mode 100644 frontend/src/components/DiceRoller.tsx create mode 100644 frontend/src/lib/guide.ts diff --git a/README.md b/README.md index 4124f1e..7cc0474 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,25 @@ together: campaign management, a guided dice-roll character builder, live character sheets, a mid-combat "quick stats" panel, weapons/inventory/spells, monsters, and a real-time encounter/combat tracker. -See `CLAUDE_BUILD_PROMPT.md` and `/docs` for the full spec this was built -from (`GAME_RULES_REFERENCE.md` is the authoritative rules/math reference; -`ROLL_YOUR_CHARACTER.md` is the character-builder flow spec). +## How it works + +`/docs` describes the app as it currently behaves, one subject per file: + +| Document | Covers | +|---|---| +| `docs/CHARACTERS.md` | Building a character, every number on the sheet, levels, money, permissions | +| `docs/WEAPONS.md` | The weapon pool, weapon levels and how damage grows | +| `docs/SPELLS.md` | The spell list, who can use which spells, the spell library | +| `docs/ITEMS.md` | The item pool and character inventory | +| `docs/ENCOUNTERS.md` | Battles and NPC quests, turns, rewards, what players see | +| `docs/MONSTERS.md` | The monster list and built-in bestiary | +| `docs/NPCS.md` | Non-player characters | + +`CLAUDE_BUILD_PROMPT.md`, `docs/GAME_RULES_REFERENCE.md` and +`docs/ROLL_YOUR_CHARACTER.md` are the original specifications the first +version was built from. The app has since moved on in places (gear levels, +the builder's story steps, picking a motivation); the documents above are the +current behaviour. ## Stack diff --git a/backend/package.json b/backend/package.json index 216ef83..d0a9f65 100644 --- a/backend/package.json +++ b/backend/package.json @@ -11,6 +11,7 @@ "dev": "node --watch src/index.js", "start": "node src/index.js", "test": "node --experimental-vm-modules node_modules/.bin/jest", + "docs:lists": "node scripts/generate-doc-lists.js", "prisma:migrate": "prisma migrate dev", "prisma:generate": "prisma generate", "prisma:seed": "prisma db seed", diff --git a/backend/prisma/migrations/20261005130000_item_pool_starting_options_gold_ledger/migration.sql b/backend/prisma/migrations/20261005130000_item_pool_starting_options_gold_ledger/migration.sql new file mode 100644 index 0000000..1a7bc6d --- /dev/null +++ b/backend/prisma/migrations/20261005130000_item_pool_starting_options_gold_ledger/migration.sql @@ -0,0 +1,95 @@ +-- AlterTable: starting-option flags. Existing pool entries keep the previous +-- behaviour (everything was offered at character creation); new ones opt in. +ALTER TABLE "weapons" ADD COLUMN "isStartingOption" BOOLEAN NOT NULL DEFAULT false; +ALTER TABLE "spells" ADD COLUMN "isStartingOption" BOOLEAN NOT NULL DEFAULT false; +UPDATE "weapons" SET "isStartingOption" = true; +UPDATE "spells" SET "isStartingOption" = true; + +-- CreateTable +CREATE TABLE "items" ( + "id" TEXT NOT NULL, + "campaignId" TEXT NOT NULL, + "name" TEXT NOT NULL, + "description" TEXT, + "isStartingOption" BOOLEAN NOT NULL DEFAULT false, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "items_pkey" PRIMARY KEY ("id") +); + +-- Move free-text inventory into the campaign item pool: one pool item per +-- distinct name (case-insensitive) per campaign, then point each row at it. +INSERT INTO "items" ("id", "campaignId", "name", "description") +SELECT DISTINCT ON (c."campaignId", lower(i."name")) + 'itm_' || md5(c."campaignId" || ':' || lower(i."name")), + c."campaignId", i."name", i."description" +FROM "inventory_items" i +JOIN "characters" c ON c."id" = i."characterId" +ORDER BY c."campaignId", lower(i."name"), i."id"; + +ALTER TABLE "inventory_items" ADD COLUMN "itemId" TEXT; + +UPDATE "inventory_items" i +SET "itemId" = 'itm_' || md5(c."campaignId" || ':' || lower(i."name")) +FROM "characters" c +WHERE c."id" = i."characterId"; + +-- A character that held the same item on several rows keeps one, with the +-- quantities summed. +UPDATE "inventory_items" keep +SET "quantity" = agg.total, "equipped" = agg.any_equipped +FROM ( + SELECT "characterId", "itemId", min("id") AS keep_id, sum("quantity")::int AS total, bool_or("equipped") AS any_equipped + FROM "inventory_items" + GROUP BY "characterId", "itemId" +) agg +WHERE keep."id" = agg.keep_id; + +DELETE FROM "inventory_items" d +USING ( + SELECT "characterId", "itemId", min("id") AS keep_id + FROM "inventory_items" + GROUP BY "characterId", "itemId" +) agg +WHERE d."characterId" = agg."characterId" AND d."itemId" = agg."itemId" AND d."id" <> agg.keep_id; + +ALTER TABLE "inventory_items" ALTER COLUMN "itemId" SET NOT NULL; +ALTER TABLE "inventory_items" DROP COLUMN "name"; +ALTER TABLE "inventory_items" DROP COLUMN "description"; + +-- CreateTable +CREATE TABLE "gold_transactions" ( + "id" TEXT NOT NULL, + "characterId" TEXT NOT NULL, + "amount" INTEGER NOT NULL, + "balanceAfter" INTEGER NOT NULL, + "reason" TEXT, + "createdById" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "gold_transactions_pkey" PRIMARY KEY ("id") +); + +-- Give characters that already hold gold an opening ledger entry. +INSERT INTO "gold_transactions" ("id", "characterId", "amount", "balanceAfter", "reason") +SELECT 'gtx_' || md5("id"), "id", "gold", "gold", 'Opening balance' +FROM "characters" +WHERE "gold" > 0; + +-- CreateIndex +CREATE UNIQUE INDEX "inventory_items_characterId_itemId_key" ON "inventory_items"("characterId", "itemId"); + +-- CreateIndex +CREATE INDEX "gold_transactions_characterId_createdAt_idx" ON "gold_transactions"("characterId", "createdAt"); + +-- AddForeignKey +ALTER TABLE "items" ADD CONSTRAINT "items_campaignId_fkey" FOREIGN KEY ("campaignId") REFERENCES "campaigns"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "inventory_items" ADD CONSTRAINT "inventory_items_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "items"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "gold_transactions" ADD CONSTRAINT "gold_transactions_characterId_fkey" FOREIGN KEY ("characterId") REFERENCES "characters"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "gold_transactions" ADD CONSTRAINT "gold_transactions_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/backend/prisma/migrations/20261005150000_gear_levels/migration.sql b/backend/prisma/migrations/20261005150000_gear_levels/migration.sql new file mode 100644 index 0000000..d3359fd --- /dev/null +++ b/backend/prisma/migrations/20261005150000_gear_levels/migration.sql @@ -0,0 +1,21 @@ +-- AlterTable: how many ladder rungs a weapon climbs per level (1 standard, 2 powerful, 3 legendary) +ALTER TABLE "weapons" ADD COLUMN "damageScaling" INTEGER NOT NULL DEFAULT 1; + +-- AlterTable: the level of the copy a character holds +ALTER TABLE "character_weapons" ADD COLUMN "level" INTEGER NOT NULL DEFAULT 1; + +-- AlterTable: items can optionally carry dice (damage, healing, ...) that scale the same way +ALTER TABLE "items" ADD COLUMN "damageDice" TEXT, +ADD COLUMN "damageScaling" INTEGER NOT NULL DEFAULT 1; + +-- AlterTable +ALTER TABLE "inventory_items" ADD COLUMN "level" INTEGER NOT NULL DEFAULT 1; + +-- AlterTable: spells get a fixed damage value; their classic level is the requirement +ALTER TABLE "spells" ADD COLUMN "damageDice" TEXT; + +-- A spell above its holder's level can no longer be prepared. +UPDATE "character_spells" cs +SET "prepared" = false +FROM "spells" s, "characters" c +WHERE s."id" = cs."spellId" AND c."id" = cs."characterId" AND s."level" > c."level"; diff --git a/backend/prisma/migrations/20261005170000_gear_starting_level/migration.sql b/backend/prisma/migrations/20261005170000_gear_starting_level/migration.sql new file mode 100644 index 0000000..374b33a --- /dev/null +++ b/backend/prisma/migrations/20261005170000_gear_starting_level/migration.sql @@ -0,0 +1,7 @@ +-- AlterTable: the level a weapon or item starts at (its dice are the damage at this level) +ALTER TABLE "weapons" ADD COLUMN "minLevel" INTEGER NOT NULL DEFAULT 1; +ALTER TABLE "items" ADD COLUMN "minLevel" INTEGER NOT NULL DEFAULT 1; + +-- Gear levels now stop at 9. +UPDATE "character_weapons" SET "level" = 9 WHERE "level" > 9; +UPDATE "inventory_items" SET "level" = 9 WHERE "level" > 9; diff --git a/backend/prisma/migrations/20261005180000_encounter_modes_npcs_rewards/migration.sql b/backend/prisma/migrations/20261005180000_encounter_modes_npcs_rewards/migration.sql new file mode 100644 index 0000000..85875d4 --- /dev/null +++ b/backend/prisma/migrations/20261005180000_encounter_modes_npcs_rewards/migration.sql @@ -0,0 +1,69 @@ +-- CreateEnum +CREATE TYPE "EncounterMode" AS ENUM ('BATTLE', 'QUEST'); + +-- CreateEnum +CREATE TYPE "NpcDisposition" AS ENUM ('FRIENDLY', 'NEUTRAL', 'HOSTILE'); + +-- CreateEnum +CREATE TYPE "RewardType" AS ENUM ('GOLD', 'WEAPON', 'ITEM'); + +-- AlterTable +ALTER TABLE "encounter_participants" ADD COLUMN "npcId" TEXT; + +-- AlterTable +ALTER TABLE "encounters" ADD COLUMN "activeParticipantId" TEXT, +ADD COLUMN "description" TEXT, +ADD COLUMN "dmNotes" TEXT, +ADD COLUMN "mode" "EncounterMode" NOT NULL DEFAULT 'BATTLE'; + +-- CreateTable +CREATE TABLE "npcs" ( + "id" TEXT NOT NULL, + "campaignId" TEXT NOT NULL, + "name" TEXT NOT NULL, + "role" TEXT, + "disposition" "NpcDisposition" NOT NULL DEFAULT 'NEUTRAL', + "description" TEXT, + "dmNotes" TEXT, + "ac" INTEGER, + "maxHp" INTEGER, + "attackBonus" INTEGER, + "damageDice" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "npcs_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "encounter_rewards" ( + "id" TEXT NOT NULL, + "encounterId" TEXT NOT NULL, + "type" "RewardType" NOT NULL, + "gold" INTEGER, + "weaponId" TEXT, + "itemId" TEXT, + "quantity" INTEGER NOT NULL DEFAULT 1, + "level" INTEGER NOT NULL DEFAULT 1, + "note" TEXT, + "awardedTo" TEXT, + "awardedAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "encounter_rewards_pkey" PRIMARY KEY ("id") +); + +-- AddForeignKey +ALTER TABLE "npcs" ADD CONSTRAINT "npcs_campaignId_fkey" FOREIGN KEY ("campaignId") REFERENCES "campaigns"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "encounter_rewards" ADD CONSTRAINT "encounter_rewards_encounterId_fkey" FOREIGN KEY ("encounterId") REFERENCES "encounters"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "encounter_rewards" ADD CONSTRAINT "encounter_rewards_weaponId_fkey" FOREIGN KEY ("weaponId") REFERENCES "weapons"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "encounter_rewards" ADD CONSTRAINT "encounter_rewards_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "items"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "encounter_participants" ADD CONSTRAINT "encounter_participants_npcId_fkey" FOREIGN KEY ("npcId") REFERENCES "npcs"("id") ON DELETE SET NULL ON UPDATE CASCADE; + diff --git a/backend/prisma/migrations/20261005200000_builder_story_steps/migration.sql b/backend/prisma/migrations/20261005200000_builder_story_steps/migration.sql new file mode 100644 index 0000000..dc54f6e --- /dev/null +++ b/backend/prisma/migrations/20261005200000_builder_story_steps/migration.sql @@ -0,0 +1,4 @@ +-- AlterEnum: three story steps between skills and equipment +ALTER TYPE "BuildStage" ADD VALUE 'CHOOSING_ABILITIES' BEFORE 'CHOOSING_EQUIPMENT'; +ALTER TYPE "BuildStage" ADD VALUE 'CHOOSING_BACKGROUND' BEFORE 'CHOOSING_EQUIPMENT'; +ALTER TYPE "BuildStage" ADD VALUE 'CHOOSING_APPEARANCE' BEFORE 'CHOOSING_EQUIPMENT'; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 6892ae9..55560d5 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -86,6 +86,9 @@ enum BuildStage { ROLLING_MOTIVATION ASSIGNING_SCORES ASSIGNING_PROFICIENCIES + CHOOSING_ABILITIES + CHOOSING_BACKGROUND + CHOOSING_APPEARANCE CHOOSING_EQUIPMENT COMPLETE } @@ -96,6 +99,25 @@ enum EncounterStatus { COMPLETE } +// What kind of scene an encounter is: a fight run in initiative order, or a +// quest scene built around NPCs and an objective. +enum EncounterMode { + BATTLE + QUEST +} + +enum NpcDisposition { + FRIENDLY + NEUTRAL + HOSTILE +} + +enum RewardType { + GOLD + WEAPON + ITEM +} + enum NoteVisibility { DM_ONLY SHARED @@ -122,6 +144,7 @@ model User { charactersOwned Character[] @relation("PlayerCharacters") charactersCreated Character[] @relation("CreatedBy") notesAuthored Note[] + goldTransactions GoldTransaction[] @@map("users") } @@ -143,7 +166,9 @@ model Campaign { characters Character[] weapons Weapon[] spells Spell[] + items Item[] monsters Monster[] + npcs Npc[] encounters Encounter[] notes Note[] locations Location[] @@ -211,11 +236,13 @@ model Character { armorBonus Int @default(0) // flat AC bonus from equipped armor/shield speedOverride Int? - specialAbilities String? // free-text list shown in the quick-stats panel + // The next three are composed by the builder from the player's picks + // (game/data/characterOptions.js). After that only the DM can edit them. + specialAbilities String? // shown in the quick-stats panel gold Int @default(0) - background String? // free-text story background, player-editable - appearance String? // free-text character look/description, player-editable + background String? + appearance String? privateNotes String? // visible to the owning player only — not even the DM diceMode DiceMode @default(DIGITAL) // chosen once, before the first build roll @@ -236,6 +263,7 @@ model Character { skillProficiencies CharacterSkillProficiency[] saveProficiencies CharacterSaveProficiency[] inventoryItems InventoryItem[] + goldTransactions GoldTransaction[] weapons CharacterWeapon[] spells CharacterSpell[] notes Note[] @@ -283,10 +311,20 @@ model Weapon { properties String[] // e.g. ["finesse", "light", "thrown"] rangeNormal Int? rangeLong Int? + // damageDice is the level-1 damage; a held copy's dice climb the damage + // ladder (game/calculations.js) by this many rungs per level above 1. + damageScaling Int @default(1) + // The level this weapon starts at: a held copy is never below it, and + // damageDice is the damage at this level. + minLevel Int @default(1) + // Offered in the character builder's starting-equipment step. Off by default: + // the DM opts entries in, so the pool can hold gear that must be earned. + isStartingOption Boolean @default(false) createdAt DateTime @default(now()) campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade) assigned CharacterWeapon[] + rewards EncounterReward[] @@map("weapons") } @@ -297,6 +335,7 @@ model CharacterWeapon { weaponId String quantity Int @default(1) equipped Boolean @default(false) + level Int @default(1) // this copy's level; the character must be at least this level to use it character Character @relation(fields: [characterId], references: [id], onDelete: Cascade) weapon Weapon @relation(fields: [weaponId], references: [id], onDelete: Cascade) @@ -305,19 +344,58 @@ model CharacterWeapon { @@map("character_weapons") } +// Campaign-level item pool, DM-managed like weapons and spells. +model Item { + id String @id @default(cuid()) + campaignId String + name String + description String? + damageDice String? // optional dice (damage, healing...) at its starting level; scales like a weapon's + damageScaling Int @default(1) + minLevel Int @default(1) + isStartingOption Boolean @default(false) + createdAt DateTime @default(now()) + + campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade) + held InventoryItem[] + rewards EncounterReward[] + + @@map("items") +} + +// An Item from the campaign pool held by a character. model InventoryItem { id String @id @default(cuid()) characterId String - name String - description String? + itemId String quantity Int @default(1) equipped Boolean @default(false) + level Int @default(1) character Character @relation(fields: [characterId], references: [id], onDelete: Cascade) + item Item @relation(fields: [itemId], references: [id], onDelete: Cascade) + @@unique([characterId, itemId]) @@map("inventory_items") } +// Ledger behind Character.gold: every change to the balance is one row here. +model GoldTransaction { + id String @id @default(cuid()) + characterId String + amount Int // signed: positive = gained, negative = spent + balanceAfter Int + reason String? + createdById String? + createdAt DateTime @default(now()) + + character Character @relation(fields: [characterId], references: [id], onDelete: Cascade) + createdBy User? @relation(fields: [createdById], references: [id], onDelete: SetNull) + + @@index([characterId, createdAt]) + @@map("gold_transactions") +} + // --------------------------------------------------------------------------- // Spells // --------------------------------------------------------------------------- @@ -326,12 +404,14 @@ model Spell { id String @id @default(cuid()) campaignId String name String - level Int // 0 = cantrip + level Int // 0 = cantrip. Also the character level needed to use the spell. + damageDice String? // fixed; spells don't level up school String? castingTime String? range String? duration String? description String? + isStartingOption Boolean @default(false) campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade) known CharacterSpell[] @@ -381,30 +461,84 @@ model Monster { @@map("monsters") } +// A non-player character the DM runs: a quest-giver, shopkeeper, rival... +// Combat stats are optional — most NPCs are there to be talked to. +model Npc { + id String @id @default(cuid()) + campaignId String + name String + role String? // e.g. "Innkeeper", "Captain of the Watch" + disposition NpcDisposition @default(NEUTRAL) + description String? // what the party can see and knows + dmNotes String? // secrets, motives — never sent to players + ac Int? + maxHp Int? + attackBonus Int? + damageDice String? + createdAt DateTime @default(now()) + + campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade) + encounterAppearances EncounterParticipant[] + + @@map("npcs") +} + model Encounter { id String @id @default(cuid()) campaignId String name String + mode EncounterMode @default(BATTLE) status EncounterStatus @default(PLANNING) currentRound Int @default(1) + // Whose turn it is in a battle; null until the fight starts. + activeParticipantId String? + description String? // the scene / objective, shown to everyone + dmNotes String? // never sent to players createdAt DateTime @default(now()) updatedAt DateTime @updatedAt campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade) participants EncounterParticipant[] + rewards EncounterReward[] @@map("encounters") } -// A row per combatant in an encounter — either a character or a monster. -// currentHp/maxHp are snapshotted here (not just read off Character/Monster) -// so damage tracking during a fight doesn't need to mutate the character's or -// monster's permanent record until the DM chooses to apply it back. +// Loot the DM lines up for an encounter and later hands to a character. Until +// it is awarded it is the DM's secret; awarding it is what actually changes +// the character (gold ledger entry, or the weapon/item added to what they hold). +model EncounterReward { + id String @id @default(cuid()) + encounterId String + type RewardType + gold Int? // GOLD + weaponId String? // WEAPON + itemId String? // ITEM + quantity Int @default(1) + level Int @default(1) // gear level the weapon/item is handed over at + note String? + awardedTo String? // who received it, as display text ("Aria", "Aria, Bo") + awardedAt DateTime? + createdAt DateTime @default(now()) + + encounter Encounter @relation(fields: [encounterId], references: [id], onDelete: Cascade) + weapon Weapon? @relation(fields: [weaponId], references: [id], onDelete: Cascade) + item Item? @relation(fields: [itemId], references: [id], onDelete: Cascade) + + @@map("encounter_rewards") +} + +// A row per combatant in an encounter — a character, a monster or an NPC. +// A monster's currentHp/maxHp live here, per instance. A character's HP has +// one source of truth, the Character row: encounters read and write that, and +// the columns here only hold the last values seen (used if the character is +// later deleted and the row loses its link). model EncounterParticipant { id String @id @default(cuid()) encounterId String characterId String? monsterId String? + npcId String? displayName String // denormalized so a monster can be renamed per-instance, e.g. "Goblin #2" initiative Int @default(0) currentHp Int @@ -415,6 +549,7 @@ model EncounterParticipant { encounter Encounter @relation(fields: [encounterId], references: [id], onDelete: Cascade) character Character? @relation(fields: [characterId], references: [id], onDelete: SetNull) monster Monster? @relation(fields: [monsterId], references: [id], onDelete: SetNull) + npc Npc? @relation(fields: [npcId], references: [id], onDelete: SetNull) @@map("encounter_participants") } diff --git a/backend/prisma/seed.js b/backend/prisma/seed.js index 185add7..8d8ea7d 100644 --- a/backend/prisma/seed.js +++ b/backend/prisma/seed.js @@ -44,7 +44,7 @@ async function main() { }, }); - await prisma.weapon.createMany({ data: weapons.map((w) => ({ ...w, campaignId: campaign.id })) }); + await prisma.weapon.createMany({ data: weapons.map((w) => ({ ...w, isStartingOption: true, campaignId: campaign.id })) }); await prisma.location.createMany({ data: aldenfell.locations.map((l) => ({ ...l, campaignId: campaign.id })), diff --git a/backend/scripts/generate-doc-lists.js b/backend/scripts/generate-doc-lists.js new file mode 100644 index 0000000..1f587fa --- /dev/null +++ b/backend/scripts/generate-doc-lists.js @@ -0,0 +1,117 @@ +// Writes the full lists (every library spell, weapon and monster, and every +// option the character builder offers) into the docs, straight from the data +// files the app itself uses, so the docs cannot drift from the app. +// +// npm run docs:lists (from /backend) +// +// Each list lives between a pair of markers in a doc: +// ... +// Only the text between the markers is replaced; everything else in the docs +// is written by hand. +const fs = require('fs'); +const path = require('path'); +const { WEAPON_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../src/game/data/library'); +const options = require('../src/game/data/characterOptions'); +const { SPECIES } = require('../src/game/data/species'); +const { CLASSES } = require('../src/game/data/classes'); + +const DOCS = path.join(__dirname, '..', '..', 'docs'); + +const cell = (value) => (value === null || value === undefined || value === '' ? '—' : String(value).replace(/\|/g, '\\|')); +const table = (headers, rows) => + [`| ${headers.join(' | ')} |`, `|${headers.map(() => '---').join('|')}|`, ...rows.map((r) => `| ${r.map(cell).join(' | ')} |`)].join('\n'); +const signed = (n) => (n >= 0 ? `+${n}` : `${n}`); +const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`; + +function spellLibrary() { + const levels = [...new Set(SPELL_LIBRARY.map((s) => s.level))].sort((a, b) => a - b); + return levels + .map((level) => { + const spells = SPELL_LIBRARY.filter((s) => s.level === level).sort((a, b) => a.name.localeCompare(b.name)); + const heading = level === 0 ? `### Cantrips (${spells.length})` : `### Level ${level} (${plural(spells.length, 'spell')})`; + const who = level === 0 ? 'Usable by any character.' : `Needs character level ${level}.`; + return `${heading}\n\n${who}\n\n${table(['Spell', 'School', 'Damage', 'What it does'], spells.map((s) => [s.name, s.school, s.damageDice, s.description]))}`; + }) + .join('\n\n'); +} + +const ATTACK_WITH = { STR: 'Strength', DEX: 'Dexterity', FINESSE: 'Strength or Dexterity (finesse)' }; + +function weaponLibrary() { + const categories = [...new Set(WEAPON_LIBRARY.map((w) => w.category))]; + return categories + .map((category) => { + const weapons = WEAPON_LIBRARY.filter((w) => w.category === category); + const rows = weapons.map((w) => [ + w.name, + w.damageDice, + w.damageType, + ATTACK_WITH[w.attackAbility], + w.properties.join(', '), + w.rangeNormal ? `${w.rangeNormal}/${w.rangeLong} ft` : null, + ]); + return `### ${category} (${weapons.length})\n\n${table(['Weapon', 'Base damage', 'Type', 'Attacks with', 'Properties', 'Range'], rows)}`; + }) + .join('\n\n'); +} + +function monsterLibrary() { + const rows = MONSTER_LIBRARY.map((m) => [ + m.name, + m.challengeRating, + m.ac, + m.maxHp, + m.speed, + signed(m.attackBonus), + m.damageDice, + [m.strScore, m.dexScore, m.conScore, m.intScore, m.wisScore, m.chaScore].join(' / '), + m.specialTrait, + m.notes, + ]); + return table(['Monster', 'CR', 'AC', 'HP', 'Speed', 'Attack', 'Damage', 'STR / DEX / CON / INT / WIS / CHA', 'Trait', 'Notes'], rows); +} + +function builderLists() { + const abilities = (list) => list.map((a) => `**${a.name}** — ${a.text}`).join('
'); + const groups = (list) => + list + .map((g) => { + const pick = g.min === g.max ? `pick ${g.min}` : `pick ${g.min} to ${g.max}`; + return `**${g.label}** — ${g.prompt} (${pick})\n\n${table(['Option', 'What it adds'], g.options.map((o) => [o.label, o.text]))}`; + }) + .join('\n\n'); + + return [ + `### Motivations\n\n${options.MOTIVATIONS.map((m) => `- ${m.label}`).join('\n')}`, + `### Special abilities granted by species\n\n${table(['Species', 'Abilities'], Object.keys(SPECIES).map((key) => [SPECIES[key].name, abilities(options.SPECIES_TRAITS[key])]))}`, + `### Special abilities granted by class\n\n${table(['Class', 'Abilities'], Object.keys(CLASSES).sort().map((key) => [CLASSES[key].name, abilities(options.CLASS_FEATURES[key])]))}`, + `### Talents (pick ${options.TALENT_PICKS})\n\n${table(['Talent', 'What it does'], options.TALENTS.map((t) => [t.name, t.text]))}`, + `### Background questions\n\n${groups(options.BACKGROUND_GROUPS)}`, + `### Appearance questions\n\n${groups(options.APPEARANCE_GROUPS)}`, + ].join('\n\n'); +} + +const SECTIONS = { + 'SPELLS.md': { 'spell-library': spellLibrary }, + 'WEAPONS.md': { 'weapon-library': weaponLibrary }, + 'MONSTERS.md': { 'monster-library': monsterLibrary }, + 'CHARACTERS.md': { 'builder-lists': builderLists }, +}; + +for (const [file, sections] of Object.entries(SECTIONS)) { + const filePath = path.join(DOCS, file); + const original = fs.readFileSync(filePath, 'utf8'); + const newline = original.includes('\r\n') ? '\r\n' : '\n'; + let text = original.replace(/\r\n/g, '\n'); + for (const [name, render] of Object.entries(sections)) { + const begin = ``; + const end = ``; + const from = text.indexOf(begin); + const to = text.indexOf(end); + if (from === -1 || to === -1 || to < from) throw new Error(`${file}: missing the "${name}" markers`); + text = `${text.slice(0, from + begin.length)}\n${render()}\n${text.slice(to)}`; + } + const output = text.replace(/\n/g, newline); + if (output !== original) fs.writeFileSync(filePath, output); + console.log(`${output === original ? 'unchanged' : 'updated '} docs/${file}`); +} diff --git a/backend/src/game/buildFlow.js b/backend/src/game/buildFlow.js index fd774cb..6c05d07 100644 --- a/backend/src/game/buildFlow.js +++ b/backend/src/game/buildFlow.js @@ -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, }; diff --git a/backend/src/game/calculations.js b/backend/src/game/calculations.js index 3e4f744..771fcbf 100644 --- a/backend/src/game/calculations.js +++ b/backend/src/game/calculations.js @@ -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, }; diff --git a/backend/src/game/calculations.test.js b/backend/src/game/calculations.test.js index 0c2f5c7..70143fd 100644 --- a/backend/src/game/calculations.test.js +++ b/backend/src/game/calculations.test.js @@ -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 + }); }); diff --git a/backend/src/game/data/characterOptions.js b/backend/src/game/data/characterOptions.js new file mode 100644 index 0000000..abe6ba1 --- /dev/null +++ b/backend/src/game/data/characterOptions.js @@ -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, +}; diff --git a/backend/src/game/data/spellsLibrary.js b/backend/src/game/data/spellsLibrary.js index 084bfc8..83fd7d8 100644 --- a/backend/src/game/data/spellsLibrary.js +++ b/backend/src/game/data/spellsLibrary.js @@ -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'] }, diff --git a/backend/src/routes/api.integration.test.js b/backend/src/routes/api.integration.test.js index a0023bc..7367f3c 100644 --- a/backend/src/routes/api.integration.test.js +++ b/backend/src/routes/api.integration.test.js @@ -7,6 +7,10 @@ const crypto = require('crypto'); const prisma = require('../db'); const { createApp } = require('../app'); +// Each test registers several users (bcrypt) and walks whole flows against a +// real database, which doesn't reliably fit Jest's 5 second default. +jest.setTimeout(30000); + const app = createApp(); app.set('io', { to: () => ({ emit: () => {} }) }); // stub Socket.io for tests @@ -38,6 +42,21 @@ function uniqueEmail(prefix) { return `${prefix}-${crypto.randomUUID()}@test.local`; } +// Valid picks for the three story steps that sit between skills and equipment. +const STORY_PICKS = { + talents: ['ALERT', 'KEEN_EYE'], + background: { upbringing: ['SOLDIER'], home: ['VILLAGE'], turningPoint: ['BETRAYED'], personality: ['BRAVE', 'CURIOUS'], flaw: ['GREEDY'] }, + appearance: { build: ['MUSCULAR'], height: ['TALL'], hair: ['RED'], eyes: ['GREEN'], complexion: ['WEATHERED'], features: ['SCAR'], style: ['CLOAK'] }, +}; + +// Walks a character from the special-abilities step through to equipment. +async function storySteps(characterId, auth) { + const choose = (body) => request(app).post(`/characters/${characterId}/build/choose`).set(auth).send(body); + await choose({ talents: STORY_PICKS.talents }); + await choose({ picks: STORY_PICKS.background }); + return choose({ picks: STORY_PICKS.appearance }); +} + function itIfDb(name, fn) { test(name, async () => { if (!dbAvailable) { @@ -111,7 +130,7 @@ describe('campaigns + characters + build flow', () => { const weaponRes = await request(app) .post(`/campaigns/${campaign.id}/weapons`) .set('Authorization', `Bearer ${dmToken}`) - .send({ name: 'Test Dagger', damageDice: '1d4', damageType: 'piercing', attackAbility: 'FINESSE', properties: [] }); + .send({ name: 'Test Dagger', damageDice: '1d4', damageType: 'piercing', attackAbility: 'FINESSE', properties: [], isStartingOption: true }); expect(weaponRes.status).toBe(201); const weaponId = weaponRes.body.weapon.id; @@ -162,6 +181,11 @@ describe('campaigns + characters + build flow', () => { .set(auth) .send({ skillProficiencies: [{ skill: 'ATHLETICS', proficient: true, expertise: false }] }); expect(chooseRes.status).toBe(200); + expect(chooseRes.body.buildStage).toBe('CHOOSING_ABILITIES'); + + // Special abilities, background, appearance + chooseRes = await storySteps(characterId, auth); + expect(chooseRes.status).toBe(200); expect(chooseRes.body.buildStage).toBe('CHOOSING_EQUIPMENT'); // Step 6: equipment @@ -227,6 +251,814 @@ async function setupCampaign(namePrefix) { }; } +// Walks the build flow to COMPLETE with whatever the dice give (or stops at the +// equipment step, for tests that exercise it). +async function buildCharacter(campaignId, auth, name, { stopBeforeEquipment = false } = {}) { + const characterRes = await request(app).post(`/campaigns/${campaignId}/characters`).set(auth).send({ name }); + const characterId = characterRes.body.character.id; + let rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth); + const species = rollRes.body.buildState.speciesChoices.options[0]; + await request(app) + .post(`/characters/${characterId}/build/choose`) + .set(auth) + .send(species === 'HALF_ELF' ? { species, halfElfBonusAbilities: ['STR', 'INT'] } : { species }); + rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth); + while (rollRes.body.buildState.classChoices.type === 'reroll') { + rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth); + } + const characterClass = rollRes.body.buildState.classChoices.options[0]; + await request(app).post(`/characters/${characterId}/build/choose`).set(auth).send({ characterClass }); + await request(app).post(`/characters/${characterId}/build/roll`).set(auth); + await request(app) + .post(`/characters/${characterId}/build/choose`) + .set(auth) + .send({ assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); + await request(app).post(`/characters/${characterId}/build/choose`).set(auth).send({}); + await storySteps(characterId, auth); + if (stopBeforeEquipment) return characterId; + await request(app).post(`/characters/${characterId}/build/choose`).set(auth).send({ weaponIds: [], spellIds: [] }); + await request(app).post(`/characters/${characterId}/build/finalize`).set(auth); + return characterId; +} + +describe('copy character to another campaign', () => { + itIfDb('copies stats, gear and spells into the target campaign and leaves the original alone', async () => { + const source = await setupCampaign('copysource'); + const target = await setupCampaign('copytarget'); + const { playerAuth } = source; + await request(app).post(`/campaigns/join/${target.campaign.inviteCode}`).set(playerAuth); + + const dagger = await request(app).post(`/campaigns/${source.campaign.id}/weapons/from-library`).set(source.dmAuth).send({ key: 'dagger' }); + const longsword = await request(app).post(`/campaigns/${source.campaign.id}/weapons/from-library`).set(source.dmAuth).send({ key: 'longsword' }); + const spell = await request(app) + .post(`/campaigns/${source.campaign.id}/spells`) + .set(source.dmAuth) + .send({ name: 'Test Bolt', level: 1 }); + // The target already has a Dagger (different case) — it must be reused, not duplicated. + const targetDagger = await request(app) + .post(`/campaigns/${target.campaign.id}/weapons`) + .set(target.dmAuth) + .send({ name: 'DAGGER', damageDice: '1d4', damageType: 'piercing', attackAbility: 'FINESSE', properties: [] }); + + const rope = await request(app) + .post(`/campaigns/${source.campaign.id}/items`) + .set(source.dmAuth) + .send({ name: 'Rope', description: '50 ft of hemp', isStartingOption: true }); + + const characterId = await buildCharacter(source.campaign.id, playerAuth, 'Traveller'); + await request(app).post(`/characters/${characterId}/weapons`).set(source.dmAuth).send({ weaponId: dagger.body.weapon.id }); + await request(app).patch(`/characters/${characterId}/weapons/${dagger.body.weapon.id}`).set(playerAuth).send({ equipped: true }); + await request(app).post(`/characters/${characterId}/weapons`).set(source.dmAuth).send({ weaponId: longsword.body.weapon.id, level: 2 }); + await request(app).post(`/characters/${characterId}/spells`).set(source.dmAuth).send({ spellId: spell.body.spell.id }); + await request(app).post(`/characters/${characterId}/inventory`).set(source.dmAuth).send({ itemId: rope.body.item.id, quantity: 2 }); + await request(app).post(`/characters/${characterId}/gold`).set(playerAuth).send({ amount: 42, reason: 'Savings' }); + await request(app).patch(`/characters/${characterId}`).set(source.dmAuth).send({ level: 3 }); + const original = ( + await request(app).patch(`/characters/${characterId}`).set(playerAuth).send({ currentHp: 1, privateNotes: 'secret' }) + ).body.character; + + const copyRes = await request(app).post(`/characters/${characterId}/copy`).set(playerAuth).send({ targetCampaignId: target.campaign.id }); + expect(copyRes.status).toBe(201); + const copy = copyRes.body.character; + expect(copy.id).not.toBe(characterId); + expect(copy.campaignId).toBe(target.campaign.id); + expect(copy.userId).toBe(original.userId); + expect(copy.buildStage).toBe('COMPLETE'); + expect(copy.level).toBe(3); + expect(copy.gold).toBe(42); + expect(copy.privateNotes).toBe('secret'); + expect(copy.species).toBe(original.species); + expect(copy.characterClass).toBe(original.characterClass); + expect(copy.rolledScores).toEqual(original.rolledScores); + expect(copy.sheet.skills).toEqual(original.sheet.skills); + expect(copy.sheet.saves).toEqual(original.sheet.saves); + expect(copy.currentHp).toBe(copy.sheet.hp.max); // arrives at full HP + expect(copy.inventoryItems.map((i) => [i.item.name, i.item.description, i.quantity])).toEqual([['Rope', '50 ft of hemp', 2]]); + expect(copy.inventoryItems[0].item.campaignId).toBe(target.campaign.id); + // Pool entries created by a copy are never starting options in the target. + expect(copy.inventoryItems[0].item.isStartingOption).toBe(false); + const copyLedger = await request(app).get(`/characters/${copy.id}/gold`).set(playerAuth); + expect(copyLedger.body.transactions.map((t) => [t.amount, t.balanceAfter])).toEqual([[42, 42]]); + expect(copy.spells.map((s) => s.spell.name)).toEqual(['Test Bolt']); + + const copiedDagger = copy.weapons.find((w) => w.weapon.name.toLowerCase() === 'dagger'); + expect(copiedDagger.weaponId).toBe(targetDagger.body.weapon.id); + expect(copiedDagger.equipped).toBe(true); + expect(copy.weapons.find((w) => w.weapon.name === 'Longsword')).toMatchObject({ level: 2, scaledDamageDice: '1d10' }); + expect(copy.weapons.every((w) => w.weapon.campaignId === target.campaign.id)).toBe(true); + expect(copy.spells.every((s) => s.spell.campaignId === target.campaign.id)).toBe(true); + + const targetWeapons = await request(app).get(`/campaigns/${target.campaign.id}/weapons`).set(playerAuth); + expect(targetWeapons.body.weapons.map((w) => w.name).sort()).toEqual(['DAGGER', 'Longsword']); + + const originalAfter = await request(app).get(`/characters/${characterId}`).set(playerAuth); + expect(originalAfter.body.character.campaignId).toBe(source.campaign.id); + expect(originalAfter.body.character.currentHp).toBe(1); + expect(originalAfter.body.character.weapons).toHaveLength(2); + }); + + itIfDb('enforces membership, ownership, build state and privacy', async () => { + const source = await setupCampaign('copyrules'); + const other = await setupCampaign('copyrules-other'); + const characterId = await buildCharacter(source.campaign.id, source.playerAuth, 'Homebody'); + await request(app).patch(`/characters/${characterId}`).set(source.playerAuth).send({ privateNotes: 'secret' }); + + // Owner isn't a member of the other campaign. + let res = await request(app).post(`/characters/${characterId}/copy`).set(source.playerAuth).send({ targetCampaignId: other.campaign.id }); + expect(res.status).toBe(403); + + // Same campaign is not "another campaign". + res = await request(app).post(`/characters/${characterId}/copy`).set(source.playerAuth).send({ targetCampaignId: source.campaign.id }); + expect(res.status).toBe(400); + + // A fellow player in both campaigns can't copy someone else's character. + await request(app).post(`/campaigns/join/${source.campaign.inviteCode}`).set(other.playerAuth); + res = await request(app).post(`/characters/${characterId}/copy`).set(other.playerAuth).send({ targetCampaignId: other.campaign.id }); + expect(res.status).toBe(403); + + // An unfinished character can't be copied. + const unfinished = await request(app).post(`/campaigns/${source.campaign.id}/characters`).set(source.playerAuth).send({ name: 'Half Built' }); + await request(app).post(`/campaigns/join/${other.campaign.inviteCode}`).set(source.playerAuth); + res = await request(app) + .post(`/characters/${unfinished.body.character.id}/copy`) + .set(source.playerAuth) + .send({ targetCampaignId: other.campaign.id }); + expect(res.status).toBe(400); + + // The source DM can copy it, becomes the copy's owner, and never receives the player's private notes. + await request(app).post(`/campaigns/join/${other.campaign.inviteCode}`).set(source.dmAuth); + res = await request(app).post(`/characters/${characterId}/copy`).set(source.dmAuth).send({ targetCampaignId: other.campaign.id }); + expect(res.status).toBe(201); + expect(res.body.character.privateNotes).toBeNull(); + const dmMe = await request(app).get('/auth/me').set(source.dmAuth); + expect(res.body.character.userId).toBe(dmMe.body.user.id); + }); +}); + +describe('who can change what on a character', () => { + itIfDb('keeps level, XP and location with the DM, and gold out of PATCH entirely', async () => { + const { dmAuth, playerAuth, campaign } = await setupCampaign('dmonly'); + const characterId = await buildCharacter(campaign.id, playerAuth, 'Ambitious'); + const location = await request(app).post(`/campaigns/${campaign.id}/locations`).set(dmAuth).send({ name: 'Keep' }); + + const dmOnly = [ + { level: 20 }, + { xp: 9000 }, + { currentLocationId: location.body.location.id }, + { speedOverride: 90 }, + // Composed by the builder from the player's picks; only the DM rewrites them. + { specialAbilities: 'Flight — I can fly.' }, + { background: 'Secretly the king.' }, + { appearance: 'Ten feet tall.' }, + ]; + for (const body of dmOnly) { + const res = await request(app).patch(`/characters/${characterId}`).set(playerAuth).send(body); + expect(res.status).toBe(403); + } + expect((await request(app).patch(`/characters/${characterId}`).set(playerAuth).send({ gold: 999 })).status).toBe(400); + expect((await request(app).patch(`/characters/${characterId}`).set(dmAuth).send({ gold: 999 })).status).toBe(400); + + // The player can still edit the rest of their own sheet. + expect((await request(app).patch(`/characters/${characterId}`).set(playerAuth).send({ armorBonus: 2 })).status).toBe(200); + + const dmRes = await request(app) + .patch(`/characters/${characterId}`) + .set(dmAuth) + .send({ level: 2, xp: 300, currentLocationId: location.body.location.id }); + expect(dmRes.status).toBe(200); + expect(dmRes.body.character.level).toBe(2); + expect(dmRes.body.character.gold).toBe(0); + }); + + itIfDb('only the DM hands out, removes or re-counts gear; the owner can equip and prepare', async () => { + const { dmAuth, playerAuth, campaign } = await setupCampaign('gear'); + const characterId = await buildCharacter(campaign.id, playerAuth, 'Packrat'); + const weaponId = (await request(app).post(`/campaigns/${campaign.id}/weapons/from-library`).set(dmAuth).send({ key: 'dagger' })).body.weapon.id; + const spellId = (await request(app).post(`/campaigns/${campaign.id}/spells`).set(dmAuth).send({ name: 'Spark', level: 0 })).body.spell.id; + const itemRes = await request(app).post(`/campaigns/${campaign.id}/items`).set(dmAuth).send({ name: 'Rope', description: '50 ft' }); + expect(itemRes.status).toBe(201); + const itemId = itemRes.body.item.id; + + // Players can see the pool but not add to it or help themselves from it. + expect((await request(app).get(`/campaigns/${campaign.id}/items`).set(playerAuth)).body.items).toHaveLength(1); + expect((await request(app).post(`/campaigns/${campaign.id}/items`).set(playerAuth).send({ name: 'Crown' })).status).toBe(403); + expect((await request(app).post(`/characters/${characterId}/weapons`).set(playerAuth).send({ weaponId })).status).toBe(403); + expect((await request(app).post(`/characters/${characterId}/inventory`).set(playerAuth).send({ itemId })).status).toBe(403); + expect((await request(app).post(`/characters/${characterId}/spells`).set(playerAuth).send({ spellId })).status).toBe(403); + + expect((await request(app).post(`/characters/${characterId}/weapons`).set(dmAuth).send({ weaponId })).status).toBe(201); + expect((await request(app).post(`/characters/${characterId}/spells`).set(dmAuth).send({ spellId })).status).toBe(201); + expect((await request(app).post(`/characters/${characterId}/inventory`).set(dmAuth).send({ itemId, quantity: 2 })).status).toBe(201); + // Giving the same item again stacks it. + const stacked = await request(app).post(`/characters/${characterId}/inventory`).set(dmAuth).send({ itemId }); + expect(stacked.body.inventoryItem.quantity).toBe(3); + expect(stacked.body.inventoryItem.item.name).toBe('Rope'); + + // Owner: equip / prepare yes, quantity and removal no. + expect((await request(app).patch(`/characters/${characterId}/inventory/${itemId}`).set(playerAuth).send({ equipped: true })).status).toBe(200); + expect((await request(app).patch(`/characters/${characterId}/weapons/${weaponId}`).set(playerAuth).send({ equipped: true })).status).toBe(200); + expect((await request(app).patch(`/characters/${characterId}/spells/${spellId}`).set(playerAuth).send({ prepared: true })).status).toBe(200); + expect((await request(app).patch(`/characters/${characterId}/inventory/${itemId}`).set(playerAuth).send({ quantity: 99 })).status).toBe(403); + expect((await request(app).delete(`/characters/${characterId}/inventory/${itemId}`).set(playerAuth)).status).toBe(403); + expect((await request(app).delete(`/characters/${characterId}/weapons/${weaponId}`).set(playerAuth)).status).toBe(403); + + // An inventory edit can only reach the character in the URL. + const otherId = await buildCharacter(campaign.id, dmAuth, 'Bystander'); + expect((await request(app).patch(`/characters/${otherId}/inventory/${itemId}`).set(dmAuth).send({ equipped: true })).status).toBe(404); + expect((await request(app).delete(`/characters/${otherId}/inventory/${itemId}`).set(dmAuth)).status).toBe(404); + + expect((await request(app).patch(`/characters/${characterId}/inventory/${itemId}`).set(dmAuth).send({ quantity: 1 })).status).toBe(200); + expect((await request(app).delete(`/characters/${characterId}/weapons/${weaponId}`).set(dmAuth)).status).toBe(204); + expect((await request(app).delete(`/characters/${characterId}/spells/${spellId}`).set(dmAuth)).status).toBe(204); + + const sheet = (await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character; + expect(sheet.weapons).toHaveLength(0); + expect(sheet.spells).toHaveLength(0); + expect(sheet.inventoryItems).toHaveLength(1); + expect(sheet.inventoryItems[0]).toMatchObject({ quantity: 1, equipped: true }); + + // Deleting the pool item takes it out of every inventory. + expect((await request(app).delete(`/campaigns/${campaign.id}/items/${itemId}`).set(dmAuth)).status).toBe(204); + expect((await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character.inventoryItems).toHaveLength(0); + }); + + itIfDb('a DM cannot edit or delete another campaign\'s pool entries through their own campaign', async () => { + const mine = await setupCampaign('poolmine'); + const theirs = await setupCampaign('pooltheirs'); + const weaponId = (await request(app).post(`/campaigns/${theirs.campaign.id}/weapons/from-library`).set(theirs.dmAuth).send({ key: 'dagger' })).body.weapon.id; + const itemId = (await request(app).post(`/campaigns/${theirs.campaign.id}/items`).set(theirs.dmAuth).send({ name: 'Relic' })).body.item.id; + + expect((await request(app).patch(`/campaigns/${mine.campaign.id}/weapons/${weaponId}`).set(mine.dmAuth).send({ name: 'Hacked' })).status).toBe(404); + expect((await request(app).delete(`/campaigns/${mine.campaign.id}/weapons/${weaponId}`).set(mine.dmAuth)).status).toBe(404); + expect((await request(app).delete(`/campaigns/${mine.campaign.id}/items/${itemId}`).set(mine.dmAuth)).status).toBe(404); + + const weapons = (await request(app).get(`/campaigns/${theirs.campaign.id}/weapons`).set(theirs.dmAuth)).body.weapons; + expect(weapons.map((w) => w.name)).toEqual(['Dagger']); + }); +}); + +describe('giving to another character', () => { + itIfDb('moves weapons, items, spells and gold from one character to another', async () => { + const { dmAuth, playerAuth, campaign } = await setupCampaign('give'); + const other = await setupCampaign('give-other'); + const c = `/campaigns/${campaign.id}`; + const giverId = await buildCharacter(campaign.id, playerAuth, 'Aria'); + const friendId = await buildCharacter(campaign.id, dmAuth, 'Bo'); + const unfinishedId = (await request(app).post(`${c}/characters`).set(dmAuth).send({ name: 'Unfinished' })).body.character.id; + const outsiderId = await buildCharacter(other.campaign.id, other.dmAuth, 'Outsider'); + + const spear = (await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Spear', damageDice: '1d6', damageType: 'piercing', attackAbility: 'STR' })).body.weapon; + const potion = (await request(app).post(`${c}/items`).set(dmAuth).send({ name: 'Potion', damageDice: '2d4+2' })).body.item; + const spell = (await request(app).post(`${c}/spells`).set(dmAuth).send({ name: 'Fire Bolt', level: 0, damageDice: '1d10' })).body.spell; + const g = `/characters/${giverId}`; + await request(app).post(`${g}/weapons`).set(dmAuth).send({ weaponId: spear.id, level: 3 }); + await request(app).post(`${g}/inventory`).set(dmAuth).send({ itemId: potion.id, quantity: 3 }); + await request(app).post(`${g}/spells`).set(dmAuth).send({ spellId: spell.id }); + await request(app).post(`${g}/gold`).set(dmAuth).send({ amount: 30 }); + // Bo already has one potion, at level 2. + await request(app).post(`/characters/${friendId}/inventory`).set(dmAuth).send({ itemId: potion.id, level: 2 }); + + const give = (body, auth = playerAuth, from = giverId) => request(app).post(`/characters/${from}/give`).set(auth).send(body); + const sheet = async (id) => (await request(app).get(`/characters/${id}`).set(dmAuth)).body.character; + + // Who and where. + const stranger = await request(app).post('/auth/register').send({ email: uniqueEmail('give-stranger'), password: 'password123', displayName: 'Stranger' }); + cleanupUserIds.push(stranger.body.user.id); + const strangerAuth = { Authorization: `Bearer ${stranger.body.token}` }; + await request(app).post(`/campaigns/join/${campaign.inviteCode}`).set(strangerAuth); + expect((await give({ kind: 'gold', toCharacterId: friendId, amount: 1 }, strangerAuth)).status).toBe(403); // not their character + expect((await give({ kind: 'gold', toCharacterId: giverId, amount: 1 })).status).toBe(400); // to itself + expect((await give({ kind: 'gold', toCharacterId: outsiderId, amount: 1 })).status).toBe(400); // another campaign + expect((await give({ kind: 'gold', toCharacterId: unfinishedId, amount: 1 })).status).toBe(400); // still being built + + // Gold: both ledgers record it, and you can't give what you don't have. + expect((await give({ kind: 'gold', toCharacterId: friendId, amount: 31 })).status).toBe(400); + expect((await give({ kind: 'gold', toCharacterId: friendId, amount: 0 })).status).toBe(400); + const gaveGold = await give({ kind: 'gold', toCharacterId: friendId, amount: 12 }); + expect(gaveGold.status).toBe(200); + expect(gaveGold.body.character.gold).toBe(18); + expect((await sheet(friendId)).gold).toBe(12); + const ledger = async (id) => (await request(app).get(`/characters/${id}/gold`).set(dmAuth)).body.transactions[0]; + expect(await ledger(giverId)).toMatchObject({ amount: -12, reason: 'Gave to Bo', balanceAfter: 18 }); + expect(await ledger(friendId)).toMatchObject({ amount: 12, reason: 'Received from Aria', balanceAfter: 12 }); + + // Items: part of a stack moves; the recipient's existing stack keeps its own level. + expect((await give({ kind: 'item', toCharacterId: friendId, id: potion.id, quantity: 4 })).status).toBe(400); + expect((await give({ kind: 'item', toCharacterId: friendId, id: potion.id, quantity: 2 })).status).toBe(200); + expect((await sheet(giverId)).inventoryItems.map((i) => [i.item.name, i.quantity])).toEqual([['Potion', 1]]); + expect((await sheet(friendId)).inventoryItems.map((i) => [i.item.name, i.quantity, i.level])).toEqual([['Potion', 3, 2]]); + // Giving the last one empties the giver's inventory of it. + expect((await give({ kind: 'item', toCharacterId: friendId, id: potion.id })).status).toBe(200); + expect((await sheet(giverId)).inventoryItems).toEqual([]); + expect((await give({ kind: 'item', toCharacterId: friendId, id: potion.id })).status).toBe(400); // nothing left + + // Weapons: arrive at the giver's level, unequipped — held but unusable if the recipient is too low. + await request(app).patch(g).set(dmAuth).send({ level: 3 }); + await request(app).patch(`${g}/weapons/${spear.id}`).set(playerAuth).send({ equipped: true }); + expect((await give({ kind: 'weapon', toCharacterId: friendId, id: spear.id })).status).toBe(200); + expect((await sheet(giverId)).weapons).toEqual([]); + expect((await sheet(friendId)).weapons.map((w) => [w.weapon.name, w.level, w.quantity, w.equipped, w.usable])).toEqual([['Spear', 3, 1, false, false]]); + + // Spells move too: the giver no longer knows it, and nobody ends up knowing it twice. + expect((await give({ kind: 'spell', toCharacterId: friendId, id: spell.id })).status).toBe(200); + expect((await sheet(giverId)).spells).toEqual([]); + expect((await sheet(friendId)).spells.map((s) => s.spell.name)).toEqual(['Fire Bolt']); + expect((await give({ kind: 'spell', toCharacterId: friendId, id: spell.id })).status).toBe(400); // no longer known + await request(app).post(`${g}/spells`).set(dmAuth).send({ spellId: spell.id }); + expect((await give({ kind: 'spell', toCharacterId: friendId, id: spell.id })).status).toBe(400); // Bo already knows it + expect((await sheet(giverId)).spells).toHaveLength(1); // and Aria kept hers + + // The DM can move things between characters as well. + expect((await give({ kind: 'weapon', toCharacterId: giverId, id: spear.id }, dmAuth, friendId)).status).toBe(200); + expect((await sheet(giverId)).weapons.map((w) => [w.weapon.name, w.level])).toEqual([['Spear', 3]]); + }); +}); + +describe('hit points', () => { + itIfDb('stay between 0 and max on the sheet, including after a level drop', async () => { + const { dmAuth, playerAuth, campaign } = await setupCampaign('hpclamp'); + const characterId = await buildCharacter(campaign.id, playerAuth, 'Sturdy'); + const patch = (auth, body) => request(app).patch(`/characters/${characterId}`).set(auth).send(body); + + const level5 = (await patch(dmAuth, { level: 5 })).body.character; + const full = (await patch(playerAuth, { currentHp: 9999 })).body.character; + expect(full.currentHp).toBe(level5.sheet.hp.max); + + expect((await patch(playerAuth, { currentHp: -50 })).body.character.currentHp).toBe(0); + + await patch(playerAuth, { currentHp: 9999 }); + const level1 = (await patch(dmAuth, { level: 1 })).body.character; + expect(level1.sheet.hp.max).toBeLessThan(level5.sheet.hp.max); + expect(level1.currentHp).toBe(level1.sheet.hp.max); + }); + + itIfDb('are shared between the character sheet and the encounter tracker', async () => { + const { dmAuth, playerAuth, campaign } = await setupCampaign('hpsync'); + const characterId = await buildCharacter(campaign.id, playerAuth, 'Brawler'); + const maxHp = (await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character.sheet.hp.max; + + const encounterId = (await request(app).post(`/campaigns/${campaign.id}/encounters`).set(dmAuth).send({ name: 'Brawl' })).body.encounter.id; + const added = await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ characterId, initiative: 12 }); + const participantId = added.body.participant.id; + const combatant = async () => (await request(app).get(`/encounters/${encounterId}`).set(playerAuth)).body.encounter.participants[0]; + const sheetHp = async () => (await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character.currentHp; + + // Damage in the tracker lands on the sheet. + const hit = await request(app).patch(`/encounters/${encounterId}/participants/${participantId}`).set(dmAuth).send({ currentHp: maxHp - 3 }); + expect(hit.status).toBe(200); + expect(await sheetHp()).toBe(maxHp - 3); + + // Healing on the sheet shows in the tracker. + await request(app).patch(`/characters/${characterId}`).set(playerAuth).send({ currentHp: maxHp - 1 }); + expect((await combatant()).currentHp).toBe(maxHp - 1); + + // The tracker is clamped like the sheet, and can't give a character a different max. + await request(app).patch(`/encounters/${encounterId}/participants/${participantId}`).set(dmAuth).send({ currentHp: -20, maxHp: 500 }); + expect(await sheetHp()).toBe(0); + expect((await combatant()).maxHp).toBe(maxHp); + + // A level-up moves the tracker's max too. + await request(app).patch(`/characters/${characterId}`).set(dmAuth).send({ level: 4 }); + expect((await combatant()).maxHp).toBeGreaterThan(maxHp); + + // Monsters are clamped to their own max. + const monsterId = (await request(app).post(`/campaigns/${campaign.id}/monsters/from-library`).set(dmAuth).send({ key: 'goblin' })).body.monster.id; + const monster = (await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ monsterId })).body.participant; + const healed = await request(app).patch(`/encounters/${encounterId}/participants/${monster.id}`).set(dmAuth).send({ currentHp: 9999 }); + expect(healed.body.participant.currentHp).toBe(monster.maxHp); + + // A combatant can only be edited through its own encounter. + const otherEncounterId = (await request(app).post(`/campaigns/${campaign.id}/encounters`).set(dmAuth).send({ name: 'Elsewhere' })).body.encounter.id; + const wrong = await request(app).patch(`/encounters/${otherEncounterId}/participants/${participantId}`).set(dmAuth).send({ initiative: 1 }); + expect(wrong.status).toBe(404); + }); +}); + +describe('money tracker', () => { + itIfDb('logs every change to the balance and refuses to overspend', async () => { + const { dmAuth, playerAuth, campaign } = await setupCampaign('gold'); + await request(app).patch(`/campaigns/${campaign.id}`).set(dmAuth).send({ startingGold: 15 }); + const characterId = (await request(app).post(`/campaigns/${campaign.id}/characters`).set(playerAuth).send({ name: 'Merchant' })).body.character.id; + const gold = (auth, body) => request(app).post(`/characters/${characterId}/gold`).set(auth).send(body); + + const reward = await gold(dmAuth, { amount: 50, reason: 'Bounty on the wolf pack' }); + expect(reward.status).toBe(201); + expect(reward.body.gold).toBe(65); + + const spend = await gold(playerAuth, { amount: -20, reason: 'New boots' }); + expect(spend.status).toBe(201); + expect(spend.body.gold).toBe(45); + + const overspend = await gold(playerAuth, { amount: -46 }); + expect(overspend.status).toBe(400); + expect((await gold(playerAuth, { amount: 0 })).status).toBe(400); + expect((await gold(playerAuth, { amount: 1.5 })).status).toBe(400); + + // Another player can read the ledger but not write to it. + const stranger = await request(app) + .post('/auth/register') + .send({ email: uniqueEmail('gold-other'), password: 'password123', displayName: 'Other' }); + cleanupUserIds.push(stranger.body.user.id); + const strangerAuth = { Authorization: `Bearer ${stranger.body.token}` }; + await request(app).post(`/campaigns/join/${campaign.inviteCode}`).set(strangerAuth); + expect((await gold(strangerAuth, { amount: 5 })).status).toBe(403); + + const ledger = await request(app).get(`/characters/${characterId}/gold`).set(strangerAuth); + expect(ledger.status).toBe(200); + expect(ledger.body.gold).toBe(45); + expect(ledger.body.transactions.map((t) => [t.amount, t.balanceAfter, t.reason, t.createdBy.displayName])).toEqual([ + [-20, 45, 'New boots', 'Player'], + [50, 65, 'Bounty on the wolf pack', 'DM'], + [15, 15, 'Starting gold', 'Player'], + ]); + }); +}); + +describe('starting options', () => { + itIfDb('only pool entries the DM marked can be picked while building, and items share the weapon allowance', async () => { + const { dmAuth, playerAuth, campaign } = await setupCampaign('starting'); + await request(app).patch(`/campaigns/${campaign.id}`).set(dmAuth).send({ startingItemCount: 2, startingSpellCount: 1 }); + const other = await setupCampaign('starting-other'); + + const post = (path, body, c = campaign, auth = dmAuth) => request(app).post(`/campaigns/${c.id}/${path}`).set(auth).send(body); + const club = (await post('weapons', { name: 'Club', damageDice: '1d4', damageType: 'bludgeoning', attackAbility: 'STR', isStartingOption: true })).body.weapon; + const vorpal = (await post('weapons/from-library', { key: 'longsword' })).body.weapon; + const torch = (await post('items', { name: 'Torch', isStartingOption: true })).body.item; + const bedroll = (await post('items', { name: 'Bedroll', isStartingOption: true })).body.item; + const crown = (await post('items', { name: 'Crown of Kings' })).body.item; + const spark = (await post('spells', { name: 'Spark', level: 0, isStartingOption: true })).body.spell; + const wish = (await post('spells', { name: 'Wish', level: 9 })).body.spell; + const foreign = (await post('items', { name: 'Foreign', isStartingOption: true }, other.campaign, other.dmAuth)).body.item; + + // Library and hand-made entries are not starting options unless marked. + expect(club.isStartingOption).toBe(true); + expect(vorpal.isStartingOption).toBe(false); + expect(crown.isStartingOption).toBe(false); + + const characterId = await buildCharacter(campaign.id, playerAuth, 'Newcomer', { stopBeforeEquipment: true }); + const choose = (body) => request(app).post(`/characters/${characterId}/build/choose`).set(playerAuth).send(body); + + expect((await choose({ weaponIds: [vorpal.id] })).status).toBe(400); // not a starting option + expect((await choose({ itemIds: [crown.id] })).status).toBe(400); + expect((await choose({ itemIds: [foreign.id] })).status).toBe(400); // another campaign + expect((await choose({ itemIds: [torch.id, torch.id] })).status).toBe(400); // duplicates + expect((await choose({ weaponIds: [club.id], itemIds: [torch.id, bedroll.id] })).status).toBe(400); // 3 > allowance of 2 + + const character = (await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character; + const isCaster = ['RANGER', 'WIZARD', 'SORCERER', 'CLERIC', 'PALADIN', 'BARD', 'WARLOCK', 'DRUID'].includes(character.buildState.characterClass); + if (isCaster) expect((await choose({ spellIds: [wish.id] })).status).toBe(400); + + const ok = await choose({ weaponIds: [club.id], itemIds: [torch.id], spellIds: isCaster ? [spark.id] : [] }); + expect(ok.status).toBe(200); + const finalized = (await request(app).post(`/characters/${characterId}/build/finalize`).set(playerAuth)).body.character; + expect(finalized.weapons.map((w) => w.weapon.name)).toEqual(['Club']); + expect(finalized.inventoryItems.map((i) => i.item.name)).toEqual(['Torch']); + expect(finalized.spells.map((s) => s.spell.name)).toEqual(isCaster ? ['Spark'] : []); + + // The DM can flip the flag later. + const flipped = await request(app).patch(`/campaigns/${campaign.id}/items/${crown.id}`).set(dmAuth).send({ isStartingOption: true }); + expect(flipped.body.item.isStartingOption).toBe(true); + const spellFlip = await request(app).patch(`/campaigns/${campaign.id}/spells/${wish.id}`).set(dmAuth).send({ isStartingOption: true }); + expect(spellFlip.body.spell.isStartingOption).toBe(true); + }); +}); + +describe('gear levels', () => { + itIfDb('weapons and items scale with their own level and need a character of that level', async () => { + const { dmAuth, playerAuth, campaign } = await setupCampaign('gearlevels'); + const characterId = await buildCharacter(campaign.id, playerAuth, 'Squire'); + const c = `/campaigns/${campaign.id}`; + const spear = (await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Spear', damageDice: '1d6', damageType: 'piercing', attackAbility: 'STR' })).body.weapon; + const relic = (await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Relic Blade', damageDice: '1d8', damageType: 'slashing', attackAbility: 'STR', damageScaling: 3 })).body.weapon; + const potion = (await request(app).post(`${c}/items`).set(dmAuth).send({ name: 'Healing Potion', damageDice: '2d4+2' })).body.item; + const rope = (await request(app).post(`${c}/items`).set(dmAuth).send({ name: 'Rope' })).body.item; + expect(spear.damageScaling).toBe(1); + expect(relic.damageScaling).toBe(3); + expect((await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Bad', damageDice: '1d4', damageType: 'x', attackAbility: 'STR', damageScaling: 4 })).status).toBe(400); + + const ch = `/characters/${characterId}`; + const sheet = async () => (await request(app).get(ch).set(playerAuth)).body.character; + const held = async (name) => (await sheet()).weapons.find((w) => w.weapon.name === name); + + // Given at level 1 by default; the DM can give at a higher level. + await request(app).post(`${ch}/weapons`).set(dmAuth).send({ weaponId: spear.id }); + await request(app).post(`${ch}/weapons`).set(dmAuth).send({ weaponId: relic.id, level: 2 }); + await request(app).post(`${ch}/inventory`).set(dmAuth).send({ itemId: potion.id }); + await request(app).post(`${ch}/inventory`).set(dmAuth).send({ itemId: rope.id }); + expect(await held('Spear')).toMatchObject({ level: 1, scaledDamageDice: '1d6', usable: true }); + expect(await held('Relic Blade')).toMatchObject({ level: 2, scaledDamageDice: '2d6', usable: false }); + + // A level 1 character holds the level 2 blade but can't equip it. + expect((await request(app).patch(`${ch}/weapons/${relic.id}`).set(playerAuth).send({ equipped: true })).status).toBe(400); + expect((await request(app).patch(`${ch}/weapons/${spear.id}`).set(playerAuth).send({ equipped: true })).status).toBe(200); + expect((await request(app).post(`${ch}/weapons`).set(dmAuth).send({ weaponId: relic.id, level: 21 })).status).toBe(400); + + // Only the DM levels gear. Levelling the equipped spear past its holder takes it off. + expect((await request(app).patch(`${ch}/weapons/${spear.id}`).set(playerAuth).send({ level: 5 })).status).toBe(403); + const levelled = await request(app).patch(`${ch}/weapons/${spear.id}`).set(dmAuth).send({ level: 3 }); + expect(levelled.status).toBe(200); + expect(levelled.body.characterWeapon).toMatchObject({ level: 3, equipped: false }); + expect(await held('Spear')).toMatchObject({ scaledDamageDice: '1d10', usable: false }); + + // Unusable weapons stay out of quick stats and the encounter view. + const quick = async () => (await request(app).get(`${ch}/quick-stats`).set(playerAuth)).body.quickStats.weapons; + expect(await quick()).toEqual([]); + + // At character level 3 both are usable, at their own level's dice. + await request(app).patch(ch).set(dmAuth).send({ level: 3 }); + expect(await held('Spear')).toMatchObject({ usable: true }); + expect((await request(app).patch(`${ch}/weapons/${spear.id}`).set(playerAuth).send({ equipped: true })).status).toBe(200); + expect((await request(app).patch(`${ch}/weapons/${relic.id}`).set(playerAuth).send({ equipped: true })).status).toBe(200); + expect((await quick()).map((w) => [w.name, w.level, w.damageDice]).sort()).toEqual([ + ['Relic Blade', 2, '2d6'], + ['Spear', 3, '1d10'], + ]); + + const encounterId = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Drill' })).body.encounter.id; + await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ characterId }); + const combat = async () => + (await request(app).get(`/encounters/${encounterId}`).set(playerAuth)).body.encounter.participants[0].characterCombatInfo; + expect((await combat()).weapons.map((w) => w.damageDice).sort()).toEqual(['1d10', '2d6']); + + // Items level the same way; an item with no dice just has a level requirement. + const items = async () => (await sheet()).inventoryItems; + await request(app).patch(`${ch}/inventory/${potion.id}`).set(dmAuth).send({ level: 2 }); + await request(app).patch(`${ch}/inventory/${rope.id}`).set(dmAuth).send({ level: 5 }); + const [potionHeld, ropeHeld] = ['Healing Potion', 'Rope'].map(async (name) => (await items()).find((i) => i.item.name === name)); + expect(await potionHeld).toMatchObject({ level: 2, scaledDamageDice: '1d6+1d8', usable: true }); + expect(await ropeHeld).toMatchObject({ level: 5, scaledDamageDice: null, usable: false }); + expect((await request(app).patch(`${ch}/inventory/${rope.id}`).set(playerAuth).send({ equipped: true })).status).toBe(400); + + // Dropping the character back to level 1 unequips what is now out of reach. + await request(app).patch(ch).set(dmAuth).send({ level: 1 }); + expect((await sheet()).weapons.map((w) => [w.weapon.name, w.equipped, w.usable]).sort()).toEqual([ + ['Relic Blade', false, false], + ['Spear', false, false], + ]); + expect((await combat()).weapons).toEqual([]); + }); + + itIfDb('a spell needs a character of at least its classic level, and carries a fixed damage value', async () => { + const { dmAuth, playerAuth, campaign } = await setupCampaign('spelllevels'); + const characterId = await buildCharacter(campaign.id, playerAuth, 'Apprentice'); + const c = `/campaigns/${campaign.id}`; + const ch = `/characters/${characterId}`; + const cantrip = (await request(app).post(`${c}/spells`).set(dmAuth).send({ name: 'Fire Bolt', level: 0, damageDice: '1d10' })).body.spell; + const fireball = (await request(app).post(`${c}/spells`).set(dmAuth).send({ name: 'Fireball', level: 3, damageDice: '8d6', isStartingOption: true })).body.spell; + expect(fireball.damageDice).toBe('8d6'); + + for (const spell of [cantrip, fireball]) await request(app).post(`${ch}/spells`).set(dmAuth).send({ spellId: spell.id }); + const spells = async () => (await request(app).get(ch).set(playerAuth)).body.character.spells; + expect((await spells()).map((s) => [s.spell.name, s.usable]).sort()).toEqual([['Fire Bolt', true], ['Fireball', false]]); + + expect((await request(app).patch(`${ch}/spells/${cantrip.id}`).set(playerAuth).send({ prepared: true })).status).toBe(200); + expect((await request(app).patch(`${ch}/spells/${fireball.id}`).set(playerAuth).send({ prepared: true })).status).toBe(400); + // Spells have no level of their own to raise. + expect((await request(app).patch(`${ch}/spells/${fireball.id}`).set(dmAuth).send({ level: 1 })).body.characterSpell.spell.level).toBe(3); + + await request(app).patch(ch).set(dmAuth).send({ level: 3 }); + expect((await request(app).patch(`${ch}/spells/${fireball.id}`).set(playerAuth).send({ prepared: true })).status).toBe(200); + + const encounterId = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Blast' })).body.encounter.id; + await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ characterId }); + const combatSpells = async () => + (await request(app).get(`/encounters/${encounterId}`).set(playerAuth)).body.encounter.participants[0].characterCombatInfo.spells; + expect((await combatSpells()).map((s) => [s.name, s.damageDice]).sort()).toEqual([['Fire Bolt', '1d10'], ['Fireball', '8d6']]); + + await request(app).patch(ch).set(dmAuth).send({ level: 2 }); + expect((await spells()).find((s) => s.spell.name === 'Fireball')).toMatchObject({ prepared: false, usable: false }); + expect((await combatSpells()).map((s) => s.name)).toEqual(['Fire Bolt']); + + // A brand-new (level 1) character can't start with a level 3 spell, even a starting option. + await request(app).patch(c).set(dmAuth).send({ startingSpellCount: 1 }); + const newId = await buildCharacter(campaign.id, playerAuth, 'Hopeful', { stopBeforeEquipment: true }); + const pick = await request(app).post(`/characters/${newId}/build/choose`).set(playerAuth).send({ spellIds: [fireball.id] }); + expect(pick.status).toBe(400); + }); +}); + +describe('gear starting levels', () => { + itIfDb('a weapon that starts at a higher level is given there, never goes below it, and scales from it', async () => { + const { dmAuth, playerAuth, campaign } = await setupCampaign('minlevel'); + await request(app).patch(`/campaigns/${campaign.id}`).set(dmAuth).send({ startingItemCount: 2 }); + const c = `/campaigns/${campaign.id}`; + const greatsword = ( + await request(app) + .post(`${c}/weapons`) + .set(dmAuth) + .send({ name: 'Greatsword', damageDice: '2d6', damageType: 'slashing', attackAbility: 'STR', minLevel: 3, isStartingOption: true }) + ).body.weapon; + expect(greatsword.minLevel).toBe(3); + expect((await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Bad', damageDice: '1d4', damageType: 'x', attackAbility: 'STR', minLevel: 10 })).status).toBe(400); + const club = (await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Club', damageDice: '1d4', damageType: 'bludgeoning', attackAbility: 'STR', isStartingOption: true })).body.weapon; + + // Too high for a new character, even though it is ticked as a starting option. + const newbie = await buildCharacter(campaign.id, playerAuth, 'Newbie', { stopBeforeEquipment: true }); + expect((await request(app).post(`/characters/${newbie}/build/choose`).set(playerAuth).send({ weaponIds: [greatsword.id] })).status).toBe(400); + expect((await request(app).post(`/characters/${newbie}/build/choose`).set(playerAuth).send({ weaponIds: [club.id] })).status).toBe(200); + + const characterId = await buildCharacter(campaign.id, playerAuth, 'Veteran'); + const ch = `/characters/${characterId}`; + const held = async (name) => (await request(app).get(ch).set(playerAuth)).body.character.weapons.find((w) => w.weapon.name === name); + + expect((await request(app).post(`${ch}/weapons`).set(dmAuth).send({ weaponId: greatsword.id, level: 2 })).status).toBe(400); + const given = await request(app).post(`${ch}/weapons`).set(dmAuth).send({ weaponId: greatsword.id }); + expect(given.body.characterWeapon.level).toBe(3); + expect(await held('Greatsword')).toMatchObject({ level: 3, scaledDamageDice: '2d6', usable: false }); + + expect((await request(app).patch(`${ch}/weapons/${greatsword.id}`).set(dmAuth).send({ level: 2 })).status).toBe(400); + expect((await request(app).patch(`${ch}/weapons/${greatsword.id}`).set(dmAuth).send({ level: 10 })).status).toBe(400); // gear stops at 9 + await request(app).patch(`${ch}/weapons/${greatsword.id}`).set(dmAuth).send({ level: 5 }); + expect(await held('Greatsword')).toMatchObject({ level: 5, scaledDamageDice: '2d8' }); + expect((await request(app).patch(`${ch}/weapons/${greatsword.id}`).set(dmAuth).send({ level: 9 })).status).toBe(200); + + // Raising a pool entry's starting level lifts copies that are now below it. + await request(app).post(`${ch}/weapons`).set(dmAuth).send({ weaponId: club.id }); + await request(app).patch(`${ch}/weapons/${club.id}`).set(playerAuth).send({ equipped: true }); + await request(app).patch(`${c}/weapons/${club.id}`).set(dmAuth).send({ minLevel: 2 }); + expect(await held('Club')).toMatchObject({ level: 2, scaledDamageDice: '1d4', equipped: false, usable: false }); + }); +}); + +describe('encounters', () => { + async function scene(prefix) { + const ctx = await setupCampaign(prefix); + const c = `/campaigns/${ctx.campaign.id}`; + const heroId = await buildCharacter(ctx.campaign.id, ctx.playerAuth, 'Aria'); + const allyId = await buildCharacter(ctx.campaign.id, ctx.dmAuth, 'Bo'); + return { ...ctx, c, heroId, allyId }; + } + + itIfDb('have a mode, a public description and DM-only notes', async () => { + const { dmAuth, playerAuth, c } = await scene('encmode'); + const quest = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'The Missing Miller', mode: 'QUEST', description: 'Find the miller.' })).body.encounter; + expect(quest.mode).toBe('QUEST'); + const battle = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Ambush' })).body.encounter; + expect(battle.mode).toBe('BATTLE'); + + const e = `/encounters/${quest.id}`; + expect((await request(app).patch(e).set(playerAuth).send({ mode: 'BATTLE' })).status).toBe(403); + const patched = await request(app).patch(e).set(dmAuth).send({ dmNotes: 'The miller is the werewolf.' }); + expect(patched.body.encounter.dmNotes).toBe('The miller is the werewolf.'); + + const playerView = (await request(app).get(e).set(playerAuth)).body.encounter; + expect(playerView.description).toBe('Find the miller.'); + expect(playerView.dmNotes).toBeUndefined(); + const playerList = (await request(app).get(`${c}/encounters`).set(playerAuth)).body.encounters; + expect(playerList.map((x) => [x.name, x.mode]).sort()).toEqual([['Ambush', 'BATTLE'], ['The Missing Miller', 'QUEST']]); + expect(playerList.every((x) => x.dmNotes === undefined)).toBe(true); + const dmList = (await request(app).get(`${c}/encounters`).set(dmAuth)).body.encounters; + expect(dmList.find((x) => x.id === quest.id).dmNotes).toBe('The miller is the werewolf.'); + }); + + itIfDb('NPCs are DM-managed and join encounters without leaking the DM\'s notes or stats', async () => { + const { dmAuth, playerAuth, c } = await scene('npcs'); + const other = await setupCampaign('npcs-other'); + + expect((await request(app).post(`${c}/npcs`).set(playerAuth).send({ name: 'Nope' })).status).toBe(403); + expect((await request(app).get(`${c}/npcs`).set(playerAuth)).status).toBe(403); + const mayor = ( + await request(app) + .post(`${c}/npcs`) + .set(dmAuth) + .send({ name: 'Mayor Orla', role: 'Mayor', disposition: 'FRIENDLY', description: 'Tired but kind.', dmNotes: 'Secretly bankrupt.', ac: 11, maxHp: 9 }) + ).body.npc; + const hermit = (await request(app).post(`${c}/npcs`).set(dmAuth).send({ name: 'Old Hermit' })).body.npc; + expect(hermit.disposition).toBe('NEUTRAL'); + expect((await request(app).get(`${c}/npcs`).set(dmAuth)).body.npcs.map((n) => n.name)).toEqual(['Mayor Orla', 'Old Hermit']); + expect((await request(app).patch(`${c}/npcs/${mayor.id}`).set(dmAuth).send({ disposition: 'HOSTILE' })).body.npc.disposition).toBe('HOSTILE'); + // Another campaign's DM can't reach it. + expect((await request(app).patch(`/campaigns/${other.campaign.id}/npcs/${mayor.id}`).set(other.dmAuth).send({ name: 'Hacked' })).status).toBe(404); + + const encounterId = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Town Hall', mode: 'QUEST' })).body.encounter.id; + const e = `/encounters/${encounterId}`; + expect((await request(app).post(`${e}/participants`).set(dmAuth).send({ npcId: mayor.id })).status).toBe(201); + expect((await request(app).post(`${e}/participants`).set(dmAuth).send({ npcId: hermit.id })).status).toBe(201); + expect((await request(app).post(`${e}/participants`).set(dmAuth).send({ npcId: mayor.id, monsterId: 'x' })).status).toBe(400); + + const byName = (encounter) => Object.fromEntries(encounter.participants.map((p) => [p.displayName, p])); + const dmView = byName((await request(app).get(e).set(dmAuth)).body.encounter); + expect(dmView['Mayor Orla']).toMatchObject({ kind: 'NPC', currentHp: 9, maxHp: 9 }); + expect(dmView['Mayor Orla'].npc).toMatchObject({ role: 'Mayor', disposition: 'HOSTILE', dmNotes: 'Secretly bankrupt.', ac: 11 }); + expect(dmView['Old Hermit']).toMatchObject({ kind: 'NPC', maxHp: 0 }); // no combat stats + + const playerView = byName((await request(app).get(e).set(playerAuth)).body.encounter); + expect(playerView['Mayor Orla'].npc).toEqual({ id: mayor.id, name: 'Mayor Orla', role: 'Mayor', disposition: 'HOSTILE', description: 'Tired but kind.' }); + + // Deleting an NPC takes it out of the scenes it was in. + expect((await request(app).delete(`${c}/npcs/${hermit.id}`).set(dmAuth)).status).toBe(204); + expect(Object.keys(byName((await request(app).get(e).set(dmAuth)).body.encounter))).toEqual(['Mayor Orla']); + }); + + itIfDb('show the DM full monster stat blocks and everyone a character\'s headline numbers', async () => { + const { dmAuth, playerAuth, c, heroId } = await scene('encdetail'); + const goblin = (await request(app).post(`${c}/monsters/from-library`).set(dmAuth).send({ key: 'goblin' })).body.monster; + const encounterId = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Cave' })).body.encounter.id; + const e = `/encounters/${encounterId}`; + await request(app).post(`${e}/participants`).set(dmAuth).send({ monsterId: goblin.id, initiative: 5 }); + await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: heroId, initiative: 15 }); + + const [hero, monster] = (await request(app).get(e).set(dmAuth)).body.encounter.participants; + expect(hero.kind).toBe('CHARACTER'); + expect(hero.characterCombatInfo).toMatchObject({ level: 1 }); + for (const key of ['armorClass', 'speed', 'initiativeBonus', 'passivePerception', 'proficiencyBonus', 'tempHp']) { + expect(typeof hero.characterCombatInfo[key]).toBe('number'); + } + expect(Object.keys(hero.characterCombatInfo.abilities)).toEqual(['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA']); + expect(monster.kind).toBe('MONSTER'); + expect(monster.monster).toMatchObject({ ac: goblin.ac, attackBonus: goblin.attackBonus, damageDice: goblin.damageDice }); + + const playerMonster = (await request(app).get(e).set(playerAuth)).body.encounter.participants[1]; + expect(playerMonster.monster).toEqual({ id: goblin.id, name: goblin.name }); + }); + + itIfDb('track whose turn it is down the initiative order and roll the round over', async () => { + const { dmAuth, playerAuth, c, heroId, allyId } = await scene('turns'); + const goblin = (await request(app).post(`${c}/monsters/from-library`).set(dmAuth).send({ key: 'goblin' })).body.monster; + const encounterId = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Bridge' })).body.encounter.id; + const e = `/encounters/${encounterId}`; + expect((await request(app).post(`${e}/next-turn`).set(dmAuth)).status).toBe(400); // nobody to take a turn + + const add = async (body) => (await request(app).post(`${e}/participants`).set(dmAuth).send(body)).body.participant.id; + const slow = await add({ monsterId: goblin.id, initiative: 3 }); + const fast = await add({ characterId: heroId, initiative: 18 }); + const mid = await add({ characterId: allyId, initiative: 10 }); + + const state = (res) => [res.body.encounter.activeParticipantId, res.body.encounter.currentRound, res.body.encounter.status]; + expect((await request(app).post(`${e}/next-turn`).set(playerAuth)).status).toBe(403); + + // Beginning the battle puts the highest initiative on turn. + expect(state(await request(app).patch(e).set(dmAuth).send({ status: 'ACTIVE' }))).toEqual([fast, 1, 'ACTIVE']); + expect(state(await request(app).post(`${e}/next-turn`).set(dmAuth))).toEqual([mid, 1, 'ACTIVE']); + + // Removing whoever is on turn passes it on. + const removed = await request(app).delete(`${e}/participants/${mid}`).set(dmAuth); + expect(removed.body.encounter.activeParticipantId).toBe(slow); + + // Past the end of the order: back to the top, next round. + expect(state(await request(app).post(`${e}/next-turn`).set(dmAuth))).toEqual([fast, 2, 'ACTIVE']); + expect((await request(app).get(e).set(playerAuth)).body.encounter.participants.map((p) => p.id)).toEqual([fast, slow]); + }); + + itIfDb('rewards stay secret until awarded, then land on the character exactly once', async () => { + const { dmAuth, playerAuth, c, heroId, allyId } = await scene('rewards'); + const other = await setupCampaign('rewards-other'); + const sword = (await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Flame Tongue', damageDice: '1d8', damageType: 'fire', attackAbility: 'STR', minLevel: 2 })).body.weapon; + const potion = (await request(app).post(`${c}/items`).set(dmAuth).send({ name: 'Healing Potion', damageDice: '2d4+2' })).body.item; + const foreign = (await request(app).post(`/campaigns/${other.campaign.id}/items`).set(other.dmAuth).send({ name: 'Foreign' })).body.item; + + const encounterId = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Dragon Hoard' })).body.encounter.id; + const e = `/encounters/${encounterId}`; + await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: heroId, initiative: 12 }); + await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: allyId, initiative: 8 }); + + const add = (body, auth = dmAuth) => request(app).post(`${e}/rewards`).set(auth).send(body); + expect((await add({ type: 'GOLD', gold: 5 }, playerAuth)).status).toBe(403); + expect((await add({ type: 'GOLD', gold: 0 })).status).toBe(400); + expect((await add({ type: 'ITEM', itemId: foreign.id })).status).toBe(400); + expect((await add({ type: 'WEAPON', weaponId: sword.id, level: 1 })).status).toBe(400); // below its starting level + const gold = (await add({ type: 'GOLD', gold: 101, note: 'The hoard' })).body.reward; + const purse = (await add({ type: 'GOLD', gold: 10 })).body.reward; + const blade = (await add({ type: 'WEAPON', weaponId: sword.id })).body.reward; + const potions = (await add({ type: 'ITEM', itemId: potion.id, quantity: 3, level: 2 })).body.reward; + const junk = (await add({ type: 'GOLD', gold: 1 })).body.reward; + expect(blade.level).toBe(2); + + // Unawarded loot is the DM's secret. + expect((await request(app).get(e).set(dmAuth)).body.encounter.rewards).toHaveLength(5); + expect((await request(app).get(e).set(playerAuth)).body.encounter.rewards).toEqual([]); + expect((await request(app).delete(`${e}/rewards/${junk.id}`).set(dmAuth)).status).toBe(200); + + const award = (rewardId, body, auth = dmAuth) => request(app).post(`${e}/rewards/${rewardId}/award`).set(auth).send(body); + expect((await award(gold.id, { split: true }, playerAuth)).status).toBe(403); + expect((await award(blade.id, { split: true })).status).toBe(400); // only gold splits + + // 101 gold between two: 51 to the higher initiative, 50 to the other. + expect((await award(gold.id, { split: true })).status).toBe(200); + expect((await award(gold.id, { characterId: heroId })).status).toBe(400); // already awarded + expect((await award(purse.id, { characterId: allyId })).status).toBe(200); + expect((await award(blade.id, { characterId: heroId })).status).toBe(200); + expect((await award(potions.id, { characterId: heroId })).status).toBe(200); + + const hero = (await request(app).get(`/characters/${heroId}`).set(playerAuth)).body.character; + expect(hero.gold).toBe(51); + expect(hero.weapons.map((w) => [w.weapon.name, w.level, w.quantity])).toEqual([['Flame Tongue', 2, 1]]); + expect(hero.inventoryItems.map((i) => [i.item.name, i.level, i.quantity, i.scaledDamageDice])).toEqual([['Healing Potion', 2, 3, '1d6+1d8']]); + const heroLedger = (await request(app).get(`/characters/${heroId}/gold`).set(playerAuth)).body.transactions; + expect(heroLedger.map((t) => [t.amount, t.reason, t.createdBy.displayName])).toEqual([[51, 'Reward: Dragon Hoard', 'DM']]); + expect((await request(app).get(`/characters/${allyId}`).set(dmAuth)).body.character.gold).toBe(60); + + // Players now see what was handed out, and to whom. + const seen = (await request(app).get(e).set(playerAuth)).body.encounter.rewards; + expect(seen.map((r) => [r.type, r.awardedTo]).sort()).toEqual([ + ['GOLD', 'Aria, Bo'], + ['GOLD', 'Bo'], + ['ITEM', 'Aria'], + ['WEAPON', 'Aria'], + ]); + }); +}); + describe('dice mode', () => { itIfDb('rejects an out-of-range physical roll and accepts a valid one, matching the digital shape', async () => { const { dmAuth, campaign } = await setupCampaign('dicemode'); @@ -250,6 +1082,221 @@ describe('dice mode', () => { // Dice mode can no longer change once rolling has started. const lateSwitch = await request(app).patch(`/characters/${characterId}/build/dice-mode`).set(dmAuth).send({ diceMode: 'DIGITAL' }); expect(lateSwitch.status).toBe(400); + + // Physical ability scores: six sets of four d6, lowest die dropped. + await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({ species: validRoll.body.buildState.speciesChoices.options[0] }); + await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth).send({ value: 1 }); + await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({ characterClass: 'FIGHTER' }); + const sets = [[6, 6, 5, 1], [5, 5, 4, 2], [4, 4, 4, 1], [3, 3, 4, 2], [6, 2, 2, 1], [5, 4, 3, 3]]; + const badSets = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth).send({ abilitySets: [[7, 1, 1, 1], ...sets.slice(1)] }); + expect(badSets.status).toBe(400); + const abilityRoll = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth).send({ abilitySets: sets }); + expect(abilityRoll.status).toBe(200); + expect(abilityRoll.body.buildState.abilityRolls.map((r) => r.total)).toEqual([17, 14, 12, 10, 10, 12]); + expect(abilityRoll.body.buildState.abilityRolls[0]).toEqual({ dice: [6, 6, 5, 1], dropped: 1, total: 17 }); + }); +}); + +describe('story steps: special abilities, background and appearance', () => { + itIfDb('are picked from fixed lists, composed by the server, and then only the DM can edit them', async () => { + const { dmAuth, playerAuth, campaign } = await setupCampaign('story'); // skipMotivationRoll: true + const optionsRes = await request(app).get('/characters/build/options').set(playerAuth); + expect(optionsRes.status).toBe(200); + const options = optionsRes.body; + expect(options.motivations).toHaveLength(6); + expect(options.talentPicks).toBe(2); + expect(options.background.map((g) => g.key)).toEqual(['upbringing', 'home', 'turningPoint', 'personality', 'flaw']); + expect(options.appearance.map((g) => g.key)).toEqual(['build', 'height', 'hair', 'eyes', 'complexion', 'features', 'style']); + expect(Object.keys(options.speciesTraits)).toHaveLength(10); + expect(Object.keys(options.classFeatures)).toHaveLength(12); + + const id = (await request(app).post(`/campaigns/${campaign.id}/characters`).set(playerAuth).send({ name: 'Storied' })).body.character.id; + const b = `/characters/${id}/build`; + const post = (path, body) => request(app).post(`${b}/${path}`).set(playerAuth).send(body); + await request(app).patch(`${b}/dice-mode`).set(playerAuth).send({ diceMode: 'PHYSICAL' }); + await post('roll', { value: 3 }); + await post('choose', { species: 'DWARF' }); + await post('roll', { value: 1 }); + await post('choose', { characterClass: 'BARBARIAN' }); + await post('roll', { abilitySets: [[6, 6, 5, 1], [5, 5, 4, 2], [4, 4, 4, 1], [3, 3, 4, 2], [6, 2, 2, 1], [5, 4, 3, 3]] }); + await post('choose', { assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); + expect((await post('choose', {})).body.buildStage).toBe('CHOOSING_ABILITIES'); + + // Talents: exactly two, different, from the list. + for (const talents of [[], ['ALERT'], ['ALERT', 'ALERT'], ['ALERT', 'FLIGHT'], ['ALERT', 'KEEN_EYE', 'LINGUIST']]) { + expect((await post('choose', { talents })).status).toBe(400); + } + expect((await post('choose', { talents: ['ALERT', 'KEEN_EYE'] })).body.buildStage).toBe('CHOOSING_BACKGROUND'); + + // Background: one per group (one or two personality traits), nothing invented. + const bg = STORY_PICKS.background; + expect((await post('choose', { picks: { ...bg, upbringing: [] } })).status).toBe(400); + expect((await post('choose', { picks: { ...bg, upbringing: ['SOLDIER', 'NOBLE'] } })).status).toBe(400); + expect((await post('choose', { picks: { ...bg, upbringing: ['EMPEROR'] } })).status).toBe(400); + expect((await post('choose', { picks: { ...bg, personality: ['BRAVE', 'KIND', 'LOYAL'] } })).status).toBe(400); + const bgRes = await post('choose', { picks: { ...bg, smuggled: ['free text'] } }); + expect(bgRes.body.buildStage).toBe('CHOOSING_APPEARANCE'); + expect(bgRes.body.buildState.backgroundPicks).toEqual(bg); // unknown groups are dropped + + // Appearance: distinguishing features are optional. + expect((await post('choose', { picks: { ...STORY_PICKS.appearance, hair: [] } })).status).toBe(400); + expect((await post('choose', { picks: { ...STORY_PICKS.appearance, features: [] } })).body.buildStage).toBe('CHOOSING_EQUIPMENT'); + + await post('choose', { weaponIds: [], itemIds: [], spellIds: [] }); + const character = (await post('finalize')).body.character; + + // Species traits, then class features, then the picked talents — one per line. + expect(character.specialAbilities.split('\n').map((line) => line.split(' — ')[0])).toEqual([ + 'Darkvision', + 'Dwarven Resilience', + 'Rage', + 'Unarmored Defense', + 'Alert', + 'Keen Eye', + ]); + expect(character.background.split('\n')).toEqual([ + 'Upbringing: Soldier — Served in an army or militia, and still thinks in terms of orders and watches.', + 'Home: A small village — Everyone knew everyone, and nothing stayed secret.', + 'Turning point: Was betrayed — By someone they trusted completely.', + 'Personality: Brave, Curious', + 'Flaw: Greedy — Cannot walk past treasure.', + ]); + expect(character.appearance.split('\n')).toEqual([ + 'Build: Muscular', + 'Height: Tall', + 'Hair: Red', + 'Eyes: Green', + 'Skin: Weathered', + 'Usually wears: A hooded cloak', + ]); + + // Locked for the player; the DM can still rewrite them as the story moves on. + const sheet = `/characters/${id}`; + expect((await request(app).patch(sheet).set(playerAuth).send({ specialAbilities: 'Flight' })).status).toBe(403); + const dmEdit = await request(app).patch(sheet).set(dmAuth).send({ specialAbilities: `${character.specialAbilities}\nReckless Attack — Gained at level 2.` }); + expect(dmEdit.status).toBe(200); + expect(dmEdit.body.character.specialAbilities).toContain('Reckless Attack'); + }); +}); + +describe('going back in the builder', () => { + itIfDb('returns to earlier steps with the same rolls, lets the choice change, and never re-rolls', async () => { + const { dmAuth, playerAuth, campaign } = await setupCampaign('back'); + await request(app).patch(`/campaigns/${campaign.id}`).set(dmAuth).send({ skipMotivationRoll: false }); + const id = (await request(app).post(`/campaigns/${campaign.id}/characters`).set(playerAuth).send({ name: 'Undecided' })).body.character.id; + const b = `/characters/${id}/build`; + const post = (path, body, auth = playerAuth) => request(app).post(`${b}/${path}`).set(auth).send(body); + const stage = (res) => res.body.buildStage; + + expect((await post('back')).status).toBe(400); // nothing before the first step + await request(app).patch(`${b}/dice-mode`).set(playerAuth).send({ diceMode: 'PHYSICAL' }); + + // Species: a 3 offers Dwarf or Halfling. + await post('roll', { value: 3 }); + expect((await post('roll', { value: 6 })).status).toBe(400); // one roll only + expect(stage(await post('choose', { species: 'DWARF' }))).toBe('ROLLING_CLASS'); + + // Back before rolling for class: same species roll, and the pick can change. + const backToSpecies = await post('back'); + expect(stage(backToSpecies)).toBe('ROLLING_SPECIES'); + expect(backToSpecies.body.buildState).toMatchObject({ speciesRoll: 3, species: 'DWARF' }); + expect((await post('roll', { value: 6 })).status).toBe(400); // still no re-roll + expect((await post('choose', { species: 'ELF' })).status).toBe(400); // not offered by the roll + await post('choose', { species: 'HALFLING' }); + + // Class: a 4 offers Cleric or Paladin. + await post('roll', { value: 4 }); + await post('choose', { characterClass: 'CLERIC' }); + // Motivation is picked from the list, not rolled. + expect((await post('roll', { value: 2 })).status).toBe(400); + expect((await post('choose', {})).status).toBe(400); + expect((await post('choose', { motivation: 7 })).status).toBe(400); + const motivated = await post('choose', { motivation: 2 }); + expect(stage(motivated)).toBe('ASSIGNING_SCORES'); + expect(motivated.body.buildState).toMatchObject({ motivationChoice: 2, motivationText: 'Seeking fortune or wealth' }); + + await post('roll', { abilitySets: [[6, 6, 5, 1], [5, 5, 4, 2], [4, 4, 4, 1], [3, 3, 4, 2], [6, 2, 2, 1], [5, 4, 3, 3]] }); + const assigned = await post('choose', { assignments: { STR: 3, DEX: 2, CON: 1, INT: 4, WIS: 0, CHA: 5 } }); + expect(stage(assigned)).toBe('ASSIGNING_PROFICIENCIES'); + const clericSkills = assigned.body.buildState.skillProficiencies; + + // Back to the scores and forward again: same rolls, same skills, new assignment. + const backToScores = await post('back'); + expect(stage(backToScores)).toBe('ASSIGNING_SCORES'); + expect(backToScores.body.buildState.abilityRolls.map((r) => r.total)).toEqual([17, 14, 12, 10, 10, 12]); + expect((await post('roll', {})).status).toBe(400); + const reassigned = await post('choose', { assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); + expect(reassigned.body.buildState.skillProficiencies).toEqual(clericSkills); + + // All the way back to class (through motivation), switch to Paladin and return. + expect(stage(await post('back'))).toBe('ASSIGNING_SCORES'); + expect(stage(await post('back'))).toBe('ROLLING_MOTIVATION'); + const backToClass = await post('back'); + expect(stage(backToClass)).toBe('ROLLING_CLASS'); + expect(backToClass.body.buildState).toMatchObject({ classRoll: 4, characterClass: 'CLERIC' }); + expect((await post('roll', { value: 8 })).status).toBe(400); + await post('choose', { characterClass: 'PALADIN' }); + await post('choose', { motivation: 5 }); // the motivation can change on the way back through + const asPaladin = await post('choose', { assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); + const paladinOptions = ['ATHLETICS', 'INSIGHT', 'INTIMIDATION', 'MEDICINE', 'PERSUASION', 'RELIGION']; + expect(asPaladin.body.buildState.skillProficiencies.every((s) => paladinOptions.includes(s.skill))).toBe(true); + + // Switching back to Cleric brings back the Cleric's original skills, not a fresh draw. + await post('back'); + await post('back'); + await post('back'); + await post('choose', { characterClass: 'CLERIC' }); + await post('choose', { motivation: 5 }); + const asClericAgain = await post('choose', { assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); + expect(asClericAgain.body.buildState.skillProficiencies).toEqual(clericSkills); + + // Equipment: back from the finalize prompt reopens the selection. + await post('choose', {}); + await storySteps(id, playerAuth); + await post('choose', { weaponIds: [], itemIds: [], spellIds: [] }); + const reopened = await post('back'); + expect(stage(reopened)).toBe('CHOOSING_EQUIPMENT'); + expect(reopened.body.buildState.equipment).toBeUndefined(); + expect((await post('finalize')).status).toBe(400); // equipment must be confirmed again + // Back through the story steps: each keeps what was picked. + const backToAppearance = await post('back'); + expect(stage(backToAppearance)).toBe('CHOOSING_APPEARANCE'); + expect(backToAppearance.body.buildState.appearancePicks).toEqual(STORY_PICKS.appearance); + expect(stage(await post('back'))).toBe('CHOOSING_BACKGROUND'); + expect(stage(await post('back'))).toBe('CHOOSING_ABILITIES'); + await storySteps(id, playerAuth); + await post('choose', { weaponIds: [], itemIds: [], spellIds: [] }); + + // Only the owner or DM can step a build back, and not once it is finished. + const stranger = await request(app).post('/auth/register').send({ email: uniqueEmail('back-other'), password: 'password123', displayName: 'Other' }); + cleanupUserIds.push(stranger.body.user.id); + const strangerAuth = { Authorization: `Bearer ${stranger.body.token}` }; + await request(app).post(`/campaigns/join/${campaign.inviteCode}`).set(strangerAuth); + expect((await post('back', undefined, strangerAuth)).status).toBe(403); + + const finalized = await post('finalize'); + expect(finalized.body.character).toMatchObject({ + species: 'HALFLING', + characterClass: 'CLERIC', + buildStage: 'COMPLETE', + motivation: 'Driven by curiosity or knowledge', + }); + expect(finalized.body.character.rolledScores).toEqual({ STR: 17, DEX: 14, CON: 12, INT: 10, WIS: 10, CHA: 12 }); + expect((await post('back')).status).toBe(400); + }); + + itIfDb('skips the motivation step on the way back when the campaign skips it', async () => { + const { playerAuth, campaign } = await setupCampaign('backskip'); // skipMotivationRoll: true + const id = await buildCharacter(campaign.id, playerAuth, 'Brisk', { stopBeforeEquipment: true }); + const back = () => request(app).post(`/characters/${id}/build/back`).set(playerAuth); + expect((await back()).body.buildStage).toBe('CHOOSING_APPEARANCE'); + expect((await back()).body.buildStage).toBe('CHOOSING_BACKGROUND'); + expect((await back()).body.buildStage).toBe('CHOOSING_ABILITIES'); + expect((await back()).body.buildStage).toBe('ASSIGNING_PROFICIENCIES'); + expect((await back()).body.buildStage).toBe('ASSIGNING_SCORES'); + expect((await back()).body.buildStage).toBe('ROLLING_CLASS'); + expect((await back()).body.buildStage).toBe('ROLLING_SPECIES'); + expect((await back()).status).toBe(400); }); }); @@ -309,10 +1356,16 @@ describe('locations', () => { .post(`/campaigns/${campaign.id}/characters`) .set(playerAuth) .send({ name: 'Wanderer' }); - const patchRes = await request(app) + const playerPatchRes = await request(app) .patch(`/characters/${charRes.body.character.id}`) .set(playerAuth) .send({ currentLocationId: locationId }); + expect(playerPatchRes.status).toBe(403); + + const patchRes = await request(app) + .patch(`/characters/${charRes.body.character.id}`) + .set(dmAuth) + .send({ currentLocationId: locationId }); expect(patchRes.status).toBe(200); expect(patchRes.body.character.currentLocationId).toBe(locationId); }); @@ -336,6 +1389,21 @@ describe('default content library', () => { expect(addRes.body.weapon.name).toBe('Longsword'); expect(addRes.body.weapon.campaignId).toBe(campaign.id); + // Library spells show their level and default damage before they are added, + // and carry both into the campaign. + const byKey = Object.fromEntries(listRes.body.spells.map((s) => [s.key, s])); + expect(byKey.fireball).toMatchObject({ level: 3, damageDice: '8d6' }); + expect(byKey['fire-bolt']).toMatchObject({ level: 0, damageDice: '1d10' }); + expect(byKey['cure-wounds'].damageDice).toBeUndefined(); // healing, not damage + expect(listRes.body.spells.filter((s) => s.damageDice).length).toBeGreaterThan(30); + const spellRes = await request(app).post(`/campaigns/${campaign.id}/spells/from-library`).set(dmAuth).send({ key: 'fireball' }); + expect(spellRes.body.spell).toMatchObject({ name: 'Fireball', level: 3, damageDice: '8d6', isStartingOption: false }); + + // Monster stat blocks are the DM's. + await request(app).post(`/campaigns/${campaign.id}/monsters/from-library`).set(dmAuth).send({ key: 'goblin' }); + expect((await request(app).get(`/campaigns/${campaign.id}/monsters`).set(dmAuth)).body.monsters).toHaveLength(1); + expect((await request(app).get(`/campaigns/${campaign.id}/monsters`).set(playerAuth)).status).toBe(403); + const playerAddRes = await request(app) .post(`/campaigns/${campaign.id}/monsters/from-library`) .set(playerAuth) @@ -434,6 +1502,7 @@ describe('encounter combat info', () => { .set(dmAuth) .send({ assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({}); + await storySteps(characterId, dmAuth); await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({ weaponIds: [], spellIds: [] }); await request(app).post(`/characters/${characterId}/build/finalize`).set(dmAuth); diff --git a/backend/src/routes/campaigns.routes.js b/backend/src/routes/campaigns.routes.js index 579826b..ba66e3c 100644 --- a/backend/src/routes/campaigns.routes.js +++ b/backend/src/routes/campaigns.routes.js @@ -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); diff --git a/backend/src/routes/characters.routes.js b/backend/src/routes/characters.routes.js index 08dcf1b..82202e4 100644 --- a/backend/src/routes/characters.routes.js +++ b/backend/src/routes/characters.routes.js @@ -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); } diff --git a/backend/src/routes/encounters.routes.js b/backend/src/routes/encounters.routes.js index 64ecfec..f008c0a 100644 --- a/backend/src/routes/encounters.routes.js +++ b/backend/src/routes/encounters.routes.js @@ -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); } diff --git a/backend/src/utils/grants.js b/backend/src/utils/grants.js new file mode 100644 index 0000000..cf00f0d --- /dev/null +++ b/backend/src/utils/grants.js @@ -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 }; diff --git a/docs/Aldenfell - Full Campaign Book.docx b/docs/Aldenfell - Full Campaign Book.docx deleted file mode 100644 index 72556c85b4358051280ace6624498baf25d57ea9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 79809 zcmeEsQ?oEU(B!dg+qRx#+qP}nwr$(CZQHhueZRZi+MlqSi`-;VmCQ`1r!p-s1q^}$ z00sa7002M;0BK1M>j?+|Py+@4fD8Zuq$Ol$>uh4{tf%Z@Z{nmw=Wb(7PzVAu(KVqdZbQm*E-`$NN`VWSb4$QD>EUI? zy!8nIS#c}9iL}sfpL>!N1CjY`K(WMr0HWAP-JbrqOdX&P7v{Fz8EwEYG6ftvE;k>c z3MuJ~wx?DCC^>;N&c!Gth55jzqJ+QlsYQiPagmIW_@tMdt|g9rx&M73xbo49zsRd- z0i=c?BhtTaP#%4+J-^-2(L_8WrjC}0Z2S8I29Wy~T3Kiuoy(xA>Ad6?yL5PFj=RsrazO!5|ooc zQ5vX`b68*r@8Rh){m3U&!mlS~&=y3LbIV2~O+~p5Dr;})zRdX`?55%gc)rrJoFzh{xBn0#z^gc{9y2X@%mIs#As5!e5Xk79cna=R}80DlB90L1^C z;%4V)OmA#wRrwQYcQ-IP*M~HgTCP z^!pPH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T*r#bk`tdj(p43al)gKT&2uDk}{Nj zHO+m_h(~N*E}y4OuAn?dBO$$Qj&u2|!U*9dJ^CLJ!--Upu(Oq4+=vBJrrsm5-LIQaqF|3&*TK=X zkQq7?mel%!EPBCCl4-=#^B3aN`>(AT` zXftwnHz0G%feK92e_f=%?KK2}4}M_!hK{1EjiJ5PZ&a3*{HFtg7@Wp)AVeBSeV{=9 zZ(A)eS>#_?AirmR{0hvoks`N#0swrFAbwZe{DqtW{+8bdHvXPH@+@Jg6J;J>P2 ze|7Pzctg;{I7#jf8keg|2+J^hp2u9|Jnlh z3tUF^2l$uvz^@*Dt+D>)frsV~5C5pY{)+!+-QzDb08mE<0{D-b$gl8!#{R#" entry to the character's + money log. Gold can also be **split** evenly between the characters in the + encounter; any remainder goes one gold each down the initiative order. +- Awarding a weapon or item adds it to what the character holds, at the + reward's level. A character below that level holds it but cannot use it yet + (section 10). +- A reward can go to any character in the campaign, not only those in the + encounter. +- Removing a reward from the list does not take back anything already awarded. + +## 16. Copying to another campaign + +A complete character can be copied into another campaign from the "Copy to +Another Campaign" card on its sheet. + +- **Who:** the owner, or the DM of the character's campaign. You must already + be a member of the target campaign. +- **Copied:** name, species, class, level, XP, ability scores, skill and save + proficiencies, armor bonus, speed override, special abilities, gold (as a + single opening entry in the copy's money log), background, appearance, + motivation, inventory, weapons and spells, with each weapon's and item's + level. +- **Not copied:** location, character notes and encounter entries. +- The copy arrives at **full HP** with no temp HP. +- The copy is **owned by whoever made it**. If a DM copies a player's + character, the DM owns the copy and the player's private notes are not + carried over. +- **Weapons, spells and items** are matched to the target campaign's pools by + name (ignoring case). Any that are missing are added to the target's pool, + never as starting options. +- The copy is independent: the original is untouched and the two never sync. + +## 17. Permissions + +| Action | Owner | DM of the campaign | Other members | +|---|---|---|---| +| View the sheet and quick stats | Yes | Yes | Yes | +| View private notes | Yes | No | No | +| Run the builder | Yes | Yes | No | +| Change HP, temp HP, armor bonus | Yes | Yes | No | +| Edit special abilities, background, appearance (after the build) | No | Yes | No | +| Tick Equipped / Prepared | Yes | Yes | No | +| Give, remove or re-count weapons, spells and items | No | Yes | No | +| Level a weapon or item up or down | No | Yes | No | +| Record a gold gain or spend | Yes | Yes | No | +| Give gold, weapons, items or spells to another character | Yes | Yes | No | +| View the money log | Yes | Yes | Yes | +| Change level, XP, location or speed override | No | Yes | No | +| Post a character note | Yes | Yes | Yes | +| Copy to another campaign | Yes | Yes | No | +| Delete the character | No | Yes | No | + +People outside the campaign cannot see a character at all. + +## 18. Deleting + +- Only the DM can delete a character (from the campaign page). +- Deleting removes its proficiencies, inventory, weapon and spell assignments, + money log and notes. Encounter entries that pointed at it stay in the + encounter, with the name and the last HP seen, but lose everything else. +- Deleting a **campaign** deletes every character in it. + +## 19. What is not modelled + +Use special abilities (via the DM), items or notes for these; the app does no +calculations for them. + +- The effects of special abilities: species traits and class features are + written on the sheet for the DM to apply, but nothing is calculated from them +- Class features beyond level 1 (the DM adds them to the sheet by hand), + subclasses and multiclassing +- Spell slots, spell preparation limits and concentration +- Ability score increases and feats on level-up +- Armor and shields as items (only the single armor bonus number) +- Weapon proficiency (everyone is proficient with everything) +- Rolling attacks, damage, saves or checks for a character (the dice roller, + bottom left of every page, is a plain roller that knows nothing about the + sheet) +- Death saves, conditions on the sheet, and resting +- Automatic levelling from XP +- Alignment, languages, tool proficiencies and backgrounds-as-rules +- Encumbrance and item weight +- Currencies other than gold, and item prices + +## 20. Everything the builder offers + +Every motivation, special ability, talent, background answer and appearance +answer a player can end up with. + +This list is written from the app's own data by `npm run docs:lists` (in `/backend`). Re-run it after changing the data; do not edit the list by hand. + + +### Motivations + +- Revenge for a past wrong +- Seeking fortune or wealth +- Protecting someone they love +- Redemption for a past mistake +- Driven by curiosity or knowledge +- Duty or oath to a cause or order + +### Special abilities granted by species + +| Species | Abilities | +|---|---| +| Human | **Versatile** — Once per day, reroll one skill check you just failed and keep the new result. | +| Half-Elf | **Darkvision** — See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.
**Fey Ancestry** — Advantage on saves against being charmed, and magic cannot put you to sleep. | +| Elf | **Darkvision** — See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.
**Fey Ancestry** — Advantage on saves against being charmed, and magic cannot put you to sleep.
**Trance** — You do not sleep. Four hours of meditation rests you as well as a full night. | +| Gnome | **Darkvision** — See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.
**Gnome Cunning** — Advantage on Intelligence, Wisdom and Charisma saves against magic. | +| Dwarf | **Darkvision** — See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.
**Dwarven Resilience** — Advantage on saves against poison, and poison damage against you is halved. | +| Halfling | **Lucky** — When you roll a 1 on a d20 for an attack, check or save, reroll it and use the new roll.
**Brave** — Advantage on saves against being frightened. | +| Dragonborn | **Breath Weapon** — Once per rest, exhale destructive energy: creatures in a 15-foot cone take 2d6 damage (Dexterity save for half).
**Draconic Resistance** — Damage of your breath weapon’s type against you is halved. | +| Tiefling | **Darkvision** — See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.
**Hellish Resistance** — Fire damage against you is halved. | +| Half-Orc | **Darkvision** — See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.
**Relentless Endurance** — Once per day, when you would drop to 0 hit points, drop to 1 instead. | +| Orc | **Darkvision** — See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.
**Aggressive** — As a bonus action, move up to your speed toward an enemy you can see. | + +### Special abilities granted by class + +| Class | Abilities | +|---|---| +| Barbarian | **Rage** — Twice per day, for one minute: +2 melee damage, advantage on Strength checks and saves, and physical damage against you is halved.
**Unarmored Defense** — Without armor, add your Constitution modifier to your AC (ask your DM to set your armor bonus). | +| Bard | **Bardic Inspiration** — A few times per day, as a bonus action, give an ally a d6 to add to one attack, check or save.
**Jack of Many Tales** — You have heard a story about nearly everything: ask your DM for one useful rumour per session. | +| Cleric | **Divine Domain** — Choose with your DM what your god stands for (life, light, war, knowledge…). It shapes the favours you can ask.
**Healing Hands** — Once per rest, touch a creature to restore 1d8 + your Wisdom modifier hit points. | +| Druid | **Druidic** — You know the secret language of druids and can leave hidden messages in it.
**Nature’s Voice** — You can calm and make simple requests of ordinary animals. | +| Fighter | **Second Wind** — Once per rest, as a bonus action, recover 1d10 + your level hit points.
**Fighting Style** — Choose one with your DM: +2 to ranged attacks, +1 AC in armor, or +2 damage with a one-handed weapon. | +| Monk | **Martial Arts** — Your unarmed strikes deal 1d4 damage and can use Dexterity. After attacking, make one unarmed strike as a bonus action.
**Unarmored Defense** — Without armor, add your Wisdom modifier to your AC (ask your DM to set your armor bonus). | +| Paladin | **Divine Sense** — A few times per day, sense any celestial, fiend or undead within 60 feet.
**Lay on Hands** — A pool of healing equal to 5 × your level per day, spent by touch however you like. | +| Ranger | **Favored Enemy** — Choose a kind of creature with your DM. Advantage on checks to track them and to recall what you know about them.
**Natural Explorer** — In the wild you cannot get lost, you find twice as much food, and difficult terrain does not slow your group. | +| Rogue | **Sneak Attack** — 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.
**Thieves’ Cant** — You know the secret slang and signs of the criminal underworld. | +| Sorcerer | **Innate Magic** — Your magic comes from within: you need no spellbook and no prayers.
**Wild Talent** — Once per day, reroll the damage dice of one spell and keep the better result. | +| Warlock | **Otherworldly Patron** — Choose with your DM who granted your power, and what they want in return.
**Pact Magic** — Your magic returns after a short rest, not only a long one. | +| Wizard | **Spellbook** — Your spells are written in a book. You can copy new spells into it when you find them.
**Arcane Recovery** — Once per day, after a short rest, regain some of your spent magic. | + +### Talents (pick 2) + +| Talent | What it does | +|---|---| +| Alert | You cannot be surprised while you are awake. | +| Keen Eye | Advantage on checks to spot hidden doors, traps and things out of place. | +| Silver Tongue | Once per day, reroll a Persuasion or Deception check and keep the better result. | +| Light Sleeper | You wake at the slightest sound, and keeping watch does not tire you. | +| Iron Stomach | Advantage on saves against spoiled food, strong drink and swallowed poisons. | +| Animal Friend | Ordinary animals are calm around you unless provoked. | +| Quick Hands | Once per turn, draw, stow or pick up an object without using your action. | +| Sure-Footed | Advantage on checks to keep your balance or avoid being knocked down. | +| Linguist | You speak two extra languages of your choice, agreed with your DM. | +| Field Medic | Steadying a dying creature is automatic for you; no roll needed. | +| Strong Back | You can carry, lift and drag twice as much as your size suggests. | +| Good Memory | You recall exactly anything you have seen or heard in the last month. | +| Streetwise | In any town you can find a place to sleep, a rumour, and someone who buys things without asking questions. | +| Tough as Nails | Once per day, shrug off a blow: reduce one instance of damage by 1d6. | + +### Background questions + +**Upbringing** — What were you before you became an adventurer? (pick 1) + +| Option | What it adds | +|---|---| +| Soldier | Served in an army or militia, and still thinks in terms of orders and watches. | +| Acolyte | Raised in a temple, tending shrines and copying scripture. | +| Criminal | Made a living outside the law, and knows who to ask for what. | +| Noble | Born to wealth and a family name that opens doors — and makes enemies. | +| Scholar | Spent years among books, chasing answers to old questions. | +| Farmer | Worked the land from dawn to dusk, and knows the value of a good harvest. | +| Sailor | Grew up on deck, at home with rope, salt and bad weather. | +| Guild artisan | Learned a craft in a workshop and takes pride in good work. | +| Entertainer | Sang, juggled or acted for coin in taverns and market squares. | +| Outlander | Raised far from towns, among hunters, herders or nomads. | +| Urchin | Grew up alone on city streets, surviving on wits and quick feet. | +| Hermit | Lived apart from the world for years, with only thoughts for company. | +| Merchant | Travelled the trade roads buying low and selling high. | +| Village healer | Set bones, brewed remedies and sat with the sick. | + +**Home** — Where did you grow up? (pick 1) + +| Option | What it adds | +|---|---| +| A crowded city | Noise, alleys and a thousand strangers. | +| A small village | Everyone knew everyone, and nothing stayed secret. | +| A harbour town | Ships, gulls and news from far away. | +| A mountain hold | Thin air, stone halls and long winters. | +| Deep in the forest | Under old trees, far from any road. | +| A frontier fort | The last wall before the wild. | +| On the road | Never in one place long enough to call it home. | +| A remote monastery | Bells, silence and routine. | + +**Turning point** — What set you on the road? (pick 1) + +| Option | What it adds | +|---|---| +| Lost someone dear | And have not been the same since. | +| Was betrayed | By someone they trusted completely. | +| Survived a disaster | Fire, flood, plague or war — and walked away when others did not. | +| Found a secret | Something they were never meant to see. | +| Owes a debt | One that cannot be repaid by staying home. | +| Was cast out | Rightly or wrongly, there is no going back. | +| Was saved by a stranger | And means to pass the favour on. | +| Heard a calling | A dream, a sign or a voice that would not let them rest. | +| Could not stand the quiet | An ordinary life was never going to be enough. | + +**Personality** — How do others describe you? Pick one or two. (pick 1 to 2) + +| Option | What it adds | +|---|---| +| Brave | — | +| Cautious | — | +| Curious | — | +| Kind | — | +| Hot-headed | — | +| Sarcastic | — | +| Loyal | — | +| Honest to a fault | — | +| Cheerful | — | +| Quiet | — | +| Proud | — | +| Superstitious | — | +| Generous | — | +| Stubborn | — | + +**Flaw** — What gets you into trouble? (pick 1) + +| Option | What it adds | +|---|---| +| Greedy | Cannot walk past treasure. | +| Reckless | Acts first and thinks later. | +| Holds grudges | Never forgets a slight. | +| Too trusting | Believes a good story. | +| Loses their nerve | When it matters most. | +| Boastful | Promises more than they can deliver. | +| Secretive | Keeps things even from friends. | +| Soft-hearted | Cannot refuse someone in need. | +| Short temper | Easily provoked. | + +### Appearance questions + +**Build** — What shape are you? (pick 1) + +| Option | What it adds | +|---|---| +| Slight | — | +| Lean | — | +| Average | — | +| Stocky | — | +| Muscular | — | +| Heavyset | — | + +**Height** — For your species, are you… (pick 1) + +| Option | What it adds | +|---|---| +| Short | — | +| Average height | — | +| Tall | — | +| Towering | — | + +**Hair** — Hair (or what you have instead). (pick 1) + +| Option | What it adds | +|---|---| +| Black | — | +| Brown | — | +| Blonde | — | +| Red | — | +| Grey | — | +| White | — | +| An unusual colour | — | +| Bald | — | +| None — scales, horns or crest | — | + +**Eyes** — Eye colour. (pick 1) + +| Option | What it adds | +|---|---| +| Brown | — | +| Blue | — | +| Green | — | +| Grey | — | +| Amber | — | +| Black | — | +| Violet | — | +| Mismatched | — | + +**Skin** — Skin or scales. (pick 1) + +| Option | What it adds | +|---|---| +| Pale | — | +| Fair | — | +| Tanned | — | +| Brown | — | +| Dark | — | +| Weathered | — | +| Ashen grey | — | +| Green-tinged | — | +| Deep red | — | +| Scaled | — | + +**Distinguishing features** — What would a stranger remember? Pick up to two, or none. (pick 0 to 2) + +| Option | What it adds | +|---|---| +| A scar across the face | — | +| A tattoo | — | +| Freckles | — | +| A broken nose | — | +| An eyepatch | — | +| A braided beard | — | +| Piercings | — | +| A birthmark | — | +| An old burn | — | +| A missing finger | — | +| A slight limp | — | +| An easy grin | — | + +**Usually wears** — What are you usually seen in? (pick 1) + +| Option | What it adds | +|---|---| +| Travel-worn leathers | — | +| Well-kept armor | — | +| A hooded cloak | — | +| Fine clothes | — | +| Patched and mended clothes | — | +| Long robes | — | +| Furs and hides | — | +| Bright colours | — | +| Plain, practical clothes | — | + diff --git a/docs/ENCOUNTERS.md b/docs/ENCOUNTERS.md new file mode 100644 index 0000000..ff78e36 --- /dev/null +++ b/docs/ENCOUNTERS.md @@ -0,0 +1,215 @@ +# Encounters + +How encounters work in this app: the two kinds of scene, who can be in one, +how a battle is run, and how rewards are handed out. + +This describes the code as it stands. The rules live in +`backend/src/routes/encounters.routes.js`. Related: +[CHARACTERS.md](CHARACTERS.md), [MONSTERS.md](MONSTERS.md), +[NPCS.md](NPCS.md), [WEAPONS.md](WEAPONS.md), [ITEMS.md](ITEMS.md). + +## Contents + +1. [The basics](#1-the-basics) +2. [Battle or quest](#2-battle-or-quest) +3. [Status](#3-status) +4. [The scene and DM notes](#4-the-scene-and-dm-notes) +5. [Who is in the scene](#5-who-is-in-the-scene) +6. [Hit points](#6-hit-points) +7. [Initiative, turns and rounds](#7-initiative-turns-and-rounds) +8. [Conditions](#8-conditions) +9. [Rewards](#9-rewards) +10. [What each side sees](#10-what-each-side-sees) +11. [Permissions](#11-permissions) +12. [What is not modelled](#12-what-is-not-modelled) + +--- + +## 1. The basics + +- An encounter is one **scene** the DM runs: a fight, or a meeting with + people who want something. +- Encounters belong to a campaign and are listed on the campaign page. The DM + creates them; every member can open them. +- The encounter page updates live for everyone who has it open. +- The DM runs everything. Players watch, and see less than the DM does. + +## 2. Battle or quest + +Every encounter has a mode, chosen when it is created and switchable at any +time from the top of the page. + +| | Battle | NPC quest | +|---|---|---| +| For | A fight | A scene built around people and an objective | +| Layout | Everyone in one list, in initiative order | Three groups: "People you meet", "The party", "Creatures" | +| Rounds and turns | Yes | No | +| Initiative | Typed in per combatant | Not shown | +| Start button | Begin Battle | Begin Quest | +| End button | End Battle | Complete Quest | + +Everything else (hit points, conditions, rewards, the scene description, DM +notes) works the same in both. + +## 3. Status + +| Status | Meaning | How to get there | +|---|---|---| +| Planning | Being set up | Every new encounter starts here | +| In progress | Being played | Begin Battle / Begin Quest, or Reopen | +| Complete | Finished | End Battle / Complete Quest | + +Status is a label. Nothing is locked when an encounter is complete: the DM +can still change HP, add people and award rewards. Encounters cannot be +deleted or renamed from the screen. + +## 4. The scene and DM notes + +| Box | For | Who sees it | +|---|---|---| +| The Scene / Quest | Describing the battlefield, or what is being asked of the party | Everyone | +| DM Notes | Tactics, secrets, what happens if the party fails | **DM only** | + +Both save when the DM clicks out of the box. + +## 5. Who is in the scene + +The DM adds people from the "Add to the scene" panel. + +| Kind | Comes from | Can be added more than once | +|---|---|---| +| Character | The campaign's finished characters | No | +| Monster | The campaign's monster list ([MONSTERS.md](MONSTERS.md)) | Yes | +| NPC | The campaign's NPC list ([NPCS.md](NPCS.md)) | No | + +Each has a card. The card's left edge is coloured by kind, and it shows: + +- **Characters:** level, species and class; HP, AC, speed, initiative bonus, + passive perception, proficiency bonus and spell save DC. Under "details": + ability scores, saves, the weapons and spells the character can use (with + attack and damage numbers), and special abilities. The name links to the + character sheet. +- **Monsters:** for the DM, AC, speed, attack and damage, and under "details" + ability scores, trait and notes. +- **NPCs:** role, attitude and description; for the DM also AC, attack, + damage and DM notes. + +Details start open for the DM and closed for players. Weapons and spells +above a character's level are left out, because the character cannot use +them. + +The DM removes someone with "Remove" on their card. Removing whoever is on +turn passes the turn to the next combatant. + +## 6. Hit points + +The DM types an amount and clicks Damage or Heal on a card. + +| Combatant | Where the HP lives | +|---|---| +| Character | On the **character sheet**. The encounter shows the sheet's HP and changes it directly, so the two always agree. Max HP comes from the sheet. | +| Monster | In the encounter, per copy. Starts at the monster's max. | +| NPC | In the encounter. An NPC with no HP set has no health bar. | + +- HP always stays between 0 and max. +- At 0 HP a combatant is marked **Down** and dimmed. It keeps its place in + the order; nothing is removed automatically. +- A character's temporary HP is shown beside its HP but is not used up + automatically. + +## 7. Initiative, turns and rounds + +Battles only. + +- The DM types each combatant's **initiative** when adding them, and can + change it on the card. The app does not roll it. The list is ordered + highest first; ties keep the order they were added in. +- **Begin Battle** puts the first combatant on turn. Their card is + highlighted and the header names them. +- **Next Turn** passes the turn to the next in the order. After the last + combatant it returns to the top and the **round** goes up by one. +- **Next Round** skips straight to the top of the next round. + +## 8. Conditions + +The DM adds a condition to any card from the "+ Condition" list, and removes +one by clicking its ✕. Everyone sees them. + +The list: Blinded, Charmed, Deafened, Frightened, Grappled, Incapacitated, +Invisible, Paralyzed, Petrified, Poisoned, Prone, Restrained, Stunned, +Unconscious, Concentrating. + +Conditions are labels to remind the table. They do not change any numbers, +and they do not expire on their own. + +## 9. Rewards + +The DM lines up loot in the Rewards panel, on any encounter at any time. + +| Reward | What the DM sets | +|---|---| +| Gold | An amount | +| Weapon | A weapon from the pool, a level (not below its starting level), a quantity | +| Item | An item from the pool, a level, a quantity | + +Each can carry a short note ("Goblin chief's purse"). + +**A reward does nothing until it is awarded**, and it can be awarded once. + +| Button | What happens | +|---|---| +| Award (pick a character) | The whole reward goes to that character. It can be any finished character in the campaign, not only those in the encounter. | +| Split (gold only) | Shared evenly between the characters in the encounter. Any remainder goes one gold each, highest initiative first: 101 gold between two is 51 and 50. | + +- **Gold** is added to the character's balance with a money-log entry reading + "Reward: ". +- A **weapon or item** is added to what the character holds, at the reward's + level, stacking with any they already have. If the character is below that + level they hold it but cannot use it yet. +- Removing a reward from the list does **not** take back what was awarded. +- Spells cannot be rewards; the DM grants those on the character sheet. + +Until a reward is awarded only the DM can see it. Afterwards players see what +it was and who received it. + +## 10. What each side sees + +| | DM | Players | +|---|---|---| +| Scene description | Yes | Yes | +| DM notes | Yes | Never | +| Characters | Full card | Full card | +| Monsters | Full stat block | Name, HP, conditions | +| NPCs | Everything | Name, role, attitude, description, HP bar | +| Rewards | All | Only awarded ones | +| Controls (add, damage, turns, rewards) | Yes | None | + +The server only sends a player what the right-hand column lists, so hidden +information cannot be dug out of the page. + +## 11. Permissions + +| Action | DM | Players | +|---|---|---| +| Create an encounter | Yes | No | +| Open an encounter | Yes | Yes | +| Change mode, status, scene or DM notes | Yes | No | +| Add or remove anyone | Yes | No | +| Change HP, initiative or conditions | Yes | No | +| Advance turns and rounds | Yes | No | +| Add, remove or award rewards | Yes | No | + +People outside the campaign cannot open its encounters. + +## 12. What is not modelled + +- Rolling initiative, attacks, damage or saves (use the dice roller, bottom + left of every page) +- Applying an attack's damage automatically +- Death saves and stabilising +- Conditions with durations or mechanical effects +- Maps, positions, distances and areas of effect +- Experience points and encounter difficulty +- Spells as rewards +- Deleting or renaming an encounter from the screen +- A log of what happened during the encounter diff --git a/docs/ITEMS.md b/docs/ITEMS.md new file mode 100644 index 0000000..40ec8ad --- /dev/null +++ b/docs/ITEMS.md @@ -0,0 +1,151 @@ +# Items and Inventory + +How items work in this app: the campaign's item pool, what a character +carries, item levels, and how items are handed out. + +This describes the code as it stands. Related: [WEAPONS.md](WEAPONS.md) (items +level up the same way weapons do), [SPELLS.md](SPELLS.md), +[CHARACTERS.md](CHARACTERS.md) (money is covered there, in section 12). + +## Contents + +1. [The basics](#1-the-basics) +2. [The item pool](#2-the-item-pool) +3. [A character's inventory](#3-a-characters-inventory) +4. [Item levels](#4-item-levels) +5. [Dice on items](#5-dice-on-items) +6. [Starting items](#6-starting-items) +7. [Items as rewards](#7-items-as-rewards) +8. [Permissions](#8-permissions) +9. [What is not modelled](#9-what-is-not-modelled) + +--- + +## 1. The basics + +- Every campaign has its own **item pool**: rope, potions, keys, quest items, + anything that is not a weapon or a spell. +- A character's **inventory** is the items it holds from that pool. Players + cannot type in items of their own. +- The DM creates items and hands them out. Players can only tick Equipped. +- Items are **descriptive**. Holding or equipping one never changes a number + on the sheet. + +## 2. The item pool + +The pool is the "Items Pool" card on the campaign page (DM only). + +| Field | What it is | +|---|---| +| Name | Free text, up to 120 characters | +| Description | Optional. Shown under the item in a character's inventory | +| Base dice | Optional dice such as `2d4+2`, for items that deal damage or heal (section 5) | +| Starts at level | 1 to 9. The lowest level this item can be (section 4) | +| Growth | Standard, Powerful or Legendary. Only matters if the item has dice | +| Starting option | Whether a brand-new character may pick it in the builder (section 6) | + +- **Adding:** the "+ Add Item" form. There is no built-in library of items. +- **Changing:** starting level, growth (when the item has dice) and the + starting-option tick box can be changed in the table. Name, description and + dice cannot be changed on screen once created (the API accepts it); remove + and re-add instead. +- **Removing:** the ✕ button. This takes the item out of **every inventory** + and off every encounter's reward list. There is no undo. + +## 3. A character's inventory + +On a character's sheet, the DM picks an item from the pool and clicks Give. + +| Each held item has | Who changes it | +|---|---| +| Quantity | The DM, with the − and + buttons | +| Level | The DM, with the level picker | +| Equipped | The owning player or the DM | + +- Giving an item the character already holds **adds to the stack**. A + character holds one stack per item, and the whole stack shares one level. +- Quantity cannot go below 1; to take the last one away the DM uses ✕. +- **Using up** an item (drinking a potion) is not automatic: the DM lowers the + quantity or removes it. +- **Equipped** is a label. It does not change Armor Class or anything else; + armor is represented by the single "armor bonus" number on the sheet. + +**Passing items on.** A character's owner (or the DM) can give some or all of +a held stack to another character in the campaign from the "Give to Another +Character" card on the sheet. The items leave the giver and arrive with the +recipient at the giver's level, unequipped. If the recipient already holds +that item, their stack grows and keeps its own level. Gold is given the same +way, and both characters' money logs record it. + +## 4. Item levels + +Items use the same level system as weapons (a house rule of this app): + +- Each held stack has a **level from 1 to 9**, never below the pool entry's + starting level. +- A character must be **at least the item's level** to use it. A higher-level + item is still held, but shows "Requires level N" and cannot be equipped. +- Only the DM changes an item's level. +- If the DM levels an item past its holder, or lowers the character's level, + it is unequipped automatically. + +For an item with no dice, the level is purely a requirement: a level 3 amulet +is one a character cannot use until level 3. + +## 5. Dice on items + +An item can carry optional dice: a healing potion's `2d4+2`, a firebomb's +`3d6`. The app does not know whether they heal or harm; the DM applies them. + +The dice grow with the item's level exactly as a weapon's do, climbing the +same ladder (1d4 → 1d6 → 1d8 → 1d10 → 1d12 → 2d6 → …) by one, two or three +rungs per level depending on Growth. The full ladder is in +[WEAPONS.md, section 6](WEAPONS.md#6-how-damage-grows). + +| Healing Potion, `2d4+2`, Standard growth | Dice shown | +|---|---| +| Level 1 | 2d4+2 (as typed) | +| Level 2 | 1d6+1d8 | +| Level 3 | 2d8 | + +The dice are shown beside the item in the inventory. Nothing is rolled or +applied automatically; use the dice roller. + +## 6. Starting items + +In the builder's equipment step a new character can pick items that are: + +- ticked as a **starting option** in the pool, and +- **starting level 1**. + +Starting items and starting weapons share the campaign's "starting items" +allowance. Each arrives at level 1, quantity 1, unequipped. + +## 7. Items as rewards + +On an encounter the DM can line up an item as a reward, at a chosen level and +quantity, and later award it to a character. Awarding adds it to the +character's inventory, stacking with any they already hold. See +[ENCOUNTERS.md](ENCOUNTERS.md). + +## 8. Permissions + +| Action | DM | Owning player | Other players | +|---|---|---|---| +| See the item pool | Yes | Yes | Yes | +| Add, change or remove pool items | Yes | No | No | +| Give an item from the pool, or take one away | Yes | No | No | +| Give a held item to another character | Yes | Yes | No | +| Change quantity or level | Yes | No | No | +| Equip or unequip | Yes | Yes, if the character can use it | No | +| See a character's inventory | Yes | Yes | Yes | + +## 9. What is not modelled + +- Any effect of an item on stats (AC, speed, abilities) +- Armor and shields as items +- Using up items automatically, charges, and attunement +- Weight, carrying capacity and containers +- Prices, buying and selling (record the gold change in the money log) +- Swaps as a single step (each side gives separately), and asking the + recipient to accept diff --git a/docs/MONSTERS.md b/docs/MONSTERS.md new file mode 100644 index 0000000..3ed05d9 --- /dev/null +++ b/docs/MONSTERS.md @@ -0,0 +1,170 @@ +# Monsters + +How monsters work in this app: the campaign's monster list, the built-in +bestiary, and how monsters behave in an encounter. + +This describes the code as it stands. The built-in list is +`backend/src/game/data/monstersLibrary.js`. Related: +[ENCOUNTERS.md](ENCOUNTERS.md), [NPCS.md](NPCS.md). + +## Contents + +1. [The basics](#1-the-basics) +2. [What a monster holds](#2-what-a-monster-holds) +3. [Managing monsters](#3-managing-monsters) +4. [The built-in bestiary](#4-the-built-in-bestiary) +5. [Monsters in encounters](#5-monsters-in-encounters) +6. [What players see](#6-what-players-see) +7. [Permissions](#7-permissions) +8. [What is not modelled](#8-what-is-not-modelled) + +--- + +## 1. The basics + +- Every campaign has its own **monster list**. Only the DM can see or change + it. +- A monster in the list is a **template**. Each time it is added to an + encounter it becomes a separate combatant with its own hit points. +- Stat blocks are the DM's. Players see a monster only as a name and a health + bar in an encounter. + +## 2. What a monster holds + +| Field | What it is | +|---|---| +| Name | Up to 80 characters | +| AC | Armor Class | +| Max HP | Hit points each copy starts an encounter with | +| Speed | In feet. 30 unless set otherwise | +| Ability scores | STR, DEX, CON, INT, WIS, CHA. 10 unless set otherwise | +| Attack bonus | Added to the monster's attack roll | +| Damage | Dice for its main attack, e.g. `1d6+2` | +| Challenge rating | A rough danger rating, e.g. `1/4`, `2` | +| Special trait | A short note such as "Pack Tactics" | +| Notes | Anything else: what it attacks with, how it behaves | + +None of these are calculated or used in formulas. They are reference numbers +shown to the DM during a fight. A monster's ability modifiers are worked out +from its scores for display only. + +## 3. Managing monsters + +The list is the "Monsters" card on the campaign page (DM only). + +- **Adding by hand:** "+ Add Monster" asks for name, AC, max HP, attack bonus + and damage. Speed is set to 30 and every ability score to 10; challenge + rating, trait and notes are left empty. +- **Adding from the bestiary:** "📚 From Library" copies a complete stat block. +- **Changing:** there is no edit form (the API accepts changes, but no screen + offers them). Remove and re-add, or add from the library. +- **Removing:** the ✕ button, immediately, with no confirmation. Copies + already in encounters stay there with their name and HP, but lose their + stat block. + +## 4. The built-in bestiary + +38 monsters, from harmless to dangerous. Each library row shows challenge +rating, AC, HP, attack and damage, plus its trait and notes, before you add +it. Adding copies the monster into your campaign; the copy is yours, and later +changes to the library do not affect it. + +The full bestiary, weakest first. "Attack" is the bonus added to the +monster's attack roll. + +This list is written from the app's own data by `npm run docs:lists` (in `/backend`). Re-run it after changing the data; do not edit the list by hand. + + +| Monster | CR | AC | HP | Speed | Attack | Damage | STR / DEX / CON / INT / WIS / CHA | Trait | Notes | +|---|---|---|---|---|---|---|---|---|---| +| Commoner | 0 | 10 | 4 | 30 | +2 | 1d4 | 10 / 10 / 10 / 10 / 10 / 10 | — | An ordinary villager, armed with a club. | +| Giant Rat | 1/8 | 12 | 7 | 30 | +4 | 1d4+2 | 7 / 15 / 11 / 2 / 10 / 4 | Pack Tactics | Bite, piercing damage. | +| Kobold | 1/8 | 12 | 5 | 30 | +4 | 1d4+2 | 7 / 15 / 9 / 8 / 7 / 8 | Pack Tactics, Sunlight Sensitivity | Dagger, piercing damage. | +| Bandit | 1/8 | 12 | 11 | 30 | +3 | 1d6+1 | 11 / 12 / 12 / 10 / 10 / 10 | — | Scimitar, slashing damage. | +| Cultist | 1/8 | 12 | 9 | 30 | +3 | 1d6+1 | 11 / 12 / 10 / 10 / 11 / 10 | Dark Devotion | Scimitar, slashing damage. | +| Stirge | 1/8 | 12 | 2 | 10 | +5 | 1d4 | 4 / 16 / 11 / 2 / 8 / 6 | Blood Drain | Proboscis; attaches and drains hp on a hit. | +| Goblin | 1/4 | 15 | 7 | 30 | +4 | 1d6+2 | 8 / 14 / 10 / 10 / 8 / 8 | Nimble Escape | Scimitar, slashing damage. | +| Skeleton | 1/4 | 13 | 13 | 30 | +4 | 1d6+2 | 10 / 14 / 15 / 6 / 8 / 5 | Undead — vulnerable to bludgeoning | Shortsword, piercing damage. | +| Zombie | 1/4 | 8 | 22 | 20 | +3 | 1d6+1 | 13 / 6 / 16 / 3 / 6 / 5 | Undead Fortitude | Slam, bludgeoning damage. | +| Wolf | 1/4 | 13 | 11 | 40 | +4 | 2d4+2 | 12 / 15 / 12 / 3 / 12 / 6 | Pack Tactics | Bite; can knock prone on a hit. | +| Giant Wolf Spider | 1/4 | 13 | 11 | 40 | +3 | 1d6+1 | 12 / 16 / 13 / 3 / 12 / 4 | Poison bite | Spider climb; bite deals poison damage. | +| Scout | 1/2 | 13 | 16 | 30 | +4 | 1d6+2 | 11 / 14 / 12 / 11 / 13 / 11 | Keen Hearing and Sight | Shortsword or longbow. | +| Orc | 1/2 | 13 | 15 | 30 | +5 | 1d12+3 | 16 / 12 / 16 / 7 / 11 / 10 | Aggressive | Greataxe, slashing damage. | +| Hobgoblin | 1/2 | 18 | 11 | 30 | +3 | 1d8+1 | 13 / 12 / 12 / 10 / 10 / 9 | Martial Advantage | Longsword, slashing damage. | +| Thug | 1/2 | 11 | 32 | 30 | +4 | 1d6+2 | 15 / 11 / 14 / 10 / 10 / 11 | Pack Tactics | Mace, bludgeoning damage. | +| Gnoll | 1/2 | 15 | 22 | 30 | +3 | 1d8+1 | 14 / 12 / 11 / 6 / 10 / 7 | Rampage | Spear, piercing damage. | +| Lizardfolk | 1/2 | 15 | 22 | 30 | +3 | 1d6+1 | 15 / 10 / 13 / 7 / 12 / 7 | Hold Breath | Club or spear, piercing damage. | +| Black Bear | 1/2 | 11 | 19 | 40 | +3 | 1d6+2 | 15 / 10 / 14 / 2 / 12 / 7 | Keen Smell | Bite and claw attacks. | +| Giant Spider | 1 | 14 | 26 | 30 | +5 | 1d8+3 | 14 / 16 / 12 / 2 / 11 / 4 | Web, poison bite | Bite deals piercing plus poison damage. | +| Ghoul | 1 | 12 | 22 | 30 | +2 | 2d6+2 | 13 / 15 / 10 / 7 / 10 / 6 | Claws paralyze on a hit | Undead. | +| Dire Wolf | 1 | 14 | 37 | 50 | +5 | 2d6+3 | 17 / 15 / 15 / 3 / 12 / 7 | Pack Tactics | Bite; can knock prone on a hit. | +| Brown Bear | 1 | 11 | 34 | 40 | +5 | 1d8+5 | 19 / 10 / 16 / 2 / 13 / 7 | Keen Smell | Multiattack: bite and claws. | +| Harpy | 1 | 11 | 38 | 20 | +4 | 2d4+2 | 12 / 13 / 12 / 7 / 10 / 13 | Luring Song | Flying speed 40 ft; claws deal slashing damage. | +| Ochre Jelly | 2 | 8 | 45 | 10 | +5 | 2d6+3 | 15 / 6 / 14 / 2 / 6 / 1 | Amorphous, splits when damaged by slashing | Pseudopod, bludgeoning plus acid damage. | +| Ogre | 2 | 11 | 59 | 40 | +6 | 2d8+4 | 19 / 8 / 16 / 5 / 7 / 7 | — | Greatclub, bludgeoning damage. | +| Griffon | 2 | 12 | 59 | 30 | +6 | 2d6+4 | 18 / 15 / 16 / 2 / 13 / 8 | Keen Sight | Flying speed 80 ft; multiattack beak and claws. | +| Ankheg | 2 | 14 | 39 | 30 | +6 | 2d6+4 | 17 / 11 / 13 / 1 / 13 / 6 | Burrow speed 10 ft; can spit acid | Bite, piercing plus acid damage. | +| Manticore | 3 | 14 | 68 | 30 | +5 | 1d8+3 | 17 / 16 / 17 / 7 / 12 / 8 | Tail spikes (ranged) | Flying speed 50 ft; multiattack claws or tail spikes. | +| Basilisk | 3 | 15 | 52 | 20 | +5 | 2d6+3 | 16 / 8 / 15 / 2 / 8 / 7 | Petrifying Gaze | Bite, piercing damage. | +| Owlbear | 3 | 13 | 59 | 40 | +7 | 1d10+5 | 20 / 12 / 17 / 3 / 12 / 7 | Keen Sight and Smell | Multiattack: beak and claws. | +| Wight | 3 | 14 | 45 | 30 | +4 | 1d8+2 | 15 / 14 / 16 / 10 / 13 / 15 | Life Drain, Sunlight Sensitivity | Longsword or life-draining touch. | +| Werewolf | 3 | 12 | 58 | 30 | +4 | 1d8+2 | 15 / 13 / 14 / 10 / 11 / 10 | Shapechanger, regeneration | Bite (hybrid/wolf form) or multiattack claws + bite. | +| Doppelganger | 3 | 14 | 52 | 30 | +4 | 2d4+2 | 11 / 18 / 14 / 11 / 12 / 14 | Shapechanger, Ambusher | Multiattack slam. | +| Displacer Beast | 3 | 13 | 85 | 40 | +7 | 2d6+4 | 18 / 15 / 16 / 6 / 12 / 8 | Displacement (attacks vs. it have disadvantage) | Multiattack: two tentacles. | +| Ettin | 4 | 12 | 85 | 40 | +7 | 2d8+4 | 21 / 8 / 17 / 6 / 10 / 8 | Two heads — advantage on Perception, can’t be surprised easily | Multiattack: battleaxe and morningstar. | +| Hill Giant | 5 | 13 | 105 | 40 | +8 | 3d8+5 | 21 / 8 / 19 / 5 / 9 / 6 | — | Greatclub, bludgeoning damage. | +| Troll | 5 | 15 | 84 | 30 | +7 | 2d6+4 | 18 / 13 / 20 / 7 / 9 / 7 | Regeneration (vulnerable to fire/acid) | Multiattack: bite and two claws. | +| Wraith | 5 | 13 | 67 | 0 | +6 | 4d8+4 | 6 / 16 / 16 / 12 / 14 / 15 | Incorporeal, life drain, flying 60 ft | Undead; life drain touch attack. | + + +## 5. Monsters in encounters + +On an encounter page, the DM chooses "Monster" in the "Add to the scene" +panel, picks one, and types its initiative. + +- The same monster can be added **any number of times**. Each copy has its + own HP and conditions. Copies share the monster's name; the screen has no + way to rename one (the API allows it). +- A copy starts at the monster's max HP. Its HP stays between 0 and its max. +- At 0 HP a copy is marked **Down** and dimmed, but keeps its place in the + initiative order until the DM removes it. +- HP belongs to the encounter: a monster starts fresh in the next one. + +The DM's card for a monster shows AC, speed, attack bonus and damage at a +glance, and under "details" its six ability scores with modifiers, its trait +and its notes. + +## 6. What players see + +| Players see | Players never see | +|---|---| +| The monster's name | AC, speed, attack bonus, damage | +| Its health bar and current/max HP | Ability scores, challenge rating | +| Its conditions | Trait and notes | +| Its place in the initiative order | The campaign's monster list | + +This is enforced by the server: stat blocks are never sent to a player's +browser. + +Players do see a monster's exact HP numbers. If you would rather keep those +secret, that is not currently possible. + +## 7. Permissions + +| Action | DM | Players | +|---|---|---| +| See the monster list and stat blocks | Yes | No | +| Browse the built-in bestiary | Yes | Yes (it is standard reference material) | +| Add or remove monsters | Yes | No | +| Add a monster to an encounter | Yes | No | +| Change a monster's HP, initiative or conditions | Yes | No | +| See a monster in an encounter | Everything | Name, HP, conditions | + +## 8. What is not modelled + +- Multiple attacks, spells, legendary actions and resistances (use Notes) +- Rolling a monster's attacks or damage (use the dice roller) +- Saving throw bonuses and skills +- Experience points for defeating monsters +- Encounter difficulty calculated from challenge ratings +- Monster hit dice, and rolling HP rather than using the fixed value diff --git a/docs/NPCS.md b/docs/NPCS.md new file mode 100644 index 0000000..5b47b68 --- /dev/null +++ b/docs/NPCS.md @@ -0,0 +1,123 @@ +# NPCs + +How non-player characters work in this app: what the DM records about them, +how they are brought into a scene, and what players can and cannot see. + +This describes the code as it stands. Related: [ENCOUNTERS.md](ENCOUNTERS.md), +[MONSTERS.md](MONSTERS.md). + +## Contents + +1. [The basics](#1-the-basics) +2. [What an NPC holds](#2-what-an-npc-holds) +3. [Managing NPCs](#3-managing-npcs) +4. [NPCs in encounters](#4-npcs-in-encounters) +5. [What players see](#5-what-players-see) +6. [NPC or monster?](#6-npc-or-monster) +7. [Permissions](#7-permissions) +8. [What is not modelled](#8-what-is-not-modelled) + +--- + +## 1. The basics + +- An NPC is a person the DM plays: an innkeeper, a quest-giver, a rival, a + villain. +- Every campaign has its own **NPC list**. Only the DM can see or change it. +- An NPC does nothing by sitting in the list. Players meet one when the DM + **adds it to an encounter**. +- NPCs are mainly for talking to. Combat stats are optional. + +## 2. What an NPC holds + +| Field | What it is | Who sees it | +|---|---|---| +| Name | Up to 80 characters | Everyone, once in an encounter | +| Role | A few words: "Innkeeper", "Captain of the Watch" | Everyone | +| Attitude | Friendly, Neutral or Hostile toward the party | Everyone | +| Description | What the party can see and knows | Everyone | +| DM notes | Secrets, motives, what they are hiding | **DM only** | +| AC | Optional | DM only | +| HP | Optional. Without it the NPC has no health bar | See section 5 | +| Attack bonus | Optional | DM only | +| Damage | Optional dice, e.g. `1d6` | DM only | + +A new NPC is Neutral unless you choose otherwise. + +## 3. Managing NPCs + +The NPC list is the "NPCs" card on the campaign page (DM only). + +- **Adding:** "+ Add NPC" opens a form with every field above. Only the name + is required. +- **Changing:** there is no edit form. To change an NPC, remove it and add it + again (the API accepts changes, but no screen offers them). +- **Removing:** the ✕ button, after a confirmation. This also **removes the + NPC from every encounter** it was in. + +## 4. NPCs in encounters + +On an encounter page, the DM chooses "NPC" in the "Add to the scene" panel +and picks one. Each NPC can be in an encounter once. + +- In an **NPC quest** encounter, NPCs are listed first under "People you + meet", ahead of the party and any creatures. +- In a **battle**, an NPC takes its place in the initiative order like anyone + else, using the initiative the DM types in. +- An NPC with HP gets a health bar, and the DM can damage and heal it. This + HP belongs to the encounter: the same NPC starts at full HP in the next one. +- An NPC with no HP has no health bar and cannot be marked Down. +- Conditions (Prone, Charmed…) can be put on an NPC like any combatant. + +An NPC's card shows its attitude as a coloured badge, its role under its +name, and its description in full. The DM's card also shows AC, attack, +damage and the DM notes. + +## 5. What players see + +Players only ever see an NPC through an encounter it is in: + +| Players see | Players never see | +|---|---| +| Name, role, attitude, description | DM notes | +| Health bar and conditions, if the NPC has HP | AC, attack bonus, damage | + +This is enforced by the server, not just hidden on screen: the hidden fields +are never sent to a player's browser. + +Changing an NPC's attitude changes what players see straight away, so +flipping a "Friendly" NPC to "Hostile" is itself a reveal. + +## 6. NPC or monster? + +| | NPC | Monster | +|---|---|---| +| Meant for | People with names and motives | Things to fight | +| Has a description players can read | Yes | No | +| Has an attitude | Yes | No | +| Has DM-only notes | Yes | Yes | +| Combat stats | Optional, basic | Full stat block | +| Can be in an encounter more than once | No | Yes (a pack of goblins) | +| Built-in library | No | Yes | + +A named villain the party will both talk to and fight works well as an NPC +with HP, AC, attack and damage filled in. + +## 7. Permissions + +| Action | DM | Players | +|---|---|---| +| See the NPC list | Yes | No | +| Add or remove NPCs | Yes | No | +| Add an NPC to an encounter | Yes | No | +| Change an NPC's HP or conditions in an encounter | Yes | No | +| See an NPC in an encounter | Everything | Name, role, attitude, description, health bar | + +## 8. What is not modelled + +- Ability scores, saves, skills and spells for NPCs +- NPC inventory, gold and shops +- Where an NPC is (they are not tied to locations) +- Relationships, reputation and attitude toward individual characters +- A record of which NPCs the party has met, outside of encounters +- Portraits diff --git a/docs/SPELLS.md b/docs/SPELLS.md new file mode 100644 index 0000000..61ef8f4 --- /dev/null +++ b/docs/SPELLS.md @@ -0,0 +1,387 @@ +# Spells + +How spells work in this app: the campaign's spell list, how a character comes +to know a spell, who can use which spells, and what the spellcasting numbers +mean. + +This describes the code as it stands. The built-in list is +`backend/src/game/data/spellsLibrary.js`. Related: [WEAPONS.md](WEAPONS.md), +[ITEMS.md](ITEMS.md), [CHARACTERS.md](CHARACTERS.md). + +## Contents + +1. [The basics](#1-the-basics) +2. [The spell list](#2-the-spell-list) +3. [The built-in library](#3-the-built-in-library) +4. [Granting spells to characters](#4-granting-spells-to-characters) +5. [Spell level and who can use it](#5-spell-level-and-who-can-use-it) +6. [Damage](#6-damage) +7. [Spellcasting numbers](#7-spellcasting-numbers) +8. [Starting spells](#8-starting-spells) +9. [Permissions](#9-permissions) +10. [What is not modelled](#10-what-is-not-modelled) +11. [The complete spell library](#11-the-complete-spell-library) + +--- + +## 1. The basics + +- Every campaign has its own **spell list**. A spell exists in one campaign + only. +- A character **knows** spells from that list, each with a Prepared tick box. +- The DM runs the list and decides who learns what. Players can only prepare + and unprepare the spells they know. +- Unlike weapons and items, a spell has **no level of its own to raise**. Its + level is fixed, and so is its damage. + +## 2. The spell list + +The list is the "Spell List" card on the campaign page (DM only). + +| Field | What it is | +|---|---| +| Name | Free text, up to 80 characters | +| Level | Cantrip, or level 1 to 9. Also the character level needed to use it (section 5) | +| School | Free text: Evocation, Illusion… | +| What it does | One sentence. Shown wherever the spell is shown | +| Damage | Picked from a list, or "No damage". Fixed; it does not grow | +| Starting option | Whether a brand-new character may pick it in the builder (section 8) | +| Casting time, range, duration | Stored for library spells but not shown on any screen | + +A cantrip is a spell of level 0. The app always calls it a **cantrip**, never +"level 0" or "level 1". + +- **Adding:** by hand with the "+ Add Spell" form (name, level, school, + damage and what it does), or from the library. +- **Changing:** damage (the drop-down in the table) and the starting-option + tick box. Name, level, school and description cannot be changed on screen + once created (the API accepts it); remove and re-add instead. +- **Damage choices:** the drop-down offers "No damage", then 1 to 6, 8 or 10 + dice of d4, d6, d8, d10 or d12 (1d4 up to 10d12), plus the three unusual + values the library uses (`3d4+3`, `2d8+4d6`, `20`). +- **Removing:** the ✕ button. Every character who knows the spell forgets it. + There is no undo. + +## 3. The built-in library + +"📚 From Library" offers 131 standard spells to copy into the list: + +| Level | Spells | +|---|---| +| Cantrips | 26 | +| 1 | 30 | +| 2 | 26 | +| 3 | 21 | +| 4 | 13 | +| 5 | 15 | + +Before you add one, each row shows: + +- whether it is a **cantrip** or its **level**, and who can use it; +- its **default damage**, or "no damage"; +- its school; +- **what it does**, in a sentence. + +Every library spell is listed in full in +[section 11](#11-the-complete-spell-library). + +35 of the library spells deal damage and come with a default, taken from the +standard rules at the spell's own level. For example: + +| Spell | Level | Default damage | +|---|---|---| +| Fire Bolt | Cantrip | 1d10 | +| Sacred Flame | Cantrip | 1d8 | +| Magic Missile | 1 | 3d4+3 (all three darts together) | +| Burning Hands | 1 | 3d6 | +| Scorching Ray | 2 | 2d6 (per ray; there are three) | +| Fireball | 3 | 8d6 | +| Ice Storm | 4 | 2d8+4d6 | +| Cone of Cold | 5 | 8d8 | + +Spells that heal, protect or control (Cure Wounds, Shield, Hold Person…) have +no default. Pick a value from the Damage drop-down after adding if you want +one shown. + +A spell added from the library is **not** a starting option until ticked. The +library has nothing above level 5; add higher spells by hand. + +## 4. Granting spells to characters + +On a character's sheet, the DM picks a spell from the list and clicks Grant. + +- Any class can be granted any spell. Whether a non-spellcaster should have + one is the DM's call. +- The DM can remove a known spell with ✕. +- The owning player ticks **Prepared**. Prepared is a label: there is no limit + on how many spells are prepared. +- **Passing a spell on.** A character's owner (or the DM) can give a known + spell to another character in the campaign from the "Give to Another + Character" card on the sheet. The spell moves: the giver no longer knows + it. It cannot be given to someone who already knows it, and a recipient + below the spell's level knows it but cannot use it yet. +- The "Spells Known" card only appears on a sheet when the campaign's spell + list has at least one spell. +- Each known spell shows its level (or "Cantrip"), its damage, and what it + does. + +## 5. Spell level and who can use it + +This is a house rule of this app. In standard D&D a 3rd-level spell needs a +5th-level caster; here the two numbers are the same. + +**A character must be at least the spell's level to use it.** Cantrips are +open to everyone. + +| Spell | Who can use it | +|---|---| +| Cantrip | Any character | +| Level 1 | Any character (everyone starts at level 1) | +| Level 2 | Characters of level 2 and above | +| Level 3 | Characters of level 3 and above | +| … | … | +| Level 9 | Characters of level 9 and above | + +A spell above the character's level can still be **known**, but it shows +"Requires level N", cannot be prepared, and is left out of encounters. If the +DM lowers a character's level, spells now out of reach are unprepared +automatically. + +## 6. Damage + +A spell's damage is whatever is picked in its Damage drop-down, shown beside +the spell on the sheet and in encounters. It does not change with the character's +level, and nothing is added to it. + +## 7. Spellcasting numbers + +Shown only for classes with a spellcasting ability: + +| Class | Spellcasting ability | +|---|---| +| Wizard | Intelligence | +| Cleric, Druid, Ranger | Wisdom | +| Bard, Paladin, Sorcerer, Warlock | Charisma | +| Barbarian, Fighter, Monk, Rogue | None | + +| Number | Formula | Used when | +|---|---|---| +| Spell save DC | 8 + proficiency bonus + spellcasting ability modifier | A target rolls to resist your spell | +| Spell attack bonus | Proficiency bonus + spellcasting ability modifier | You roll to hit with a spell | + +A character without a spellcasting class can still be granted spells, but has +no save DC or attack bonus shown. + +## 8. Starting spells + +In the builder's equipment step a new character can pick spells that are: + +- ticked as a **starting option** in the list, +- **cantrips or level 1** (a new character is level 1), and +- only if the character's **class has a spellcasting ability**. + +The number allowed is the campaign's "starting spells" setting. Starting +spells arrive unprepared. + +## 9. Permissions + +| Action | DM | Owning player | Other players | +|---|---|---|---| +| See the spell list and the library | Yes | Yes | Yes | +| Add, change or remove spells in the list | Yes | No | No | +| Grant a spell from the list, or remove one | Yes | No | No | +| Give a known spell to another character | Yes | Yes | No | +| Prepare or unprepare | Yes | Yes, if the character can use it | No | +| See a character's spells | Yes | Yes | Yes | + +## 10. What is not modelled + +- Spell slots, and casting a spell at a higher level +- Cantrip damage increasing at higher character levels +- Limits on how many spells can be prepared or known +- Concentration, components, rituals +- Class spell lists (any spell can be granted to anyone) +- Healing amounts as a separate value (pick them in Damage if you want them + shown) +- Applying spell damage to a target automatically + +## 11. The complete spell library + +Every spell "📚 From Library" offers, with the damage it arrives with. + +This list is written from the app's own data by `npm run docs:lists` (in `/backend`). Re-run it after changing the data; do not edit the list by hand. + + +### Cantrips (26) + +Usable by any character. + +| Spell | School | Damage | What it does | +|---|---|---|---| +| Acid Splash | Conjuration | 1d6 | Hurl a bubble of acid at one or two creatures within 5 feet of each other. | +| Blade Ward | Abjuration | — | Resist bludgeoning, piercing, and slashing damage until your next turn. | +| Chill Touch | Necromancy | 1d8 | A ghostly hand deals necrotic damage and prevents healing. | +| Dancing Lights | Illusion | — | Create up to four torch-sized lights that you can move. | +| Druidcraft | Transmutation | — | A small, harmless nature-flavored effect: predict weather, sprout a seedling, and the like. | +| Eldritch Blast | Evocation | 1d10 | A beam of crackling energy strikes one creature for force damage. | +| Fire Bolt | Evocation | 1d10 | Hurl a mote of fire that deals fire damage on a hit. | +| Friends | Enchantment | — | Advantage on Charisma checks against one creature for the duration. | +| Guidance | Divination | — | Add 1d4 to one ability check of your choice. | +| Light | Evocation | — | An object sheds bright light in a 20-foot radius. | +| Mage Hand | Conjuration | — | A spectral hand manipulates objects, opens doors, and carries small items. | +| Mending | Transmutation | — | Repairs a single break or tear in an object. | +| Message | Transmutation | — | Whisper a message to a target that only they can hear, with a whispered reply. | +| Minor Illusion | Illusion | — | Create a sound or an image of an object for the duration. | +| Poison Spray | Conjuration | 1d12 | Project a puff of noxious gas that deals poison damage. | +| Prestidigitation | Transmutation | — | A minor magical trick — light a candle, clean an object, chill or warm food, and the like. | +| Produce Flame | Conjuration | 1d8 | A flickering flame in your hand sheds light and can be hurled for fire damage. | +| Ray of Frost | Evocation | 1d8 | A ray of freezing energy deals cold damage and slows the target. | +| Resistance | Abjuration | — | The target adds 1d4 to one saving throw of its choice. | +| Sacred Flame | Evocation | 1d8 | Radiant flame descends on a creature that must succeed a Dexterity save or take damage. | +| Shillelagh | Transmutation | — | Imbue a club or quarterstaff with magic, using Wisdom for its attack and damage. | +| Shocking Grasp | Evocation | 1d8 | Lightning springs from your hand, dealing damage and preventing reactions. | +| Spare the Dying | Necromancy | — | A creature you touch that has 0 hit points becomes stable. | +| Thorn Whip | Transmutation | 1d6 | A vine-like whip deals damage and drags the target closer. | +| True Strike | Divination | — | Gain advantage on your next attack roll against the target. | +| Vicious Mockery | Enchantment | 1d4 | A string of insults deals psychic damage and imposes disadvantage on the target’s next attack. | + +### Level 1 (30 spells) + +Needs character level 1. + +| Spell | School | Damage | What it does | +|---|---|---|---| +| Alarm | Abjuration | — | Set an audible or mental alarm against intruders. | +| Animal Friendship | Enchantment | — | Convince a beast that you mean it no harm. | +| Bane | Enchantment | — | Up to three creatures subtract 1d4 from attack rolls and saves. | +| Bless | Enchantment | — | Up to three creatures add 1d4 to attack rolls and saves. | +| Burning Hands | Evocation | 3d6 | A thin sheet of flame sweeps out from your hands. | +| Charm Person | Enchantment | — | A humanoid you can see regards you as a friendly acquaintance. | +| Color Spray | Illusion | — | A dazzling array of flashing colors can blind weak creatures. | +| Command | Enchantment | — | Speak a one-word command a creature must obey. | +| Comprehend Languages | Divination | — | Understand any spoken or written language. | +| Cure Wounds | Evocation | — | A creature you touch regains hit points. | +| Detect Magic | Divination | — | Sense the presence of magic within 30 feet. | +| Disguise Self | Illusion | — | Change your appearance, including clothing and gear. | +| Entangle | Conjuration | — | Grasping weeds and vines sprout in a 20-foot square. | +| Faerie Fire | Evocation | — | Objects in a 20-foot cube are outlined in light, granting attackers advantage. | +| Feather Fall | Transmutation | — | Falling creatures slow to a gentle descent. | +| Fog Cloud | Conjuration | — | A 20-foot-radius sphere of fog heavily obscures the area. | +| Guiding Bolt | Evocation | 4d6 | A flash of light streaks to a target, dealing radiant damage. | +| Healing Word | Evocation | — | A creature you can see regains hit points. | +| Hunter's Mark | Divination | 1d6 | Deal extra damage to a marked target and track it magically. | +| Identify | Divination | — | Learn the properties of a magic item or the nature of a spell affecting a creature. | +| Jump | Transmutation | — | A creature's jump distance triples. | +| Longstrider | Transmutation | — | A creature's speed increases by 10 feet. | +| Mage Armor | Abjuration | — | A protective magical force gives the target a base AC of 13 + Dex modifier. | +| Magic Missile | Evocation | 3d4+3 | Three darts of magical force each strike a target unerringly. | +| Protection from Evil and Good | Abjuration | — | Protect a creature from aberrations, celestials, elementals, fey, fiends, and undead. | +| Shield | Abjuration | — | An invisible barrier grants +5 AC until the start of your next turn. | +| Sleep | Enchantment | — | Creatures in a 20-foot radius fall unconscious, weakest hit points first. | +| Speak with Animals | Divination | — | Comprehend and verbally communicate with beasts. | +| Thunderwave | Evocation | 2d8 | A wave of thunderous force sweeps out, damaging and pushing creatures. | +| Witch Bolt | Evocation | 1d12 | A beam of lightning forms a sustained arc that damages the target each turn. | + +### Level 2 (26 spells) + +Needs character level 2. + +| Spell | School | Damage | What it does | +|---|---|---|---| +| Aid | Abjuration | — | Bolster allies with additional hit points. | +| Alter Self | Transmutation | — | Assume a variety of minor physical changes. | +| Animal Messenger | Enchantment | — | Send a tiny animal to deliver a short message. | +| Blindness/Deafness | Necromancy | — | Blind or deafen a creature that fails a Constitution save. | +| Blur | Illusion | — | Your outline blurs, giving attackers disadvantage. | +| Darkvision | Transmutation | — | Grant a creature darkvision out to 60 feet. | +| Enhance Ability | Transmutation | — | Grant advantage on checks with one chosen ability. | +| Enlarge/Reduce | Transmutation | — | A creature or object doubles or halves in size. | +| Flaming Sphere | Conjuration | 2d6 | A 5-foot-diameter sphere of fire rolls where you direct it. | +| Gust of Wind | Evocation | — | A line of strong wind pushes creatures and extinguishes flames. | +| Hold Person | Enchantment | — | Paralyze a humanoid that fails a Wisdom save. | +| Invisibility | Illusion | — | A creature you touch becomes invisible. | +| Lesser Restoration | Abjuration | — | End one disease or condition afflicting the target. | +| Levitate | Transmutation | — | A creature or object rises vertically and can be moved. | +| Mirror Image | Illusion | — | Three illusory duplicates of yourself spring into being. | +| Misty Step | Conjuration | — | Teleport up to 30 feet in a burst of silvery mist. | +| Moonbeam | Evocation | 2d10 | A silvery beam of pale light shines down in a 5-foot-radius cylinder. | +| Pass without Trace | Abjuration | — | The party becomes exceptionally difficult to track. | +| Scorching Ray | Evocation | 2d6 | Three rays of fire streak toward targets within range. | +| Shatter | Evocation | 3d8 | A sudden loud ringing noise deals thunder damage in a 10-foot-radius sphere. | +| Silence | Illusion | — | No sound can be created within or pass through a 20-foot-radius sphere. | +| Spider Climb | Transmutation | — | A creature gains the ability to move on vertical surfaces and ceilings. | +| Spiritual Weapon | Evocation | 1d8 | A spectral weapon attacks a target and can be moved each turn. | +| Suggestion | Enchantment | — | Plant a reasonable-sounding suggestion in a creature’s mind. | +| Web | Conjuration | — | Thick, sticky webs fill a 20-foot cube. | +| Zone of Truth | Enchantment | — | Creatures in a 15-foot-radius sphere can’t speak a deliberate lie. | + +### Level 3 (21 spells) + +Needs character level 3. + +| Spell | School | Damage | What it does | +|---|---|---|---| +| Animate Dead | Necromancy | — | Raise a skeleton or zombie from a corpse to fight for you. | +| Beacon of Hope | Abjuration | — | Bolster creatures against despair, granting advantage on saves and max healing. | +| Call Lightning | Conjuration | 3d10 | A storm cloud forms and you can call down bolts of lightning. | +| Counterspell | Abjuration | — | Interrupt a creature casting a spell. | +| Daylight | Evocation | — | A 60-foot-radius sphere of bright light spreads out. | +| Dispel Magic | Abjuration | — | End one active spell affecting a creature, object, or effect. | +| Fear | Illusion | — | Creatures in the cone become frightened and drop what they’re holding. | +| Fireball | Evocation | 8d6 | A bright streak explodes into flame, dealing fire damage in a 20-foot radius. | +| Fly | Transmutation | — | The target gains a flying speed of 60 feet. | +| Haste | Transmutation | — | Double the target’s speed and grant an extra action. | +| Lightning Bolt | Evocation | 8d6 | A stroke of lightning blasts out in a line, dealing lightning damage. | +| Mass Healing Word | Evocation | — | Up to six creatures you can see regain hit points. | +| Nondetection | Abjuration | — | Hide a target from divination magic. | +| Protection from Energy | Abjuration | — | Resistance to one damage type of your choice. | +| Remove Curse | Abjuration | — | Lift a curse from a creature or object. | +| Revivify | Necromancy | — | A creature that died within the last minute returns to life with 1 hit point. | +| Sleet Storm | Conjuration | — | Freezing rain falls in a 40-foot-radius cylinder, icing the ground. | +| Slow | Transmutation | — | Up to six creatures are hindered, halving their speed and worse. | +| Spirit Guardians | Conjuration | 3d8 | Protective spirits swirl around you, damaging enemies that enter. | +| Stinking Cloud | Conjuration | — | A 20-foot-radius sphere of yellow, nauseating gas spreads out. | +| Water Breathing | Transmutation | — | Up to ten creatures can breathe underwater. | + +### Level 4 (13 spells) + +Needs character level 4. + +| Spell | School | Damage | What it does | +|---|---|---|---| +| Banishment | Abjuration | — | Send a creature to a harmless demiplane. | +| Blight | Necromancy | 8d8 | Necromantic energy withers a creature, dealing necrotic damage. | +| Confusion | Enchantment | — | Creatures in a 10-foot-radius sphere act randomly. | +| Dimension Door | Conjuration | — | Teleport yourself (and possibly a companion) to a spot you can visualize. | +| Fire Shield | Evocation | 2d8 | Wreathe yourself in flame that damages attackers and grants resistance. | +| Freedom of Movement | Abjuration | — | The target’s movement is unaffected by difficult terrain and restraints. | +| Greater Invisibility | Illusion | — | The target becomes invisible even while attacking. | +| Guardian of Faith | Conjuration | 20 | A Large spectral guardian appears and attacks enemies near it. | +| Ice Storm | Evocation | 2d8+4d6 | Hail hammers a 20-foot-radius cylinder, dealing bludgeoning and cold damage. | +| Polymorph | Transmutation | — | Transform a creature into a new form. | +| Stone Shape | Transmutation | — | Reshape a chunk of stone into a form you desire. | +| Stoneskin | Abjuration | — | The target gains resistance to nonmagical bludgeoning, piercing, and slashing damage. | +| Wall of Fire | Evocation | 5d8 | Conjure a wall of fire that damages creatures passing through it. | + +### Level 5 (15 spells) + +Needs character level 5. + +| Spell | School | Damage | What it does | +|---|---|---|---| +| Animate Objects | Transmutation | — | Up to ten nonmagical objects animate and fight for you. | +| Cloudkill | Conjuration | 5d8 | A 20-foot-radius sphere of poisonous, yellow-green fog billows out. | +| Cone of Cold | Evocation | 8d8 | A blast of cold air deals cold damage to everything in the cone. | +| Contagion | Necromancy | — | Infect a creature with a magical disease. | +| Dispel Evil and Good | Abjuration | — | Protection and the ability to banish otherworldly creatures. | +| Dominate Person | Enchantment | — | Attempt to beguile a humanoid and control its actions. | +| Flame Strike | Evocation | 8d6 | A column of divine fire roars down, dealing fire and radiant damage. | +| Greater Restoration | Abjuration | — | Undo a debilitating effect: reduced ability score, exhaustion, or curse. | +| Hold Monster | Enchantment | — | Paralyze one creature that fails a Wisdom save. | +| Insect Plague | Conjuration | 4d10 | A swarm of biting, stinging insects fills a 20-foot-radius sphere. | +| Legend Lore | Divination | — | Learn what you know, or have heard, about a name, place, or object. | +| Mass Cure Wounds | Evocation | — | Up to six creatures in a 30-foot-radius sphere regain hit points. | +| Raise Dead | Necromancy | — | Return a dead creature to life, as long as its body is mostly intact. | +| Wall of Force | Evocation | — | An invisible wall of force springs into existence, impenetrable to physical force. | +| Wall of Stone | Evocation | — | A nonmagical wall of solid stone springs into existence. | + diff --git a/docs/WEAPONS.md b/docs/WEAPONS.md new file mode 100644 index 0000000..ac5a49b --- /dev/null +++ b/docs/WEAPONS.md @@ -0,0 +1,280 @@ +# Weapons + +How weapons work in this app: the campaign's weapon pool, how a character +comes to hold a weapon, weapon levels, and how attack and damage numbers are +worked out. + +This describes the code as it stands. The formulas live in +`backend/src/game/calculations.js`; the built-in list is +`backend/src/game/data/weaponsLibrary.js`. Related: [ITEMS.md](ITEMS.md), +[SPELLS.md](SPELLS.md), [CHARACTERS.md](CHARACTERS.md). + +## Contents + +1. [The basics](#1-the-basics) +2. [The weapon pool](#2-the-weapon-pool) +3. [The built-in library](#3-the-built-in-library) +4. [Giving weapons to characters](#4-giving-weapons-to-characters) +5. [Weapon levels](#5-weapon-levels) +6. [How damage grows](#6-how-damage-grows) +7. [Attack and damage numbers](#7-attack-and-damage-numbers) +8. [Starting weapons](#8-starting-weapons) +9. [Weapons as rewards](#9-weapons-as-rewards) +10. [Permissions](#10-permissions) +11. [What is not modelled](#11-what-is-not-modelled) +12. [The complete weapon library](#12-the-complete-weapon-library) + +--- + +## 1. The basics + +- Every campaign has its own **weapon pool**. A weapon exists in one campaign + only. +- A character never owns a free-standing weapon: it holds a **copy** of a pool + entry, with its own quantity, level and equipped flag. +- The DM runs the pool and decides who gets what. Players can only equip and + unequip what they hold. + +## 2. The weapon pool + +The pool is the "Weapons Pool" card on the campaign page (DM only). + +| Field | What it is | +|---|---| +| Name | Free text, up to 80 characters | +| Base damage | Dice such as `1d8` or `2d6` — the damage at the weapon's starting level | +| Damage type | Free text: slashing, piercing, fire… | +| Attack ability | Strength, Dexterity, or Finesse (whichever of the two is higher for the wielder) | +| Starts at level | 1 to 9. The lowest level this weapon can be (section 5) | +| Growth | Standard, Powerful or Legendary: how fast the dice climb per level (section 6) | +| Starting option | Whether a brand-new character may pick it in the builder (section 8) | +| Properties, range | Stored for library weapons (light, thrown, 20/60 ft…) but not shown or used anywhere | + +- **Adding:** by hand with the "+ Add Weapon" form, or from the library. +- **Changing:** starting level, growth and the starting-option tick box can be + changed in the table. Name, damage, type and ability cannot be changed on + screen once created (the API accepts it); remove and re-add instead. +- **Removing:** the ✕ button. This takes the weapon away from **every + character holding it** and off every encounter's reward list. There is no + undo. +- The same weapon can be added twice; nothing stops duplicate names. + +## 3. The built-in library + +"📚 From Library" offers 37 standard weapons to copy into the pool: + +| Category | Count | Examples | +|---|---|---| +| Simple melee | 10 | Club 1d4, Dagger 1d4, Mace 1d6, Spear 1d6 | +| Simple ranged | 4 | Shortbow, Light Crossbow, Dart, Sling | +| Martial melee | 18 | Longsword 1d8, Rapier 1d8, Greataxe 1d12, Greatsword 2d6 | +| Martial ranged | 5 | Longbow, Heavy Crossbow, Hand Crossbow | + +A weapon added from the library arrives with starting level 1, Standard +growth, and **not** ticked as a starting option. Change those in the table +afterwards. Every library weapon is listed in +[section 12](#12-the-complete-weapon-library). + +## 4. Giving weapons to characters + +On a character's sheet, the DM picks a weapon from the pool and clicks Give. + +- It arrives at the weapon's starting level, quantity 1, unequipped. +- Giving a weapon the character already holds **adds to the stack**; the stack + keeps the level it has. A character holds one stack per weapon, so two + copies of the same weapon at different levels is not possible. +- The DM can take a weapon away with ✕ on the sheet. +- The owning player ticks **Equipped**. Equipped is a label only: unequipped + weapons still show their numbers, and nothing limits how many are equipped. + +**Passing a weapon on.** A character's owner (or the DM) can give a held +weapon to another character in the campaign from the "Give to Another +Character" card on the sheet. Some or all of the stack moves: it leaves the +giver and arrives with the recipient at the giver's level, unequipped. If the +recipient already holds that weapon, their stack grows and keeps its own +level. A recipient below the weapon's level holds it but cannot use it yet. + +## 5. Weapon levels + +This is a house rule of this app, not standard D&D. + +- Each held copy has a **level from 1 to 9**. Two characters can hold the same + weapon at different levels. +- Only the DM changes a copy's level, with the level picker beside it on the + sheet. Each option shows the damage at that level. +- A copy can never go below the pool entry's **starting level**. Raising a + pool entry's starting level lifts any copies below it and unequips them. + +**Who can use it.** A character must be at least the copy's level: + +| Character level | Can use weapons of level | +|---|---| +| 1 | 1 | +| 2 | 1–2 | +| 5 | 1–5 | +| 9 and above | 1–9 | + +A weapon above its holder's level is still held, but it shows "Requires level +N", cannot be equipped, and is left out of quick stats and encounters. If the +DM levels a weapon past its holder, or lowers the character's level, it is +unequipped automatically. + +## 6. How damage grows + +The dice in the pool are the damage at the weapon's starting level. Each level +above that moves the dice up a fixed ladder, in the smallest steps dice allow: + +| Rung | Dice | Average | +|---|---|---| +| 1 | 1d4 | 2.5 | +| 2 | 1d6 | 3.5 | +| 3 | 1d8 | 4.5 | +| 4 | 1d10 | 5.5 | +| 5 | 1d12 | 6.5 | +| 6 | 2d6 | 7 | +| 7 | 1d6+1d8 | 8 | +| 8 | 2d8 | 9 | +| 9 | 1d8+1d10 | 10 | +| 10 | 2d10 | 11 | +| 11 | 1d10+1d12 | 12 | +| 12 | 2d12 | 13 | +| 13 | 3d8 | 13.5 | +| … | adding a die each time the current dice max out | | + +Every rung is +1 average damage over the last, or +0.5 where a die is added. + +**Growth** sets how many rungs a weapon climbs per level: + +| Growth | Rungs per level | A 1d6 weapon at levels 1, 2, 3, 4 | At level 9 | +|---|---|---|---| +| Standard | 1 | 1d6, 1d8, 1d10, 1d12 | 2d10 | +| Powerful | 2 | 1d6, 1d10, 2d6, 2d8 | 1d10+2d12 | +| Legendary | 3 | 1d6, 1d12, 2d8, 1d10+1d12 | 4d12 | + +A weapon with a higher starting level counts from there: a 2d6 greatsword that +starts at level 3 with Standard growth is 2d6 at level 3, 1d6+1d8 at level 4 +and 2d8 at level 5. + +- At its starting level a weapon always shows its dice exactly as typed. +- Dice that are not on the ladder (`1d4+1`, `2d4+2`) climb from the highest + rung that is not stronger than them: `2d4+2` (average 7) continues from 2d6. +- Dice the app cannot read (free text such as "special") never change. + +## 7. Attack and damage numbers + +| Number | Formula | +|---|---| +| Attack bonus | Ability modifier + proficiency bonus | +| Damage | The dice at the copy's level + ability modifier | + +- The ability modifier is Strength, Dexterity, or the higher of the two for a + Finesse weapon. +- The weapon's level changes the **dice only**, never the bonuses. +- Every character is treated as proficient with every weapon. + +These numbers appear on the character sheet, in the quick-stats drawer, and +on the character's card in an encounter. + +## 8. Starting weapons + +In the builder's equipment step a new character can pick weapons that are: + +- ticked as a **starting option** in the pool, and +- **starting level 1** (a new character is level 1). + +Starting weapons and starting items share the campaign's "starting items" +allowance. They arrive at level 1, unequipped. + +## 9. Weapons as rewards + +On an encounter the DM can line up a weapon as a reward, at a chosen level +(not below its starting level) and quantity, and later award it to a +character. Awarding adds it to what the character holds, exactly as giving it +on the sheet would. See [ENCOUNTERS.md](ENCOUNTERS.md). + +## 10. Permissions + +| Action | DM | Owning player | Other players | +|---|---|---|---| +| See the pool and the library | Yes | Yes | Yes | +| Add, change or remove pool entries | Yes | No | No | +| Give a weapon from the pool, or take one away | Yes | No | No | +| Give a held weapon to another character | Yes | Yes | No | +| Change a held weapon's level or quantity | Yes | No | No | +| Equip or unequip | Yes | Yes, if the character can use it | No | +| See a character's weapons | Yes | Yes | Yes | + +## 11. What is not modelled + +- Weapon proficiency by class (everyone is proficient with everything) +- Properties: two-handed, versatile, light, reach, loading, thrown +- Range and ammunition +- Critical hits, advantage, and rolling the attack itself (use the dice roller) +- Magic bonuses such as +1 weapons (use a higher level or growth instead) +- Price and weight + +## 12. The complete weapon library + +Every weapon "📚 From Library" offers. Base damage is the damage at level 1. +Properties and range are carried into the campaign but not shown or used. + +This list is written from the app's own data by `npm run docs:lists` (in `/backend`). Re-run it after changing the data; do not edit the list by hand. + + +### Simple Melee (10) + +| Weapon | Base damage | Type | Attacks with | Properties | Range | +|---|---|---|---|---|---| +| Club | 1d4 | bludgeoning | Strength | light | — | +| Dagger | 1d4 | piercing | Strength or Dexterity (finesse) | finesse, light, thrown | 20/60 ft | +| Greatclub | 1d8 | bludgeoning | Strength | two-handed | — | +| Handaxe | 1d6 | slashing | Strength | light, thrown | 20/60 ft | +| Javelin | 1d6 | piercing | Strength | thrown | 30/120 ft | +| Light Hammer | 1d4 | bludgeoning | Strength | light, thrown | 20/60 ft | +| Mace | 1d6 | bludgeoning | Strength | — | — | +| Quarterstaff | 1d6 | bludgeoning | Strength | versatile (1d8) | — | +| Sickle | 1d4 | slashing | Strength | light | — | +| Spear | 1d6 | piercing | Strength | thrown, versatile (1d8) | 20/60 ft | + +### Simple Ranged (4) + +| Weapon | Base damage | Type | Attacks with | Properties | Range | +|---|---|---|---|---|---| +| Light Crossbow | 1d8 | piercing | Dexterity | ammunition, loading, two-handed | 80/320 ft | +| Dart | 1d4 | piercing | Strength or Dexterity (finesse) | finesse, thrown | 20/60 ft | +| Shortbow | 1d6 | piercing | Dexterity | ammunition, two-handed | 80/320 ft | +| Sling | 1d4 | bludgeoning | Dexterity | ammunition | 30/120 ft | + +### Martial Melee (18) + +| Weapon | Base damage | Type | Attacks with | Properties | Range | +|---|---|---|---|---|---| +| Battleaxe | 1d8 | slashing | Strength | versatile (1d10) | — | +| Flail | 1d8 | bludgeoning | Strength | — | — | +| Glaive | 1d10 | slashing | Strength | heavy, reach, two-handed | — | +| Greataxe | 1d12 | slashing | Strength | heavy, two-handed | — | +| Greatsword | 2d6 | slashing | Strength | heavy, two-handed | — | +| Halberd | 1d10 | slashing | Strength | heavy, reach, two-handed | — | +| Lance | 1d12 | piercing | Strength | reach, special | — | +| Longsword | 1d8 | slashing | Strength | versatile (1d10) | — | +| Maul | 2d6 | bludgeoning | Strength | heavy, two-handed | — | +| Morningstar | 1d8 | piercing | Strength | — | — | +| Pike | 1d10 | piercing | Strength | heavy, reach, two-handed | — | +| Rapier | 1d8 | piercing | Strength or Dexterity (finesse) | finesse | — | +| Scimitar | 1d6 | slashing | Strength or Dexterity (finesse) | finesse, light | — | +| Shortsword | 1d6 | piercing | Strength or Dexterity (finesse) | finesse, light | — | +| Trident | 1d6 | piercing | Strength | thrown, versatile (1d8) | 20/60 ft | +| War Pick | 1d8 | piercing | Strength | — | — | +| Warhammer | 1d8 | bludgeoning | Strength | versatile (1d10) | — | +| Whip | 1d4 | slashing | Strength or Dexterity (finesse) | finesse, reach | — | + +### Martial Ranged (5) + +| Weapon | Base damage | Type | Attacks with | Properties | Range | +|---|---|---|---|---|---| +| Blowgun | 1 | piercing | Dexterity | ammunition, loading | 25/100 ft | +| Hand Crossbow | 1d6 | piercing | Dexterity | ammunition, light, loading | 30/120 ft | +| Heavy Crossbow | 1d10 | piercing | Dexterity | ammunition, heavy, loading, two-handed | 100/400 ft | +| Longbow | 1d8 | piercing | Dexterity | ammunition, heavy, two-handed | 150/600 ft | +| Net | - | special | Dexterity | special, thrown | 5/15 ft | + diff --git a/frontend/src/api/queries.ts b/frontend/src/api/queries.ts index 8874406..36833ef 100644 --- a/frontend/src/api/queries.ts +++ b/frontend/src/api/queries.ts @@ -1,6 +1,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { apiClient } from './client'; import type { + BuildOptions, Campaign, CampaignLibrary, CampaignMemberSummary, @@ -8,11 +9,14 @@ import type { CharacterSummary, DiceMode, Encounter, + EncounterMode, EncounterParticipant, - InventoryItem, + GoldTransaction, + Item, Location, Monster, Note, + Npc, QuickStats, Spell, Weapon, @@ -120,10 +124,11 @@ export function useCharacter(characterId: string | undefined) { }); } +// `gold` is deliberately not patchable — it only moves through useAdjustGold. export function usePatchCharacter(characterId: string) { const qc = useQueryClient(); return useMutation({ - mutationFn: async (data: Partial) => + mutationFn: async (data: Partial>) => (await apiClient.patch<{ character: CharacterDetail }>(`/characters/${characterId}`, data)).data.character, onSuccess: (character) => { qc.setQueryData(['character', characterId], character); @@ -140,6 +145,38 @@ export function useDeleteCharacter(campaignId: string) { }); } +// What one character can hand to another. Whatever is given leaves the giver. +export type Gift = + | { kind: 'gold'; amount: number } + | { kind: 'weapon' | 'item'; id: string; quantity: number } + | { kind: 'spell'; id: string }; + +export function useGive(characterId: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async (gift: Gift & { toCharacterId: string }) => + (await apiClient.post<{ character: CharacterDetail }>(`/characters/${characterId}/give`, gift)).data.character, + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['character'] }); // both sheets, and both money logs + qc.invalidateQueries({ queryKey: ['campaign'] }); + }, + }); +} + +export function useCopyCharacter(characterId: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async (targetCampaignId: string) => + (await apiClient.post<{ character: CharacterDetail }>(`/characters/${characterId}/copy`, { targetCampaignId })).data + .character, + onSuccess: (character) => { + qc.setQueryData(['character', character.id], character); + // The copy can add missing weapons/spells to the target campaign's pools. + qc.invalidateQueries({ queryKey: ['campaign', character.campaignId] }); + }, + }); +} + export function useQuickStats(characterId: string | undefined, enabled: boolean) { return useQuery({ queryKey: ['character', characterId, 'quick-stats'], @@ -153,6 +190,14 @@ export function useQuickStats(characterId: string | undefined, enabled: boolean) // Character build flow // -------------------------------------------------------------------------- +export function useBuildOptions() { + return useQuery({ + queryKey: ['build-options'], + staleTime: Infinity, // fixed lists — they never change while the app is open + queryFn: async () => (await apiClient.get('/characters/build/options')).data, + }); +} + function invalidateCharacter(qc: ReturnType, characterId: string) { qc.invalidateQueries({ queryKey: ['character', characterId] }); } @@ -191,6 +236,16 @@ export function useBuildChoose(characterId: string) { }); } +// Steps back one step so its choice can be changed. Dice are never re-rolled. +export function useBuildBack(characterId: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async () => + (await apiClient.post<{ buildStage: string; buildState: Record }>(`/characters/${characterId}/build/back`)).data, + onSuccess: () => invalidateCharacter(qc, characterId), + }); +} + export function useBuildFinalize(characterId: string) { const qc = useQueryClient(); return useMutation({ @@ -208,6 +263,8 @@ export function useBuildFinalize(characterId: string) { // Weapons / inventory / spells on a character // -------------------------------------------------------------------------- +// Handing out, removing and re-counting gear is DM-only on the server; the +// owning player can only toggle equipped / prepared. export function useAssignWeapon(characterId: string) { const qc = useQueryClient(); return useMutation({ @@ -217,20 +274,29 @@ export function useAssignWeapon(characterId: string) { }); } +export function useRemoveCharacterWeapon(characterId: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async (weaponId: string) => apiClient.delete(`/characters/${characterId}/weapons/${weaponId}`), + onSuccess: () => invalidateCharacter(qc, characterId), + }); +} + export function usePatchCharacterWeapon(characterId: string) { const qc = useQueryClient(); return useMutation({ - mutationFn: async ({ weaponId, ...data }: { weaponId: string; equipped?: boolean; quantity?: number }) => + mutationFn: async ({ weaponId, ...data }: { weaponId: string; equipped?: boolean; quantity?: number; level?: number }) => (await apiClient.patch(`/characters/${characterId}/weapons/${weaponId}`, data)).data, onSuccess: () => invalidateCharacter(qc, characterId), }); } -export function useAddInventoryItem(characterId: string) { +// itemId here is the campaign pool item's id, as with weapons and spells. +export function useAssignItem(characterId: string) { const qc = useQueryClient(); return useMutation({ - mutationFn: async (data: { name: string; description?: string; quantity?: number }) => - (await apiClient.post<{ item: InventoryItem }>(`/characters/${characterId}/inventory`, data)).data.item, + mutationFn: async (data: { itemId: string; quantity?: number }) => + (await apiClient.post(`/characters/${characterId}/inventory`, data)).data, onSuccess: () => invalidateCharacter(qc, characterId), }); } @@ -238,13 +304,13 @@ export function useAddInventoryItem(characterId: string) { export function usePatchInventoryItem(characterId: string) { const qc = useQueryClient(); return useMutation({ - mutationFn: async ({ itemId, ...data }: { itemId: string; quantity?: number; equipped?: boolean }) => + mutationFn: async ({ itemId, ...data }: { itemId: string; quantity?: number; equipped?: boolean; level?: number }) => (await apiClient.patch(`/characters/${characterId}/inventory/${itemId}`, data)).data, onSuccess: () => invalidateCharacter(qc, characterId), }); } -export function useDeleteInventoryItem(characterId: string) { +export function useRemoveInventoryItem(characterId: string) { const qc = useQueryClient(); return useMutation({ mutationFn: async (itemId: string) => apiClient.delete(`/characters/${characterId}/inventory/${itemId}`), @@ -270,6 +336,38 @@ export function usePatchCharacterSpell(characterId: string) { }); } +export function useRemoveCharacterSpell(characterId: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async (spellId: string) => apiClient.delete(`/characters/${characterId}/spells/${spellId}`), + onSuccess: () => invalidateCharacter(qc, characterId), + }); +} + +// -------------------------------------------------------------------------- +// Money tracker +// -------------------------------------------------------------------------- + +export function useGoldLedger(characterId: string | undefined) { + return useQuery({ + queryKey: ['character', characterId, 'gold'], + enabled: Boolean(characterId), + queryFn: async () => + (await apiClient.get<{ gold: number; transactions: GoldTransaction[] }>(`/characters/${characterId}/gold`)).data + .transactions, + }); +} + +// amount is signed: positive = gained, negative = spent. +export function useAdjustGold(characterId: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async (data: { amount: number; reason?: string }) => + (await apiClient.post<{ gold: number; transaction: GoldTransaction }>(`/characters/${characterId}/gold`, data)).data, + onSuccess: () => invalidateCharacter(qc, characterId), // prefix match also refreshes the ledger + }); +} + // -------------------------------------------------------------------------- // Campaign weapons / spells / monsters pools // -------------------------------------------------------------------------- @@ -291,6 +389,58 @@ export function useCreateWeapon(campaignId: string) { }); } +// Edits (or, with useDeletePoolEntry, removes) one entry of a campaign pool. +// Used for the "starting option" toggle on weapons, spells and items. +type Pool = 'weapons' | 'spells' | 'items' | 'npcs'; + +export function usePatchPoolEntry(campaignId: string, pool: Pool) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async ({ + id, + ...data + }: { + id: string; + isStartingOption?: boolean; + damageDice?: string | null; + damageScaling?: number; + minLevel?: number; + name?: string; + description?: string | null; + }) => + (await apiClient.patch(`/campaigns/${campaignId}/${pool}/${id}`, data)).data, + onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, pool] }), + }); +} + +export function useDeletePoolEntry(campaignId: string, pool: Pool) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async (id: string) => apiClient.delete(`/campaigns/${campaignId}/${pool}/${id}`), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['campaign', campaignId, pool] }); + qc.invalidateQueries({ queryKey: ['character'] }); // characters holding it just lost it + }, + }); +} + +export function useCampaignItems(campaignId: string | undefined) { + return useQuery({ + queryKey: ['campaign', campaignId, 'items'], + enabled: Boolean(campaignId), + queryFn: async () => (await apiClient.get<{ items: Item[] }>(`/campaigns/${campaignId}/items`)).data.items, + }); +} + +export function useCreateItem(campaignId: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async (data: Omit) => + (await apiClient.post<{ item: Item }>(`/campaigns/${campaignId}/items`, data)).data.item, + onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'items'] }), + }); +} + export function useCampaignSpells(campaignId: string | undefined) { return useQuery({ queryKey: ['campaign', campaignId, 'spells'], @@ -308,10 +458,11 @@ export function useCreateSpell(campaignId: string) { }); } -export function useCampaignMonsters(campaignId: string | undefined) { +// Monster stat blocks are DM-only on the server, so only the DM asks for them. +export function useCampaignMonsters(campaignId: string | undefined, isDM: boolean) { return useQuery({ queryKey: ['campaign', campaignId, 'monsters'], - enabled: Boolean(campaignId), + enabled: Boolean(campaignId) && isDM, queryFn: async () => (await apiClient.get<{ monsters: Monster[] }>(`/campaigns/${campaignId}/monsters`)).data.monsters, }); @@ -422,9 +573,8 @@ export function useCampaignEncounters(campaignId: string | undefined) { export function useCreateEncounter(campaignId: string) { const qc = useQueryClient(); return useMutation({ - mutationFn: async (name: string) => - (await apiClient.post<{ encounter: Encounter }>(`/campaigns/${campaignId}/encounters`, { name })).data - .encounter, + mutationFn: async (data: { name: string; mode?: EncounterMode }) => + (await apiClient.post<{ encounter: Encounter }>(`/campaigns/${campaignId}/encounters`, data)).data.encounter, onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'encounters'] }), }); } @@ -440,7 +590,7 @@ export function useEncounter(encounterId: string | undefined) { export function useAddParticipant(encounterId: string) { const qc = useQueryClient(); return useMutation({ - mutationFn: async (data: { characterId?: string; monsterId?: string; displayName?: string; initiative?: number }) => + mutationFn: async (data: { characterId?: string; monsterId?: string; npcId?: string; displayName?: string; initiative?: number }) => (await apiClient.post(`/encounters/${encounterId}/participants`, data)).data, onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }), }); @@ -475,13 +625,91 @@ export function useAdvanceRound(encounterId: string) { export function usePatchEncounter(encounterId: string) { const qc = useQueryClient(); return useMutation({ - mutationFn: async (data: { status?: EncounterStatusInput; name?: string }) => - (await apiClient.patch(`/encounters/${encounterId}`, data)).data, - onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }), + mutationFn: async (data: { + status?: EncounterStatusInput; + mode?: EncounterMode; + name?: string; + description?: string | null; + dmNotes?: string | null; + }) => (await apiClient.patch(`/encounters/${encounterId}`, data)).data, + onSuccess: (_data, variables) => { + qc.invalidateQueries({ queryKey: ['encounter', encounterId] }); + // The campaign page lists encounters by name, mode and status. + if (variables.status || variables.mode || variables.name) qc.invalidateQueries({ queryKey: ['campaign'] }); + }, }); } type EncounterStatusInput = 'PLANNING' | 'ACTIVE' | 'COMPLETE'; +export function useNextTurn(encounterId: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async () => (await apiClient.post(`/encounters/${encounterId}/next-turn`)).data, + onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }), + }); +} + +// -------------------------------------------------------------------------- +// Encounter rewards — DM lines loot up, then awards it to a character +// -------------------------------------------------------------------------- + +export type NewReward = + | { type: 'GOLD'; gold: number; note?: string } + | { type: 'WEAPON'; weaponId: string; quantity?: number; level?: number; note?: string } + | { type: 'ITEM'; itemId: string; quantity?: number; level?: number; note?: string }; + +export function useAddReward(encounterId: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async (data: NewReward) => (await apiClient.post(`/encounters/${encounterId}/rewards`, data)).data, + onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }), + }); +} + +export function useDeleteReward(encounterId: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async (rewardId: string) => apiClient.delete(`/encounters/${encounterId}/rewards/${rewardId}`), + onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }), + }); +} + +// Awarding is what actually changes the character: a gold ledger entry, or +// the weapon/item added to what they hold. +export function useAwardReward(encounterId: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async ({ rewardId, ...target }: { rewardId: string } & ({ characterId: string } | { split: true })) => + (await apiClient.post(`/encounters/${encounterId}/rewards/${rewardId}/award`, target)).data, + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['encounter', encounterId] }); + qc.invalidateQueries({ queryKey: ['character'] }); + qc.invalidateQueries({ queryKey: ['campaign'] }); + }, + }); +} + +// -------------------------------------------------------------------------- +// NPCs — a DM-only pool; players meet them through encounters +// -------------------------------------------------------------------------- + +export function useCampaignNpcs(campaignId: string | undefined, isDM: boolean) { + return useQuery({ + queryKey: ['campaign', campaignId, 'npcs'], + enabled: Boolean(campaignId) && isDM, + queryFn: async () => (await apiClient.get<{ npcs: Npc[] }>(`/campaigns/${campaignId}/npcs`)).data.npcs, + }); +} + +export function useCreateNpc(campaignId: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: async (data: Partial> & { name: string }) => + (await apiClient.post<{ npc: Npc }>(`/campaigns/${campaignId}/npcs`, data)).data.npc, + onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'npcs'] }), + }); +} + // -------------------------------------------------------------------------- // Notes // -------------------------------------------------------------------------- diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index 61bd64e..397ecc0 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -33,11 +33,50 @@ export type BuildStage = | 'ROLLING_MOTIVATION' | 'ASSIGNING_SCORES' | 'ASSIGNING_PROFICIENCIES' + | 'CHOOSING_ABILITIES' + | 'CHOOSING_BACKGROUND' + | 'CHOOSING_APPEARANCE' | 'CHOOSING_EQUIPMENT' | 'COMPLETE'; export type DiceMode = 'DIGITAL' | 'PHYSICAL'; +// The fixed lists the builder's story steps are made of (served by the API so +// the page never keeps its own copy). +export interface NamedAbility { + name: string; + text: string; +} + +export interface PickOption { + key: string; + label: string; + text?: string; +} + +// One question in the background or appearance step; the player picks between +// `min` and `max` of its options. +export interface PickGroup { + key: string; + label: string; + prompt: string; + min: number; + max: number; + options: PickOption[]; +} + +export type Picks = Record; + +export interface BuildOptions { + motivations: { key: number; label: string }[]; + speciesTraits: Record; + classFeatures: Record; + talents: (NamedAbility & { key: string })[]; + talentPicks: number; + background: PickGroup[]; + appearance: PickGroup[]; +} + export interface User { id: string; email: string; @@ -77,6 +116,7 @@ export interface CharacterSummary { buildStage: BuildStage; currentHp: number; tempHp: number; + gold: number; maxHp: number | null; armorClass: number | null; currentLocationId: string | null; @@ -121,6 +161,12 @@ export interface Weapon { properties: string[]; rangeNormal: number | null; rangeLong: number | null; + // damageDice is the damage at minLevel (the level the weapon starts at); a + // held copy climbs this many rungs of the damage ladder per level above + // that (1 standard, 2 powerful, 3 legendary). + damageScaling: number; + minLevel: number; + isStartingOption: boolean; } export interface CharacterWeapon { @@ -129,6 +175,9 @@ export interface CharacterWeapon { weaponId: string; quantity: number; equipped: boolean; + level: number; + scaledDamageDice: string; // the dice at this copy's level + usable: boolean; // false while the character is below this copy's level weapon: Weapon; } @@ -142,6 +191,8 @@ export interface Spell { range: string | null; duration: string | null; description: string | null; + damageDice: string | null; + isStartingOption: boolean; } export interface CharacterSpell { @@ -149,16 +200,42 @@ export interface CharacterSpell { characterId: string; spellId: string; prepared: boolean; + usable: boolean; // false while the character is below the spell's level spell: Spell; } +// An entry in the campaign's DM-managed item pool. +export interface Item { + id: string; + campaignId: string; + name: string; + description: string | null; + damageDice: string | null; // optional dice (damage, healing…) at its starting level + damageScaling: number; + minLevel: number; + isStartingOption: boolean; +} + export interface InventoryItem { id: string; characterId: string; - name: string; - description: string | null; + itemId: string; quantity: number; equipped: boolean; + level: number; + scaledDamageDice: string | null; + usable: boolean; + item: Item; +} + +export interface GoldTransaction { + id: string; + characterId: string; + amount: number; // signed: positive = gained, negative = spent + balanceAfter: number; + reason: string | null; + createdAt: string; + createdBy: { displayName: string } | null; } export interface SkillProficiency { @@ -230,10 +307,47 @@ export interface Monster { } export type EncounterStatus = 'PLANNING' | 'ACTIVE' | 'COMPLETE'; +export type EncounterMode = 'BATTLE' | 'QUEST'; +export type NpcDisposition = 'FRIENDLY' | 'NEUTRAL' | 'HOSTILE'; + +// What players see of an NPC in an encounter. +export interface NpcPublic { + id: string; + name: string; + role: string | null; + disposition: NpcDisposition; + description: string | null; +} + +// The DM's full record. dmNotes and the combat stats never reach a player. +export interface Npc extends NpcPublic { + dmNotes: string | null; + ac: number | null; + maxHp: number | null; + attackBonus: number | null; + damageDice: string | null; +} + +export interface EncounterReward { + id: string; + encounterId: string; + type: 'GOLD' | 'WEAPON' | 'ITEM'; + gold: number | null; + weaponId: string | null; + itemId: string | null; + quantity: number; + level: number; + note: string | null; + awardedTo: string | null; + awardedAt: string | null; + weapon: Weapon | null; + item: Item | null; +} export interface CombatWeapon { characterWeaponId: string; name: string; + level: number; equipped: boolean; quantity: number; attackBonus: number; @@ -246,11 +360,24 @@ export interface CombatSpell { characterSpellId: string; name: string; level: number; + description: string | null; + damageDice: string | null; prepared: boolean; } export interface CharacterCombatInfo { + level: number; + species: Species | null; + characterClass: CharacterClass | null; armorClass: number; + tempHp: number; + speed: number; + initiativeBonus: number; + passivePerception: number; + proficiencyBonus: number; + abilities: Record; + saves: Record; + specialAbilities: string | null; weapons: CombatWeapon[]; spells: CombatSpell[]; spellcasting: { ability: Ability; saveDC: number; attackBonus: number } | null; @@ -267,8 +394,12 @@ export interface EncounterParticipant { maxHp: number; conditions: string[]; isMonster: boolean; + kind: 'CHARACTER' | 'MONSTER' | 'NPC'; + npcId: string | null; character?: { id: string; name: string } | null; - monster?: { id: string; name: string } | null; + // The DM gets the whole stat block; players only the id and name. + monster?: ({ id: string; name: string } & Partial) | null; + npc?: (NpcPublic & Partial) | null; characterCombatInfo?: CharacterCombatInfo; } @@ -276,10 +407,15 @@ export interface Encounter { id: string; campaignId: string; name: string; + mode: EncounterMode; status: EncounterStatus; currentRound: number; + activeParticipantId: string | null; + description: string | null; + dmNotes?: string | null; // DM only createdAt: string; participants?: EncounterParticipant[]; + rewards?: EncounterReward[]; // players only receive the awarded ones } export interface Note { @@ -314,6 +450,7 @@ export interface LibrarySpell { range: string | null; duration: string | null; description: string | null; + damageDice?: string; // default damage; absent for spells that deal none classes: CharacterClass[]; } @@ -346,6 +483,7 @@ export interface QuickStatsWeapon { characterWeaponId: string; weaponId: string; name: string; + level: number; equipped: boolean; quantity: number; attackBonus: number; diff --git a/frontend/src/components/DiceRoller.tsx b/frontend/src/components/DiceRoller.tsx new file mode 100644 index 0000000..eeb7019 --- /dev/null +++ b/frontend/src/components/DiceRoller.tsx @@ -0,0 +1,166 @@ +import { useEffect, useState } from 'react'; +import { fmtMod } from '../lib/format'; + +const DICE = [4, 6, 8, 10, 12, 20, 100]; +const MAX_DICE = 20; +const HISTORY_LENGTH = 8; + +interface Roll { + id: number; + sides: number; + modifier: number; + dice: number[]; + total: number; +} + +// One fair roll of an n-sided die. Uses the browser's cryptographic random +// source, discarding values that would make some faces slightly likelier. +function rollDie(sides: number): number { + const limit = Math.floor(0x100000000 / sides) * sides; + const buffer = new Uint32Array(1); + do { + crypto.getRandomValues(buffer); + } while (buffer[0] >= limit); + return (buffer[0] % sides) + 1; +} + +function notation(count: number, sides: number, modifier: number): string { + return `${count}d${sides}${modifier ? fmtMod(modifier) : ''}`; +} + +// A table-side dice roller, reachable from every page. These rolls are for +// the player's own use at the table: they are not sent to the server and do +// not feed the character builder, whose dice stay locked in server-side. +export function DiceRoller() { + const [open, setOpen] = useState(false); + const [sides, setSides] = useState(20); + const [count, setCount] = useState(1); + const [modifier, setModifier] = useState(0); + const [history, setHistory] = useState([]); + + useEffect(() => { + if (!open) return; + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false); + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, [open]); + + const latest = history[0]; + + function roll() { + const dice = Array.from({ length: count }, () => rollDie(sides)); + const total = dice.reduce((sum, d) => sum + d, 0) + modifier; + setHistory((prev) => [{ id: (prev[0]?.id ?? 0) + 1, sides, modifier, dice, total }, ...prev].slice(0, HISTORY_LENGTH)); + } + + // The natural 20 and natural 1 only mean something on a single d20. + const natural = latest && latest.sides === 20 && latest.dice.length === 1 ? latest.dice[0] : null; + + return ( + <> + + + {open && ( +

+
+
+ Roll Dice +
+ +
+ +
+ {DICE.map((d) => ( + + ))} +
+ +
+
+ Dice + + + {count} + + +
+ +
+ + + +
+ {latest ? ( + <> + {/* Keyed on the roll so the pop animation replays every time, even on a repeat result. */} +
+ {latest.total} +
+ {natural === 20 &&
Natural 20!
} + {natural === 1 &&
Natural 1
} + {(latest.dice.length > 1 || latest.modifier !== 0) && ( +
+ {latest.dice.join(' + ')} + {latest.modifier !== 0 && ` ${latest.modifier > 0 ? '+' : '−'} ${Math.abs(latest.modifier)}`} = {latest.total} +
+ )} + + ) : ( +

+ Pick a die and roll. +

+ )} +
+ + {history.length > 1 && ( + <> +
+ Earlier rolls + +
+ {history.slice(1).map((r) => ( +
+ + {notation(r.dice.length, r.sides, r.modifier)} + {r.dice.length > 1 && ({r.dice.join(', ')})} + + {r.total} +
+ ))} + + )} +
+ )} + + ); +} diff --git a/frontend/src/components/InfoTip.tsx b/frontend/src/components/InfoTip.tsx index ac82fb7..39daad1 100644 --- a/frontend/src/components/InfoTip.tsx +++ b/frontend/src/components/InfoTip.tsx @@ -22,12 +22,24 @@ export const STAT_HELP: Record = { DAMAGE_BONUS: 'Damage Bonus — added to the weapon’s damage dice on a hit. Same ability modifier as the attack bonus.', CHALLENGE_RATING: 'Challenge Rating — a rough measure of how dangerous a monster is on its own, used to gauge encounter difficulty.', HIT_DICE: 'Hit Dice — the die your class rolls (or uses the fixed average of) when your HP increases at each level.', + // Character builder + DICE_MODE: 'Digital dice are rolled by the app. Physical dice are rolled by you at the table, and you type in what came up. Either way a roll is final once it is made.', + WILDCARD: 'Wildcard — the luckiest result. Instead of choosing between two options you may pick any of them.', + SPECIES_BONUS: 'Species bonus — points your species adds on top of the ability scores you roll. They are added automatically.', + SAVE_PROFICIENCY: 'Each class is trained in two saving throws. On those you add your proficiency bonus when resisting spells, traps and other effects.', + KEY_ABILITY: 'Key abilities — the scores this class leans on most. Put your best rolls here.', + SPELLCASTING: 'Spellcasting ability — the score that powers this class’s spells. A higher score makes your spells harder to resist and more accurate.', + ROLL_4D6: 'Roll four six-sided dice and add up the best three (the lowest is dropped). Do that six times to get six scores, usually between 8 and 16.', + STARTING_EQUIPMENT: 'Your DM chooses which weapons, items and spells are available to brand-new characters, and how many you may take.', + DAMAGE_DICE: 'Damage dice — what you roll when this weapon hits. “1d8” means one eight-sided die. Your Strength or Dexterity modifier is added on top.', }; -export function InfoTip({ term, label = 'What is this?' }: { term: keyof typeof STAT_HELP; label?: string }) { +// `term` looks up a standard explanation above; `text` supplies a one-off +// (a species, a skill, an ability) without adding it to the shared list. +export function InfoTip({ term, text: custom, label = 'What is this?' }: { term?: keyof typeof STAT_HELP; text?: string; label?: string }) { const [open, setOpen] = useState(false); const id = useId(); - const text = STAT_HELP[term]; + const text = custom ?? (term ? STAT_HELP[term] : undefined); if (!text) return null; return ( diff --git a/frontend/src/components/Layout.tsx b/frontend/src/components/Layout.tsx index 7920d71..00acf2a 100644 --- a/frontend/src/components/Layout.tsx +++ b/frontend/src/components/Layout.tsx @@ -1,5 +1,6 @@ import { Link, Outlet } from 'react-router-dom'; import { useAuth } from '../auth/AuthContext'; +import { DiceRoller } from './DiceRoller'; export function Layout() { const { user, logout } = useAuth(); @@ -27,6 +28,7 @@ export function Layout() {
+ ); } diff --git a/frontend/src/components/QuickStatsDrawer.tsx b/frontend/src/components/QuickStatsDrawer.tsx index 49efc65..c12328a 100644 --- a/frontend/src/components/QuickStatsDrawer.tsx +++ b/frontend/src/components/QuickStatsDrawer.tsx @@ -72,7 +72,7 @@ export function QuickStatsDrawer({ characterId, onClose }: { characterId: string {w.name} {w.equipped && equipped}

- {w.damageDice} {w.damageType} {fmtMod(w.damageBonus)} + Lv {w.level} · {w.damageDice} {w.damageType} {fmtMod(w.damageBonus)}

diff --git a/frontend/src/hooks/useCampaignSocket.ts b/frontend/src/hooks/useCampaignSocket.ts index 84d36de..e625431 100644 --- a/frontend/src/hooks/useCampaignSocket.ts +++ b/frontend/src/hooks/useCampaignSocket.ts @@ -28,6 +28,7 @@ export function useCampaignSocket(campaignId: string | undefined) { const onCharacterUpdated = () => { qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'characters'] }); qc.invalidateQueries({ queryKey: ['character'] }); + qc.invalidateQueries({ queryKey: ['encounter'] }); // a character combatant shows the sheet HP }; const onCharacterCreated = () => { qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'characters'] }); diff --git a/frontend/src/index.css b/frontend/src/index.css index 2ea4fb1..ce42ebb 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -733,3 +733,456 @@ table.data-table tbody tr:hover { font-size: 2.2rem; } } + +/* ---------------------------------------------------------------------- */ +/* Encounter screen */ +/* ---------------------------------------------------------------------- */ + +.badge-friendly { + border-color: var(--success); + color: var(--success-strong); +} +.badge-neutral { + border-color: var(--border); + color: var(--text-muted); +} +.badge-hostile { + border-color: var(--danger); + color: var(--danger-strong); +} +.badge-live { + border-color: var(--success); + color: var(--success-strong); +} + +.encounter-layout { + display: grid; + grid-template-columns: 1fr; + gap: 1.25rem; + align-items: start; +} +@media (min-width: 960px) { + .encounter-layout { + grid-template-columns: minmax(0, 1fr) 330px; + } +} + +.section-label { + font-family: var(--font-display); + color: var(--text-muted); + font-size: 0.8rem; + text-transform: uppercase; + letter-spacing: 0.1em; + margin: 0 0 0.5rem; +} +.card + .section-label, +.empty-state + .section-label { + margin-top: 1.5rem; +} + +/* One combatant. The left edge is colour-coded by who it is. */ +.combatant { + border-left: 4px solid var(--border); + padding: 1rem 1.1rem; +} +.combatant-character { + border-left-color: var(--arcane); +} +.combatant-monster { + border-left-color: var(--danger); +} +.combatant-npc { + border-left-color: var(--success); +} +.combatant.is-active { + border-color: var(--accent-strong); + box-shadow: 0 0 0 1px var(--accent-strong), 0 0 22px rgba(201, 162, 39, 0.25), var(--shadow-deep); +} +.combatant.is-down { + opacity: 0.6; +} +.combatant-name { + font-family: var(--font-display); + font-size: 1.1rem; + color: var(--text); +} +.combatant-sub { + color: var(--text-muted); + font-size: 0.85rem; +} +.turn-marker { + color: var(--accent-strong); + font-family: var(--font-display); + font-size: 0.75rem; + text-transform: uppercase; + letter-spacing: 0.08em; +} + +.stat-chips { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; +} +.stat-chip { + display: inline-flex; + align-items: baseline; + gap: 0.35rem; + background: var(--bg-inset); + border: 1px solid var(--border-soft); + border-radius: 6px; + padding: 0.2rem 0.55rem; + font-size: 0.9rem; +} +.stat-chip span { + font-size: 0.65rem; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--text-dim); +} +.stat-chip b { + color: var(--accent-strong); + font-weight: 600; +} + +.condition-chip { + display: inline-flex; + align-items: center; + gap: 0.25rem; + padding: 0.15rem 0.5rem; + border-radius: 999px; + font-size: 0.8rem; + border: 1px solid var(--danger); + color: var(--danger-strong); + background: var(--danger-soft); +} +.condition-chip button { + background: none; + border: none; + color: inherit; + cursor: pointer; + padding: 0 0.1rem; + font-size: 0.85rem; + line-height: 1; +} + +.combatant-details { + margin-top: 0.75rem; + padding-top: 0.75rem; + border-top: 1px solid var(--border-soft); + font-size: 0.92rem; +} +.combatant-details p { + margin: 0.3rem 0; +} +.detail-row { + display: flex; + justify-content: space-between; + gap: 0.5rem; + padding: 0.2rem 0; +} + +.reward-row { + padding: 0.55rem 0; + border-bottom: 1px solid var(--border-soft); +} +.reward-row:last-child { + border-bottom: none; +} +.reward-row.is-awarded { + color: var(--text-muted); +} + +.textarea-block { + display: block; + width: 100%; + resize: vertical; +} + +/* ---------------------------------------------------------------------- */ +/* Character builder: pick-then-confirm choices */ +/* ---------------------------------------------------------------------- */ + +.step-intro { + color: var(--text-muted); + margin: 0 0 1rem; +} + +.build-steps { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; +} +.build-steps .badge.is-done { + border-color: var(--accent); + color: var(--accent-strong); +} +.build-steps .badge.is-current { + border-color: var(--accent-strong); + background: var(--accent-soft); + color: var(--accent-strong); + font-weight: 700; +} + +.choice-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); + gap: 0.75rem; + text-align: left; +} +.choice-card { + display: flex; + flex-direction: column; + gap: 0.4rem; + text-align: left; + font-family: var(--font-body); + font-size: 0.95rem; + color: var(--text); + background: var(--bg-inset); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 0.9rem 1rem; + cursor: pointer; + transition: border-color 0.15s ease, box-shadow 0.15s ease, transform 0.15s ease; +} +.choice-card:hover { + border-color: var(--accent); + transform: translateY(-1px); +} +.choice-card:focus-visible { + outline: none; + box-shadow: 0 0 0 3px var(--accent-soft); +} +.choice-card.is-selected { + border-color: var(--accent-strong); + box-shadow: 0 0 0 1px var(--accent-strong), 0 0 18px rgba(201, 162, 39, 0.25); + background: linear-gradient(160deg, var(--bg-card-hover) 0%, var(--bg-inset) 100%); +} +.choice-card-title { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + font-family: var(--font-display); + font-size: 1.1rem; + color: var(--accent-strong); +} +.choice-card-blurb { + color: var(--text-muted); + font-style: italic; +} +.choice-card-facts { + color: var(--text-muted); + font-size: 0.85rem; +} + +.step-footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + flex-wrap: wrap; + margin-top: 1.25rem; + padding-top: 1rem; + border-top: 1px solid var(--border-soft); + text-align: left; +} + +.stat-block.is-key { + border-color: var(--accent); +} +.key-marker { + color: var(--accent-strong); + font-size: 0.7rem; + text-transform: uppercase; + letter-spacing: 0.06em; +} + +/* ---------------------------------------------------------------------- */ +/* Dice roller — on every page, bottom-left (quick stats owns bottom-right) */ +/* ---------------------------------------------------------------------- */ + +.fab-dice { + position: fixed; + bottom: 1.25rem; + left: 1.25rem; + z-index: 80; + border-radius: 999px; + width: 60px; + height: 60px; + display: flex; + align-items: center; + justify-content: center; + background: radial-gradient(circle at 35% 30%, #3a2e18, #1c160c 70%); + border: 2px solid var(--accent); + color: var(--accent-strong); + font-size: 1.6rem; + cursor: pointer; + box-shadow: 0 6px 24px rgba(0, 0, 0, 0.5), 0 0 18px rgba(201, 162, 39, 0.3); + transition: transform 0.15s ease; +} +.fab-dice:hover { + transform: translateY(-2px) rotate(-8deg); +} + +.dice-panel { + position: fixed; + bottom: calc(1.25rem + 60px + 0.75rem); + left: 1.25rem; + z-index: 85; + width: min(340px, calc(100vw - 2.5rem)); + max-height: calc(100vh - 8rem); + overflow-y: auto; + background: linear-gradient(180deg, #1c160d 0%, #120e08 100%); + border: 1px solid var(--accent); + border-radius: var(--radius); + box-shadow: var(--shadow-deep); + padding: 1rem; +} + +.dice-choices { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 0.4rem; +} +.die-btn { + font-family: var(--font-display); + font-size: 0.95rem; + padding: 0.55rem 0; + border-radius: 6px; + border: 1px solid var(--border); + background: var(--bg-inset); + color: var(--text); + cursor: pointer; + transition: border-color 0.15s ease, color 0.15s ease; +} +.die-btn:hover { + border-color: var(--accent); + color: var(--accent-strong); +} +.die-btn.is-selected { + border-color: var(--accent-strong); + background: var(--accent-soft); + color: var(--accent-strong); + font-weight: 700; +} + +.dice-label { + font-size: 0.7rem; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--text-dim); +} + +.dice-result { + text-align: center; + min-height: 6.5rem; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + margin: 0.75rem 0; + padding: 0.5rem; + background: var(--bg-inset); + border: 1px solid var(--border-soft); + border-radius: var(--radius); +} +.roll-result.is-crit { + color: var(--success-strong); + text-shadow: 0 0 20px rgba(122, 178, 102, 0.6); +} +.roll-result.is-fumble { + color: var(--danger-strong); + text-shadow: 0 0 20px rgba(216, 84, 84, 0.5); +} +.dice-callout { + font-family: var(--font-display); + font-size: 0.8rem; + text-transform: uppercase; + letter-spacing: 0.1em; + color: var(--success-strong); +} +.dice-callout.is-fumble { + color: var(--danger-strong); +} +.dice-breakdown { + color: var(--text-muted); + font-size: 0.85rem; + word-break: break-word; +} +.dice-history-row { + padding: 0.25rem 0; + border-top: 1px solid var(--border-soft); + font-size: 0.9rem; +} +.dice-history-dice { + color: var(--text-dim); + font-size: 0.8rem; +} + +/* ---------------------------------------------------------------------- */ +/* Character builder: story steps (motivation, abilities, background, look) */ +/* ---------------------------------------------------------------------- */ + +.pick-group { + padding: 0.75rem 0; + border-top: 1px solid var(--border-soft); +} +.pick-group:first-of-type { + border-top: none; +} +.pick-group-label { + font-family: var(--font-display); + color: var(--accent); + font-size: 0.9rem; + text-transform: uppercase; + letter-spacing: 0.06em; +} +.pick-chips { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; + margin-top: 0.5rem; +} +.pick-chip { + font-family: var(--font-body); + font-size: 0.95rem; + padding: 0.35rem 0.8rem; + border-radius: 999px; + border: 1px solid var(--border); + background: var(--bg-inset); + color: var(--text); + cursor: pointer; + transition: border-color 0.15s ease, color 0.15s ease; +} +.pick-chip:hover:not(:disabled) { + border-color: var(--accent); +} +.pick-chip.is-selected { + border-color: var(--accent-strong); + background: var(--accent-soft); + color: var(--accent-strong); + font-weight: 600; +} +.pick-chip:disabled { + opacity: 0.45; + cursor: not-allowed; +} +.pick-detail { + color: var(--text-muted); + font-style: italic; + margin: 0.4rem 0 0; +} + +.granted-ability { + padding: 0.4rem 0; + border-bottom: 1px solid var(--border-soft); +} +.granted-ability:last-child { + border-bottom: none; +} + +/* Text the builder composed, shown read-only on the sheet. */ +.composed-text { + margin: 0; + white-space: pre-wrap; +} diff --git a/frontend/src/lib/format.ts b/frontend/src/lib/format.ts index 6673c22..10fc70e 100644 --- a/frontend/src/lib/format.ts +++ b/frontend/src/lib/format.ts @@ -86,3 +86,24 @@ export function extractErrorMessage(err: unknown): string { if (err instanceof Error) return err.message; return 'Something went wrong.'; } + +// A cantrip is spell level 0. It is always called a cantrip, never "level 0" +// or "level 1". +export function spellLevelLabel(level: number): string { + return level === 0 ? 'Cantrip' : `Level ${level}`; +} + +// Who can use a spell: a character of at least its level; cantrips, anyone. +export function spellRequirementLabel(level: number): string { + return level === 0 ? 'any character can use it' : `needs character level ${level}`; +} + +// The damage values offered for a spell, grouped by how many dice are rolled. +const SPELL_DIE_SIZES = [4, 6, 8, 10, 12]; +const SPELL_DIE_COUNTS = [1, 2, 3, 4, 5, 6, 8, 10]; +export const SPELL_DAMAGE_GROUPS: { label: string; options: string[] }[] = SPELL_DIE_COUNTS.map((count) => ({ + label: count === 1 ? '1 die' : `${count} dice`, + options: SPELL_DIE_SIZES.map((size) => `${count}d${size}`), +})); +// Values the spell library uses that don't fit the pattern above. +export const SPELL_DAMAGE_SPECIALS = ['3d4+3', '2d8+4d6', '20']; diff --git a/frontend/src/lib/guide.ts b/frontend/src/lib/guide.ts new file mode 100644 index 0000000..521e6bd --- /dev/null +++ b/frontend/src/lib/guide.ts @@ -0,0 +1,229 @@ +import type { Ability, CharacterClass, Species } from '../api/types'; + +// Plain-language explanations for someone building their first character. +// Everything here describes what a choice does to the *numbers* — plus a line +// of flavour. The special abilities a species or class grants are listed +// separately, from the server's own lists (useBuildOptions). + +export const SPECIES_SPEED: Record = { + HUMAN: 30, + HALF_ELF: 30, + ELF: 30, + GNOME: 25, + DWARF: 25, + HALFLING: 25, + DRAGONBORN: 30, + TIEFLING: 30, + HALF_ORC: 30, + ORC: 30, +}; + +export const SPECIES_GUIDE: Record = { + HUMAN: { + blurb: 'Adaptable and ambitious, found in every corner of the world.', + goodFor: 'A little better at everything (+1 to all six abilities). A safe pick for any class.', + }, + HALF_ELF: { + blurb: 'Walks between two worlds, with human drive and elven grace.', + goodFor: 'Very charming (+2 Charisma), and you choose two more abilities to raise by 1. Great for talkers and Charisma spellcasters.', + }, + ELF: { + blurb: 'Graceful, long-lived and quick on their feet.', + goodFor: 'Nimble (+2 Dexterity): harder to hit, acts sooner in a fight, better with bows and light blades.', + }, + GNOME: { + blurb: 'Small, curious tinkerers with sharp minds.', + goodFor: 'Clever (+2 Intelligence): ideal for Wizards and knowledge skills. A little slower on foot.', + }, + DWARF: { + blurb: 'Stout, stubborn mountain folk who are hard to put down.', + goodFor: 'Tough (+2 Constitution): more hit points at every level. A little slower on foot.', + }, + HALFLING: { + blurb: 'Small, cheerful and surprisingly brave.', + goodFor: 'Nimble (+2 Dexterity): harder to hit and good at sneaking. A little slower on foot.', + }, + DRAGONBORN: { + blurb: 'Proud, scaled warriors with dragon blood.', + goodFor: 'Strong (+2 Strength) with presence (+1 Charisma): hits hard up close. Great for Paladins and Fighters.', + }, + TIEFLING: { + blurb: 'Marked by an infernal bloodline, and used to being stared at.', + goodFor: 'Magnetic (+2 Charisma) and bright (+1 Intelligence): great for Warlocks, Sorcerers and Bards.', + }, + HALF_ORC: { + blurb: 'Fierce and enduring, with something to prove.', + goodFor: 'Strong (+2 Strength) and hardy (+1 Constitution): hits hard and takes hits. Great for Barbarians and Fighters.', + }, + ORC: { + blurb: 'Powerful and relentless, raised to survive.', + goodFor: 'Strong (+2 Strength) and hardy (+1 Constitution): built for the front line.', + }, +}; + +export type Toughness = 'Fragile' | 'Average' | 'Sturdy' | 'Very tough'; + +export const CLASS_GUIDE: Record< + CharacterClass, + { blurb: string; playsLike: string; keyAbilities: Ability[]; skillCount: number; difficulty: 'Easy' | 'Medium' | 'Tricky' } +> = { + FIGHTER: { + blurb: 'A trained warrior, at home with any weapon.', + playsLike: 'Stand at the front, hit things, take hits. The simplest class to play well.', + keyAbilities: ['STR', 'DEX', 'CON'], + skillCount: 2, + difficulty: 'Easy', + }, + BARBARIAN: { + blurb: 'A fierce warrior driven by raw fury.', + playsLike: 'Charge in and soak up damage — you have the most hit points of any class.', + keyAbilities: ['STR', 'CON'], + skillCount: 2, + difficulty: 'Easy', + }, + ROGUE: { + blurb: 'A sneak, scout and scoundrel who relies on cunning.', + playsLike: 'Strike from the shadows and solve problems with skills — you get more skills than anyone.', + keyAbilities: ['DEX'], + skillCount: 4, + difficulty: 'Medium', + }, + RANGER: { + blurb: 'A hunter and tracker of the wild places.', + playsLike: 'Fight from range or up close, with a little nature magic and plenty of outdoor skills.', + keyAbilities: ['DEX', 'WIS'], + skillCount: 3, + difficulty: 'Medium', + }, + WIZARD: { + blurb: 'A scholar who has studied magic from books.', + playsLike: 'Stay back and cast spells. Powerful but fragile — the fewest hit points of any class.', + keyAbilities: ['INT'], + skillCount: 2, + difficulty: 'Tricky', + }, + SORCERER: { + blurb: 'Born with magic in the blood.', + playsLike: 'Stay back and cast spells through sheer force of personality. Powerful but fragile.', + keyAbilities: ['CHA'], + skillCount: 2, + difficulty: 'Tricky', + }, + CLERIC: { + blurb: 'A priest who channels the power of a god.', + playsLike: 'Heal and protect the party, and hold your own in a fight. Every group is glad to have one.', + keyAbilities: ['WIS'], + skillCount: 2, + difficulty: 'Medium', + }, + PALADIN: { + blurb: 'A holy knight sworn to an oath.', + playsLike: 'A front-line fighter with a little divine magic to back up the sword.', + keyAbilities: ['STR', 'CHA'], + skillCount: 2, + difficulty: 'Medium', + }, + BARD: { + blurb: 'A performer whose words and music carry magic.', + playsLike: 'The party’s talker and helper: spells, skills, and a way out of trouble.', + keyAbilities: ['CHA'], + skillCount: 3, + difficulty: 'Medium', + }, + WARLOCK: { + blurb: 'Made a pact with a powerful being in exchange for magic.', + playsLike: 'A spellcaster with a few strong tricks used often, rather than many used rarely.', + keyAbilities: ['CHA'], + skillCount: 2, + difficulty: 'Medium', + }, + DRUID: { + blurb: 'A guardian of nature who draws magic from the wild.', + playsLike: 'A flexible spellcaster: healing, nature magic and control of the battlefield.', + keyAbilities: ['WIS'], + skillCount: 2, + difficulty: 'Tricky', + }, + MONK: { + blurb: 'A martial artist who has trained body and mind.', + playsLike: 'Fast and precise: dart around the fight striking quickly, with little need for gear.', + keyAbilities: ['DEX', 'WIS'], + skillCount: 2, + difficulty: 'Medium', + }, +}; + +export function hitDieToughness(hitDie: number): Toughness { + if (hitDie <= 6) return 'Fragile'; + if (hitDie <= 8) return 'Average'; + if (hitDie <= 10) return 'Sturdy'; + return 'Very tough'; +} + +// What each ability changes on the sheet this app builds. +export const ABILITY_GUIDE: Record = { + STR: { + short: 'Physical power', + affects: 'Strength — hitting and damage with heavy melee weapons, the Athletics skill (climbing, jumping, grappling), and Strength saves.', + }, + DEX: { + short: 'Agility and reflexes', + affects: + 'Dexterity — your Armor Class (how hard you are to hit), your Initiative (how early you act), attacks with bows and light blades, and Acrobatics, Sleight of Hand and Stealth.', + }, + CON: { + short: 'Health and stamina', + affects: 'Constitution — your hit points, at level 1 and again every level after. Also Constitution saves. Useful for everyone.', + }, + INT: { + short: 'Memory and reasoning', + affects: 'Intelligence — the Arcana, History, Investigation, Nature and Religion skills, and a Wizard’s spells.', + }, + WIS: { + short: 'Awareness and intuition', + affects: + 'Wisdom — noticing things (Perception and Passive Perception), plus Insight, Medicine, Survival and Animal Handling, and the spells of Clerics, Druids and Rangers.', + }, + CHA: { + short: 'Force of personality', + affects: 'Charisma — Persuasion, Deception, Intimidation and Performance, and the spells of Bards, Paladins, Sorcerers and Warlocks.', + }, +}; + +export const SKILL_GUIDE: Record = { + ACROBATICS: { ability: 'DEX', what: 'Staying on your feet: balancing, tumbling, flips.' }, + ANIMAL_HANDLING: { ability: 'WIS', what: 'Calming, controlling or reading the mood of an animal.' }, + ARCANA: { ability: 'INT', what: 'Knowing about magic, spells and magical creatures.' }, + ATHLETICS: { ability: 'STR', what: 'Climbing, jumping, swimming and wrestling.' }, + DECEPTION: { ability: 'CHA', what: 'Lying convincingly and hiding the truth.' }, + HISTORY: { ability: 'INT', what: 'Recalling past events, kingdoms, wars and legends.' }, + INSIGHT: { ability: 'WIS', what: 'Reading people: spotting lies and sensing intentions.' }, + INTIMIDATION: { ability: 'CHA', what: 'Getting your way through threats and menace.' }, + INVESTIGATION: { ability: 'INT', what: 'Searching for clues and working out what they mean.' }, + MEDICINE: { ability: 'WIS', what: 'Steadying the dying and diagnosing illness.' }, + NATURE: { ability: 'INT', what: 'Knowing about plants, animals, weather and terrain.' }, + PERCEPTION: { ability: 'WIS', what: 'Noticing things: hidden enemies, traps, faint sounds. Rolled more than any other skill.' }, + PERFORMANCE: { ability: 'CHA', what: 'Entertaining a crowd with music, acting or storytelling.' }, + PERSUASION: { ability: 'CHA', what: 'Winning people over with honest charm and good arguments.' }, + RELIGION: { ability: 'INT', what: 'Knowing about gods, rites, holy symbols and cults.' }, + SLEIGHT_OF_HAND: { ability: 'DEX', what: 'Picking pockets, palming objects, planting things unseen.' }, + STEALTH: { ability: 'DEX', what: 'Moving quietly and staying hidden.' }, + SURVIVAL: { ability: 'WIS', what: 'Tracking, finding food and shelter, not getting lost.' }, +}; + +// One line under each step heading: what this step is and why it matters. +export const STEP_GUIDE = { + SPECIES: 'Your species is who your character was born as. It nudges a few ability scores up and sets how fast you move.', + CLASS: 'Your class is what your character does — warrior, spellcaster, sneak. It sets your hit points, which saves you are good at, your skills, and whether you cast spells.', + MOTIVATION: 'Why is your character out adventuring? This is pure story — it changes no numbers, but it gives you something to play.', + SCORES: + 'Six numbers that describe your character. Higher is better: 10 is average, and every 2 points above 10 adds +1 to related rolls. You roll six scores, then decide which ability gets which.', + SKILLS: 'Skills are things your character is trained in. When you roll for one of these, you add your proficiency bonus on top.', + ABILITIES: + 'Special abilities are the tricks that make your character more than numbers. Your species and class each grant some automatically, and you pick a couple of talents of your own. Your DM applies them at the table.', + BACKGROUND: 'Who was your character before the adventure began? Pick one answer to each question. It changes no numbers — it tells you and your DM who you are playing.', + APPEARANCE: 'What do people see when your character walks in? Pick from each list to build the description.', + EQUIPMENT: 'What you set out with. Your DM decides what is on offer here, and can hand out more as you play.', +} as const; + +export const STEP_NAMES = ['Species', 'Class', 'Motivation', 'Scores', 'Skills', 'Abilities', 'Background', 'Appearance', 'Equipment'] as const; diff --git a/frontend/src/lib/previewCalc.ts b/frontend/src/lib/previewCalc.ts index 2bff687..ffd3494 100644 --- a/frontend/src/lib/previewCalc.ts +++ b/frontend/src/lib/previewCalc.ts @@ -62,3 +62,70 @@ export interface PreviewAbilities { } export const ABILITY_ORDER: Ability[] = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA']; + +// -------------------------------------------------------------------------- +// Gear levels — mirrors scaledDamageDice in backend/src/game/calculations.js. +// Used only to label the DM's level pickers ("Lv 3 · 1d10"); the dice actually +// shown for held gear always come from the server. +// -------------------------------------------------------------------------- + +export const MAX_GEAR_LEVEL = 9; +export const DAMAGE_SCALING_LABELS: Record = { 1: 'Standard', 2: 'Powerful', 3: 'Legendary' }; + +const DIE_SIZES = [4, 6, 8, 10, 12]; + +function formatDice(sizes: number[]): string { + 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('+'); +} + +function buildDamageLadder(rungs: number): { dice: string; average: number }[] { + const ladder: { dice: string; average: number }[] = []; + let k = 1; + let steps = 0; + while (ladder.length < rungs) { + if (steps > k * (DIE_SIZES.length - 1)) { + const previousAverage = ladder[ladder.length - 1].average; + k += 1; + steps = Math.floor(previousAverage - k * 2.5) + 1; + continue; + } + const sizes: number[] = []; + for (let i = 0; i < k; i++) sizes.push(DIE_SIZES[Math.floor(steps / k) + (i >= k - (steps % k) ? 1 : 0)]); + ladder.push({ dice: formatDice(sizes), average: k * 2.5 + steps }); + steps += 1; + } + return ladder; +} + +const DAMAGE_LADDER = buildDamageLadder(120); + +function diceAverage(expression: string | null): number | null { + if (!expression || !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: number): number { + return Math.min(Math.max(Math.round(level || 1), 1), MAX_GEAR_LEVEL); +} + +// `minLevel` is the level the gear starts at; baseDice is its damage there. +export function scaledDamageDice(baseDice: string, level = 1, scaling = 1, minLevel = 1): string { + 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(scaling || 1), 1), 3); + return DAMAGE_LADDER[Math.min(baseRung + levelsGained * rungsPerLevel, DAMAGE_LADDER.length - 1)].dice; +} diff --git a/frontend/src/pages/CampaignHomePage.tsx b/frontend/src/pages/CampaignHomePage.tsx index 2005e4b..f9465cc 100644 --- a/frontend/src/pages/CampaignHomePage.tsx +++ b/frontend/src/pages/CampaignHomePage.tsx @@ -14,6 +14,12 @@ import { useCreateWeapon, useCampaignSpells, useCreateSpell, + useCampaignItems, + useCreateItem, + usePatchPoolEntry, + useDeletePoolEntry, + useCampaignNpcs, + useCreateNpc, useCampaignNotes, useCreateNote, useUpdateCampaign, @@ -30,9 +36,10 @@ import { useAuth } from '../auth/AuthContext'; import { useCampaignSocket } from '../hooks/useCampaignSocket'; import { Spinner, ErrorBanner } from '../components/Spinner'; import { usePagination, Pagination } from '../components/Paginated'; -import { extractErrorMessage } from '../lib/format'; +import { SPELL_DAMAGE_GROUPS, SPELL_DAMAGE_SPECIALS, extractErrorMessage, spellLevelLabel, spellRequirementLabel } from '../lib/format'; import { speciesIcon } from '../lib/speciesIcons'; -import type { CharacterSummary, LibraryMonster, LibrarySpell, LibraryWeapon } from '../api/types'; +import { DAMAGE_SCALING_LABELS, MAX_GEAR_LEVEL } from '../lib/previewCalc'; +import type { CharacterSummary, EncounterMode, LibraryMonster, LibrarySpell, LibraryWeapon, NpcDisposition } from '../api/types'; function CharacterRow({ character, isDM, onDelete }: { character: CharacterSummary; isDM: boolean; onDelete: () => void }) { const inProgress = character.buildStage !== 'COMPLETE'; @@ -71,17 +78,137 @@ function CharacterRow({ character, isDM, onDelete }: { character: CharacterSumma ); } +// The two trailing cells every pool table row shares: the "offered at +// character creation" toggle and the remove button. +function PoolRowControls({ + entry, + onToggleStarting, + onDelete, +}: { + entry: { name: string; isStartingOption: boolean }; + onToggleStarting: (isStartingOption: boolean) => void; + onDelete: () => void; +}) { + return ( + <> + + onToggleStarting(e.target.checked)} + /> + + + + + + ); +} + +// How fast a weapon's or item's dice grow as the DM levels a held copy up. +function ScalingSelect({ name, value, onChange }: { name?: string; value?: number; onChange?: (scaling: number) => void }) { + return ( + + ); +} + +const GEAR_LEVELS = Array.from({ length: MAX_GEAR_LEVEL }, (_, i) => i + 1); + +// The level a weapon or item starts at. A held copy is never below it, and a +// character must be at least this level to use it. +function StartLevelSelect({ name, value, onChange }: { name?: string; value?: number; onChange?: (minLevel: number) => void }) { + return ( + + ); +} + +const MODE_LABELS: Record = { BATTLE: '⚔ Battle', QUEST: '📜 Quest' }; + +// A spell's damage is picked from a list rather than typed. A value that is +// not in the list (set through the API, say) is still shown and kept. +function SpellDamageSelect({ + name, + spellName, + value, + onChange, +}: { + name?: string; + spellName?: string; + value?: string | null; + onChange?: (damageDice: string | null) => void; +}) { + const known = [...SPELL_DAMAGE_GROUPS.flatMap((g) => g.options), ...SPELL_DAMAGE_SPECIALS]; + const others = value && !known.includes(value) ? [...SPELL_DAMAGE_SPECIALS, value] : SPELL_DAMAGE_SPECIALS; + return ( + + ); +} + function LibraryPicker({ items, onAdd, adding, renderMeta, + renderDetail, placeholder, }: { items: T[]; onAdd: (key: string) => void; adding: boolean; renderMeta: (item: T) => string; + // A sentence on what the entry is or does, shown under its name. + renderDetail?: (item: T) => string | null; placeholder: string; }) { const [query, setQuery] = useState(''); @@ -97,6 +224,7 @@ function LibraryPicker({
{item.name} {renderMeta(item)} + {renderDetail?.(item) &&
{renderDetail(item)}
}
)} {encounters?.length === 0 &&
No encounters yet.
} {encounters?.map((enc) => ( - {enc.name} - {enc.status} · Round {enc.currentRound} + + {MODE_LABELS[enc.mode]} + {enc.name} + + + {enc.status} + {enc.mode === 'BATTLE' && ` · Round ${enc.currentRound}`} + ))} + {isDM && ( +
+
+ NPCs + +
+

+ The people your party meets. Add them to an encounter to bring them into a scene. Players never see your notes or an + NPC's stats. +

+ {showNpcForm && ( +
{ + e.preventDefault(); + const form = e.target as HTMLFormElement; + const fd = new FormData(form); + const text = (key: string) => String(fd.get(key) || '').trim() || null; + const num = (key: string) => (fd.get(key) ? Number(fd.get(key)) : null); + try { + await createNpc.mutateAsync({ + name: String(fd.get('name')), + role: text('role'), + disposition: fd.get('disposition') as NpcDisposition, + description: text('description'), + dmNotes: text('dmNotes'), + ac: num('ac'), + maxHp: num('maxHp'), + attackBonus: num('attackBonus'), + damageDice: text('damageDice'), + }); + form.reset(); + } catch (err) { + setFormError(extractErrorMessage(err)); + } + }} + > +
+ + + +
+