Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cbda10668b | ||
|
|
16b5ac05ca | ||
|
|
9d0a4a2252 | ||
|
|
555765916f | ||
|
|
9b3637576d | ||
|
|
8811f14732 | ||
|
|
c3f2b0dfa7 | ||
|
|
86ef106969 | ||
|
|
18d9e7301c | ||
|
|
e7b6e0065a | ||
|
|
57fba68a48 | ||
|
|
61221f262c | ||
|
|
e9f8169286 | ||
|
|
3a867fd1a1 | ||
|
|
37c561c5d3 | ||
|
|
7b3d121151 | ||
|
|
f04e3497f4 | ||
|
|
0ddf9846a2 | ||
|
|
9c97d61ce5 |
@@ -11,13 +11,15 @@ monsters, and a real-time encounter/combat tracker.
|
||||
|
||||
| Document | Covers |
|
||||
|---|---|
|
||||
| `docs/CHARACTERS.md` | Building a character, every number on the sheet, levels, money, permissions |
|
||||
| `docs/CHARACTERS.md` | Building a character, every number on the sheet, levelling up, rests, money, permissions |
|
||||
| `docs/WEAPONS.md` | The weapon pool and library, equipping, weapon levels and how damage grows |
|
||||
| `docs/SPELLS.md` | The spell list, who can use which spells, the spell library |
|
||||
| `docs/SPELLS.md` | The spell list, who can use which spells, spell slots, the spell library |
|
||||
| `docs/ITEMS.md` | The item pool and library, armor and other gear effects, what can be equipped, items for sale |
|
||||
| `docs/ENCOUNTERS.md` | Battles and NPC quests, turns, rewards, trade, what players see |
|
||||
| `docs/MONSTERS.md` | The monster list and built-in bestiary |
|
||||
| `docs/NPCS.md` | Non-player characters, what they sell and the rates they change money at |
|
||||
| `docs/CAMPAIGN_SETTINGS.md` | Every campaign setting: dice, ability scores, subclasses and multiclassing, auto-rolled attacks, XP, crits |
|
||||
| `docs/SEEDS.md` | World seeds: ready-made campaigns a DM starts from a code, and how to add one |
|
||||
|
||||
`CLAUDE_BUILD_PROMPT.md`, `docs/GAME_RULES_REFERENCE.md` and
|
||||
`docs/ROLL_YOUR_CHARACTER.md` are the original specifications the first
|
||||
@@ -32,28 +34,138 @@ The same four destinations are always on screen: **Campaigns** (the list),
|
||||
including a character sheet or an encounter) and **Account**.
|
||||
|
||||
- On a wide screen they are links along the top bar, and the dice roller
|
||||
floats at the bottom left.
|
||||
floats at the bottom left. **A number with a dotted underline rolls when
|
||||
clicked** (a skill, a save, an attack, damage), with the bonus already in
|
||||
and advantage or disadvantage if the roller is set to it. The DM's "🎲 Call
|
||||
for a roll…" rolls one check for the whole party.
|
||||
- On a phone or small tablet (900px wide or less) they are a bar along the
|
||||
bottom of the screen, with the **dice roller** as its last button. Nothing
|
||||
floats over the page: the 🧙 character button sits in the top bar.
|
||||
- The **🧙 character button** is on every page (floating at the bottom right
|
||||
on a wide screen). It opens a panel with your character's numbers and
|
||||
everything they hold; the DM can open it for any character.
|
||||
- The campaign page and the character sheet are long, so each starts with a
|
||||
row of **section links** (Characters, Encounters, NPCs, Monsters...) that
|
||||
jump straight to that part of the page.
|
||||
on a wide screen). It opens a panel with your character's numbers, saving
|
||||
throws, skills and everything they hold; the DM can open it for any
|
||||
character. "📋 Sheet" on an encounter card and 📋 on the party overview open
|
||||
the same panel for that character, without leaving the page.
|
||||
- **In an encounter** a strip across the top lists everyone in turn order and
|
||||
stays in view; a click goes to that card. On a wide screen the stat block
|
||||
of whoever is on turn stays in view beside the cards, and **📌 Pin** keeps
|
||||
anyone else's there instead. For the DM, **N** is Next Turn and **S** opens
|
||||
the sheet of whoever is on turn.
|
||||
- The DM adds **several of a monster at once** (numbered for them), rolls
|
||||
initiative for all the monsters and NPCs with one button, and can give a
|
||||
**condition a number of rounds**, after which it comes off by itself.
|
||||
Hovering over a condition shows its rule, and damaging someone who is
|
||||
Concentrating shows the save to call for.
|
||||
- The **campaign page shows one part at a time**, picked from a row of
|
||||
buttons under its name: Overview (characters and encounters), NPCs,
|
||||
Locations, Weapons, Items, Spells, Monsters, Notes and Settings for the DM;
|
||||
Overview, Places and Notes for a player. Each button shows how many things
|
||||
are in that part. On a phone the row is one line that scrolls sideways. The
|
||||
part showing is in the address (`?view=weapons`), so it can be bookmarked
|
||||
and the back button steps through the parts.
|
||||
- **Search this campaign**, the box above that row, looks through everything
|
||||
that has been added to the campaign at once: characters, encounters,
|
||||
locations and notes, and for the DM also NPCs, weapons, items, spells and
|
||||
monsters. It matches names and descriptions, every word typed, in any
|
||||
order. A result opens that thing. Each of the DM's lists also has a search
|
||||
box of its own.
|
||||
- The DM's lists (NPCs, weapons, items, spells, monsters) are short rows: a
|
||||
name and a few words. **Clicking a row opens a pop-out** with everything
|
||||
about it and everything that can be changed. Adding one, by hand or from the
|
||||
library, is a pop-out too. One added by hand opens its own pop-out, with an
|
||||
**"+ Add another"** button at the top that goes straight back to an empty
|
||||
form. A pop-out is a window over the page on a wide
|
||||
screen and the whole screen on a phone; ✕, Escape or a click outside it
|
||||
closes it.
|
||||
- Every paged list has Prev and Next, and with three pages or more the page
|
||||
number is a menu to **jump straight to any page**.
|
||||
- The DM's **🛏 Rest…** button, beside "Characters" on the campaign page and
|
||||
on the party overview, rests any of the party at once: a short rest says
|
||||
which Hit Dice each character can roll and heals from what they rolled; a
|
||||
long rest puts back HP, spell slots and Hit Dice.
|
||||
- A caster's **spell slots** are on their sheet and in the character panel:
|
||||
the player presses Use when they cast, and only the DM gives a slot back.
|
||||
- Each encounter shows the DM **how hard it is** (Easy to Deadly, from the
|
||||
monsters' challenge ratings against the party) and what it is worth in
|
||||
**XP**, which one button shares out. A sheet shows XP and when a level is
|
||||
due; levelling up stays the DM's call.
|
||||
- A character's **condition and counters** are on the sheet and in the panel:
|
||||
inspiration, exhaustion, conditions (which stay with the character from one
|
||||
encounter to the next) and class counters such as Rage and Ki, which the
|
||||
player spends and a rest gives back.
|
||||
- Every class has its **full catalogue of official subclasses** (123, from the
|
||||
2014 books and the 2024 Player’s Handbook), with features up to level 20.
|
||||
One is picked in the builder (a die can suggest one) or in the level-up
|
||||
checklist at level 2 or 3, and shown beside the class everywhere; the DM can
|
||||
change it from the sheet, and switch a 2014 path to its 2024 update. Every
|
||||
sheet shows **the road ahead**: what each level from 1 to 20 gives.
|
||||
- **Class features that change a number are worked out**: Unarmored Defense
|
||||
(barbarian, monk), Draconic Resilience, Fast Movement, Unarmored Movement,
|
||||
Aura of Protection, Diamond Soul, Slippery Mind and Jack of All Trades are
|
||||
counted on the sheet, by what is equipped (armor and shields are marked
|
||||
items) and by level in the class that gives them.
|
||||
- **Armor holds Dexterity back** as in the rules: all of it counts toward AC
|
||||
in light armor, at most +2 in medium, none in heavy.
|
||||
- **Stricter battles.** A spell with no slot of its level or higher left
|
||||
cannot be cast (cantrips never need one), and a player changes the weapon
|
||||
in hand only as the battle begins or on their own turn after attacking.
|
||||
- **Free roam**, a third kind of encounter beside battles and quests: the DM
|
||||
ticks the nearby locations and adds the characters who are there, and
|
||||
each player sends their own character to a place to meet who is found there
|
||||
and shop (a place's own shop, or an NPC's wares) where they stand.
|
||||
- **Completed encounters are hidden** from the campaign's list until "Show
|
||||
completed" is ticked.
|
||||
- **Faster battles.** A colour-coded **turn-order track** (PCs blue, NPCs
|
||||
green, monsters red) shows this round, a 🏁 flag where it ends, and the
|
||||
next. Click a name (or press 1–9) to **target**. Whoever is on turn picks a
|
||||
**weapon or spell**; the d20 is typed in or rolled and the app says **hit,
|
||||
miss or critical**, or, for a spell, asks each target for its **saving
|
||||
throw** against the caster's DC. The DM overrules anything and applies it
|
||||
with one click. With **auto-roll** on, a monster's or NPC's turn opens with
|
||||
its attack already aimed and rolled, to accept, edit or discard. A "What
|
||||
now" line always says what the scene is waiting on.
|
||||
- **Dice that roll.** Each die is drawn as its own shape, tumbles in and
|
||||
lands on its result; a natural 20 glows. In a campaign the server makes
|
||||
every roll and the **DM sees each one** as it lands, in the roller's
|
||||
"Everyone's rolls" tab, beside the dice button, and on the encounter page.
|
||||
A campaign can play with digital dice, real dice typed in (and checked), or
|
||||
both, and can keep each player's rolls between them and the DM.
|
||||
- **Multiclassing** (a campaign setting): the level-up checklist asks which
|
||||
class gains the level, checks both classes' ability requirements, and works
|
||||
out HP, Hit Dice, spell slots, counters and features by each class's own
|
||||
level. The sheet suggests well-known multiclass routes from where the
|
||||
character stands. Eldritch Knights and Arcane Tricksters now have their
|
||||
spell slots.
|
||||
- **43 species** (the 2014 core, the 2024 Aasimar and Goliath, and the species
|
||||
of Monsters of the Multiverse) and **13 classes**, the Artificer included. A campaign can do without them: untick "Characters choose a
|
||||
subclass" in its Settings and every class follows one path, unasked.
|
||||
- **Campaign settings** come in four groups. **Characters**: starting gold
|
||||
and gear, how ability scores are made (4d6, standard array or point buy),
|
||||
subclasses, multiclassing. **Dice & rolls**: digital, physical or both, and
|
||||
who sees a roll. **Combat**: auto-rolled monster and NPC attacks, the
|
||||
critical hit rule, monster HP, the area penalty. **Progression**: XP
|
||||
tracking (off for milestone levelling) and HP on a level up.
|
||||
- **⬆ Level up…** (DM, beside Rest) approves a level for any of the party at
|
||||
once. Each player gets a notice, sees what the level gives and makes their
|
||||
own picks in the checklist: HP (the average, or a roll where the campaign
|
||||
rolls), the class's new special abilities, a subclass, a Boon, spells and
|
||||
the free weapon upgrade. A level waiting shows on the sheet and the
|
||||
campaign page until it is taken; the DM sees who still has picks to make,
|
||||
and can finish any of them.
|
||||
- The character sheet is long, so it starts with a row of **section links**
|
||||
that jump straight to that part of the page.
|
||||
- On a small screen every table (weapons, items, spells, monsters, the party
|
||||
overview) is shown as a stack of cards, one per row, with each figure
|
||||
labelled, and rows of controls wrap rather than run off the side.
|
||||
|
||||
## Stack
|
||||
|
||||
- **Backend:** Node.js + Express, JavaScript, Prisma ORM, PostgreSQL, Socket.io, JWT auth (bcrypt + jsonwebtoken), zod validation.
|
||||
- **Backend:** Node.js + Express, JavaScript, Prisma ORM (with the `pg` driver adapter), PostgreSQL, Socket.io, JWT auth (bcrypt + jsonwebtoken), zod validation.
|
||||
- **Frontend:** React + Vite + TypeScript, React Router, TanStack Query, socket.io-client.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 18+ (tested on Node 22)
|
||||
- Node.js 20.19+ (tested on Node 24)
|
||||
- A running PostgreSQL instance (local install, Docker, or a hosted service like Neon/Supabase)
|
||||
|
||||
## First-time setup
|
||||
@@ -65,7 +177,8 @@ npm install # installs both workspaces (backend + frontend)
|
||||
cd backend
|
||||
cp .env.example .env # edit DATABASE_URL and JWT_SECRET
|
||||
npx prisma migrate dev --name init
|
||||
npx prisma db seed # adds the admin account + the Aldenfell campaign if missing (see output for login/invite code)
|
||||
npx prisma generate # migrate no longer does this itself
|
||||
npx prisma db seed # adds the admin account if it is missing (see output for the login and the world codes)
|
||||
|
||||
# Frontend
|
||||
cd ../frontend
|
||||
@@ -82,26 +195,33 @@ npm run dev:frontend # Vite dev server, prints its own port (5173 by default)
|
||||
```
|
||||
|
||||
Open the frontend URL, register an account (or log in with the seeded admin
|
||||
account — see the seed script's console output for credentials and invite
|
||||
code), and start playing.
|
||||
account — see the seed script's console output for the credentials), and
|
||||
start playing.
|
||||
|
||||
The seed only adds: it never touches an existing account or campaign, so it is
|
||||
safe to run on a server with real data. It skips the campaign if the admin
|
||||
already has an active "Aldenfell"; archive or delete that one in the app
|
||||
(Campaign Settings) and run it again for a fresh copy. `SEED_ADMIN_EMAIL`,
|
||||
`SEED_ADMIN_PASSWORD` and `SEED_ADMIN_NAME` set the account it creates.
|
||||
`npx prisma db seed -- --reset` wipes every user and campaign first.
|
||||
The database seed creates the admin account and nothing else. It only adds: an
|
||||
existing account, and its password, is left alone, so it is safe to run on a
|
||||
server with real data. `SEED_ADMIN_EMAIL`, `SEED_ADMIN_PASSWORD` and
|
||||
`SEED_ADMIN_NAME` set the account it creates. `npx prisma db seed -- --reset`
|
||||
wipes every user and campaign first.
|
||||
|
||||
A second campaign, Hollowcrown: The Rift Between Worlds, has its own seed and
|
||||
is not part of the default one. It follows the same rules (it only adds, and
|
||||
skips if the admin already has an active Hollowcrown):
|
||||
## Worlds
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npm run seed:hollowcrown
|
||||
```
|
||||
Campaigns are created in the app: blank, or from a **world seed** by its
|
||||
code. On the Campaigns page click "+ New Campaign" and enter a code under "Or
|
||||
start from a ready-made world"; the whole world is built for you as its DM.
|
||||
|
||||
On a server, after pulling a new version, run `npm run deploy` in `backend`
|
||||
| Code | World |
|
||||
|---|---|
|
||||
| `ALDENF` | Aldenfell |
|
||||
| `HOLLOW` | Hollowcrown: The Rift Between Worlds |
|
||||
|
||||
Each world is one file in `/backend/seeds`. Drop another file in and its code
|
||||
works straight away, with no restart; `npm run seeds:check` (from the repo
|
||||
root or `backend`) checks every file and says what is wrong with one.
|
||||
`docs/SEEDS.md` has the format.
|
||||
|
||||
On a server, after pulling a new version, run `npm install` in the repo root
|
||||
(when dependencies changed) and then `npm run deploy` in `backend`
|
||||
and then restart the backend. It applies new migrations **and** regenerates
|
||||
the Prisma client; without the second half the server keeps running with the
|
||||
old data model and pages that use anything new fail to load (for example
|
||||
@@ -115,8 +235,9 @@ cd backend
|
||||
npm test
|
||||
```
|
||||
|
||||
The calculation engine (`src/game/calculations.js`) is fully unit tested and
|
||||
runs with no external dependencies. The route-level integration tests in
|
||||
The calculation engine (`src/game/calculations.js`) and the world seeds
|
||||
(`src/seeds`, which also checks every file in `/backend/seeds`) are unit
|
||||
tested and run with no external dependencies. The route-level integration tests in
|
||||
`src/routes/api.integration.test.js` need a real, migrated database reachable
|
||||
via `DATABASE_URL` — they skip themselves gracefully (with a console warning)
|
||||
if the DB isn't reachable, so `npm test` still passes in an environment with
|
||||
@@ -126,14 +247,17 @@ no database configured.
|
||||
|
||||
```
|
||||
/backend — Express + Prisma API, Socket.io server
|
||||
/prisma — schema.prisma, seed.js
|
||||
/seed-data — reference JSON (weapons seeded per-campaign; species/classes/skills
|
||||
are ported into src/game/data/*.js and used directly by the
|
||||
calculation engine, not stored as DB rows)
|
||||
prisma.config.js — where the Prisma CLI finds the schema, the database and the seed
|
||||
/prisma — schema.prisma, migrations, seed.js (the admin account only)
|
||||
/seeds — world seeds: one file per ready-made campaign, created by code
|
||||
/seed-data — reference JSON (species/classes/skills/weapons, ported into
|
||||
src/game/data/*.js and used directly by the calculation engine,
|
||||
not stored as DB rows)
|
||||
/src
|
||||
/game — calculations.js (the ONLY place D&D formulas live) + buildFlow.js
|
||||
/game — calculations.js (the ONLY place D&D formulas live) + buildFlow.js + levelUp.js
|
||||
/middleware — auth + campaign/character authorization
|
||||
/routes — auth, campaigns, characters, encounters, notes
|
||||
/seeds — finds, checks and creates campaigns from the world seeds
|
||||
/sockets — Socket.io room wiring
|
||||
/frontend — React + Vite + TypeScript app
|
||||
/docs — game rules & character-builder specs (reference material)
|
||||
|
||||
+11
-12
@@ -1,12 +1,9 @@
|
||||
{
|
||||
"name": "backend",
|
||||
"version": "1.11.1",
|
||||
"version": "1.31.0",
|
||||
"private": true,
|
||||
"type": "commonjs",
|
||||
"main": "src/index.js",
|
||||
"prisma": {
|
||||
"seed": "node prisma/seed.js"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "node --watch src/index.js",
|
||||
"start": "node src/index.js",
|
||||
@@ -15,23 +12,25 @@
|
||||
"prisma:migrate": "prisma migrate dev",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:seed": "prisma db seed",
|
||||
"seeds:check": "node scripts/check-seeds.js",
|
||||
"deploy": "prisma migrate deploy && prisma generate",
|
||||
"seed:hollowcrown": "node prisma/seed-hollowcrown.js",
|
||||
"prisma:studio": "prisma studio"
|
||||
},
|
||||
"dependencies": {
|
||||
"@prisma/client": "^5.20.0",
|
||||
"bcrypt": "^5.1.1",
|
||||
"@prisma/adapter-pg": "^7.10.0",
|
||||
"@prisma/client": "^7.10.0",
|
||||
"bcrypt": "^6.0.0",
|
||||
"compression": "^1.8.2",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.4.5",
|
||||
"express": "^4.21.0",
|
||||
"dotenv": "^18.0.6",
|
||||
"express": "^5.2.1",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"socket.io": "^4.8.0",
|
||||
"zod": "^3.23.8"
|
||||
"zod": "^4.6.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jest": "^29.7.0",
|
||||
"prisma": "^5.20.0",
|
||||
"jest": "^30.5.2",
|
||||
"prisma": "^7.10.0",
|
||||
"supertest": "^7.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
// Prisma CLI configuration: where the schema and migrations live, which
|
||||
// database to run them against, and the command behind `prisma db seed`.
|
||||
require('dotenv').config({ quiet: true });
|
||||
const { defineConfig, env } = require('prisma/config');
|
||||
|
||||
module.exports = defineConfig({
|
||||
schema: 'prisma/schema.prisma',
|
||||
migrations: {
|
||||
path: 'prisma/migrations',
|
||||
seed: 'node prisma/seed.js',
|
||||
},
|
||||
datasource: {
|
||||
url: env('DATABASE_URL'),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
-- CreateIndex: the columns every list is looked up by. Postgres does not
|
||||
-- index a foreign key on its own.
|
||||
CREATE INDEX "locations_campaignId_idx" ON "locations"("campaignId");
|
||||
CREATE INDEX "campaign_members_userId_idx" ON "campaign_members"("userId");
|
||||
CREATE INDEX "characters_campaignId_idx" ON "characters"("campaignId");
|
||||
CREATE INDEX "characters_userId_idx" ON "characters"("userId");
|
||||
CREATE INDEX "weapons_campaignId_idx" ON "weapons"("campaignId");
|
||||
CREATE INDEX "items_campaignId_idx" ON "items"("campaignId");
|
||||
CREATE INDEX "spells_campaignId_idx" ON "spells"("campaignId");
|
||||
CREATE INDEX "monsters_campaignId_idx" ON "monsters"("campaignId");
|
||||
CREATE INDEX "npcs_campaignId_idx" ON "npcs"("campaignId");
|
||||
CREATE INDEX "encounters_campaignId_idx" ON "encounters"("campaignId");
|
||||
CREATE INDEX "encounter_rewards_encounterId_idx" ON "encounter_rewards"("encounterId");
|
||||
CREATE INDEX "sale_offers_campaignId_idx" ON "sale_offers"("campaignId");
|
||||
CREATE INDEX "sale_offers_npcId_idx" ON "sale_offers"("npcId");
|
||||
CREATE INDEX "sale_offers_encounterId_idx" ON "sale_offers"("encounterId");
|
||||
CREATE INDEX "encounter_participants_encounterId_idx" ON "encounter_participants"("encounterId");
|
||||
CREATE INDEX "encounter_participants_characterId_idx" ON "encounter_participants"("characterId");
|
||||
CREATE INDEX "notes_campaignId_idx" ON "notes"("campaignId");
|
||||
CREATE INDEX "notes_characterId_idx" ON "notes"("characterId");
|
||||
@@ -0,0 +1,5 @@
|
||||
-- AlterTable: what a character has spent since their last rest. Spell slots
|
||||
-- by slot level (the first entry is 1st-level slots), and Hit Dice. How many
|
||||
-- of each there are comes from class and level, so only what is used is kept.
|
||||
ALTER TABLE "characters" ADD COLUMN "spellSlotsUsed" INTEGER[] DEFAULT ARRAY[]::INTEGER[],
|
||||
ADD COLUMN "hitDiceUsed" INTEGER NOT NULL DEFAULT 0;
|
||||
@@ -0,0 +1,24 @@
|
||||
-- AlterTable: the path a character takes within their class, as a key from
|
||||
-- game/data/subclasses.js.
|
||||
ALTER TABLE "characters" ADD COLUMN "subclass" TEXT;
|
||||
|
||||
-- Until now every class followed one path, written onto the sheet as the
|
||||
-- character levelled. Finished characters already at the level their class
|
||||
-- chooses at are given that path as their subclass.
|
||||
UPDATE "characters" SET "subclass" = CASE "characterClass"
|
||||
WHEN 'BARBARIAN' THEN 'BERSERKER'
|
||||
WHEN 'BARD' THEN 'LORE'
|
||||
WHEN 'CLERIC' THEN 'LIFE'
|
||||
WHEN 'DRUID' THEN 'LAND'
|
||||
WHEN 'FIGHTER' THEN 'CHAMPION'
|
||||
WHEN 'MONK' THEN 'OPEN_HAND'
|
||||
WHEN 'PALADIN' THEN 'DEVOTION'
|
||||
WHEN 'RANGER' THEN 'HUNTER'
|
||||
WHEN 'ROGUE' THEN 'THIEF'
|
||||
WHEN 'SORCERER' THEN 'DRACONIC'
|
||||
WHEN 'WARLOCK' THEN 'FIEND'
|
||||
WHEN 'WIZARD' THEN 'EVOCATION'
|
||||
END
|
||||
WHERE "buildStage" = 'COMPLETE'
|
||||
AND "characterClass" IS NOT NULL
|
||||
AND "level" >= CASE WHEN "characterClass" IN ('CLERIC', 'DRUID', 'WIZARD') THEN 2 ELSE 3 END;
|
||||
@@ -0,0 +1,20 @@
|
||||
-- AlterTable: how a character is doing beyond HP, and the class counters
|
||||
-- (Rage, Ki...) spent since the rest that gives them back, as { key: used }.
|
||||
ALTER TABLE "characters" ADD COLUMN "resourcesUsed" JSONB NOT NULL DEFAULT '{}',
|
||||
ADD COLUMN "inspiration" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "exhaustion" INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN "conditions" TEXT[] DEFAULT ARRAY[]::TEXT[];
|
||||
|
||||
-- A character's conditions used to be kept per encounter. They are the
|
||||
-- character's own now, so those given in an encounter still in progress move
|
||||
-- onto the character.
|
||||
UPDATE "characters" c SET "conditions" = held.conditions
|
||||
FROM (
|
||||
SELECT p."characterId", array_agg(DISTINCT condition) AS conditions
|
||||
FROM "encounter_participants" p
|
||||
JOIN "encounters" e ON e."id" = p."encounterId"
|
||||
CROSS JOIN LATERAL unnest(p."conditions") AS condition
|
||||
WHERE p."characterId" IS NOT NULL AND e."status" = 'ACTIVE'
|
||||
GROUP BY p."characterId"
|
||||
) held
|
||||
WHERE c."id" = held."characterId";
|
||||
@@ -0,0 +1,3 @@
|
||||
-- AlterTable: conditions that wear off by themselves, as
|
||||
-- { condition: rounds left }, counted down each time the round goes up.
|
||||
ALTER TABLE "encounter_participants" ADD COLUMN "conditionRounds" JSONB NOT NULL DEFAULT '{}';
|
||||
@@ -0,0 +1,3 @@
|
||||
-- AlterTable: the experience points handed out for an encounter, in all;
|
||||
-- null until the DM awards them.
|
||||
ALTER TABLE "encounters" ADD COLUMN "xpAwarded" INTEGER;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- AlterTable: a campaign can do without subclasses. Off, nobody chooses one
|
||||
-- and each class follows its first.
|
||||
ALTER TABLE "campaigns" ADD COLUMN "subclassesEnabled" BOOLEAN NOT NULL DEFAULT true;
|
||||
@@ -0,0 +1,30 @@
|
||||
-- Campaign settings: which dice, multiclassing, auto-rolled monster and NPC
|
||||
-- attacks, XP tracking, HP on a level up, the ability-score method, who sees
|
||||
-- a roll, and what a critical hit does.
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CampaignDiceMode" AS ENUM ('DIGITAL', 'PHYSICAL', 'BOTH');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "HpMethod" AS ENUM ('AVERAGE', 'ROLL');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ScoreMethod" AS ENUM ('ROLL_4D6', 'STANDARD_ARRAY', 'POINT_BUY');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "RollVisibility" AS ENUM ('ALL', 'OWN');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CritRule" AS ENUM ('DOUBLE_DICE', 'MAX_PLUS_ROLL');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "campaigns" ADD COLUMN "abilityScoreMethod" "ScoreMethod" NOT NULL DEFAULT 'ROLL_4D6',
|
||||
ADD COLUMN "autoRollMonsters" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "autoRollNpcs" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "critRule" "CritRule" NOT NULL DEFAULT 'DOUBLE_DICE',
|
||||
ADD COLUMN "diceMode" "CampaignDiceMode" NOT NULL DEFAULT 'BOTH',
|
||||
ADD COLUMN "hideMonsterRolls" BOOLEAN NOT NULL DEFAULT true,
|
||||
ADD COLUMN "hpOnLevelUp" "HpMethod" NOT NULL DEFAULT 'AVERAGE',
|
||||
ADD COLUMN "multiclassEnabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "rollVisibility" "RollVisibility" NOT NULL DEFAULT 'ALL',
|
||||
ADD COLUMN "trackXp" BOOLEAN NOT NULL DEFAULT true;
|
||||
@@ -0,0 +1,47 @@
|
||||
-- More species: the 2024 Aasimar and Goliath, and the species of Monsters of
|
||||
-- the Multiverse. Most of them choose their ability bonuses (+2/+1 or
|
||||
-- +1/+1/+1), so a Half-Elf's two +1 picks become one general set of chosen
|
||||
-- bonuses, { ability: amount }. Existing Half-Elves keep theirs.
|
||||
|
||||
ALTER TYPE "Species" ADD VALUE 'AASIMAR';
|
||||
ALTER TYPE "Species" ADD VALUE 'GOLIATH';
|
||||
ALTER TYPE "Species" ADD VALUE 'AARAKOCRA';
|
||||
ALTER TYPE "Species" ADD VALUE 'BUGBEAR';
|
||||
ALTER TYPE "Species" ADD VALUE 'CENTAUR';
|
||||
ALTER TYPE "Species" ADD VALUE 'CHANGELING';
|
||||
ALTER TYPE "Species" ADD VALUE 'DEEP_GNOME';
|
||||
ALTER TYPE "Species" ADD VALUE 'DUERGAR';
|
||||
ALTER TYPE "Species" ADD VALUE 'ELADRIN';
|
||||
ALTER TYPE "Species" ADD VALUE 'FAIRY';
|
||||
ALTER TYPE "Species" ADD VALUE 'FIRBOLG';
|
||||
ALTER TYPE "Species" ADD VALUE 'AIR_GENASI';
|
||||
ALTER TYPE "Species" ADD VALUE 'EARTH_GENASI';
|
||||
ALTER TYPE "Species" ADD VALUE 'FIRE_GENASI';
|
||||
ALTER TYPE "Species" ADD VALUE 'WATER_GENASI';
|
||||
ALTER TYPE "Species" ADD VALUE 'GITHYANKI';
|
||||
ALTER TYPE "Species" ADD VALUE 'GITHZERAI';
|
||||
ALTER TYPE "Species" ADD VALUE 'GOBLIN';
|
||||
ALTER TYPE "Species" ADD VALUE 'HARENGON';
|
||||
ALTER TYPE "Species" ADD VALUE 'HOBGOBLIN';
|
||||
ALTER TYPE "Species" ADD VALUE 'KENKU';
|
||||
ALTER TYPE "Species" ADD VALUE 'KOBOLD';
|
||||
ALTER TYPE "Species" ADD VALUE 'LIZARDFOLK';
|
||||
ALTER TYPE "Species" ADD VALUE 'MINOTAUR';
|
||||
ALTER TYPE "Species" ADD VALUE 'SEA_ELF';
|
||||
ALTER TYPE "Species" ADD VALUE 'SHADAR_KAI';
|
||||
ALTER TYPE "Species" ADD VALUE 'SHIFTER';
|
||||
ALTER TYPE "Species" ADD VALUE 'TABAXI';
|
||||
ALTER TYPE "Species" ADD VALUE 'TORTLE';
|
||||
ALTER TYPE "Species" ADD VALUE 'TRITON';
|
||||
ALTER TYPE "Species" ADD VALUE 'YUAN_TI';
|
||||
ALTER TYPE "Species" ADD VALUE 'OWLIN';
|
||||
ALTER TYPE "Species" ADD VALUE 'SATYR';
|
||||
|
||||
ALTER TABLE "characters" ADD COLUMN "speciesBonusChoices" JSONB NOT NULL DEFAULT '{}';
|
||||
|
||||
UPDATE "characters"
|
||||
SET "speciesBonusChoices" = jsonb_build_object("halfElfBonusAbility1"::text, 1, "halfElfBonusAbility2"::text, 1)
|
||||
WHERE "halfElfBonusAbility1" IS NOT NULL AND "halfElfBonusAbility2" IS NOT NULL;
|
||||
|
||||
ALTER TABLE "characters" DROP COLUMN "halfElfBonusAbility1",
|
||||
DROP COLUMN "halfElfBonusAbility2";
|
||||
@@ -0,0 +1,5 @@
|
||||
-- The Artificer joins the classes, and the builder gets a step to choose a
|
||||
-- subclass right after the class.
|
||||
ALTER TYPE "BuildStage" ADD VALUE 'CHOOSING_SUBCLASS' AFTER 'ROLLING_CLASS';
|
||||
|
||||
ALTER TYPE "CharacterClass" ADD VALUE 'ARTIFICER';
|
||||
@@ -0,0 +1,19 @@
|
||||
-- Multiclassing: levels a character takes in classes besides their first.
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "character_class_levels" (
|
||||
"id" TEXT NOT NULL,
|
||||
"characterId" TEXT NOT NULL,
|
||||
"characterClass" "CharacterClass" NOT NULL,
|
||||
"level" INTEGER NOT NULL DEFAULT 1,
|
||||
"subclass" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "character_class_levels_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "character_class_levels_characterId_characterClass_key" ON "character_class_levels"("characterId", "characterClass");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "character_class_levels" ADD CONSTRAINT "character_class_levels_characterId_fkey" FOREIGN KEY ("characterId") REFERENCES "characters"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Level-ups the DM approves for players to take, and rolled HP on a level up.
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "characters" ADD COLUMN "hpRollAdjust" INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN "levelUpsPending" INTEGER NOT NULL DEFAULT 0;
|
||||
@@ -0,0 +1,28 @@
|
||||
-- Rolls made at the table's dice roller, kept so the DM can see each one.
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "dice_rolls" (
|
||||
"id" TEXT NOT NULL,
|
||||
"campaignId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"rollerName" TEXT NOT NULL,
|
||||
"label" TEXT,
|
||||
"notation" TEXT NOT NULL,
|
||||
"dice" JSONB NOT NULL,
|
||||
"modifier" INTEGER NOT NULL DEFAULT 0,
|
||||
"total" INTEGER NOT NULL,
|
||||
"natural" INTEGER,
|
||||
"mode" TEXT NOT NULL DEFAULT 'NORMAL',
|
||||
"physical" BOOLEAN NOT NULL DEFAULT false,
|
||||
"hidden" BOOLEAN NOT NULL DEFAULT false,
|
||||
"encounterId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "dice_rolls_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "dice_rolls_campaignId_createdAt_idx" ON "dice_rolls"("campaignId", "createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "dice_rolls" ADD CONSTRAINT "dice_rolls_campaignId_fkey" FOREIGN KEY ("campaignId") REFERENCES "campaigns"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,51 @@
|
||||
-- Battle actions: an attack or spell from being declared to its damage
|
||||
-- landing; named attacks for monsters; and how each spell lands (a spell
|
||||
-- attack, or a saving throw). Spells already in campaigns that came from
|
||||
-- the library are marked by name.
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "monsters" ADD COLUMN "attacks" JSONB NOT NULL DEFAULT '[]';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "spells" ADD COLUMN "attackRoll" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "halfOnSave" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "saveAbility" "Ability";
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "encounter_actions" (
|
||||
"id" TEXT NOT NULL,
|
||||
"encounterId" TEXT NOT NULL,
|
||||
"round" INTEGER NOT NULL,
|
||||
"actorParticipantId" TEXT,
|
||||
"actorName" TEXT NOT NULL,
|
||||
"kind" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"detail" JSONB NOT NULL,
|
||||
"targets" JSONB NOT NULL,
|
||||
"damage" JSONB,
|
||||
"status" TEXT NOT NULL DEFAULT 'PENDING',
|
||||
"auto" BOOLEAN NOT NULL DEFAULT false,
|
||||
"hidden" BOOLEAN NOT NULL DEFAULT false,
|
||||
"createdById" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"appliedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "encounter_actions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "encounter_actions_encounterId_status_idx" ON "encounter_actions"("encounterId", "status");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "encounter_actions" ADD CONSTRAINT "encounter_actions_encounterId_fkey" FOREIGN KEY ("encounterId") REFERENCES "encounters"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- How the library's spells land, for copies already in campaigns.
|
||||
UPDATE "spells" SET "attackRoll" = true WHERE lower("name") IN ('chill touch', 'eldritch blast', 'fire bolt', 'produce flame', 'ray of frost', 'shocking grasp', 'thorn whip', 'guiding bolt', 'witch bolt', 'scorching ray', 'spiritual weapon', 'contagion');
|
||||
UPDATE "spells" SET "saveAbility" = 'STR', "halfOnSave" = false WHERE lower("name") IN ('entangle', 'gust of wind');
|
||||
UPDATE "spells" SET "saveAbility" = 'DEX', "halfOnSave" = true WHERE lower("name") IN ('burning hands', 'flaming sphere', 'call lightning', 'fireball', 'lightning bolt', 'guardian of faith', 'ice storm', 'wall of fire', 'flame strike');
|
||||
UPDATE "spells" SET "saveAbility" = 'DEX', "halfOnSave" = false WHERE lower("name") IN ('acid splash', 'sacred flame', 'faerie fire', 'web', 'sleet storm');
|
||||
UPDATE "spells" SET "saveAbility" = 'CON', "halfOnSave" = true WHERE lower("name") IN ('thunderwave', 'moonbeam', 'shatter', 'blight', 'cloudkill', 'cone of cold', 'insect plague');
|
||||
UPDATE "spells" SET "saveAbility" = 'CON', "halfOnSave" = false WHERE lower("name") IN ('poison spray', 'blindness/deafness', 'levitate', 'stinking cloud');
|
||||
UPDATE "spells" SET "saveAbility" = 'WIS', "halfOnSave" = true WHERE lower("name") IN ('spirit guardians');
|
||||
UPDATE "spells" SET "saveAbility" = 'WIS', "halfOnSave" = false WHERE lower("name") IN ('vicious mockery', 'animal friendship', 'charm person', 'command', 'hold person', 'suggestion', 'fear', 'slow', 'confusion', 'polymorph', 'dominate person', 'hold monster');
|
||||
UPDATE "spells" SET "saveAbility" = 'CHA', "halfOnSave" = false WHERE lower("name") IN ('bane', 'zone of truth', 'banishment');
|
||||
@@ -0,0 +1,39 @@
|
||||
-- Free roam: a kind of encounter where the party wanders between places the
|
||||
-- DM has laid out. A location can have NPCs found there and things for sale.
|
||||
|
||||
-- AlterEnum
|
||||
ALTER TYPE "EncounterMode" ADD VALUE 'FREE_ROAM';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "npcs" ADD COLUMN "locationId" TEXT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "sale_offers" ADD COLUMN "locationId" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "encounter_locations" (
|
||||
"id" TEXT NOT NULL,
|
||||
"encounterId" TEXT NOT NULL,
|
||||
"locationId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "encounter_locations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "encounter_locations_encounterId_locationId_key" ON "encounter_locations"("encounterId", "locationId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "sale_offers_locationId_idx" ON "sale_offers"("locationId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "npcs" ADD CONSTRAINT "npcs_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "locations"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "encounter_locations" ADD CONSTRAINT "encounter_locations_encounterId_fkey" FOREIGN KEY ("encounterId") REFERENCES "encounters"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "encounter_locations" ADD CONSTRAINT "encounter_locations_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "locations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "sale_offers" ADD CONSTRAINT "sale_offers_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "locations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Armor and shields say what kind they are, so the sheet can tell when a
|
||||
-- character is unarmored (Unarmored Defense, a monk's speed) or in heavy
|
||||
-- armor (a barbarian's Fast Movement). Copies of the library's armor already
|
||||
-- in a campaign are marked by name; anything else the DM marks on the item.
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ArmorType" AS ENUM ('LIGHT', 'MEDIUM', 'HEAVY', 'SHIELD');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "items" ADD COLUMN "armorType" "ArmorType";
|
||||
|
||||
UPDATE "items" SET "armorType" = 'LIGHT' WHERE "name" IN ('Padded Armor', 'Leather Armor', 'Studded Leather');
|
||||
UPDATE "items" SET "armorType" = 'MEDIUM' WHERE "name" IN ('Hide Armor', 'Chain Shirt', 'Scale Mail', 'Breastplate', 'Half Plate');
|
||||
UPDATE "items" SET "armorType" = 'HEAVY' WHERE "name" IN ('Ring Mail', 'Chain Mail', 'Splint Armor', 'Plate Armor');
|
||||
UPDATE "items" SET "armorType" = 'SHIELD' WHERE "name" = 'Shield';
|
||||
+299
-15
@@ -1,7 +1,8 @@
|
||||
// D&D Campaign Manager — Prisma schema
|
||||
// Postgres. Run `npx prisma migrate dev --name init` after `DATABASE_URL` is set,
|
||||
// then `npx prisma db seed` using the seed script built from /seed-data/*.json
|
||||
// (see CLAUDE_BUILD_PROMPT.md, "Database" section).
|
||||
// Postgres. The connection (DATABASE_URL) is set in prisma.config.js, not here.
|
||||
// Run `npx prisma migrate dev` then `npx prisma generate`; `npx prisma db seed`
|
||||
// adds the admin account (prisma/seed.js). Worlds are created in the app from
|
||||
// the seeds in /backend/seeds.
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
@@ -9,7 +10,6 @@ generator client {
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -32,6 +32,39 @@ enum Species {
|
||||
TIEFLING
|
||||
HALF_ORC
|
||||
ORC
|
||||
AASIMAR
|
||||
GOLIATH
|
||||
AARAKOCRA
|
||||
BUGBEAR
|
||||
CENTAUR
|
||||
CHANGELING
|
||||
DEEP_GNOME
|
||||
DUERGAR
|
||||
ELADRIN
|
||||
FAIRY
|
||||
FIRBOLG
|
||||
AIR_GENASI
|
||||
EARTH_GENASI
|
||||
FIRE_GENASI
|
||||
WATER_GENASI
|
||||
GITHYANKI
|
||||
GITHZERAI
|
||||
GOBLIN
|
||||
HARENGON
|
||||
HOBGOBLIN
|
||||
KENKU
|
||||
KOBOLD
|
||||
LIZARDFOLK
|
||||
MINOTAUR
|
||||
SEA_ELF
|
||||
SHADAR_KAI
|
||||
SHIFTER
|
||||
TABAXI
|
||||
TORTLE
|
||||
TRITON
|
||||
YUAN_TI
|
||||
OWLIN
|
||||
SATYR
|
||||
}
|
||||
|
||||
enum CharacterClass {
|
||||
@@ -47,6 +80,7 @@ enum CharacterClass {
|
||||
WARLOCK
|
||||
DRUID
|
||||
MONK
|
||||
ARTIFICER
|
||||
}
|
||||
|
||||
enum Ability {
|
||||
@@ -83,6 +117,7 @@ enum BuildStage {
|
||||
NOT_STARTED
|
||||
ROLLING_SPECIES
|
||||
ROLLING_CLASS
|
||||
CHOOSING_SUBCLASS
|
||||
ROLLING_MOTIVATION
|
||||
ASSIGNING_SCORES
|
||||
ASSIGNING_PROFICIENCIES
|
||||
@@ -99,11 +134,13 @@ 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.
|
||||
// What kind of scene an encounter is: a fight run in initiative order, a
|
||||
// quest scene built around NPCs and an objective, or free roam, where the
|
||||
// party wanders between places the DM has laid out (to shop, to meet people).
|
||||
enum EncounterMode {
|
||||
BATTLE
|
||||
QUEST
|
||||
FREE_ROAM
|
||||
}
|
||||
|
||||
enum NpcDisposition {
|
||||
@@ -138,6 +175,42 @@ enum DiceMode {
|
||||
PHYSICAL
|
||||
}
|
||||
|
||||
// Which dice a campaign plays with. BOTH leaves it to each character (and
|
||||
// every roll can still be typed in from a real die).
|
||||
enum CampaignDiceMode {
|
||||
DIGITAL
|
||||
PHYSICAL
|
||||
BOTH
|
||||
}
|
||||
|
||||
// How a character's maximum HP grows on a level up: the fixed average of the
|
||||
// hit die (rounded up), or a roll of it.
|
||||
enum HpMethod {
|
||||
AVERAGE
|
||||
ROLL
|
||||
}
|
||||
|
||||
// How the builder arrives at the six ability scores.
|
||||
enum ScoreMethod {
|
||||
ROLL_4D6
|
||||
STANDARD_ARRAY
|
||||
POINT_BUY
|
||||
}
|
||||
|
||||
// Who sees a roll. ALL: everyone at the table. OWN: a player sees their own;
|
||||
// the DM always sees every roll.
|
||||
enum RollVisibility {
|
||||
ALL
|
||||
OWN
|
||||
}
|
||||
|
||||
// What a critical hit does to the damage: roll the dice twice (the rule), or
|
||||
// take the dice at their maximum and roll them once more on top.
|
||||
enum CritRule {
|
||||
DOUBLE_DICE
|
||||
MAX_PLUS_ROLL
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Identity & campaigns
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -179,6 +252,28 @@ model Campaign {
|
||||
// bear at one time. A pair of daggers is one weapon, made as such.
|
||||
maxEquipped Int @default(2)
|
||||
maxEquippedWeapons Int @default(1)
|
||||
// Off: nobody chooses a subclass. Each class follows its first one without
|
||||
// being asked, and subclasses are not named anywhere.
|
||||
subclassesEnabled Boolean @default(true)
|
||||
// On: a character can take levels in more than one class (game/multiclass.js).
|
||||
multiclassEnabled Boolean @default(false)
|
||||
// Which dice are rolled at this table; see CampaignDiceMode.
|
||||
diceMode CampaignDiceMode @default(BOTH)
|
||||
// On: when a monster's (or an NPC's) turn comes up in a battle, the server
|
||||
// picks a target, rolls the attack and the damage, and puts it to the DM to
|
||||
// accept, change or throw out.
|
||||
autoRollMonsters Boolean @default(false)
|
||||
autoRollNpcs Boolean @default(false)
|
||||
// Off: experience is not kept. No XP on the sheets, nothing to award after
|
||||
// an encounter, and nobody is shown as due a level.
|
||||
trackXp Boolean @default(true)
|
||||
hpOnLevelUp HpMethod @default(AVERAGE)
|
||||
abilityScoreMethod ScoreMethod @default(ROLL_4D6)
|
||||
rollVisibility RollVisibility @default(ALL)
|
||||
// On: the DM's rolls for monsters and NPCs are seen by the DM alone until
|
||||
// they are put into play.
|
||||
hideMonsterRolls Boolean @default(true)
|
||||
critRule CritRule @default(DOUBLE_DICE)
|
||||
ownerId String
|
||||
// Set while the campaign is archived: kept in full, but moved off the main
|
||||
// list and closed to new members until the DM restores it.
|
||||
@@ -197,10 +292,40 @@ model Campaign {
|
||||
saleOffers SaleOffer[]
|
||||
notes Note[]
|
||||
locations Location[]
|
||||
diceRolls DiceRoll[]
|
||||
|
||||
@@map("campaigns")
|
||||
}
|
||||
|
||||
// A roll made at the table's dice roller, kept so the table (and above all
|
||||
// the DM) can see it. Digital rolls are made by the server; physical ones are
|
||||
// typed in and checked against their dice. Who sees a roll follows the
|
||||
// campaign's rollVisibility; a `hidden` one is the DM's alone.
|
||||
model DiceRoll {
|
||||
id String @id @default(cuid())
|
||||
campaignId String
|
||||
userId String
|
||||
rollerName String // who rolled, as shown: kept so a roll outlives a renamed account
|
||||
label String? // what it was for: "Aria: Stealth"
|
||||
notation String // "1d20+3", "2d6+1d8+2"
|
||||
// Every die, in order: [{ sides, value, kept, sign }]. `kept` is false for
|
||||
// the d20 that advantage or disadvantage dropped.
|
||||
dice Json
|
||||
modifier Int @default(0)
|
||||
total Int
|
||||
natural Int? // the d20 that counted, for a roll of a single d20
|
||||
mode String @default("NORMAL") // NORMAL | ADVANTAGE | DISADVANTAGE
|
||||
physical Boolean @default(false) // rolled at the table and typed in
|
||||
hidden Boolean @default(false) // the DM's alone
|
||||
encounterId String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([campaignId, createdAt])
|
||||
@@map("dice_rolls")
|
||||
}
|
||||
|
||||
model Location {
|
||||
id String @id @default(cuid())
|
||||
campaignId String
|
||||
@@ -212,7 +337,12 @@ model Location {
|
||||
characters Character[]
|
||||
encounters Encounter[]
|
||||
visits CharacterLocationVisit[]
|
||||
// Who is found here, what is for sale here, and the free-roam scenes it is a stop in.
|
||||
npcs Npc[]
|
||||
wares SaleOffer[]
|
||||
freeRoams EncounterLocation[]
|
||||
|
||||
@@index([campaignId])
|
||||
@@map("locations")
|
||||
}
|
||||
|
||||
@@ -243,6 +373,7 @@ model CampaignMember {
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([campaignId, userId])
|
||||
@@index([userId])
|
||||
@@map("campaign_members")
|
||||
}
|
||||
|
||||
@@ -258,7 +389,17 @@ model Character {
|
||||
name String
|
||||
species Species?
|
||||
characterClass CharacterClass?
|
||||
// The path taken within the class: a key from game/data/subclasses.js. Null
|
||||
// until the class reaches the level it chooses at.
|
||||
subclass String?
|
||||
level Int @default(1)
|
||||
// Levels the DM has approved that the character has not yet taken: each is
|
||||
// one level-up checklist waiting for its picks. The player resolves them
|
||||
// (or the DM does), one at a time.
|
||||
levelUpsPending Int @default(0)
|
||||
// Where the campaign rolls HP on a level up: how far the rolls so far are
|
||||
// from the average they replace, in all (a 2 on a d8 is -3). Added to max HP.
|
||||
hpRollAdjust Int @default(0)
|
||||
xp Int @default(0)
|
||||
motivation String?
|
||||
|
||||
@@ -270,9 +411,10 @@ model Character {
|
||||
wisScore Int @default(10)
|
||||
chaScore Int @default(10)
|
||||
|
||||
// Half-Elf's flexible +1/+1 choice; null unless species = HALF_ELF
|
||||
halfElfBonusAbility1 Ability?
|
||||
halfElfBonusAbility2 Ability?
|
||||
// The ability bonuses the player chose for their species, on top of its
|
||||
// fixed ones, as { ability: amount }: a Half-Elf's +1/+1, a Goblin's +2/+1...
|
||||
// Empty for a species with nothing to choose (game/data/species.js).
|
||||
speciesBonusChoices Json @default("{}")
|
||||
|
||||
currentHp Int @default(0)
|
||||
tempHp Int @default(0)
|
||||
@@ -281,6 +423,21 @@ model Character {
|
||||
deathSaveSuccesses Int @default(0)
|
||||
deathSaveFailures Int @default(0)
|
||||
stable Boolean @default(false) // at 0 HP but no longer rolling
|
||||
// What has been spent since the last rest. Spell slots by slot level (the
|
||||
// first entry is 1st-level slots); how many there are comes from class and
|
||||
// level (game/calculations.js, spellSlotsFor). A character has one Hit Die
|
||||
// per level, spent on short rests.
|
||||
spellSlotsUsed Int[] @default([])
|
||||
hitDiceUsed Int @default(0)
|
||||
// Class counters spent since the rest that gives them back, as
|
||||
// { key: used } (game/classResources.js says which a character has).
|
||||
resourcesUsed Json @default("{}")
|
||||
// How the character is doing beyond HP. Reminders for the table: none of
|
||||
// them changes a number on the sheet. Conditions are the character's own,
|
||||
// so they outlast the encounter they were given in.
|
||||
inspiration Boolean @default(false)
|
||||
exhaustion Int @default(0) // 0 to 6
|
||||
conditions String[] @default([])
|
||||
armorBonus Int @default(0) // a flat AC adjustment the DM sets by hand, on top of what equipped gear gives
|
||||
speedOverride Int?
|
||||
|
||||
@@ -322,10 +479,31 @@ model Character {
|
||||
notes Note[]
|
||||
encounterEntries EncounterParticipant[]
|
||||
locationVisits CharacterLocationVisit[]
|
||||
// Levels in classes other than characterClass, for a multiclassed character
|
||||
// (game/multiclass.js). The first class's own level is `level` less these.
|
||||
classLevels CharacterClassLevel[]
|
||||
|
||||
@@index([campaignId])
|
||||
@@index([userId])
|
||||
@@map("characters")
|
||||
}
|
||||
|
||||
// A class a character has taken levels in besides their first (characterClass),
|
||||
// with its own level and subclass. A single-class character has none.
|
||||
model CharacterClassLevel {
|
||||
id String @id @default(cuid())
|
||||
characterId String
|
||||
characterClass CharacterClass
|
||||
level Int @default(1)
|
||||
subclass String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
character Character @relation(fields: [characterId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([characterId, characterClass])
|
||||
@@map("character_class_levels")
|
||||
}
|
||||
|
||||
model CharacterSkillProficiency {
|
||||
id String @id @default(cuid())
|
||||
characterId String
|
||||
@@ -386,6 +564,7 @@ model Weapon {
|
||||
rewards EncounterReward[]
|
||||
offers SaleOffer[]
|
||||
|
||||
@@index([campaignId])
|
||||
@@map("weapons")
|
||||
}
|
||||
|
||||
@@ -418,6 +597,10 @@ model Item {
|
||||
// item with an AC effect.
|
||||
effects Json @default("[]")
|
||||
effectNote String?
|
||||
// Set on armor and shields. Its AC is still an effect; this says what kind
|
||||
// it is, so the sheet knows when a character is unarmored (Unarmored
|
||||
// Defense, a monk's speed) or in heavy armor (a barbarian's Fast Movement).
|
||||
armorType ArmorType?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)
|
||||
@@ -425,9 +608,17 @@ model Item {
|
||||
rewards EncounterReward[]
|
||||
offers SaleOffer[]
|
||||
|
||||
@@index([campaignId])
|
||||
@@map("items")
|
||||
}
|
||||
|
||||
enum ArmorType {
|
||||
LIGHT
|
||||
MEDIUM
|
||||
HEAVY
|
||||
SHIELD
|
||||
}
|
||||
|
||||
// An Item from the campaign pool held by a character.
|
||||
model InventoryItem {
|
||||
id String @id @default(cuid())
|
||||
@@ -482,10 +673,18 @@ model Spell {
|
||||
// Brings back the dead: a character who can cast it may revive a dead ally
|
||||
// on their turn in a battle (encounters.routes.js).
|
||||
revives Boolean @default(false)
|
||||
// How it lands in a battle (game/combat.js). attackRoll: the caster rolls a
|
||||
// spell attack against AC. saveAbility: each target saves against the
|
||||
// caster's spell DC with this ability, taking half on a success when
|
||||
// halfOnSave. Neither: it simply takes effect.
|
||||
attackRoll Boolean @default(false)
|
||||
saveAbility Ability?
|
||||
halfOnSave Boolean @default(false)
|
||||
|
||||
campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)
|
||||
known CharacterSpell[]
|
||||
|
||||
@@index([campaignId])
|
||||
@@map("spells")
|
||||
}
|
||||
|
||||
@@ -524,10 +723,16 @@ model Monster {
|
||||
challengeRating String?
|
||||
specialTrait String?
|
||||
notes String?
|
||||
// Named attacks, for a monster with more than the one above: a list of
|
||||
// { name, attackBonus, damageDice, damageType?, count? }. `count` is how
|
||||
// many times it is made each turn (a multiattack). Empty: the single
|
||||
// attackBonus/damageDice above is its attack.
|
||||
attacks Json @default("[]")
|
||||
|
||||
campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)
|
||||
encounterAppearances EncounterParticipant[]
|
||||
|
||||
@@index([campaignId])
|
||||
@@map("monsters")
|
||||
}
|
||||
|
||||
@@ -549,12 +754,17 @@ model Npc {
|
||||
// for exchangeCash cash, either way. Both null: this NPC does not exchange.
|
||||
exchangeGold Int?
|
||||
exchangeCash Int?
|
||||
// Where this NPC is usually found. In a free-roam scene they are met (and
|
||||
// traded with) by whoever goes there.
|
||||
locationId String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)
|
||||
location Location? @relation(fields: [locationId], references: [id], onDelete: SetNull)
|
||||
encounterAppearances EncounterParticipant[]
|
||||
wares SaleOffer[]
|
||||
|
||||
@@index([campaignId])
|
||||
@@map("npcs")
|
||||
}
|
||||
|
||||
@@ -581,6 +791,9 @@ model Encounter {
|
||||
archivedAt DateTime?
|
||||
// Place in the campaign's own order, lowest first. The DM rearranges it.
|
||||
sortOrder Int @default(0)
|
||||
// The experience points handed out for this encounter, in all; null until
|
||||
// the DM awards them. They are awarded once.
|
||||
xpAwarded Int?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -589,10 +802,66 @@ model Encounter {
|
||||
participants EncounterParticipant[]
|
||||
rewards EncounterReward[]
|
||||
wares SaleOffer[]
|
||||
actions EncounterAction[]
|
||||
// Free roam: the places the party can go to in this scene.
|
||||
places EncounterLocation[]
|
||||
|
||||
@@index([campaignId])
|
||||
@@map("encounters")
|
||||
}
|
||||
|
||||
// A place that is a stop in a free-roam scene: one of the campaign's
|
||||
// locations, picked by the DM as somewhere the party can go right now.
|
||||
model EncounterLocation {
|
||||
id String @id @default(cuid())
|
||||
encounterId String
|
||||
locationId String
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
encounter Encounter @relation(fields: [encounterId], references: [id], onDelete: Cascade)
|
||||
location Location @relation(fields: [locationId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([encounterId, locationId])
|
||||
@@map("encounter_locations")
|
||||
}
|
||||
|
||||
// An attack or a spell in a battle, from the moment it is declared to the
|
||||
// moment its damage lands (game/combat.js). A player declares their own on
|
||||
// their turn; the DM declares anyone's; and with the campaign's auto-roll
|
||||
// settings the server declares a monster's or NPC's, already rolled. While
|
||||
// PENDING it gathers what it needs (a d20 against each target's AC, or each
|
||||
// target's saving throw, and the damage); the DM then applies it, changed as
|
||||
// they see fit, or discards it. `hidden` keeps it from the players until it
|
||||
// is applied.
|
||||
model EncounterAction {
|
||||
id String @id @default(cuid())
|
||||
encounterId String
|
||||
round Int
|
||||
actorParticipantId String?
|
||||
actorName String
|
||||
kind String // ATTACK (a d20 against AC) | SAVE (targets save against a DC) | AUTO (it just lands)
|
||||
name String // "Longsword", "Fireball", "Bite"
|
||||
// What it rolls with: { attackBonus?, saveAbility?, saveDC?, halfOnSave?,
|
||||
// damageDice?, damageBonus, damageType?, characterId?, slotLevel? }.
|
||||
detail Json
|
||||
// One entry per target: { participantId, name, kind, ac, penalty, saveBonus,
|
||||
// d20, outcome (set by the DM to overrule the dice), damage (likewise) }.
|
||||
targets Json
|
||||
// The damage once rolled or entered: { total, dice?, modifier?, crit? }.
|
||||
damage Json?
|
||||
status String @default("PENDING") // PENDING | APPLIED | DISCARDED
|
||||
auto Boolean @default(false) // declared and rolled by the server
|
||||
hidden Boolean @default(false)
|
||||
createdById String?
|
||||
createdAt DateTime @default(now())
|
||||
appliedAt DateTime?
|
||||
|
||||
encounter Encounter @relation(fields: [encounterId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([encounterId, status])
|
||||
@@map("encounter_actions")
|
||||
}
|
||||
|
||||
// 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).
|
||||
@@ -615,19 +884,22 @@ model EncounterReward {
|
||||
weapon Weapon? @relation(fields: [weaponId], references: [id], onDelete: Cascade)
|
||||
item Item? @relation(fields: [itemId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([encounterId])
|
||||
@@map("encounter_rewards")
|
||||
}
|
||||
|
||||
// Something for sale: a weapon or item from the campaign pools, at a price.
|
||||
// It belongs to an NPC (and is on offer wherever that NPC is met) or to an
|
||||
// encounter itself (a stall, a vending machine). Only the DM sets these up;
|
||||
// players see them, and buy, in a quest encounter in progress
|
||||
// (encounters.routes.js).
|
||||
// It belongs to an NPC (and is on offer wherever that NPC is met), to an
|
||||
// encounter itself (a stall, a vending machine), or to a location (a shop
|
||||
// that is always there, open to whoever goes to it in a free-roam scene).
|
||||
// Only the DM sets these up; players see them, and buy, in a quest or
|
||||
// free-roam encounter in progress (encounters.routes.js).
|
||||
model SaleOffer {
|
||||
id String @id @default(cuid())
|
||||
campaignId String
|
||||
npcId String? // exactly one of npcId / encounterId is set
|
||||
npcId String? // exactly one of npcId / encounterId / locationId is set
|
||||
encounterId String?
|
||||
locationId String?
|
||||
weaponId String? // exactly one of weaponId / itemId is set
|
||||
itemId String?
|
||||
price Int // for one, in `currency`
|
||||
@@ -639,9 +911,14 @@ model SaleOffer {
|
||||
campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)
|
||||
npc Npc? @relation(fields: [npcId], references: [id], onDelete: Cascade)
|
||||
encounter Encounter? @relation(fields: [encounterId], references: [id], onDelete: Cascade)
|
||||
location Location? @relation(fields: [locationId], references: [id], onDelete: Cascade)
|
||||
weapon Weapon? @relation(fields: [weaponId], references: [id], onDelete: Cascade)
|
||||
item Item? @relation(fields: [itemId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([campaignId])
|
||||
@@index([npcId])
|
||||
@@index([encounterId])
|
||||
@@index([locationId])
|
||||
@@map("sale_offers")
|
||||
}
|
||||
|
||||
@@ -664,7 +941,10 @@ model EncounterParticipant {
|
||||
initiative Int @default(0)
|
||||
currentHp Int
|
||||
maxHp Int
|
||||
conditions String[] @default([]) // e.g. ["poisoned", "prone"]
|
||||
conditions String[] @default([]) // e.g. ["poisoned", "prone"]; a character's own are on the Character row
|
||||
// Conditions that wear off by themselves, as { condition: rounds left }.
|
||||
// Counted down each time the round goes up; at 0 the condition is removed.
|
||||
conditionRounds Json @default("{}")
|
||||
isMonster Boolean
|
||||
|
||||
encounter Encounter @relation(fields: [encounterId], references: [id], onDelete: Cascade)
|
||||
@@ -672,6 +952,8 @@ model EncounterParticipant {
|
||||
monster Monster? @relation(fields: [monsterId], references: [id], onDelete: SetNull)
|
||||
npc Npc? @relation(fields: [npcId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([encounterId])
|
||||
@@index([characterId])
|
||||
@@map("encounter_participants")
|
||||
}
|
||||
|
||||
@@ -692,5 +974,7 @@ model Note {
|
||||
character Character? @relation(fields: [characterId], references: [id], onDelete: Cascade)
|
||||
author User @relation(fields: [authorId], references: [id])
|
||||
|
||||
@@index([campaignId])
|
||||
@@index([characterId])
|
||||
@@map("notes")
|
||||
}
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
// Adds the Hollowcrown: The Rift Between Worlds campaign
|
||||
// (seed-data/hollowcrown.js) for the admin account. Not part of the default
|
||||
// seed — run it on its own:
|
||||
//
|
||||
// npm run seed:hollowcrown
|
||||
//
|
||||
// Like every seed it only adds (see seedCampaign.js): it never touches other
|
||||
// campaigns, and does nothing if the admin already has an active Hollowcrown.
|
||||
const { run, fromLibrary } = require('./seedCampaign');
|
||||
const { WEAPON_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../src/game/data/library');
|
||||
const hollowcrown = require('../seed-data/hollowcrown.js');
|
||||
|
||||
const startingSpells = new Set(hollowcrown.startingSpells);
|
||||
for (const key of startingSpells) fromLibrary(SPELL_LIBRARY, key); // fail early on a misspelt key
|
||||
|
||||
run({
|
||||
...hollowcrown,
|
||||
// The book's starting picks come from the site library; its modern relics
|
||||
// and magic weapons are never starting options.
|
||||
weapons: [
|
||||
...hollowcrown.libraryWeapons.map((key) => fromLibrary(WEAPON_LIBRARY, key, { isStartingOption: true })),
|
||||
...hollowcrown.weapons,
|
||||
],
|
||||
// The whole spell library goes in, so a spell is there to hand out the
|
||||
// moment a character unlocks it; only the book's Session 0 list is offered
|
||||
// in the builder.
|
||||
spells: [
|
||||
...SPELL_LIBRARY.map(({ key }) => fromLibrary(SPELL_LIBRARY, key, { isStartingOption: startingSpells.has(key) })),
|
||||
...hollowcrown.spells,
|
||||
],
|
||||
monsters: [...hollowcrown.libraryMonsters.map((key) => fromLibrary(MONSTER_LIBRARY, key)), ...hollowcrown.monsters],
|
||||
});
|
||||
+48
-26
@@ -1,32 +1,54 @@
|
||||
// The default seed: the Aldenfell campaign (seed-data/aldenfell.js) for the
|
||||
// admin account. See seedCampaign.js for what a seed does and why it is safe
|
||||
// to run against a live database.
|
||||
// The database seed: makes sure the admin account exists, and nothing else.
|
||||
//
|
||||
// npx prisma db seed add what is missing
|
||||
// npx prisma db seed create the admin account if it is missing
|
||||
// npx prisma db seed -- --reset DESTRUCTIVE: delete every user, campaign,
|
||||
// character, note, etc. first
|
||||
//
|
||||
// Other campaigns have their own command (npm run seed:hollowcrown).
|
||||
// It only ever adds, so it is safe against a live database: an existing
|
||||
// account, and its password, is left alone. SEED_ADMIN_EMAIL /
|
||||
// SEED_ADMIN_PASSWORD / SEED_ADMIN_NAME override the account that is created.
|
||||
//
|
||||
// Species/classes/skills are NOT seeded as rows — they're fixed game-rule
|
||||
// tables ported into src/game/data/*.js, as is the default weapon/spell/monster
|
||||
// library DMs pull from. The default weapons (seed-data/weapons.json) ARE
|
||||
// seeded, into the campaign, since weapons are per-campaign in the schema.
|
||||
const { run, fromLibrary } = require('./seedCampaign');
|
||||
const { SPELL_LIBRARY } = require('../src/game/data/library');
|
||||
const defaultWeapons = require('../seed-data/weapons.json');
|
||||
const aldenfell = require('../seed-data/aldenfell.js');
|
||||
// Worlds are not seeded here. A campaign is created in the app, blank or from
|
||||
// one of the world seeds in /backend/seeds by its code (docs/SEEDS.md).
|
||||
//
|
||||
// Species/classes/skills are not rows either: they are fixed game-rule tables
|
||||
// in src/game/data/*.js, as is the library DMs pull weapons, items, spells
|
||||
// and monsters from.
|
||||
const bcrypt = require('bcrypt');
|
||||
const prisma = require('../src/db');
|
||||
const { loadSeeds } = require('../src/seeds');
|
||||
|
||||
run(
|
||||
{
|
||||
...aldenfell,
|
||||
// Everyday weapons are what a new character picks from; the rest are earned.
|
||||
weapons: [...defaultWeapons.map((w) => ({ ...w, isStartingOption: true })), ...aldenfell.weapons],
|
||||
items: aldenfell.items.map(({ starting, ...item }) => ({ ...item, isStartingOption: Boolean(starting) })),
|
||||
spells: [
|
||||
...aldenfell.spells.starting.map((key) => fromLibrary(SPELL_LIBRARY, key, { isStartingOption: true })),
|
||||
...aldenfell.spells.earned.map((key) => fromLibrary(SPELL_LIBRARY, key, { isStartingOption: false })),
|
||||
],
|
||||
},
|
||||
{ reset: process.argv.includes('--reset') },
|
||||
);
|
||||
const ADMIN_EMAIL = process.env.SEED_ADMIN_EMAIL || 'joshua@crosscode.co.za';
|
||||
const ADMIN_PASSWORD = process.env.SEED_ADMIN_PASSWORD || '12345678';
|
||||
const ADMIN_NAME = process.env.SEED_ADMIN_NAME || 'Joshua';
|
||||
|
||||
async function seed({ reset = false } = {}) {
|
||||
if (reset) {
|
||||
// Truncating the two roots cascades through every table that references them.
|
||||
await prisma.$executeRawUnsafe('TRUNCATE TABLE "users", "campaigns" RESTART IDENTITY CASCADE');
|
||||
console.log('Database reset: every user and campaign was deleted.');
|
||||
}
|
||||
|
||||
if (await prisma.user.findUnique({ where: { email: ADMIN_EMAIL } })) {
|
||||
console.log(`Admin account ${ADMIN_EMAIL} already exists — left as it is.`);
|
||||
} else {
|
||||
await prisma.user.create({
|
||||
data: { email: ADMIN_EMAIL, passwordHash: await bcrypt.hash(ADMIN_PASSWORD, 12), displayName: ADMIN_NAME },
|
||||
});
|
||||
console.log(`Admin/DM login created: ${ADMIN_EMAIL} / ${ADMIN_PASSWORD}`);
|
||||
console.log(' Change that password from the account page ("Account" in the navigation) once you are logged in.');
|
||||
}
|
||||
|
||||
const worlds = loadSeeds().filter((world) => !world.error);
|
||||
if (worlds.length) {
|
||||
console.log('Worlds to start a campaign from (Campaigns → New Campaign → world code):');
|
||||
for (const { code, seed: world } of worlds) console.log(` ${code} ${world.campaign.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
seed({ reset: process.argv.includes('--reset') })
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(() => prisma.$disconnect());
|
||||
|
||||
@@ -1,210 +0,0 @@
|
||||
// Shared by the campaign seeds (seed.js, seed-hollowcrown.js): makes sure the
|
||||
// admin account exists, then adds one fully-built campaign for it.
|
||||
//
|
||||
// A seed only ever ADDS, so it is safe against a live database. The admin
|
||||
// account is created if it is missing (an existing one, and its password, is
|
||||
// left alone), and the campaign is added unless that account already owns an
|
||||
// active campaign of the same name. To get a fresh copy, archive or delete the
|
||||
// old one in the app and run the seed again.
|
||||
//
|
||||
// SEED_ADMIN_EMAIL / SEED_ADMIN_PASSWORD / SEED_ADMIN_NAME override the
|
||||
// account that is created.
|
||||
//
|
||||
// `content` is one campaign, with every pool as rows shaped like the Prisma
|
||||
// models minus ids:
|
||||
// campaign, locations, weapons, items, spells, monsters, npcs,
|
||||
// sharedNotes, dmNotes (note bodies, in reading order), and
|
||||
// encounters, in the order they should list:
|
||||
// { name, mode, description, dmNotes,
|
||||
// location: a location's name (optional) — where the scene is,
|
||||
// monsters: [[monster name, count, display name?, max HP?], ...],
|
||||
// npcs: [NPC name | { name, hp }, ...],
|
||||
// rewards: [{ gold } | { weapon } | { item }, each with optional
|
||||
// quantity, level (defaults to the entry's starting level)
|
||||
// and note] }
|
||||
const bcrypt = require('bcrypt');
|
||||
const { PrismaClient } = require('@prisma/client');
|
||||
const { generateInviteCode } = require('../src/utils/inviteCode');
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
const ADMIN_EMAIL = process.env.SEED_ADMIN_EMAIL || 'joshua@crosscode.co.za';
|
||||
const ADMIN_PASSWORD = process.env.SEED_ADMIN_PASSWORD || '12345678';
|
||||
const ADMIN_NAME = process.env.SEED_ADMIN_NAME || 'Joshua';
|
||||
|
||||
// Notes list newest-first on screen, so they are stamped a second apart,
|
||||
// backwards: the first entry in the seed data is the one at the top.
|
||||
function bookOrder(index) {
|
||||
return new Date(Date.now() - index * 1000);
|
||||
}
|
||||
|
||||
function byName(rows) {
|
||||
return new Map(rows.map((row) => [row.name, row]));
|
||||
}
|
||||
|
||||
function lookup(map, name, what, encounterName) {
|
||||
const row = map.get(name);
|
||||
if (!row) throw new Error(`Encounter "${encounterName}" references unknown ${what} "${name}"`);
|
||||
return row;
|
||||
}
|
||||
|
||||
async function createCampaign(db, admin, content) {
|
||||
const campaign = await db.campaign.create({
|
||||
data: {
|
||||
...content.campaign,
|
||||
inviteCode: generateInviteCode(),
|
||||
ownerId: admin.id,
|
||||
members: { create: { userId: admin.id, role: 'DM' } },
|
||||
},
|
||||
});
|
||||
const campaignId = campaign.id;
|
||||
const inCampaign = (rows) => rows.map((row) => ({ ...row, campaignId }));
|
||||
|
||||
await db.location.createMany({ data: inCampaign(content.locations) });
|
||||
await db.weapon.createMany({ data: inCampaign(content.weapons) });
|
||||
await db.item.createMany({ data: inCampaign(content.items) });
|
||||
await db.spell.createMany({ data: inCampaign(content.spells) });
|
||||
await db.monster.createMany({ data: inCampaign(content.monsters) });
|
||||
await db.npc.createMany({ data: inCampaign(content.npcs) });
|
||||
|
||||
const monsters = byName(await db.monster.findMany({ where: { campaignId } }));
|
||||
const npcs = byName(await db.npc.findMany({ where: { campaignId } }));
|
||||
const weapons = byName(await db.weapon.findMany({ where: { campaignId } }));
|
||||
const items = byName(await db.item.findMany({ where: { campaignId } }));
|
||||
const locations = byName(await db.location.findMany({ where: { campaignId } }));
|
||||
|
||||
let rewardCount = 0;
|
||||
for (const [index, enc] of content.encounters.entries()) {
|
||||
const participants = [];
|
||||
for (const [name, count, displayName, hp] of enc.monsters || []) {
|
||||
const monster = lookup(monsters, name, 'monster', enc.name);
|
||||
const label = displayName || monster.name;
|
||||
const maxHp = hp ?? monster.maxHp;
|
||||
for (let i = 1; i <= count; i++) {
|
||||
participants.push({
|
||||
monsterId: monster.id,
|
||||
displayName: count > 1 ? `${label} #${i}` : label,
|
||||
currentHp: maxHp,
|
||||
maxHp,
|
||||
isMonster: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const entry of enc.npcs || []) {
|
||||
const { name, hp } = typeof entry === 'string' ? { name: entry } : entry;
|
||||
const npc = lookup(npcs, name, 'NPC', enc.name);
|
||||
// An NPC with no combat stats takes part with no hit points to track.
|
||||
const maxHp = hp ?? npc.maxHp ?? 0;
|
||||
participants.push({ npcId: npc.id, displayName: npc.name, currentHp: maxHp, maxHp, isMonster: false });
|
||||
}
|
||||
|
||||
// Rewards list oldest-first, so these are stamped forwards.
|
||||
const rewards = (enc.rewards || []).map(({ gold, weapon, item, quantity, level, note }, i) => {
|
||||
const createdAt = new Date(Date.now() + i);
|
||||
if (gold) return { type: 'GOLD', gold, note, createdAt };
|
||||
const entry = weapon ? lookup(weapons, weapon, 'weapon', enc.name) : lookup(items, item, 'item', enc.name);
|
||||
return {
|
||||
type: weapon ? 'WEAPON' : 'ITEM',
|
||||
[weapon ? 'weaponId' : 'itemId']: entry.id,
|
||||
quantity: quantity ?? 1,
|
||||
level: Math.max(level ?? entry.minLevel, entry.minLevel),
|
||||
note,
|
||||
createdAt,
|
||||
};
|
||||
});
|
||||
rewardCount += rewards.length;
|
||||
|
||||
await db.encounter.create({
|
||||
data: {
|
||||
campaignId,
|
||||
name: enc.name,
|
||||
mode: enc.mode,
|
||||
description: enc.description,
|
||||
dmNotes: enc.dmNotes,
|
||||
locationId: enc.location ? lookup(locations, enc.location, 'location', enc.name).id : null,
|
||||
sortOrder: index,
|
||||
participants: { create: participants },
|
||||
rewards: { create: rewards },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const notes = [
|
||||
...content.sharedNotes.map((body) => ({ body, visibility: 'SHARED' })),
|
||||
...content.dmNotes.map((body) => ({ body, visibility: 'DM_ONLY' })),
|
||||
];
|
||||
await db.note.createMany({
|
||||
data: notes.map((n, i) => ({ ...n, campaignId, authorId: admin.id, createdAt: bookOrder(i) })),
|
||||
});
|
||||
|
||||
const starting = (rows) => rows.filter((row) => row.isStartingOption).length;
|
||||
console.log(` Campaign: ${campaign.name} — invite code ${campaign.inviteCode}`);
|
||||
console.log(
|
||||
` ${content.weapons.length} weapons (${starting(content.weapons)} starting), ${content.items.length} items ` +
|
||||
`(${starting(content.items)} starting), ${content.spells.length} spells (${starting(content.spells)} starting), ` +
|
||||
`${content.locations.length} locations`,
|
||||
);
|
||||
console.log(
|
||||
` ${content.monsters.length} monsters, ${content.npcs.length} NPCs, ${content.encounters.length} encounters ` +
|
||||
`(${rewardCount} rewards lined up), ${notes.length} notes`,
|
||||
);
|
||||
}
|
||||
|
||||
async function resetDatabase() {
|
||||
// Truncating the two roots cascades through every table that references them.
|
||||
await prisma.$executeRawUnsafe('TRUNCATE TABLE "users", "campaigns" RESTART IDENTITY CASCADE');
|
||||
}
|
||||
|
||||
// `reset` is DESTRUCTIVE: every user, campaign, character, note, etc. is
|
||||
// deleted before anything is added.
|
||||
async function seed(content, { reset = false } = {}) {
|
||||
if (reset) {
|
||||
await resetDatabase();
|
||||
console.log('Database reset: every user and campaign was deleted.');
|
||||
}
|
||||
|
||||
let admin = await prisma.user.findUnique({ where: { email: ADMIN_EMAIL } });
|
||||
if (admin) {
|
||||
console.log(`Admin account ${ADMIN_EMAIL} already exists — left as it is.`);
|
||||
} else {
|
||||
admin = await prisma.user.create({
|
||||
data: { email: ADMIN_EMAIL, passwordHash: await bcrypt.hash(ADMIN_PASSWORD, 12), displayName: ADMIN_NAME },
|
||||
});
|
||||
console.log(`Admin/DM login created: ${ADMIN_EMAIL} / ${ADMIN_PASSWORD}`);
|
||||
console.log(' Change that password from the account page (click your name, top right) once you are logged in.');
|
||||
}
|
||||
|
||||
const existing = await prisma.campaign.findFirst({
|
||||
where: { ownerId: admin.id, name: content.campaign.name, archivedAt: null },
|
||||
});
|
||||
if (existing) {
|
||||
console.log(`${ADMIN_EMAIL} already has an active "${existing.name}" campaign — nothing added.`);
|
||||
console.log(' For a fresh copy, archive or delete it under Campaign Settings and run the seed again.');
|
||||
return;
|
||||
}
|
||||
|
||||
// One transaction, so a failed seed doesn't leave half a campaign behind.
|
||||
console.log('Seeding campaign...');
|
||||
await prisma.$transaction((tx) => createCampaign(tx, admin, content), { timeout: 120000, maxWait: 20000 });
|
||||
console.log('Seed complete.');
|
||||
}
|
||||
|
||||
// Runs a seed script to completion: exit code 1 on failure, connection closed either way.
|
||||
function run(content, options) {
|
||||
return seed(content, options)
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(() => prisma.$disconnect());
|
||||
}
|
||||
|
||||
// A copy of a library entry as a pool row: its `key` and picker-only tags dropped.
|
||||
function fromLibrary(library, key, extra = {}) {
|
||||
const template = library.find((entry) => entry.key === key);
|
||||
if (!template) throw new Error(`Unknown library entry "${key}"`);
|
||||
const { key: _key, category, classes, ...row } = template;
|
||||
return { ...row, ...extra };
|
||||
}
|
||||
|
||||
module.exports = { run, fromLibrary };
|
||||
@@ -0,0 +1,27 @@
|
||||
// Checks every world seed in /backend/seeds and says what each one holds, or
|
||||
// what is wrong with it. Run it after dropping in or editing a seed file:
|
||||
//
|
||||
// npm run seeds:check
|
||||
const { loadSeeds, SEEDS_DIR } = require('../src/seeds');
|
||||
|
||||
const results = loadSeeds();
|
||||
if (results.length === 0) console.log(`No seed files in ${SEEDS_DIR}.`);
|
||||
|
||||
for (const { file, code, seed, error } of results) {
|
||||
if (error) {
|
||||
console.error(`✗ ${file}\n${error.replace(/^/gm, ' ')}`);
|
||||
process.exitCode = 1;
|
||||
continue;
|
||||
}
|
||||
const starting = (rows) => rows.filter((row) => row.isStartingOption).length;
|
||||
const count = (rows, of) => rows.reduce((sum, row) => sum + (row[of] || []).length, 0);
|
||||
console.log(`✓ ${file} — code ${code} — ${seed.campaign.name}`);
|
||||
console.log(
|
||||
` ${seed.weapons.length} weapons (${starting(seed.weapons)} starting), ${seed.items.length} items (${starting(seed.items)} starting), ` +
|
||||
`${seed.spells.length} spells (${starting(seed.spells)} starting), ${seed.locations.length} locations`,
|
||||
);
|
||||
console.log(
|
||||
` ${seed.monsters.length} monsters, ${seed.npcs.length} NPCs (${count(seed.npcs, 'wares')} wares), ${seed.encounters.length} encounters ` +
|
||||
`(${count(seed.encounters, 'rewards')} rewards, ${count(seed.encounters, 'wares')} wares), ${seed.sharedNotes.length + seed.dmNotes.length} notes`,
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,9 @@ const { WEAPON_LIBRARY, ITEM_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require
|
||||
const options = require('../src/game/data/characterOptions');
|
||||
const { SPECIES } = require('../src/game/data/species');
|
||||
const { CLASSES } = require('../src/game/data/classes');
|
||||
const { BOONS, MAX_FEATURE_LEVEL } = require('../src/game/data/levelFeatures');
|
||||
const { featuresAt } = require('../src/game/levelUp');
|
||||
const { SUBCLASSES, SUBCLASS_LEVEL } = require('../src/game/data/subclasses');
|
||||
|
||||
const DOCS = path.join(__dirname, '..', '..', 'docs');
|
||||
|
||||
@@ -114,12 +117,48 @@ function builderLists() {
|
||||
].join('\n\n');
|
||||
}
|
||||
|
||||
// What "Level Up" writes for each class at each level, what each of its
|
||||
// subclasses adds, and the Boons.
|
||||
function levelFeatures() {
|
||||
const line = (f) => (f.boon ? '**Boon** (choose one)' : `**${f.name}**${f.upgrade ? ' (replaces)' : ''}: ${f.text}`);
|
||||
const classes = Object.keys(CLASSES)
|
||||
.sort()
|
||||
.map((key) => {
|
||||
const rows = [];
|
||||
for (let level = 2; level <= MAX_FEATURE_LEVEL; level++) {
|
||||
const features = featuresAt(key, level);
|
||||
rows.push([level, features.length > 0 ? features.map(line).join('<br>') : 'No new feature']);
|
||||
}
|
||||
const subclassRows = SUBCLASSES[key].flatMap((subclass) =>
|
||||
Object.keys(subclass.features)
|
||||
.map(Number)
|
||||
.sort((a, b) => a - b)
|
||||
.map((level, i) => [
|
||||
i === 0 ? `**${subclass.name}**<br>${subclass.summary}<br>_${subclass.source}${subclass.replaces ? `, updates ${SUBCLASSES[key].find((s) => s.key === subclass.replaces).name}` : ''}_` : '',
|
||||
level,
|
||||
subclass.features[level].map(line).join('<br>'),
|
||||
])
|
||||
);
|
||||
return [
|
||||
`### ${CLASSES[key].name}`,
|
||||
table(['Level', 'Written into Special Abilities'], rows),
|
||||
`**${CLASSES[key].name} subclasses** (chosen at level ${SUBCLASS_LEVEL[key]}). What each adds to the table above:`,
|
||||
table(['Subclass', 'Level', 'Written into Special Abilities'], subclassRows),
|
||||
].join('\n\n');
|
||||
});
|
||||
const boons = table(
|
||||
['Boon', 'First time', 'Can be taken'],
|
||||
BOONS.map((b) => [b.name, b.text(b.per), b.max === 1 ? 'Once' : `${b.max} times`])
|
||||
);
|
||||
return [`### Boons\n\n${boons}`, ...classes].join('\n\n');
|
||||
}
|
||||
|
||||
const SECTIONS = {
|
||||
'SPELLS.md': { 'spell-library': spellLibrary },
|
||||
'WEAPONS.md': { 'weapon-library': weaponLibrary },
|
||||
'ITEMS.md': { 'item-library': itemLibrary },
|
||||
'MONSTERS.md': { 'monster-library': monsterLibrary },
|
||||
'CHARACTERS.md': { 'builder-lists': builderLists },
|
||||
'CHARACTERS.md': { 'builder-lists': builderLists, 'level-features': levelFeatures },
|
||||
};
|
||||
|
||||
for (const [file, sections] of Object.entries(SECTIONS)) {
|
||||
|
||||
@@ -10,5 +10,6 @@
|
||||
{ "key": "BARD", "name": "Bard", "hitDie": 8, "primaryAbility": "Cha", "saveProficiencies": ["DEX", "CHA"], "spellcastingAbility": "CHA", "skillChoices": { "count": 3, "options": ["ACROBATICS", "ANIMAL_HANDLING", "ARCANA", "ATHLETICS", "DECEPTION", "HISTORY", "INSIGHT", "INTIMIDATION", "INVESTIGATION", "MEDICINE", "NATURE", "PERCEPTION", "PERFORMANCE", "PERSUASION", "RELIGION", "SLEIGHT_OF_HAND", "STEALTH", "SURVIVAL"] } },
|
||||
{ "key": "WARLOCK", "name": "Warlock", "hitDie": 8, "primaryAbility": "Cha", "saveProficiencies": ["WIS", "CHA"], "spellcastingAbility": "CHA", "skillChoices": { "count": 2, "options": ["ARCANA", "DECEPTION", "HISTORY", "INTIMIDATION", "INVESTIGATION", "NATURE", "RELIGION"] } },
|
||||
{ "key": "DRUID", "name": "Druid", "hitDie": 8, "primaryAbility": "Wis", "saveProficiencies": ["INT", "WIS"], "spellcastingAbility": "WIS", "skillChoices": { "count": 2, "options": ["ARCANA", "ANIMAL_HANDLING", "INSIGHT", "MEDICINE", "NATURE", "PERCEPTION", "RELIGION", "SURVIVAL"] } },
|
||||
{ "key": "MONK", "name": "Monk", "hitDie": 8, "primaryAbility": "Dex/Wis", "saveProficiencies": ["STR", "DEX"], "spellcastingAbility": null, "skillChoices": { "count": 2, "options": ["ACROBATICS", "ATHLETICS", "HISTORY", "INSIGHT", "RELIGION", "STEALTH"] } }
|
||||
{ "key": "MONK", "name": "Monk", "hitDie": 8, "primaryAbility": "Dex/Wis", "saveProficiencies": ["STR", "DEX"], "spellcastingAbility": null, "skillChoices": { "count": 2, "options": ["ACROBATICS", "ATHLETICS", "HISTORY", "INSIGHT", "RELIGION", "STEALTH"] } },
|
||||
{ "key": "ARTIFICER", "name": "Artificer", "hitDie": 8, "primaryAbility": "Int", "saveProficiencies": ["CON", "INT"], "spellcastingAbility": "INT", "skillChoices": { "count": 2, "options": ["ARCANA", "HISTORY", "INVESTIGATION", "MEDICINE", "NATURE", "PERCEPTION", "SLEIGHT_OF_HAND"] } }
|
||||
]
|
||||
|
||||
@@ -1,12 +1,45 @@
|
||||
[
|
||||
{ "key": "HUMAN", "name": "Human", "abilityBonuses": { "STR": 1, "DEX": 1, "CON": 1, "INT": 1, "WIS": 1, "CHA": 1 }, "speed": 30, "notes": null },
|
||||
{ "key": "HALF_ELF", "name": "Half-Elf", "abilityBonuses": { "STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 2 }, "speed": 30, "notes": "Fixed +2 CHA plus a flexible +1/+1 to two other abilities of the player's choice. The builder UI must prompt for this choice; do not hardcode a default." },
|
||||
{ "key": "ELF", "name": "Elf", "abilityBonuses": { "STR": 0, "DEX": 2, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0 }, "speed": 30, "notes": null },
|
||||
{ "key": "GNOME", "name": "Gnome", "abilityBonuses": { "STR": 0, "DEX": 0, "CON": 0, "INT": 2, "WIS": 0, "CHA": 0 }, "speed": 25, "notes": null },
|
||||
{ "key": "DWARF", "name": "Dwarf", "abilityBonuses": { "STR": 0, "DEX": 0, "CON": 2, "INT": 0, "WIS": 0, "CHA": 0 }, "speed": 25, "notes": null },
|
||||
{ "key": "HALFLING", "name": "Halfling", "abilityBonuses": { "STR": 0, "DEX": 2, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0 }, "speed": 25, "notes": null },
|
||||
{ "key": "DRAGONBORN", "name": "Dragonborn", "abilityBonuses": { "STR": 2, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 1 }, "speed": 30, "notes": null },
|
||||
{ "key": "TIEFLING", "name": "Tiefling", "abilityBonuses": { "STR": 0, "DEX": 0, "CON": 0, "INT": 1, "WIS": 0, "CHA": 2 }, "speed": 30, "notes": null },
|
||||
{ "key": "HALF_ORC", "name": "Half-Orc", "abilityBonuses": { "STR": 2, "DEX": 0, "CON": 1, "INT": 0, "WIS": 0, "CHA": 0 }, "speed": 30, "notes": null },
|
||||
{ "key": "ORC", "name": "Orc", "abilityBonuses": { "STR": 2, "DEX": 0, "CON": 1, "INT": 0, "WIS": 0, "CHA": 0 }, "speed": 30, "notes": null }
|
||||
{"key": "HUMAN", "name": "Human", "abilityBonuses": {"STR": 1, "DEX": 1, "CON": 1, "INT": 1, "WIS": 1, "CHA": 1}, "speed": 30, "notes": null},
|
||||
{"key": "HALF_ELF", "name": "Half-Elf", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 2}, "speed": 30, "flexible": {"patterns": [[1, 1]], "exclude": ["CHA"]}, "notes": "Fixed +2 CHA plus a flexible +1/+1 to two other abilities of the player's choice. The builder UI must prompt for this choice; do not hardcode a default."},
|
||||
{"key": "ELF", "name": "Elf", "abilityBonuses": {"STR": 0, "DEX": 2, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "notes": null},
|
||||
{"key": "GNOME", "name": "Gnome", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 2, "WIS": 0, "CHA": 0}, "speed": 25, "notes": null},
|
||||
{"key": "DWARF", "name": "Dwarf", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 2, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 25, "notes": null},
|
||||
{"key": "HALFLING", "name": "Halfling", "abilityBonuses": {"STR": 0, "DEX": 2, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 25, "notes": null},
|
||||
{"key": "DRAGONBORN", "name": "Dragonborn", "abilityBonuses": {"STR": 2, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 1}, "speed": 30, "notes": null},
|
||||
{"key": "TIEFLING", "name": "Tiefling", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 1, "WIS": 0, "CHA": 2}, "speed": 30, "notes": null},
|
||||
{"key": "HALF_ORC", "name": "Half-Orc", "abilityBonuses": {"STR": 2, "DEX": 0, "CON": 1, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "notes": null},
|
||||
{"key": "ORC", "name": "Orc", "abilityBonuses": {"STR": 2, "DEX": 0, "CON": 1, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "notes": null},
|
||||
{"key": "AASIMAR", "name": "Aasimar", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "GOLIATH", "name": "Goliath", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 35, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "AARAKOCRA", "name": "Aarakocra", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "BUGBEAR", "name": "Bugbear", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "CENTAUR", "name": "Centaur", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 40, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "CHANGELING", "name": "Changeling", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "DEEP_GNOME", "name": "Deep Gnome", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "DUERGAR", "name": "Duergar", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "ELADRIN", "name": "Eladrin", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "FAIRY", "name": "Fairy", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "FIRBOLG", "name": "Firbolg", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "AIR_GENASI", "name": "Air Genasi", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 35, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "EARTH_GENASI", "name": "Earth Genasi", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "FIRE_GENASI", "name": "Fire Genasi", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "WATER_GENASI", "name": "Water Genasi", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "GITHYANKI", "name": "Githyanki", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "GITHZERAI", "name": "Githzerai", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "GOBLIN", "name": "Goblin", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "HARENGON", "name": "Harengon", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "HOBGOBLIN", "name": "Hobgoblin", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "KENKU", "name": "Kenku", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "KOBOLD", "name": "Kobold", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "LIZARDFOLK", "name": "Lizardfolk", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "MINOTAUR", "name": "Minotaur", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "SEA_ELF", "name": "Sea Elf", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "SHADAR_KAI", "name": "Shadar-kai", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "SHIFTER", "name": "Shifter", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "TABAXI", "name": "Tabaxi", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "TORTLE", "name": "Tortle", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "TRITON", "name": "Triton", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "YUAN_TI", "name": "Yuan-ti", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "OWLIN", "name": "Owlin", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 30, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."},
|
||||
{"key": "SATYR", "name": "Satyr", "abilityBonuses": {"STR": 0, "DEX": 0, "CON": 0, "INT": 0, "WIS": 0, "CHA": 0}, "speed": 35, "flexible": {"patterns": [[2, 1], [1, 1, 1]]}, "notes": "Flexible: +2 to one ability and +1 to another, or +1 to three, as the player chooses. The builder UI must prompt for this choice."}
|
||||
]
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// Aldenfell campaign content: the gazetteer, bestiary and notes are condensed
|
||||
// from the Aldenfell Campaign Book; the gear, item pool, NPC list and scenes
|
||||
// are built out from it to use everything a campaign can hold.
|
||||
// Consumed by prisma/seed.js. Shapes match the Prisma models minus ids, except
|
||||
// where a section's comment says otherwise.
|
||||
// Aldenfell: a world seed (docs/SEEDS.md). A DM starts a campaign from it by
|
||||
// entering its code.
|
||||
//
|
||||
// The gazetteer, bestiary and notes are condensed from the Aldenfell Campaign
|
||||
// Book; the gear, item pool, NPC list and scenes are built out from it to use
|
||||
// everything a campaign can hold.
|
||||
|
||||
const campaign = {
|
||||
name: 'Aldenfell',
|
||||
@@ -137,17 +138,30 @@ const monsters = [
|
||||
specialTrait: 'Keen hearing and smell — advantage on Perception checks that rely on them.',
|
||||
notes: 'Medium beast, 25 XP. Bite +3 (1d6+1 piercing, DC 11 Str or prone). A chapel mastiff gone half-wild in the Sunken Vaults’ Old Crypt Hall (Room 2). Starving, not vicious — DC 12 Animal Handling or a thrown ration ends the fight.',
|
||||
},
|
||||
{
|
||||
name: 'The Hollow King', challengeRating: '10', ac: 16, maxHp: 190, speed: 30,
|
||||
strScore: 18, dexScore: 14, conScore: 18, intScore: 18, wisScore: 18, chaScore: 20, attackBonus: 9, damageDice: '4d8',
|
||||
specialTrait: 'Many, not one — it is the will of everyone the founders sacrificed, so it cannot be charmed or frightened, and it speaks in several voices. Echoing dread — starting a turn within 30 ft: DC 16 Wis or frightened. What the Court remembers (recharge 5–6): each creature within 30 ft, DC 16 Wis or 6d6 psychic and lose its reaction (half on success).',
|
||||
notes: 'A STARTING POINT, NOT THE BOOK’S: the Campaign Book gives no stat block for E26 and tells you to build one to your party’s level and the resources they brought. This one suits four level 7–8 characters; change the numbers freely. Fly 30 ft (hover). Multiattack (two Chilling Touch +9, 4d8 necrotic). Three legendary actions a round: move without provoking, one Chilling Touch, or (2 actions) pull a creature 20 ft toward the seal (DC 16 Str). The fight should never be only a sword fight — what the party does with the truth (E19, E22) matters more than its hit points.',
|
||||
},
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Weapons the party earns. The everyday weapons (seed-data/weapons.json) are
|
||||
// seeded as starting options; these are not, so they only reach a character as
|
||||
// a reward or a gift. damageDice is the damage at minLevel, and a character
|
||||
// must be at least a held copy's level to use it. damageScaling: 1 standard,
|
||||
// 2 powerful, 3 legendary.
|
||||
// Weapons. The everyday ones are copies from the site library and are what a
|
||||
// new character picks from. The rest are not starting options, so they only
|
||||
// reach a character as a reward, a gift or a purchase. damageDice is the
|
||||
// damage at minLevel, and a character must be at least a held copy's level to
|
||||
// use it. damageScaling: 1 standard, 2 powerful, 3 legendary.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const everydayWeapons = [
|
||||
'dagger', 'shortsword', 'rapier', 'longsword', 'greatsword', 'battleaxe', 'handaxe', 'warhammer', 'mace',
|
||||
'quarterstaff', 'spear', 'shortbow', 'longbow', 'light-crossbow', 'dart',
|
||||
];
|
||||
|
||||
const weapons = [
|
||||
...everydayWeapons.map((library) => ({ library, isStartingOption: true })),
|
||||
{ name: 'Unarmed Strike', damageDice: '1', damageType: 'bludgeoning', attackAbility: 'STR', properties: [], isStartingOption: true },
|
||||
{ name: 'Masterwork Dagger', damageDice: '1d6', damageType: 'piercing', attackAbility: 'FINESSE', properties: ['finesse', 'light', 'thrown'], rangeNormal: 20, rangeLong: 60, minLevel: 2, damageScaling: 1 },
|
||||
{ name: 'Smuggler’s Cutlass', damageDice: '1d8', damageType: 'slashing', attackAbility: 'FINESSE', properties: ['finesse'], rangeNormal: null, rangeLong: null, minLevel: 2, damageScaling: 1 },
|
||||
{ name: 'Warden’s Longbow', damageDice: '1d10', damageType: 'piercing', attackAbility: 'DEX', properties: ['ammunition', 'heavy', 'two-handed'], rangeNormal: 150, rangeLong: 600, minLevel: 2, damageScaling: 2 },
|
||||
@@ -159,38 +173,47 @@ const weapons = [
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Item pool. Items are descriptive: holding one never changes a number on the
|
||||
// sheet. `starting: true` offers the item in the character builder.
|
||||
// Item pool. Most items are descriptive. The ones with `effects` change the
|
||||
// sheet of whoever has them equipped (armor is an item with an AC effect), and
|
||||
// `effectNote` says what a number cannot. `isStartingOption: true` offers the
|
||||
// item in the character builder.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const items = [
|
||||
// Starting kit
|
||||
{ name: 'Potion of Healing', description: 'A red liquid that glimmers when shaken. Drink it (an action) to regain the hit points shown.', damageDice: '2d4+2', starting: true },
|
||||
{ name: 'Traveller’s Pack', description: 'Bedroll, mess kit, tinderbox, waterskin and five days of rations.', starting: true },
|
||||
{ name: 'Rope (50 ft)', description: 'Hempen rope. Holds a climber; DC 17 Strength to burst.', starting: true },
|
||||
{ name: 'Torches (bundle of 5)', description: 'Each burns for an hour: bright light for 20 feet, dim for 20 more.', starting: true },
|
||||
{ name: 'Healer’s Kit', description: 'Ten uses. Spend one to stabilise a creature at 0 hit points without a Medicine check.', starting: true },
|
||||
{ name: 'Thieves’ Tools', description: 'Picks, a small file and a mirror on a handle. Needed to pick a lock or disarm a trap.', starting: true },
|
||||
{ name: 'Shield', description: 'A wooden or steel shield, +2 Armor Class while carried. Ask the DM to add it to your armor bonus.', starting: true },
|
||||
{ name: 'Leather Armor', description: 'Boiled leather, Armor Class 11 + Dexterity. Ask the DM to set your armor bonus.', starting: true },
|
||||
{ name: 'Spellcasting Focus', description: 'A wand, holy symbol, crystal or carved staff that your spells are cast through.', starting: true },
|
||||
{ name: 'Founding Fair Token', description: 'A stamped brass token from the Lantern Market. Good for one drink at any stall, or a small favour from whoever ran the game you won it at.', starting: true },
|
||||
{ name: 'Potion of Healing', description: 'A red liquid that glimmers when shaken. Drink it (an action) to regain the hit points shown.', damageDice: '2d4+2', isStartingOption: true },
|
||||
{ name: 'Traveller’s Pack', description: 'Bedroll, mess kit, tinderbox, waterskin and five days of rations.', isStartingOption: true },
|
||||
{ name: 'Rope (50 ft)', description: 'Hempen rope. Holds a climber; DC 17 Strength to burst.', isStartingOption: true },
|
||||
{ name: 'Torches (bundle of 5)', description: 'Each burns for an hour: bright light for 20 feet, dim for 20 more.', isStartingOption: true },
|
||||
{ name: 'Healer’s Kit', description: 'Ten uses. Spend one to stabilise a creature at 0 hit points without a Medicine check.', isStartingOption: true },
|
||||
{ name: 'Thieves’ Tools', description: 'Picks, a small file and a mirror on a handle. Needed to pick a lock or disarm a trap.', isStartingOption: true },
|
||||
{ name: 'Shield', armorType: 'SHIELD', description: 'A wooden or steel shield carried on one arm.', isStartingOption: true, effects: [{ stat: 'AC', amount: 2 }], effectNote: 'Takes a hand: no two-handed weapon while it is up.' },
|
||||
{ name: 'Leather Armor', armorType: 'LIGHT', description: 'Boiled leather, light enough to sleep and sneak in.', isStartingOption: true, effects: [{ stat: 'AC', amount: 1 }] },
|
||||
{ name: 'Spellcasting Focus', description: 'A wand, holy symbol, crystal or carved staff that your spells are cast through.', isStartingOption: true },
|
||||
{ name: 'Founding Fair Token', description: 'A stamped brass token from the Lantern Market. Good for one drink at any stall, or a small favour from whoever ran the game you won it at.', isStartingOption: true },
|
||||
|
||||
// Found and earned
|
||||
{ name: 'Potion of Greater Healing', description: 'A deeper red than the common potion. Drink it (an action) to regain the hit points shown.', damageDice: '4d4+4', minLevel: 3 },
|
||||
{ library: 'studded-leather' },
|
||||
{ library: 'chain-shirt' },
|
||||
{ library: 'chain-mail' },
|
||||
{ name: 'Alchemist’s Fire', description: 'A sticky flask that ignites in air. Throw it up to 20 feet: the target burns for the damage shown at the start of each of its turns until someone spends an action putting it out.', damageDice: '1d4' },
|
||||
{ name: 'Silver Locket', description: 'A tarnished locket from the Old Crypt Hall, worth about 15 gp. The portrait inside has been scratched out.' },
|
||||
{ name: 'Smugglers’ Ledger Page', description: 'A torn page from a crate in the Sunken Vaults, stamped with a merchant sigil nobody at the Concord Exchange recognises. Half a name survives in the margin.' },
|
||||
{ name: 'Bell-Ringer’s Keepsake', description: 'A worn brass bell-clapper charm, pressed into your hand with more gratitude than its owner could put into words.' },
|
||||
{ name: 'Grey Dawn Signet', description: 'An iron ring bearing the Order’s rising sun. Shown at Grey Dawn Hall or to any patrol, it marks you as someone the Order vouches for.' },
|
||||
{ name: 'Concord Writ of Passage', description: 'A sealed Merchant Concord contract. Waives tolls and gate fees across Aldenfell while the Concord still considers you good for business.' },
|
||||
{ name: 'Warden’s Charm', description: 'A knot of greywood bark and red thread. The Wardens will know you by it, and the forest’s paths seem a little easier to find while you carry it.' },
|
||||
{ name: 'Warden’s Charm', description: 'A knot of greywood bark and red thread. The Wardens will know you by it, and the forest’s paths seem a little easier to find while you carry it.', effects: [{ stat: 'SKILL_SURVIVAL', amount: 1 }] },
|
||||
{ name: 'Stonejaw Oath-Token', description: 'A river stone the size of a fist, carved with the Stonejaw clan mark. Proof that your word was tested and held.' },
|
||||
{ name: 'Half-Burned Letter', description: 'Found among a missing person’s belongings in the Root. Most of it is ash. What is left mentions payments, a shrine, and a family crest.' },
|
||||
{ name: 'Silver Shrine Relic', description: 'A small silver figure lifted from black water beneath the Greywood, worth about 75 gp. Its style is older than the kingdom.' },
|
||||
{ name: 'Sealed Letter', description: 'Heavy paper, an unbroken wax seal, and a servant’s whispered warning about who must never know you have it.' },
|
||||
{ name: 'Root-Fiber Scrap', description: 'A length of pale root that is still, very slightly, moving. It is cold, and it does not rot.' },
|
||||
{ name: 'Seal-Stone Fragment', description: 'A shard of worked stone from the edge of the breach. Script runs along one face. It is warm, and holding it makes the bell script easier to look at.' },
|
||||
{ name: 'Seized House Documents', description: 'Ledgers and letters taken from the noble house after it was confronted. No value in coin; a great deal of value to anyone building a case.' },
|
||||
{ name: 'House Records', description: 'The fallen house’s private records: names, payments and meeting places for its contacts across Aldenfell.' },
|
||||
{ name: 'Masterwork Chain Mail', armorType: 'HEAVY', description: 'Close-linked mail from the Grey Dawn’s own armoury, fitted rather than issued.', minLevel: 5, effects: [{ stat: 'AC', amount: 7 }, { stat: 'SPEED', amount: -10 }], effectNote: 'Disadvantage on Stealth checks.' },
|
||||
{ name: 'The Seal-Stone', description: 'The stone at the heart of the seal, whole again and quiet. It is heavier than it looks, and it is never quite cold.', minLevel: 7, effects: [{ stat: 'SAVE_WIS', amount: 2 }], effectNote: 'Grows warm near anything of the Hollow Below. Its other properties are the DM’s to decide: something tied to binding, warding or detecting.' },
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -200,7 +223,7 @@ const items = [
|
||||
// DM to teach later.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const spells = {
|
||||
const spellKeys = {
|
||||
starting: [
|
||||
'chill-touch', 'eldritch-blast', 'fire-bolt', 'guidance', 'light', 'mage-hand', 'minor-illusion',
|
||||
'prestidigitation', 'produce-flame', 'ray-of-frost', 'sacred-flame', 'shocking-grasp', 'spare-the-dying',
|
||||
@@ -216,6 +239,11 @@ const spells = {
|
||||
],
|
||||
};
|
||||
|
||||
const spells = [
|
||||
...spellKeys.starting.map((library) => ({ library, isStartingOption: true })),
|
||||
...spellKeys.earned,
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// NPCs. `description` is what the party sees once the NPC is in a scene;
|
||||
// `dmNotes` never leaves the DM's screen. Combat stats only where a fight is
|
||||
@@ -242,7 +270,17 @@ const npcs = [
|
||||
{
|
||||
name: 'Mireille Costa', role: 'Merchant Concord representative', disposition: 'NEUTRAL',
|
||||
description: 'Charming and transactional, usually found at the Concord Exchange with a contract already drafted. She always has a job, and she always pays what she promised.',
|
||||
dmNotes: 'Source of paying side work (E4B → The Smugglers’ Tithe). The Concord is neutral and pragmatic, and drops anyone who becomes bad for business — including the party.',
|
||||
dmNotes: 'Source of paying side work (E4B → The Smugglers’ Tithe). The Concord is neutral and pragmatic, and drops anyone who becomes bad for business — including the party. She also sells: Concord goods at Concord prices, in any scene she is in (DC 12 Persuasion to haggle, per the DM Tables).',
|
||||
wares: [
|
||||
{ item: 'Potion of Healing', price: 50 },
|
||||
{ item: 'Potion of Greater Healing', price: 150 },
|
||||
{ item: 'Alchemist’s Fire', price: 50 },
|
||||
{ item: 'Healer’s Kit', price: 5 },
|
||||
{ item: 'Thieves’ Tools', price: 25 },
|
||||
{ item: 'Studded Leather', price: 45 },
|
||||
{ item: 'Chain Shirt', price: 50 },
|
||||
{ item: 'Chain Mail', price: 75 },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Ashwen', role: 'Warden of the Greywood', disposition: 'NEUTRAL',
|
||||
@@ -311,6 +349,8 @@ const npcs = [
|
||||
// handed out. { gold } | { weapon } | { item }, with optional
|
||||
// quantity, level (defaults to the entry's starting level) and
|
||||
// note.
|
||||
// wares — for sale at the scene itself (a stall), as on an NPC:
|
||||
// { weapon | item, price, currency?, level?, stock? }.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const encounters = [
|
||||
@@ -319,6 +359,18 @@ const encounters = [
|
||||
description: 'Highcrown’s Lantern Market at the height of the Founding Fair: lantern-strung stalls, contests of strength and skill, minstrels, and strangers from every corner of the kingdom. This is where you meet.',
|
||||
dmNotes: 'Character creation happens here (Roll-Your-Character System) — it can be the whole first half of session one. No combat. Let each PC win or lose something small at a stall, and introduce Mireille and Ser Kavan in passing so they are familiar faces by E4. Ends when the chapel bell fails to ring → E2.',
|
||||
npcs: ['Mireille Costa', 'Ser Kavan Thorne'],
|
||||
// The market stalls: everyday kit at everyday prices.
|
||||
wares: [
|
||||
{ item: 'Traveller’s Pack', price: 2 },
|
||||
{ item: 'Rope (50 ft)', price: 1 },
|
||||
{ item: 'Torches (bundle of 5)', price: 5, currency: 'COPPER' },
|
||||
{ item: 'Spellcasting Focus', price: 10 },
|
||||
{ item: 'Shield', price: 10 },
|
||||
{ item: 'Leather Armor', price: 10 },
|
||||
{ weapon: 'Dagger', price: 2 },
|
||||
{ weapon: 'Shortbow', price: 25 },
|
||||
{ weapon: 'Longsword', price: 15 },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'E2 — The Bell That Wasn’t Ringing', mode: 'QUEST', location: 'Highcrown — The Founding Chapel',
|
||||
@@ -329,9 +381,9 @@ const encounters = [
|
||||
{
|
||||
name: 'E3 — Sunken Vaults: The Old Crypt Hall', mode: 'BATTLE', location: 'Hollow Below — The Sunken Vaults (Layer 1)',
|
||||
description: 'A long hall of burial niches beneath the chapel, some sealed, some broken open. Something is growling in the dark between the pillars.',
|
||||
dmNotes: 'Vault Room 2, the hub (→ Rooms 3, 4, stair to 6). The dog is starving, not vicious: DC 12 Animal Handling or a thrown ration ends it. DC 13 Investigation: the open niches are just old theft. DC 12 Perception finds the locket.',
|
||||
dmNotes: 'Vault Room 2, the hub (→ Rooms 3, 4, stair to 6). The dog is starving, not vicious: DC 12 Animal Handling or a thrown ration ends it. DC 13 Investigation: the open niches are just old theft. DC 12 Investigation spots the locket.',
|
||||
monsters: [['Feral Guard Dog', 1]],
|
||||
rewards: [{ item: 'Silver Locket', note: 'Room 2 — DC 12 Perception' }],
|
||||
rewards: [{ item: 'Silver Locket', note: 'Room 2 — DC 12 Investigation' }],
|
||||
},
|
||||
{
|
||||
name: 'E3 — Sunken Vaults: The Restless Ossuary', mode: 'BATTLE', location: 'Hollow Below — The Sunken Vaults (Layer 1)',
|
||||
@@ -360,6 +412,17 @@ const encounters = [
|
||||
{ item: 'Concord Writ of Passage', note: 'E4B — on taking Mireille’s contract' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'E5 — Omens Montage', mode: 'QUEST', location: 'Greywood — The Old Shrine Sites',
|
||||
description: 'Small things, weeks apart. A farmer’s cattle gone dry overnight out past the shrine road. A stranger at the next table describing, detail for detail, the dream you had last night. None of it is an attack. All of it is wrong.',
|
||||
dmNotes: 'Pure atmosphere, no treasure. Run two or three as short scenes spread across sessions, never back to back:\n• Livestock and crops failing near an old shrine.\n• Shared nightmares around Highcrown — DC 12 Insight for a PC to realise their own dream matched a stranger’s account.\n• A minor noble behaving with odd, unearned loyalty to no one in particular (the corrupted house — a background detail, not a spotlight).\nThe Drowned Shrine (Root Room 5) is a good place to point an omen at. → E6 whenever it feels earned.',
|
||||
},
|
||||
{
|
||||
name: 'E7 — A Closer Look', mode: 'QUEST',
|
||||
description: 'One noble house keeps turning up at the edge of things: generous, quiet, a little too pleased with itself. Asking after it gets polite answers and closed doors.',
|
||||
dmNotes: 'If the party actively investigates the odd house from E5 they find only dead ends at this stage — by design. Stage 1 omens accumulate; they do not resolve.\nException: a party that took E2C makes a DC 13 Insight check (not 15) to catch one real thread — a servant who flinched at the mention of the house’s name. Note what they learn for E10.\n→ E8: once they have engaged with two or more E4 threads and one full E5 omen, advance the clock to Stage 2 and move to Act 2.',
|
||||
npcs: ['King Aldric Veyrmont', 'Princess Isolde Veyrmont'],
|
||||
},
|
||||
{
|
||||
name: 'E6 — The Bell-Ringer’s Debt: Collectors', mode: 'BATTLE',
|
||||
description: 'Three hard-faced men are waiting outside the bell-ringer’s door when you arrive. They are not here to hear him ring.',
|
||||
@@ -440,6 +503,23 @@ const encounters = [
|
||||
npcs: ['Threndir Ashclaw'],
|
||||
rewards: [{ weapon: 'Threndir’s Fang', note: 'A shed tooth, set in a hilt — given only if he comes to respect them' }],
|
||||
},
|
||||
{
|
||||
name: 'The Spine — Wyvern Pass', mode: 'BATTLE', location: 'The Spine — Ironvein',
|
||||
description: 'The pass above Ironvein narrows to a ledge, and the ledge runs under a shelf of rock streaked white with droppings. Something large shifts up there and looks down at you.',
|
||||
dmNotes: 'Optional travel encounter (Random Encounters, the Spine). Territorial, not evil: it attacks anything that lingers near the nest and ignores a party that keeps moving — DC 13 Stealth or Survival to pass without a fight. Stinger: DC 15 Con or poisoned for a minute. Ironvein below is the resupply stop, with its own rumours (miners going quiet, deeper tunnels avoided).',
|
||||
monsters: [['Spine Wyvern', 1]],
|
||||
},
|
||||
{
|
||||
name: 'The Spine — Sevrisk’s Hollow', mode: 'BATTLE', location: 'The Spine — Sevrisk’s Hollow',
|
||||
description: 'A low, wet cave mouth breathing green-tinged mist. The bones outside it have been arranged, not dropped. From inside comes a voice like a blade being drawn: slow, amused, and very sure of itself.',
|
||||
dmNotes: 'Optional, and dangerous: Sevrisk is the straightforward dragon fight, in contrast to Threndir. Territorial and opportunistic — she will bargain only to gain an edge, and breaks a bargain the moment it stops paying. Poison breath (recharge 5–6): 30-ft cone, DC 14 Con, 8d6. CR 5: too much for a party below level 4 without help or a plan. Her hoard is the treasure.',
|
||||
monsters: [['Sevrisk (young green dragon)', 1, 'Sevrisk']],
|
||||
rewards: [
|
||||
{ gold: 400, note: 'Sevrisk’s hoard — coin and plate' },
|
||||
{ item: 'Potion of Greater Healing', quantity: 2, note: 'In the hoard' },
|
||||
{ weapon: 'Grey Dawn Longsword', note: 'In the hoard — a knight came here once and did not leave' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'E9 — The Root: Weeping Passage', mode: 'BATTLE', location: 'Hollow Below — The Weeping Passage',
|
||||
description: 'A long tunnel beneath the Greywood where the walls weep, and the sound they make is almost a voice. Somewhere ahead, very faintly, a bell tolls.',
|
||||
@@ -467,6 +547,12 @@ const encounters = [
|
||||
{ weapon: 'Masterwork Dagger', note: 'Still in a dead hand' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'E9 — The Root: The Drowned Shrine', mode: 'QUEST', location: 'Hollow Below — The Root (Layer 2)',
|
||||
description: 'A shrine older than anything in the vaults above, half sunk in still black water. The altar is whole. The symbol carved into it belongs to no faith anyone above has practised in a very long time.',
|
||||
dmNotes: 'Root Room 5. A pre-kingdom holy site, connected to the Sunken Library in the Greywood. DC 16 History or Religion: the symbol is older than Aldenfell itself — a thread toward the Hollow King’s origin, without the full truth. A good place for a vision or omen (E5 can point here).\nThe relic: DC 13 Athletics or Investigation to lift it without disturbing the water. Disturbing it summons nothing, only ripples that spread wrong. Exits: back to Room 2, or a narrow crawl to Room 6.',
|
||||
rewards: [{ item: 'Silver Shrine Relic', note: 'In the water — DC 13 Athletics or Investigation' }],
|
||||
},
|
||||
{
|
||||
name: 'E9 — The Root: Bellcrawler Gallery', mode: 'BATTLE', location: 'Hollow Below — The Root (Layer 2)',
|
||||
description: 'Narrow ledges over a drop your torch cannot find the bottom of. From three different directions at once, a bell begins to toll.',
|
||||
@@ -474,7 +560,7 @@ const encounters = [
|
||||
monsters: [['Bellcrawler', 3]],
|
||||
rewards: [
|
||||
{ gold: 90, note: 'Scattered along the ledges' },
|
||||
{ item: 'Potion of Healing', note: 'In a fallen pack' },
|
||||
{ item: 'Potion of Healing', note: 'In a fallen pack — the book has the coin or the potion, DM’s choice' },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -482,7 +568,10 @@ const encounters = [
|
||||
description: 'Back in Highcrown with a name, a ledger, and a question nobody at court wants asked out loud: what do you do with it?',
|
||||
dmNotes: 'The ledger: every shrine “donation” falls three days after a livestock death.\n• E10A confront the house directly: DC 16 Persuasion/Intimidation with proof, DC 20 without.\n• E10B report to the crown, Isolde or Kavan: sets up Act 3 politics; if E9C, Kavan already suspected (trust bump).\n• E10C (E2C + the servant thread): private DC 13 check at advantage → confession and the sealed letter; the house never learns it is suspected. Best route into Act 3.',
|
||||
npcs: ['Princess Isolde Veyrmont', 'Ser Kavan Thorne'],
|
||||
rewards: [{ item: 'Sealed Letter', note: 'E10C only' }],
|
||||
rewards: [
|
||||
{ item: 'Sealed Letter', note: 'E10C only — the servant’s evidence' },
|
||||
{ item: 'Seized House Documents', note: 'E10A only — taken at the confrontation' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'E11 — Silence on the Border', mode: 'QUEST', location: 'Bramble Marches — Greyford Keep',
|
||||
@@ -508,6 +597,27 @@ const encounters = [
|
||||
monsters: [['Hollowed', 4]],
|
||||
rewards: [{ item: 'Seal-Stone Fragment', note: 'Key item — from the breach’s edge' }],
|
||||
},
|
||||
{
|
||||
name: 'E15 — The House Falls (or Doesn’t)', mode: 'BATTLE',
|
||||
description: 'Word travels faster than truth in Highcrown. By the time you reach the house, half the city already has an opinion about what happened there — and most of them are wrong.',
|
||||
dmNotes: 'Plays very differently by Act 2 route.\n• E15A (took E10A): the house has spent Act 2 preparing — hired guards, an alibi, perhaps a scapegoat servant. DC 18 to break the cover story, or this fight: house guards and one Hollowed-touched retainer.\n• E15B (took E10B): a tense public tribunal, no fight. DC 16 Persuasion or Insight steers it toward exile rather than execution (matters for a returning villain).\n• E15C (took E10C): the house suspects nothing. Move on its masters — the cult in Highcrown. Only this route reaches E15C-1: a cult lieutenant taken alive, who gives up the Hollow Court’s surface entrance (→ E18B).\nRemove the monsters for E15B and E15C. → E16.',
|
||||
monsters: [['Bandit Captain', 2, 'House Guard Sergeant'], ['Highcrown Cutthroat', 4, 'House Guard'], ['Hollowed', 1, 'The Retainer']],
|
||||
npcs: ['Princess Isolde Veyrmont', 'Ser Kavan Thorne'],
|
||||
rewards: [{ item: 'House Records', note: 'Names other cult contacts across Aldenfell — seeds for a side quest, or safely ignored' }],
|
||||
},
|
||||
{
|
||||
name: 'E16 — What the Marches Cost', mode: 'QUEST', location: 'Bramble Marches — Greyford Keep',
|
||||
description: 'Smoke on the horizon means something different out here than it does in Highcrown. Out here, it usually means someone made a choice that can’t be unmade.',
|
||||
dmNotes: 'The consequences of E11. No loot: this is about consequence.\n• E16A — Greyford was reinforced (E11C, Spine Clans allied): the keep holds. A rare unambiguous good outcome; let them feel it. Spine Clan standing rises.\n• E16B — Greyford was under-supplied (Smugglers’ Tithe unresolved): the keep falls or is abandoned for good. The named refugee from Refugees of the Marches is lost unless the party steps in — DC 16 Athletics or Survival chase and rescue.\n→ E17 (pay off any debt the party has run up: the E14A weakening, an unresolved side quest, unchased omens — or a quiet breather with the bell-ringer) → E18.',
|
||||
npcs: ['Greyford’s Commander'],
|
||||
},
|
||||
{
|
||||
name: 'E18 — Into the Hollow Court', mode: 'BATTLE', location: 'Hollow Below — The Hollow Court (Layer 3)',
|
||||
description: 'The stair doesn’t so much end as stop pretending to be a stair. What’s beneath Aldenfell was never built — it grew, the way a wound grows scar tissue, except the scar tissue is watching you.',
|
||||
dmNotes: 'Hollow Court Rooms 1–3. E18A enters by the Bent Stair; E18B (cult lieutenant from E15C-1) skips straight to the Memory Pool.\n• Room 1, The Bent Stair: DC 15 Wis save or lose track of how long the descent took (atmosphere, or 10 minutes lost). No monster.\n• Room 2, The Memory Pool: each PC who looks sees a vision tied to a choice they made — the payoff for the branch points. No damage; DC 17 Insight to understand it.\n• Room 3, The Court of Whispers: Vessa may speak plainly here. DC 16 Insight: she believes what she says. If it comes to a fight it is with these Hollowed guardians, never with her — remove them if the party talks.\n→ E19.',
|
||||
monsters: [['Hollowed', 4, 'Hollowed Guardian']],
|
||||
npcs: ['Vessa Hollow'],
|
||||
},
|
||||
{
|
||||
name: 'Mid-campaign scare — The Hollow King’s Shadow', mode: 'BATTLE',
|
||||
description: 'The light goes thin and the air goes cold. Something tall is standing where the wall should be, and the wall does not seem to mind.',
|
||||
@@ -525,14 +635,20 @@ const encounters = [
|
||||
description: 'One last gathering before the descent. Whoever is going to stand with you is here now — and they do not all agree about what happens next.',
|
||||
dmNotes: 'Who shows up depends on the branch list — remove anyone the party lost or alienated.\n• E21A Grey Dawn track: Kavan and his wardens, by the book.\n• E21B Spine Clans track: Korgath’s war-band; advantage on the first Survival check at E22.\n• E21C Independent: no reinforcements; every choice stays theirs.\n• Several tracks: the groups arrive and disagree — the party mediates.',
|
||||
npcs: ['Princess Isolde Veyrmont', 'Ser Kavan Thorne', 'Korgath Stonejaw', 'Ashwen'],
|
||||
rewards: [{ item: 'Potion of Greater Healing', quantity: 2, note: 'Going-away gift from whoever stands with them' }],
|
||||
rewards: [
|
||||
{ item: 'Potion of Greater Healing', quantity: 2, note: 'Going-away gift from whoever stands with them' },
|
||||
{ item: 'Masterwork Chain Mail', note: 'E21A — from the Grey Dawn armoury, if the Order stands with them' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'E22 — The Seal Chamber', mode: 'QUEST', location: 'Hollow Below — The Hollow Court (Layer 3)',
|
||||
description: 'A wound in the world, stitched shut long ago, and coming undone one thread at a time. Whatever you came here to decide, this is where you decide it.',
|
||||
dmNotes: 'Court Room 5 — the key branch. DC 18 Arcana/Religion reveals the seal is a suppression of many. Optional DC 14 Wis saves vs disorientation.\n• E22A reinforce (DC 18 Arcana/Religion): the Sealed Ending — time bought.\n• E22B break it deliberately: E23 on the party’s terms — the only path to true victory.\n• E22C do nothing: the seal fails anyway; E24–E25 are harder.\nHollowbane is the campaign’s single most significant magic item: legendary growth, starts at level 7.',
|
||||
npcs: ['Vessa Hollow'],
|
||||
rewards: [{ weapon: 'Hollowbane', note: 'Drawn from the seal itself' }],
|
||||
rewards: [
|
||||
{ weapon: 'Hollowbane', note: 'Drawn from the seal itself — the campaign’s one significant magic item' },
|
||||
{ item: 'The Seal-Stone', note: 'E22A only — the seal, reinforced rather than broken' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'E25 — The Last Approach', mode: 'BATTLE', location: 'Hollow Below — The Hollow Court (Layer 3)',
|
||||
@@ -540,6 +656,19 @@ const encounters = [
|
||||
dmNotes: 'A gauntlet of horror-register creatures; whichever faction the party rallied fights alongside them (add those NPCs). Grey Dawn = a disciplined line; Spine Clans = terrain and ritual (collapse passages); Independent = hardest, and entirely theirs. → E26, the Hollow King: build that stat block from DM Secrets, scaled to the party.',
|
||||
monsters: [['Root Stalker', 1], ['Bellcrawler', 2]],
|
||||
},
|
||||
{
|
||||
name: 'E23–E24 — The Waking', mode: 'QUEST', location: 'Hollow Below — The Hollow Court (Layer 3)',
|
||||
description: 'The Waking isn’t loud. That’s the wrong word for it. It’s the sound of something enormous remembering it has a name.',
|
||||
dmNotes: 'Hollow Court Room 6. The seal gives way, one way or another.\n• Broke it deliberately (E22B): the party arrives prepared, on their own timing — full resources, no surprise round against them.\n• It failed on its own (E22C): the Hollow King is already partly awake — apply one stage of escalation before the party acts, and E25–E26 are noticeably harder.\nE24, What the Court Remembers: not combat. Its memories bleed into the room, fragments of who it was before. DC 14 Insight recognises a fragment as manipulation rather than truth — it is recruiting sympathy, not confessing. → E25.',
|
||||
npcs: ['Vessa Hollow'],
|
||||
},
|
||||
{
|
||||
name: 'E26 — The Hollow King', mode: 'BATTLE', location: 'Hollow Below — The Hollow Court (Layer 3)',
|
||||
description: 'There is no throne and no crown. There is a shape made of everyone who was put down here, and it has finally turned to look at you.',
|
||||
dmNotes: 'The final confrontation. The book gives no stat block — it asks you to build one to the party’s level and what they brought. The “The Hollow King” monster here is a starting point for four level 7–8 characters: change it.\nThree shapes:\n• Grey Dawn track — disciplined tactics: Kavan’s wardens hold a line while the party lands the killing blow. Add Ser Kavan Thorne.\n• Spine Clans track — terrain and ritual: collapsing passages, the Memory Pool as a weapon. Add Korgath Stonejaw.\n• Independent — hardest: no reinforcements, and every choice in the last round is theirs.\nNegotiating through Vessa is a legitimate ending. → E27, Endings: Sealed, Grey Dawn, Spine Clans or Independent — and close where it opened, at the Lantern Market a year later.',
|
||||
monsters: [['The Hollow King', 1]],
|
||||
npcs: ['Vessa Hollow'],
|
||||
},
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -803,4 +932,4 @@ The Salt Coast: 1 smugglers wary of witnesses · 2 short-handed fishing crew ·
|
||||
The Bramble Marches: 1 Bandit Captain’s crew · 2 refugees on the road · 3 tense border patrol · 4 signs of the neighboring power · 5 a skirmish in progress · 6 watchful quiet.`,
|
||||
];
|
||||
|
||||
module.exports = { campaign, locations, monsters, weapons, items, spells, npcs, encounters, sharedNotes, dmNotes };
|
||||
module.exports = { code: 'ALDENF', campaign, locations, monsters, weapons, items, spells, npcs, encounters, sharedNotes, dmNotes };
|
||||
File diff suppressed because one or more lines are too long
+10
-1
@@ -1,16 +1,24 @@
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const compression = require('compression');
|
||||
|
||||
const authRoutes = require('./routes/auth.routes');
|
||||
const campaignsRoutes = require('./routes/campaigns.routes');
|
||||
const charactersRoutes = require('./routes/characters.routes');
|
||||
const encountersRoutes = require('./routes/encounters.routes');
|
||||
const notesRoutes = require('./routes/notes.routes');
|
||||
const referenceRoutes = require('./routes/reference.routes');
|
||||
|
||||
function createApp() {
|
||||
const app = express();
|
||||
|
||||
app.use(cors({ origin: process.env.CORS_ORIGIN || 'http://localhost:5173' }));
|
||||
// The site and the API are on different hosts, so a browser asks leave
|
||||
// before each kind of request. maxAge lets it remember the answer (browsers
|
||||
// cap it at two hours) and not ask again every time.
|
||||
app.use(cors({ origin: process.env.CORS_ORIGIN || 'http://localhost:5173', maxAge: 7200 }));
|
||||
// Nothing in front of the API compresses for it (frp only tunnels), so the
|
||||
// JSON is gzipped here.
|
||||
app.use(compression());
|
||||
app.use(express.json());
|
||||
|
||||
app.get('/health', (req, res) => res.json({ ok: true }));
|
||||
@@ -20,6 +28,7 @@ function createApp() {
|
||||
app.use('/characters', charactersRoutes);
|
||||
app.use('/encounters', encountersRoutes);
|
||||
app.use('/notes', notesRoutes);
|
||||
app.use('/reference', referenceRoutes);
|
||||
|
||||
app.use((req, res) => {
|
||||
res.status(404).json({ error: 'Not found' });
|
||||
|
||||
+6
-1
@@ -1,5 +1,10 @@
|
||||
// Prisma no longer reads .env itself, and this is the first thing to need it.
|
||||
require('dotenv').config({ quiet: true });
|
||||
const { PrismaClient } = require('@prisma/client');
|
||||
const { PrismaPg } = require('@prisma/adapter-pg');
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
const prisma = new PrismaClient({
|
||||
adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
|
||||
});
|
||||
|
||||
module.exports = prisma;
|
||||
|
||||
@@ -9,15 +9,21 @@ const { SPECIES_TRAITS, CLASS_FEATURES, TALENTS, TALENT_PICKS } = require('./dat
|
||||
const ALL_SPECIES = Object.keys(SPECIES);
|
||||
const ALL_CLASSES = Object.keys(CLASSES);
|
||||
|
||||
// A d8 picks a family of species; the player chooses one from it.
|
||||
const SPECIES_ROLL_DIE = 8;
|
||||
const SPECIES_ROLL_TABLE = {
|
||||
1: ['HUMAN', 'HALF_ELF'],
|
||||
2: ['ELF', 'GNOME'],
|
||||
3: ['DWARF', 'HALFLING'],
|
||||
4: ['DRAGONBORN', 'TIEFLING'],
|
||||
5: ['HALF_ORC', 'ORC'],
|
||||
6: 'WILDCARD',
|
||||
1: ['HUMAN', 'HALF_ELF', 'ELF', 'HALF_ORC'],
|
||||
2: ['DWARF', 'GNOME', 'HALFLING', 'DEEP_GNOME', 'DUERGAR'],
|
||||
3: ['DRAGONBORN', 'TIEFLING', 'AASIMAR', 'GOLIATH'],
|
||||
4: ['ORC', 'GOBLIN', 'HOBGOBLIN', 'BUGBEAR', 'KOBOLD'],
|
||||
5: ['ELADRIN', 'SEA_ELF', 'SHADAR_KAI', 'GITHYANKI', 'GITHZERAI', 'CHANGELING'],
|
||||
6: ['AIR_GENASI', 'EARTH_GENASI', 'FIRE_GENASI', 'WATER_GENASI', 'TRITON', 'TORTLE'],
|
||||
7: ['TABAXI', 'KENKU', 'AARAKOCRA', 'HARENGON', 'LIZARDFOLK', 'OWLIN', 'MINOTAUR', 'CENTAUR', 'SATYR', 'SHIFTER', 'FIRBOLG', 'FAIRY', 'YUAN_TI'],
|
||||
8: 'WILDCARD',
|
||||
};
|
||||
|
||||
// 7 offers the Artificer, or one reroll; whatever the reroll gives is final.
|
||||
const CLASS_ROLL_DIE = 8;
|
||||
const CLASS_ROLL_TABLE = {
|
||||
1: ['FIGHTER', 'BARBARIAN'],
|
||||
2: ['ROGUE', 'RANGER'],
|
||||
@@ -25,7 +31,7 @@ const CLASS_ROLL_TABLE = {
|
||||
4: ['CLERIC', 'PALADIN'],
|
||||
5: ['BARD', 'WARLOCK'],
|
||||
6: ['DRUID', 'MONK'],
|
||||
7: 'REROLL',
|
||||
7: 'ARTIFICER_OR_REROLL',
|
||||
8: 'WILDCARD',
|
||||
};
|
||||
|
||||
@@ -48,6 +54,31 @@ function rollAbilityScore() {
|
||||
return abilityScoreFromDice(dice);
|
||||
}
|
||||
|
||||
// The other two ways to make ability scores (Campaign.abilityScoreMethod).
|
||||
// The standard array is six fixed scores, assigned like rolled ones. Point
|
||||
// buy starts every score at 8 and spends a budget to raise them, to 15 at most.
|
||||
const STANDARD_ARRAY = [15, 14, 13, 12, 10, 8];
|
||||
const POINT_BUY_BUDGET = 27;
|
||||
const POINT_BUY_COSTS = { 8: 0, 9: 1, 10: 2, 11: 3, 12: 4, 13: 5, 14: 7, 15: 9 };
|
||||
|
||||
// What a set of point-buy scores costs, or null if a score is out of range.
|
||||
function pointBuyCost(scores) {
|
||||
let total = 0;
|
||||
for (const score of Object.values(scores)) {
|
||||
const cost = POINT_BUY_COSTS[score];
|
||||
if (cost === undefined) return null;
|
||||
total += cost;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
// Which dice a character rolls: the campaign's, unless it leaves the choice
|
||||
// to each character (BOTH).
|
||||
function effectiveDiceMode(campaign, character) {
|
||||
if (campaign && campaign.diceMode && campaign.diceMode !== 'BOTH') return campaign.diceMode;
|
||||
return character.diceMode;
|
||||
}
|
||||
|
||||
// Fisher-Yates-ish random pick of `count` distinct items from `options`,
|
||||
// using the same crypto RNG as dice rolls (never Math.random for anything
|
||||
// that ends up on a character sheet).
|
||||
@@ -139,21 +170,30 @@ function speciesChoicesForRoll(roll) {
|
||||
return { type: 'choice', options: entry };
|
||||
}
|
||||
|
||||
function classChoicesForRoll(roll) {
|
||||
// `rerolled`: this roll is itself the reroll a 7 allowed, so it can't be
|
||||
// rerolled again.
|
||||
function classChoicesForRoll(roll, { rerolled = false } = {}) {
|
||||
const entry = CLASS_ROLL_TABLE[roll];
|
||||
if (entry === 'WILDCARD') return { type: 'wildcard', options: ALL_CLASSES };
|
||||
if (entry === 'REROLL') return { type: 'reroll', options: [] };
|
||||
if (entry === 'ARTIFICER_OR_REROLL') return { type: 'choice', options: ['ARTIFICER'], canReroll: !rerolled };
|
||||
return { type: 'choice', options: entry };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
SPECIES_ROLL_TABLE,
|
||||
SPECIES_ROLL_DIE,
|
||||
CLASS_ROLL_TABLE,
|
||||
CLASS_ROLL_DIE,
|
||||
ALL_SPECIES,
|
||||
ALL_CLASSES,
|
||||
rollDie,
|
||||
rollAbilityScore,
|
||||
abilityScoreFromDice,
|
||||
STANDARD_ARRAY,
|
||||
POINT_BUY_BUDGET,
|
||||
POINT_BUY_COSTS,
|
||||
pointBuyCost,
|
||||
effectiveDiceMode,
|
||||
speciesChoicesForRoll,
|
||||
classChoicesForRoll,
|
||||
randomSample,
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
const { pointBuyCost, POINT_BUY_BUDGET, STANDARD_ARRAY, effectiveDiceMode } = require('./buildFlow');
|
||||
|
||||
describe('point buy', () => {
|
||||
test('all eights cost nothing', () => {
|
||||
expect(pointBuyCost({ STR: 8, DEX: 8, CON: 8, INT: 8, WIS: 8, CHA: 8 })).toBe(0);
|
||||
});
|
||||
|
||||
test('the classic 15/15/15/8/8/8 spends exactly the budget', () => {
|
||||
expect(pointBuyCost({ STR: 15, DEX: 15, CON: 15, INT: 8, WIS: 8, CHA: 8 })).toBe(POINT_BUY_BUDGET);
|
||||
});
|
||||
|
||||
test('14 and 15 cost two points a step', () => {
|
||||
expect(pointBuyCost({ STR: 13 })).toBe(5);
|
||||
expect(pointBuyCost({ STR: 14 })).toBe(7);
|
||||
expect(pointBuyCost({ STR: 15 })).toBe(9);
|
||||
});
|
||||
|
||||
test('a score out of range is refused', () => {
|
||||
expect(pointBuyCost({ STR: 16 })).toBeNull();
|
||||
expect(pointBuyCost({ STR: 7 })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
test('the standard array is the six usual scores', () => {
|
||||
expect(STANDARD_ARRAY).toEqual([15, 14, 13, 12, 10, 8]);
|
||||
});
|
||||
|
||||
describe('effectiveDiceMode', () => {
|
||||
test('a campaign with one kind of dice decides for everyone', () => {
|
||||
expect(effectiveDiceMode({ diceMode: 'PHYSICAL' }, { diceMode: 'DIGITAL' })).toBe('PHYSICAL');
|
||||
expect(effectiveDiceMode({ diceMode: 'DIGITAL' }, { diceMode: 'PHYSICAL' })).toBe('DIGITAL');
|
||||
});
|
||||
|
||||
test('BOTH leaves it to the character', () => {
|
||||
expect(effectiveDiceMode({ diceMode: 'BOTH' }, { diceMode: 'PHYSICAL' })).toBe('PHYSICAL');
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,18 @@
|
||||
const { SPECIES } = require('./data/species');
|
||||
const { CLASSES } = require('./data/classes');
|
||||
const { SKILLS } = require('./data/skills');
|
||||
const { resourceState } = require('./classResources');
|
||||
const { CR_XP, XP_THRESHOLDS, COUNT_MULTIPLIERS, LEVEL_XP } = require('./data/xp');
|
||||
const {
|
||||
FULL_CASTER_SLOTS,
|
||||
HALF_CASTER_SLOTS,
|
||||
THIRD_CASTER_SLOTS,
|
||||
PACT_SLOTS,
|
||||
CASTER_KIND,
|
||||
CLASS_SLOT_TABLES,
|
||||
SUBCLASS_CASTER_KIND,
|
||||
MAX_SLOT_LEVEL,
|
||||
} = require('./data/spellSlots');
|
||||
|
||||
const ABILITIES = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA'];
|
||||
|
||||
@@ -16,20 +28,18 @@ function proficiencyBonus(level) {
|
||||
return 2 + Math.floor((level - 1) / 4);
|
||||
}
|
||||
|
||||
// Half-Elf's flexible +1/+1 lands on whichever two abilities the player picked
|
||||
// (halfElfBonusAbilities), on top of the fixed +2 CHA in the species table.
|
||||
function speciesAbilityBonus(ability, species, halfElfBonusAbilities = []) {
|
||||
// A species' fixed bonus, plus whatever the player chose for its flexible
|
||||
// bonuses ({ ability: amount }: a Half-Elf's +1/+1, a Goblin's +2/+1...).
|
||||
// Choices count only for a species that has some to make.
|
||||
function speciesAbilityBonus(ability, species, choices = {}) {
|
||||
const speciesData = species ? SPECIES[species] : null;
|
||||
if (!speciesData) return 0;
|
||||
let bonus = speciesData.abilityBonuses[ability] || 0;
|
||||
if (species === 'HALF_ELF' && halfElfBonusAbilities.includes(ability)) {
|
||||
bonus += 1;
|
||||
}
|
||||
return bonus;
|
||||
const chosen = speciesData.flexible ? Number((choices || {})[ability]) || 0 : 0;
|
||||
return (speciesData.abilityBonuses[ability] || 0) + chosen;
|
||||
}
|
||||
|
||||
function finalAbilityScore(rolledScore, ability, species, halfElfBonusAbilities = []) {
|
||||
return rolledScore + speciesAbilityBonus(ability, species, halfElfBonusAbilities);
|
||||
function finalAbilityScore(rolledScore, ability, species, choices = {}) {
|
||||
return rolledScore + speciesAbilityBonus(ability, species, choices);
|
||||
}
|
||||
|
||||
function speciesSpeed(species) {
|
||||
@@ -54,10 +64,24 @@ function passivePerception(perceptionSkillBonus) {
|
||||
return 10 + perceptionSkillBonus;
|
||||
}
|
||||
|
||||
// Any skill has a passive score: what it comes to without a roll.
|
||||
function passiveScore(skillBonus) {
|
||||
return 10 + skillBonus;
|
||||
}
|
||||
|
||||
function armorClass(dexMod, armorBonus = 0) {
|
||||
return 10 + dexMod + armorBonus;
|
||||
}
|
||||
|
||||
// How much of a Dexterity modifier counts toward AC in the armor worn: all
|
||||
// of it in light armor or none, at most +2 in medium armor, and none of it
|
||||
// (a penalty included) in heavy armor.
|
||||
function armorDexterity(dexMod, worn = null) {
|
||||
if (worn === 'HEAVY') return 0;
|
||||
if (worn === 'MEDIUM') return Math.min(dexMod, 2);
|
||||
return dexMod;
|
||||
}
|
||||
|
||||
function initiative(dexMod) {
|
||||
return dexMod;
|
||||
}
|
||||
@@ -116,9 +140,125 @@ function getClassHitDieSize(characterClass) {
|
||||
return data ? data.hitDie : 8;
|
||||
}
|
||||
|
||||
function getClassSpellcastingAbility(characterClass) {
|
||||
// The ability a class casts with; a subclass that casts in a class that does
|
||||
// not (Eldritch Knight, Arcane Trickster) uses Intelligence.
|
||||
function getClassSpellcastingAbility(characterClass, subclass = null) {
|
||||
const data = characterClass ? CLASSES[characterClass] : null;
|
||||
return data ? data.spellcastingAbility : null;
|
||||
if (data && data.spellcastingAbility) return data.spellcastingAbility;
|
||||
return SUBCLASS_CASTER_KIND[subclass] ? 'INT' : null;
|
||||
}
|
||||
|
||||
// How a class casts (FULL, HALF, THIRD or PACT), counting a casting subclass;
|
||||
// null for none.
|
||||
function casterKind(characterClass, subclass = null) {
|
||||
return CASTER_KIND[characterClass] || SUBCLASS_CASTER_KIND[subclass] || null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Spell slots and Hit Dice: what a character has to spend between rests.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const MAX_LEVEL = 20;
|
||||
|
||||
function clampLevel(level) {
|
||||
return Math.min(Math.max(Math.round(Number(level) || 1), 1), MAX_LEVEL);
|
||||
}
|
||||
|
||||
// How many spell slots a class has at a level, by slot level (1st first), and
|
||||
// which rest gives them back. Null for a class that never has any. A warlock's
|
||||
// slots are all of one slot level, so the lower ones are 0.
|
||||
function spellSlotsFor(characterClass, level, subclass = null) {
|
||||
const kind = casterKind(characterClass, subclass);
|
||||
if (!kind) return null;
|
||||
const row = clampLevel(level) - 1;
|
||||
if (kind === 'PACT') {
|
||||
const [count, slotLevel] = PACT_SLOTS[row];
|
||||
return { kind, restoresOn: 'SHORT', max: Array.from({ length: slotLevel }, (_, i) => (i === slotLevel - 1 ? count : 0)) };
|
||||
}
|
||||
const table = CLASS_SLOT_TABLES[characterClass] || { FULL: FULL_CASTER_SLOTS, HALF: HALF_CASTER_SLOTS, THIRD: THIRD_CASTER_SLOTS }[kind];
|
||||
return { kind, restoresOn: 'LONG', max: [...table[row]] };
|
||||
}
|
||||
|
||||
// The slot tracker: for each slot level the character has, how many slots
|
||||
// there are and how many are spent. `used` is the stored tally (1st-level
|
||||
// first), which may be shorter than the class's row or hold more than it now
|
||||
// allows. Null when there are no slots to track (not a caster, or a level 1
|
||||
// paladin).
|
||||
function spellSlotState(characterClass, level, used = [], subclass = null) {
|
||||
return slotStateOf(spellSlotsFor(characterClass, level, subclass), used);
|
||||
}
|
||||
|
||||
// The slot tracker for a set of slots (spellSlotsFor's shape).
|
||||
function slotStateOf(slots, used = []) {
|
||||
if (!slots) return null;
|
||||
const levels = slots.max
|
||||
.map((max, i) => {
|
||||
const spent = Math.min(Math.max(Number((used || [])[i]) || 0, 0), max);
|
||||
return { level: i + 1, max, used: spent, remaining: max - spent };
|
||||
})
|
||||
.filter((slot) => slot.max > 0);
|
||||
return levels.length > 0 ? { kind: slots.kind, restoresOn: slots.restoresOn, levels } : null;
|
||||
}
|
||||
|
||||
// The highest level of spell a class can cast at a level; 0 for none.
|
||||
function maxSpellLevel(characterClass, level, subclass = null) {
|
||||
const slots = spellSlotsFor(characterClass, level, subclass);
|
||||
return slots ? slots.max.length : 0;
|
||||
}
|
||||
|
||||
// One Hit Die per level, of the class's size. Spent ones come back on a long rest.
|
||||
function hitDiceState(characterClass, level, used = 0) {
|
||||
const count = clampLevel(level);
|
||||
const spent = Math.min(Math.max(Number(used) || 0, 0), count);
|
||||
return { size: getClassHitDieSize(characterClass), count, used: spent, remaining: count - spent };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Experience points and encounter difficulty (data/xp.js).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// The XP one monster of a challenge rating is worth. The rating is free text
|
||||
// on a monster ("1/4", "5", "0.5"); null for anything that is not a rating.
|
||||
function challengeXp(challengeRating) {
|
||||
if (challengeRating == null) return null;
|
||||
const text = String(challengeRating).trim().replace(/^cr\s*/i, '');
|
||||
const fractions = { 0.125: '1/8', 0.25: '1/4', 0.5: '1/2' };
|
||||
const key = fractions[text] || text;
|
||||
return Object.prototype.hasOwnProperty.call(CR_XP, key) ? CR_XP[key] : null;
|
||||
}
|
||||
|
||||
// How hard a fight is for a party. `partyLevels` is the level of each
|
||||
// character in it; `challengeRatings` the rating of each monster. `xp` is
|
||||
// what the monsters are worth; `adjustedXp` is that multiplied for their
|
||||
// number, which is what is held against the party's thresholds. `rating` is
|
||||
// TRIVIAL, EASY, MEDIUM, HARD or DEADLY, or null with no party or no rated
|
||||
// monster to judge by. Monsters with no readable rating are counted in
|
||||
// `unrated` and left out of everything else.
|
||||
function encounterDifficulty(partyLevels, challengeRatings) {
|
||||
const worth = challengeRatings.map(challengeXp);
|
||||
const rated = worth.filter((xp) => xp !== null);
|
||||
const xp = rated.reduce((sum, value) => sum + value, 0);
|
||||
const multiplier = rated.length === 0 ? 1 : COUNT_MULTIPLIERS.find(([atLeast]) => rated.length >= atLeast)[1];
|
||||
const adjustedXp = Math.floor(xp * multiplier);
|
||||
|
||||
let thresholds = null;
|
||||
let rating = null;
|
||||
if (partyLevels.length > 0) {
|
||||
const [easy, medium, hard, deadly] = [0, 1, 2, 3].map((i) => partyLevels.reduce((sum, level) => sum + XP_THRESHOLDS[clampLevel(level) - 1][i], 0));
|
||||
thresholds = { easy, medium, hard, deadly };
|
||||
if (rated.length > 0) {
|
||||
rating = adjustedXp >= deadly ? 'DEADLY' : adjustedXp >= hard ? 'HARD' : adjustedXp >= medium ? 'MEDIUM' : adjustedXp >= easy ? 'EASY' : 'TRIVIAL';
|
||||
}
|
||||
}
|
||||
return { xp, adjustedXp, multiplier, rating, thresholds, monsters: rated.length, unrated: worth.length - rated.length };
|
||||
}
|
||||
|
||||
// Where a character's XP puts them: what their next level takes, and whether
|
||||
// they have it. Levelling stays the DM's decision; this only says it is due.
|
||||
function xpProgress(xp, level) {
|
||||
const at = clampLevel(level);
|
||||
const nextLevelAt = at >= MAX_LEVEL ? null : LEVEL_XP[at];
|
||||
return { nextLevelAt, levelUpDue: nextLevelAt !== null && xp >= nextLevelAt };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -156,6 +296,12 @@ function activeGear(character) {
|
||||
|
||||
const effects = [];
|
||||
const notes = [];
|
||||
// The armor on their back (the heaviest, should there be two) and whether
|
||||
// a shield is on their arm: class features turn on what is worn.
|
||||
const kinds = held.map((h) => h.entry.armorType).filter(Boolean);
|
||||
const worn = ['HEAVY', 'MEDIUM', 'LIGHT'].find((kind) => kinds.includes(kind)) || null;
|
||||
const suit = worn ? held.find((h) => h.entry.armorType === worn) : null;
|
||||
const armor = { worn, name: suit ? suit.entry.name : null, shield: kinds.includes('SHIELD') };
|
||||
for (const { entry } of held) {
|
||||
for (const effect of Array.isArray(entry.effects) ? entry.effects : []) {
|
||||
if (GEAR_STATS.includes(effect.stat) && Number.isInteger(effect.amount) && effect.amount !== 0) {
|
||||
@@ -164,7 +310,7 @@ function activeGear(character) {
|
||||
}
|
||||
if (entry.effectNote) notes.push({ source: entry.name, note: entry.effectNote });
|
||||
}
|
||||
return { effects, notes };
|
||||
return { effects, notes, armor };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -189,13 +335,14 @@ function computeCharacterSheet(character, skillProficiencies = [], saveProficien
|
||||
intScore = 10,
|
||||
wisScore = 10,
|
||||
chaScore = 10,
|
||||
halfElfBonusAbility1 = null,
|
||||
halfElfBonusAbility2 = null,
|
||||
speciesBonusChoices = {},
|
||||
armorBonus = 0,
|
||||
speedOverride = null,
|
||||
spellSlotsUsed = [],
|
||||
hitDiceUsed = 0,
|
||||
hpRollAdjust = 0,
|
||||
} = character;
|
||||
|
||||
const halfElfBonusAbilities = [halfElfBonusAbility1, halfElfBonusAbility2].filter(Boolean);
|
||||
const rolled = { STR: strScore, DEX: dexScore, CON: conScore, INT: intScore, WIS: wisScore, CHA: chaScore };
|
||||
|
||||
const gear = activeGear(character);
|
||||
@@ -205,7 +352,7 @@ function computeCharacterSheet(character, skillProficiencies = [], saveProficien
|
||||
const abilities = {};
|
||||
for (const ability of ABILITIES) {
|
||||
// A score never drops below 1, whatever is weighing the character down.
|
||||
const final = Math.max(1, finalAbilityScore(rolled[ability], ability, species, halfElfBonusAbilities) + fromGear(ability));
|
||||
const final = Math.max(1, finalAbilityScore(rolled[ability], ability, species, speciesBonusChoices) + fromGear(ability));
|
||||
abilities[ability] = {
|
||||
rolled: rolled[ability],
|
||||
final,
|
||||
@@ -215,11 +362,30 @@ function computeCharacterSheet(character, skillProficiencies = [], saveProficien
|
||||
|
||||
const profBonus = proficiencyBonus(level);
|
||||
|
||||
// Every class the character has levels in, the first first. One entry for
|
||||
// most characters; a multiclassed one adds up per class (multiclass.js).
|
||||
const classes = multiclass.classLevels(character);
|
||||
const multi = classes.length > 1;
|
||||
// What their class features do to the numbers below (classFeatures.js).
|
||||
const modifiers = Object.fromEntries(ABILITIES.map((ability) => [ability, abilities[ability].modifier]));
|
||||
const features = classFeatureEffects(classes, modifiers, profBonus, gear.armor);
|
||||
// Medium and heavy armor hold Dexterity back; said on the gear card when it bites.
|
||||
const acDex = armorDexterity(abilities.DEX.modifier, gear.armor.worn);
|
||||
if (acDex !== abilities.DEX.modifier) {
|
||||
gear.notes.push({
|
||||
source: gear.armor.name,
|
||||
note: gear.armor.worn === 'HEAVY' ? 'Heavy armor: Dexterity does not count toward AC.' : 'Medium armor: at most +2 from Dexterity counts toward AC.',
|
||||
});
|
||||
}
|
||||
|
||||
const saves = {};
|
||||
for (const ability of ABILITIES) {
|
||||
const entry = saveProficiencies.find((s) => s.ability === ability);
|
||||
const proficient = entry ? entry.proficient : false;
|
||||
saves[ability] = { proficient, bonus: saveBonus(abilities[ability].modifier, proficient, profBonus) + fromGear('SAVES', `SAVE_${ability}`) };
|
||||
const proficient = (entry ? entry.proficient : false) || features.saveProficiencies.includes(ability);
|
||||
saves[ability] = {
|
||||
proficient,
|
||||
bonus: saveBonus(abilities[ability].modifier, proficient, profBonus) + features.saveBonus + fromGear('SAVES', `SAVE_${ability}`),
|
||||
};
|
||||
}
|
||||
|
||||
const skills = {};
|
||||
@@ -232,33 +398,56 @@ function computeCharacterSheet(character, skillProficiencies = [], saveProficien
|
||||
ability,
|
||||
proficient,
|
||||
expertise,
|
||||
bonus: skillBonus(abilities[ability].modifier, proficient, profBonus, expertise) + fromGear('SKILLS', `SKILL_${skillKey}`),
|
||||
bonus: skillBonus(abilities[ability].modifier, proficient, profBonus, expertise) + (proficient ? 0 : features.halfProficiency) + fromGear('SKILLS', `SKILL_${skillKey}`),
|
||||
};
|
||||
}
|
||||
|
||||
const hitDieSize = getClassHitDieSize(characterClass);
|
||||
const spellcastingAbility = getClassSpellcastingAbility(characterClass);
|
||||
const casters = classes
|
||||
.map((entry) => ({ ...entry, ability: getClassSpellcastingAbility(entry.characterClass, entry.subclass) }))
|
||||
.filter((entry) => entry.ability && (casterKind(entry.characterClass, entry.subclass) !== 'THIRD' || entry.level >= 3));
|
||||
const casting = (ability) => ({
|
||||
ability,
|
||||
saveDC: spellSaveDC(profBonus, abilities[ability].modifier),
|
||||
attackBonus: spellAttackBonus(profBonus, abilities[ability].modifier),
|
||||
});
|
||||
const spellcastingAbility = casters.length > 0 ? casters[0].ability : null;
|
||||
|
||||
return {
|
||||
abilities,
|
||||
proficiencyBonus: profBonus,
|
||||
armorClass: armorClass(abilities.DEX.modifier, armorBonus) + fromGear('AC'),
|
||||
initiative: initiative(abilities.DEX.modifier) + fromGear('INITIATIVE'),
|
||||
speed: Math.max(0, effectiveSpeed(species, speedOverride) + fromGear('SPEED')),
|
||||
hp: { max: Math.max(1, hpMax(level, hitDieSize, abilities.CON.modifier) + fromGear('MAX_HP')) },
|
||||
hitDice: { size: hitDieSize, count: level },
|
||||
// Unarmored Defense and the like replace the 10 + DEX that AC starts from.
|
||||
armorClass: (features.acBase !== null ? features.acBase + armorBonus : armorClass(acDex, armorBonus)) + fromGear('AC'),
|
||||
initiative: initiative(abilities.DEX.modifier) + features.halfProficiency + fromGear('INITIATIVE'),
|
||||
// A speed the DM has set is their last word: a class's extra speed is
|
||||
// added to the species' own speed only.
|
||||
speed: Math.max(0, effectiveSpeed(species, speedOverride) + (speedOverride != null ? 0 : features.speed) + fromGear('SPEED')),
|
||||
hp: {
|
||||
// hpRollAdjust: how far HP rolled on level-ups is from the average counted here.
|
||||
max: Math.max(
|
||||
1,
|
||||
(multi ? multiclass.multiclassHpMax(classes, abilities.CON.modifier) : hpMax(level, hitDieSize, abilities.CON.modifier)) + (Number(hpRollAdjust) || 0) + features.hp + fromGear('MAX_HP')
|
||||
),
|
||||
},
|
||||
hitDice: multi ? multiclass.multiclassHitDice(classes, hitDiceUsed) : hitDiceState(characterClass, level, hitDiceUsed),
|
||||
saves,
|
||||
skills,
|
||||
passivePerception: passivePerception(skills.PERCEPTION.bonus) + fromGear('PASSIVE_PERCEPTION'),
|
||||
passiveInvestigation: passiveScore(skills.INVESTIGATION.bonus),
|
||||
passiveInsight: passiveScore(skills.INSIGHT.bonus),
|
||||
// What equipped gear is doing to the numbers above, and what else it does.
|
||||
gear,
|
||||
spellcasting: spellcastingAbility
|
||||
? {
|
||||
ability: spellcastingAbility,
|
||||
saveDC: spellSaveDC(profBonus, abilities[spellcastingAbility].modifier),
|
||||
attackBonus: spellAttackBonus(profBonus, abilities[spellcastingAbility].modifier),
|
||||
}
|
||||
: null,
|
||||
// The class features counted in the numbers above: [{ name, source, text }].
|
||||
features: speedOverride != null ? features.inForce.filter((f) => !['Fast Movement', 'Unarmored Movement'].includes(f.name)) : features.inForce,
|
||||
spellcasting: spellcastingAbility ? casting(spellcastingAbility) : null,
|
||||
// A multiclassed caster's DC and attack for each class that casts.
|
||||
spellcastingByClass: casters.map((entry) => ({ characterClass: entry.characterClass, ...casting(entry.ability) })),
|
||||
// The slot tracker; null for a character with no spell slots.
|
||||
spellSlots: multi ? slotStateOf(multiclass.multiclassSpellSlots(classes), spellSlotsUsed) : spellSlotState(characterClass, level, spellSlotsUsed, character.subclass),
|
||||
// A multiclassed warlock's pact slots, apart from the others; null otherwise.
|
||||
pactSlots: multi ? multiclass.pactSlotsOf(classes) : null,
|
||||
// The class counters (Rage, Ki...), with how many of each are left.
|
||||
resources: multi ? multiclass.multiclassResources(classes, character.resourcesUsed, abilities, profBonus) : resourceState(character, abilities, profBonus),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -393,7 +582,9 @@ module.exports = {
|
||||
saveBonus,
|
||||
skillBonus,
|
||||
passivePerception,
|
||||
passiveScore,
|
||||
armorClass,
|
||||
armorDexterity,
|
||||
initiative,
|
||||
hpMax,
|
||||
spellSaveDC,
|
||||
@@ -405,6 +596,17 @@ module.exports = {
|
||||
getClassSaveProficiencies,
|
||||
getClassHitDieSize,
|
||||
getClassSpellcastingAbility,
|
||||
MAX_LEVEL,
|
||||
MAX_SLOT_LEVEL,
|
||||
spellSlotsFor,
|
||||
slotStateOf,
|
||||
casterKind,
|
||||
spellSlotState,
|
||||
maxSpellLevel,
|
||||
hitDiceState,
|
||||
challengeXp,
|
||||
encounterDifficulty,
|
||||
xpProgress,
|
||||
GEAR_STATS,
|
||||
activeGear,
|
||||
computeCharacterSheet,
|
||||
@@ -416,3 +618,8 @@ module.exports = {
|
||||
scaledDamageDice,
|
||||
canUseGear,
|
||||
};
|
||||
|
||||
// multiclass.js and this file use each other, so it is required here, at
|
||||
// the end, and its functions are looked up when called.
|
||||
const multiclass = require('./multiclass');
|
||||
const { classFeatureEffects } = require('./classFeatures');
|
||||
|
||||
@@ -58,10 +58,20 @@ describe('finalAbilityScore / species bonuses', () => {
|
||||
});
|
||||
|
||||
test('half-elf gets fixed +2 CHA plus chosen +1/+1', () => {
|
||||
expect(finalAbilityScore(10, 'CHA', 'HALF_ELF', ['STR', 'INT'])).toBe(12);
|
||||
expect(finalAbilityScore(10, 'STR', 'HALF_ELF', ['STR', 'INT'])).toBe(11);
|
||||
expect(finalAbilityScore(10, 'INT', 'HALF_ELF', ['STR', 'INT'])).toBe(11);
|
||||
expect(finalAbilityScore(10, 'WIS', 'HALF_ELF', ['STR', 'INT'])).toBe(10);
|
||||
expect(finalAbilityScore(10, 'CHA', 'HALF_ELF', { STR: 1, INT: 1 })).toBe(12);
|
||||
expect(finalAbilityScore(10, 'STR', 'HALF_ELF', { STR: 1, INT: 1 })).toBe(11);
|
||||
expect(finalAbilityScore(10, 'INT', 'HALF_ELF', { STR: 1, INT: 1 })).toBe(11);
|
||||
expect(finalAbilityScore(10, 'WIS', 'HALF_ELF', { STR: 1, INT: 1 })).toBe(10);
|
||||
});
|
||||
|
||||
test('a Multiverse species takes the bonuses its player chose', () => {
|
||||
expect(finalAbilityScore(10, 'DEX', 'GOBLIN', { DEX: 2, CON: 1 })).toBe(12);
|
||||
expect(finalAbilityScore(10, 'CON', 'GOBLIN', { DEX: 2, CON: 1 })).toBe(11);
|
||||
expect(finalAbilityScore(10, 'STR', 'GOBLIN', { DEX: 2, CON: 1 })).toBe(10);
|
||||
});
|
||||
|
||||
test('chosen bonuses count only for a species that has some to choose', () => {
|
||||
expect(finalAbilityScore(10, 'STR', 'DWARF', { STR: 2 })).toBe(10);
|
||||
});
|
||||
|
||||
test('no species leaves score untouched', () => {
|
||||
@@ -199,8 +209,7 @@ describe('computeCharacterSheet — full assembly', () => {
|
||||
characterClass: 'BARD',
|
||||
strScore: 10,
|
||||
chaScore: 10,
|
||||
halfElfBonusAbility1: 'STR',
|
||||
halfElfBonusAbility2: 'INT',
|
||||
speciesBonusChoices: { STR: 1, INT: 1 },
|
||||
});
|
||||
expect(sheet.abilities.CHA.final).toBe(12); // fixed +2
|
||||
expect(sheet.abilities.STR.final).toBe(11); // chosen +1
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
// The class features that change a number on the sheet, worked out so nobody
|
||||
// has to add them by hand: Unarmored Defense, Draconic Resilience, Fast
|
||||
// Movement, Unarmored Movement, Aura of Protection, Diamond Soul, Slippery
|
||||
// Mind and Jack of All Trades. Everything else a class gives is a line of
|
||||
// text on the sheet (game/data/levelFeatures.js). Pure: no database.
|
||||
//
|
||||
// Each goes by the level in the class that gives it, so a multiclassed
|
||||
// character gets what each of their classes has earned (game/multiclass.js,
|
||||
// classLevels). Several depend on what is worn: armor and shields are items
|
||||
// marked with what kind they are (Item.armorType), and count while equipped.
|
||||
|
||||
const { SUBCLASS_LEVEL } = require('./data/subclasses');
|
||||
|
||||
// A monk's extra speed without armor or a shield, by monk level.
|
||||
function unarmoredMovement(monkLevel) {
|
||||
if (monkLevel < 2) return 0;
|
||||
if (monkLevel < 6) return 10;
|
||||
if (monkLevel < 10) return 15;
|
||||
if (monkLevel < 14) return 20;
|
||||
if (monkLevel < 18) return 25;
|
||||
return 30;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a character's class features do to the sheet's numbers.
|
||||
*
|
||||
* @param {Array<{characterClass: string, level: number, subclass: string|null}>} classes
|
||||
* @param {object} modifiers - ability modifiers by ability: { STR, DEX, CON, INT, WIS, CHA }
|
||||
* @param {number} profBonus
|
||||
* @param {{worn: 'LIGHT'|'MEDIUM'|'HEAVY'|null, shield: boolean}} armor - what is equipped
|
||||
* @returns {{
|
||||
* acBase: number|null, // what AC starts from in place of 10 + DEX, when that is better
|
||||
* speed: number, // added to walking speed
|
||||
* hp: number, // added to maximum HP
|
||||
* saveBonus: number, // added to every saving throw
|
||||
* saveProficiencies: string[],// saves the character is proficient in on top of their class's two
|
||||
* halfProficiency: number, // added to initiative and to skills they are not proficient in
|
||||
* inForce: Array<{name: string, source: string, text: string}>
|
||||
* }}
|
||||
*/
|
||||
function classFeatureEffects(classes, modifiers, profBonus, armor = { worn: null, shield: false }) {
|
||||
const levelIn = (characterClass) => {
|
||||
const entry = classes.find((c) => c.characterClass === characterClass);
|
||||
return entry ? entry.level : 0;
|
||||
};
|
||||
const unarmored = !armor.worn;
|
||||
const plain = 10 + modifiers.DEX;
|
||||
const inForce = [];
|
||||
const signed = (n) => (n >= 0 ? `+${n}` : `${n}`);
|
||||
|
||||
// Armor Class without armor: the best of the ways the character has of
|
||||
// working it out, and only when it beats 10 + DEX.
|
||||
const acWays = [];
|
||||
if (levelIn('BARBARIAN') >= 1 && unarmored) {
|
||||
acWays.push({ ac: plain + modifiers.CON, name: 'Unarmored Defense', source: 'Barbarian', text: `AC is 10 + Dexterity + Constitution (${signed(modifiers.CON)}) without armor; a shield still adds.` });
|
||||
}
|
||||
if (levelIn('MONK') >= 1 && unarmored && !armor.shield) {
|
||||
acWays.push({ ac: plain + modifiers.WIS, name: 'Unarmored Defense', source: 'Monk', text: `AC is 10 + Dexterity + Wisdom (${signed(modifiers.WIS)}) without armor or a shield.` });
|
||||
}
|
||||
const sorcerer = classes.find((c) => c.characterClass === 'SORCERER');
|
||||
const draconic = sorcerer && sorcerer.subclass === 'DRACONIC' && sorcerer.level >= SUBCLASS_LEVEL.SORCERER ? sorcerer : null;
|
||||
if (draconic && unarmored) {
|
||||
acWays.push({ ac: 13 + modifiers.DEX, name: 'Draconic Resilience', source: 'Draconic Bloodline', text: 'AC is 13 + Dexterity without armor.' });
|
||||
}
|
||||
const bestAc = acWays.sort((a, b) => b.ac - a.ac)[0];
|
||||
const acBase = bestAc && bestAc.ac > plain ? bestAc.ac : null;
|
||||
if (acBase !== null) inForce.push({ name: bestAc.name, source: bestAc.source, text: bestAc.text });
|
||||
|
||||
let hp = 0;
|
||||
if (draconic) {
|
||||
hp += draconic.level;
|
||||
inForce.push({ name: 'Draconic Resilience', source: 'Draconic Bloodline', text: `+1 maximum HP for each sorcerer level (+${draconic.level}).` });
|
||||
}
|
||||
|
||||
let speed = 0;
|
||||
if (levelIn('BARBARIAN') >= 5 && armor.worn !== 'HEAVY') {
|
||||
speed += 10;
|
||||
inForce.push({ name: 'Fast Movement', source: 'Barbarian', text: '+10 ft speed when not in heavy armor.' });
|
||||
}
|
||||
const monkSpeed = unarmored && !armor.shield ? unarmoredMovement(levelIn('MONK')) : 0;
|
||||
if (monkSpeed > 0) {
|
||||
speed += monkSpeed;
|
||||
inForce.push({ name: 'Unarmored Movement', source: 'Monk', text: `+${monkSpeed} ft speed without armor or a shield.` });
|
||||
}
|
||||
|
||||
let saveBonus = 0;
|
||||
if (levelIn('PALADIN') >= 6) {
|
||||
saveBonus = Math.max(1, modifiers.CHA);
|
||||
inForce.push({ name: 'Aura of Protection', source: 'Paladin', text: `+${saveBonus} (Charisma) to every saving throw while conscious. Allies in the aura add it by hand.` });
|
||||
}
|
||||
|
||||
const saveProficiencies = [];
|
||||
if (levelIn('MONK') >= 14) {
|
||||
saveProficiencies.push('STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA');
|
||||
inForce.push({ name: 'Diamond Soul', source: 'Monk', text: 'Proficient in every saving throw.' });
|
||||
}
|
||||
if (levelIn('ROGUE') >= 15) {
|
||||
saveProficiencies.push('WIS');
|
||||
inForce.push({ name: 'Slippery Mind', source: 'Rogue', text: 'Proficient in Wisdom saving throws.' });
|
||||
}
|
||||
|
||||
let halfProficiency = 0;
|
||||
if (levelIn('BARD') >= 2) {
|
||||
halfProficiency = Math.floor(profBonus / 2);
|
||||
inForce.push({ name: 'Jack of All Trades', source: 'Bard', text: `+${halfProficiency} (half proficiency) to initiative and to every skill you are not proficient in.` });
|
||||
}
|
||||
|
||||
return { acBase, speed, hp, saveBonus, saveProficiencies: [...new Set(saveProficiencies)], halfProficiency, inForce };
|
||||
}
|
||||
|
||||
module.exports = { classFeatureEffects, unarmoredMovement };
|
||||
@@ -0,0 +1,168 @@
|
||||
const { computeCharacterSheet } = require('./calculations');
|
||||
const { classFeatureEffects, unarmoredMovement } = require('./classFeatures');
|
||||
|
||||
// A human (+1 to everything) with STR 16, DEX 14 (+2), CON 14 (+2), INT 10,
|
||||
// WIS 16 (+3), CHA 16 (+3) once the species bonus is in.
|
||||
const scores = { species: 'HUMAN', strScore: 15, dexScore: 13, conScore: 13, intScore: 9, wisScore: 15, chaScore: 15, speciesBonusChoices: {} };
|
||||
const sheet = (character, saves = []) => computeCharacterSheet({ ...scores, level: 1, ...character }, [], saves);
|
||||
const wearing = (name, armorType, ac) => ({ equipped: true, level: 1, item: { name, armorType, effects: [{ stat: 'AC', amount: ac }] } });
|
||||
const names = (s) => s.features.map((f) => f.name);
|
||||
|
||||
describe('Armor Class without armor', () => {
|
||||
test('a barbarian adds Constitution, and keeps it behind a shield', () => {
|
||||
expect(sheet({ characterClass: 'BARBARIAN' }).armorClass).toBe(14); // 10 + 2 + 2
|
||||
const shielded = sheet({ characterClass: 'BARBARIAN', inventoryItems: [wearing('Shield', 'SHIELD', 2)] });
|
||||
expect(shielded.armorClass).toBe(16);
|
||||
expect(names(shielded)).toContain('Unarmored Defense');
|
||||
});
|
||||
|
||||
test('a monk adds Wisdom, but not with a shield', () => {
|
||||
expect(sheet({ characterClass: 'MONK' }).armorClass).toBe(15); // 10 + 2 + 3
|
||||
const shielded = sheet({ characterClass: 'MONK', inventoryItems: [wearing('Shield', 'SHIELD', 2)] });
|
||||
expect(shielded.armorClass).toBe(14); // 10 + 2, and the shield
|
||||
expect(names(shielded)).not.toContain('Unarmored Defense');
|
||||
});
|
||||
|
||||
test('armor on, it is the armor that counts', () => {
|
||||
const armored = sheet({ characterClass: 'BARBARIAN', inventoryItems: [wearing('Hide Armor', 'MEDIUM', 2)] });
|
||||
expect(armored.armorClass).toBe(14); // 10 + 2 + the hide's 2
|
||||
expect(names(armored)).toEqual([]);
|
||||
// Armor that is carried, not worn, changes nothing.
|
||||
const carried = sheet({ characterClass: 'BARBARIAN', inventoryItems: [{ ...wearing('Hide Armor', 'MEDIUM', 2), equipped: false }] });
|
||||
expect(carried.armorClass).toBe(14);
|
||||
expect(names(carried)).toContain('Unarmored Defense');
|
||||
});
|
||||
|
||||
test('it is left out when it would not help, and the DM’s extra AC still adds', () => {
|
||||
const frail = sheet({ characterClass: 'BARBARIAN', conScore: 7 }); // CON 8: -1
|
||||
expect(frail.armorClass).toBe(12);
|
||||
expect(names(frail)).toEqual([]);
|
||||
expect(sheet({ characterClass: 'BARBARIAN', armorBonus: 1 }).armorClass).toBe(15);
|
||||
});
|
||||
|
||||
test('a draconic sorcerer has 13 + Dexterity and a hit point a level, from the level the bloodline starts', () => {
|
||||
const before = sheet({ characterClass: 'SORCERER', subclass: 'DRACONIC', level: 2 });
|
||||
expect(before.armorClass).toBe(12);
|
||||
expect(before.hp.max).toBe(14); // 6 + 2, then 4 + 2
|
||||
const dragon = sheet({ characterClass: 'SORCERER', subclass: 'DRACONIC', level: 3 });
|
||||
expect(dragon.armorClass).toBe(15);
|
||||
expect(dragon.hp.max).toBe(23); // 20, and 3 more
|
||||
expect(sheet({ characterClass: 'SORCERER', subclass: 'WILD_MAGIC', level: 3 }).hp.max).toBe(20);
|
||||
});
|
||||
});
|
||||
|
||||
describe('speed', () => {
|
||||
test('a barbarian is 10 ft faster from level 5, out of heavy armor', () => {
|
||||
expect(sheet({ characterClass: 'BARBARIAN', level: 4 }).speed).toBe(30);
|
||||
expect(sheet({ characterClass: 'BARBARIAN', level: 5 }).speed).toBe(40);
|
||||
expect(sheet({ characterClass: 'BARBARIAN', level: 5, inventoryItems: [wearing('Hide Armor', 'MEDIUM', 2)] }).speed).toBe(40);
|
||||
expect(sheet({ characterClass: 'BARBARIAN', level: 5, inventoryItems: [wearing('Plate Armor', 'HEAVY', 8)] }).speed).toBe(30);
|
||||
});
|
||||
|
||||
test('a monk speeds up as they level, without armor or a shield', () => {
|
||||
expect([1, 2, 5, 6, 10, 14, 18, 20].map(unarmoredMovement)).toEqual([0, 10, 10, 15, 20, 25, 30, 30]);
|
||||
expect(sheet({ characterClass: 'MONK', level: 6 }).speed).toBe(45);
|
||||
expect(sheet({ characterClass: 'MONK', level: 6, inventoryItems: [wearing('Leather Armor', 'LIGHT', 1)] }).speed).toBe(30);
|
||||
expect(sheet({ characterClass: 'MONK', level: 6, inventoryItems: [wearing('Shield', 'SHIELD', 2)] }).speed).toBe(30);
|
||||
});
|
||||
|
||||
test('a speed the DM has set is the last word', () => {
|
||||
const set = sheet({ characterClass: 'BARBARIAN', level: 5, speedOverride: 40 });
|
||||
expect(set.speed).toBe(40);
|
||||
expect(names(set)).not.toContain('Fast Movement');
|
||||
});
|
||||
});
|
||||
|
||||
describe('saving throws', () => {
|
||||
const classSaves = (...abilities) => abilities.map((ability) => ({ ability, proficient: true }));
|
||||
const bonuses = (s) => Object.fromEntries(Object.entries(s.saves).map(([ability, save]) => [ability, save.bonus]));
|
||||
|
||||
test('a paladin’s aura adds Charisma to every save from level 6, and at least 1', () => {
|
||||
const young = sheet({ characterClass: 'PALADIN', level: 5 }, classSaves('WIS', 'CHA'));
|
||||
expect(bonuses(young)).toEqual({ STR: 3, DEX: 2, CON: 2, INT: 0, WIS: 6, CHA: 6 });
|
||||
const aura = sheet({ characterClass: 'PALADIN', level: 6 }, classSaves('WIS', 'CHA'));
|
||||
expect(bonuses(aura)).toEqual({ STR: 6, DEX: 5, CON: 5, INT: 3, WIS: 9, CHA: 9 });
|
||||
const dour = sheet({ characterClass: 'PALADIN', level: 6, chaScore: 7 }, classSaves('WIS', 'CHA')); // CHA 8: -1
|
||||
expect(bonuses(dour).STR).toBe(4);
|
||||
});
|
||||
|
||||
test('a monk is proficient in every save from level 14', () => {
|
||||
const before = sheet({ characterClass: 'MONK', level: 13 }, classSaves('STR', 'DEX'));
|
||||
expect(before.saves.WIS).toEqual({ proficient: false, bonus: 3 });
|
||||
const soul = sheet({ characterClass: 'MONK', level: 14 }, classSaves('STR', 'DEX'));
|
||||
expect(Object.values(soul.saves).every((save) => save.proficient)).toBe(true);
|
||||
expect(bonuses(soul)).toEqual({ STR: 8, DEX: 7, CON: 7, INT: 5, WIS: 8, CHA: 8 }); // +5 proficiency
|
||||
});
|
||||
|
||||
test('a rogue is proficient in Wisdom saves from level 15', () => {
|
||||
expect(sheet({ characterClass: 'ROGUE', level: 14 }, classSaves('DEX', 'INT')).saves.WIS).toEqual({ proficient: false, bonus: 3 });
|
||||
expect(sheet({ characterClass: 'ROGUE', level: 15 }, classSaves('DEX', 'INT')).saves.WIS).toEqual({ proficient: true, bonus: 8 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Jack of All Trades', () => {
|
||||
test('a bard adds half proficiency to initiative and to skills they are not proficient in', () => {
|
||||
const skills = [{ skill: 'PERFORMANCE', proficient: true, expertise: false }];
|
||||
const novice = computeCharacterSheet({ ...scores, characterClass: 'BARD', level: 1 }, skills, []);
|
||||
expect(novice.initiative).toBe(2);
|
||||
const bard = computeCharacterSheet({ ...scores, characterClass: 'BARD', level: 2 }, skills, []);
|
||||
expect(bard.initiative).toBe(3); // +2 Dexterity, +1
|
||||
expect(bard.skills.STEALTH.bonus).toBe(3);
|
||||
expect(bard.skills.PERFORMANCE.bonus).toBe(5); // +3 Charisma, +2: proficient, so no half
|
||||
expect(bard.passivePerception).toBe(14); // 10 + 3 Wisdom + 1
|
||||
expect(computeCharacterSheet({ ...scores, characterClass: 'BARD', level: 9 }, skills, []).initiative).toBe(4); // half of +4
|
||||
});
|
||||
});
|
||||
|
||||
describe('multiclassed', () => {
|
||||
test('each class counts by its own level', () => {
|
||||
// Paladin 6 / Barbarian 1: the aura, and Unarmored Defense, but no Fast Movement.
|
||||
const mixed = sheet({ characterClass: 'PALADIN', level: 7, classLevels: [{ characterClass: 'BARBARIAN', level: 1 }] });
|
||||
expect(names(mixed).sort()).toEqual(['Aura of Protection', 'Unarmored Defense']);
|
||||
expect(mixed.armorClass).toBe(14);
|
||||
// Barbarian 1 / Monk 1: the better of the two ways, not both.
|
||||
const both = sheet({ characterClass: 'BARBARIAN', level: 2, classLevels: [{ characterClass: 'MONK', level: 1 }] });
|
||||
expect(both.armorClass).toBe(15);
|
||||
expect(both.features).toHaveLength(1);
|
||||
expect(both.features[0].source).toBe('Monk');
|
||||
});
|
||||
|
||||
test('nothing for a class with none of these', () => {
|
||||
const effects = classFeatureEffects([{ characterClass: 'FIGHTER', level: 20, subclass: null }], { STR: 3, DEX: 2, CON: 2, INT: 0, WIS: 3, CHA: 3 }, 6);
|
||||
expect(effects).toEqual({ acBase: null, speed: 0, hp: 0, saveBonus: 0, saveProficiencies: [], halfProficiency: 0, inForce: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Dexterity in armor', () => {
|
||||
const { armorDexterity } = require('./calculations');
|
||||
// Dexterity 18 (+4), and a clumsy one at 8 (-1).
|
||||
const nimble = (inventoryItems) => sheet({ characterClass: 'FIGHTER', dexScore: 17, inventoryItems });
|
||||
const clumsy = (inventoryItems) => sheet({ characterClass: 'FIGHTER', dexScore: 7, inventoryItems });
|
||||
|
||||
test('all of it in light armor or none, at most +2 in medium, none in heavy', () => {
|
||||
expect([null, 'LIGHT', 'MEDIUM', 'HEAVY', 'SHIELD'].map((worn) => armorDexterity(4, worn))).toEqual([4, 4, 2, 0, 4]);
|
||||
expect([null, 'LIGHT', 'MEDIUM', 'HEAVY'].map((worn) => armorDexterity(-1, worn))).toEqual([-1, -1, -1, 0]);
|
||||
});
|
||||
|
||||
test('the sheet’s AC follows, and the gear card says why', () => {
|
||||
expect(nimble([]).armorClass).toBe(14);
|
||||
expect(nimble([wearing('Leather Armor', 'LIGHT', 1)]).armorClass).toBe(15);
|
||||
const scale = nimble([wearing('Scale Mail', 'MEDIUM', 4)]);
|
||||
expect(scale.armorClass).toBe(16); // 10 + 2 of the 4 + 4
|
||||
expect(scale.gear.notes).toEqual([{ source: 'Scale Mail', note: 'Medium armor: at most +2 from Dexterity counts toward AC.' }]);
|
||||
const plate = nimble([wearing('Plate Armor', 'HEAVY', 8), wearing('Shield', 'SHIELD', 2)]);
|
||||
expect(plate.armorClass).toBe(20); // 18, and the shield
|
||||
expect(plate.gear.notes[0]).toEqual({ source: 'Plate Armor', note: 'Heavy armor: Dexterity does not count toward AC.' });
|
||||
// Heavy armor hides a Dexterity penalty too; medium does not.
|
||||
expect(clumsy([wearing('Plate Armor', 'HEAVY', 8)]).armorClass).toBe(18);
|
||||
expect(clumsy([wearing('Scale Mail', 'MEDIUM', 4)]).armorClass).toBe(13);
|
||||
// Nothing to say when the armor holds nothing back, and only Dexterity's part in AC changes.
|
||||
expect(sheet({ characterClass: 'FIGHTER', inventoryItems: [wearing('Scale Mail', 'MEDIUM', 4)] }).gear.notes).toEqual([]);
|
||||
expect(plate.initiative).toBe(4);
|
||||
expect(plate.saves.DEX.bonus).toBe(4);
|
||||
});
|
||||
|
||||
test('an item with +AC that is not marked as armor holds nothing back', () => {
|
||||
expect(nimble([wearing('Ring of Protection', null, 1)]).armorClass).toBe(15);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
// Class counters: the things a class can do a set number of times before a
|
||||
// rest (Rage, Ki, Channel Divinity...). How many there are comes from class,
|
||||
// subclass, level and ability modifiers; the character row keeps only how
|
||||
// many are spent (`resourcesUsed`, { key: used }), as it does for spell slots.
|
||||
// Pure: no DB calls.
|
||||
//
|
||||
// What a counter does is on the sheet in the special abilities; nothing here
|
||||
// feeds another number.
|
||||
|
||||
const atLeastOne = (n) => Math.max(1, n);
|
||||
|
||||
// Each entry is offered to the classes (and, where set, the subclass) it
|
||||
// names, from `from` level on (and up to `until`, when it stops being
|
||||
// counted). `max` gets { level, mods, profBonus }, where
|
||||
// `mods` is the ability modifiers by ability. `rest` is the rest that gives
|
||||
// them back: a SHORT one comes back on a long rest too.
|
||||
const RESOURCES = [
|
||||
// At level 20 a barbarian rages as often as they like: no counter to keep.
|
||||
{ key: 'RAGE', name: 'Rage', classes: ['BARBARIAN'], max: ({ level }) => (level >= 17 ? 6 : level >= 12 ? 5 : level >= 6 ? 4 : level >= 3 ? 3 : 2), rest: 'LONG', until: 19 },
|
||||
{ key: 'ZEALOUS_PRESENCE', name: 'Zealous Presence', classes: ['BARBARIAN'], subclass: 'ZEALOT', from: 10, max: () => 1, rest: 'LONG' },
|
||||
|
||||
// Font of Inspiration: from level 5 it comes back on a short rest.
|
||||
{ key: 'BARDIC_INSPIRATION', name: 'Bardic Inspiration', classes: ['BARD'], max: ({ mods }) => atLeastOne(mods.CHA), rest: ({ level }) => (level >= 5 ? 'SHORT' : 'LONG') },
|
||||
|
||||
{ key: 'HEALING_HANDS', name: 'Healing Hands', classes: ['CLERIC'], max: () => 1, rest: 'SHORT' },
|
||||
{ key: 'CHANNEL_DIVINITY', name: 'Channel Divinity', classes: ['CLERIC'], from: 2, max: ({ level }) => (level >= 18 ? 3 : level >= 6 ? 2 : 1), rest: 'SHORT' },
|
||||
{ key: 'CHANNEL_DIVINITY', name: 'Channel Divinity', classes: ['PALADIN'], from: 3, max: () => 1, rest: 'SHORT' },
|
||||
{ key: 'WARDING_FLARE', name: 'Warding Flare', classes: ['CLERIC'], subclass: 'LIGHT', from: 2, max: ({ mods }) => atLeastOne(mods.WIS), rest: 'LONG' },
|
||||
{ key: 'WAR_PRIEST', name: 'War Priest', classes: ['CLERIC'], subclass: 'WAR', from: 2, max: ({ mods }) => atLeastOne(mods.WIS), rest: 'LONG' },
|
||||
|
||||
// An archdruid (level 20) wild shapes as often as they like.
|
||||
{ key: 'WILD_SHAPE', name: 'Wild Shape', classes: ['DRUID'], from: 2, max: () => 2, rest: 'SHORT', until: 19 },
|
||||
{ key: 'NATURAL_RECOVERY', name: 'Natural Recovery', classes: ['DRUID'], subclass: 'LAND', from: 2, max: () => 1, rest: 'LONG' },
|
||||
{ key: 'STAR_MAP', name: 'Star Map (Guiding Bolt)', classes: ['DRUID'], subclass: 'STARS', from: 2, max: ({ profBonus }) => profBonus, rest: 'LONG' },
|
||||
{ key: 'COSMIC_OMEN', name: 'Cosmic Omen', classes: ['DRUID'], subclass: 'STARS', from: 6, max: ({ profBonus }) => profBonus, rest: 'LONG' },
|
||||
|
||||
{ key: 'SECOND_WIND', name: 'Second Wind', classes: ['FIGHTER'], max: () => 1, rest: 'SHORT' },
|
||||
{ key: 'ACTION_SURGE', name: 'Action Surge', classes: ['FIGHTER'], from: 2, max: ({ level }) => (level >= 17 ? 2 : 1), rest: 'SHORT' },
|
||||
{ key: 'INDOMITABLE', name: 'Indomitable', classes: ['FIGHTER'], from: 9, max: ({ level }) => (level >= 17 ? 3 : level >= 13 ? 2 : 1), rest: 'LONG' },
|
||||
{ key: 'SUPERIORITY_DICE', name: 'Superiority Dice', classes: ['FIGHTER'], subclass: 'BATTLE_MASTER', from: 3, max: ({ level }) => (level >= 15 ? 6 : level >= 7 ? 5 : 4), rest: 'SHORT' },
|
||||
{ key: 'FIGHTING_SPIRIT', name: 'Fighting Spirit', classes: ['FIGHTER'], subclass: 'SAMURAI', from: 3, max: () => 3, rest: 'LONG' },
|
||||
|
||||
{ key: 'KI', name: 'Ki', classes: ['MONK'], from: 2, max: ({ level }) => level, rest: 'SHORT' },
|
||||
{ key: 'WHOLENESS_OF_BODY', name: 'Wholeness of Body', classes: ['MONK'], subclass: 'OPEN_HAND', from: 6, max: () => 1, rest: 'LONG' },
|
||||
|
||||
{ key: 'LAY_ON_HANDS', name: 'Lay on Hands (HP)', classes: ['PALADIN'], max: ({ level }) => 5 * level, rest: 'LONG' },
|
||||
{ key: 'DIVINE_SENSE', name: 'Divine Sense', classes: ['PALADIN'], max: ({ mods }) => atLeastOne(1 + mods.CHA), rest: 'LONG' },
|
||||
{ key: 'CLEANSING_TOUCH', name: 'Cleansing Touch', classes: ['PALADIN'], from: 14, max: ({ mods }) => atLeastOne(mods.CHA), rest: 'LONG' },
|
||||
|
||||
{ key: 'WILD_TALENT', name: 'Wild Talent', classes: ['SORCERER'], max: () => 1, rest: 'LONG' },
|
||||
{ key: 'SORCERY_POINTS', name: 'Sorcery Points', classes: ['SORCERER'], from: 2, max: ({ level }) => level, rest: 'LONG' },
|
||||
{ key: 'TIDES_OF_CHAOS', name: 'Tides of Chaos', classes: ['SORCERER'], subclass: 'WILD_MAGIC', from: 3, max: () => 1, rest: 'LONG' },
|
||||
|
||||
{ key: 'FEY_PRESENCE', name: 'Fey Presence', classes: ['WARLOCK'], subclass: 'ARCHFEY', from: 3, max: () => 1, rest: 'SHORT' },
|
||||
{ key: 'MISTY_ESCAPE', name: 'Misty Escape', classes: ['WARLOCK'], subclass: 'ARCHFEY', from: 6, max: () => 1, rest: 'SHORT' },
|
||||
{ key: 'PATRONS_LUCK', name: 'Patron’s Luck', classes: ['WARLOCK'], subclass: 'FIEND', from: 6, max: () => 1, rest: 'SHORT' },
|
||||
{ key: 'ENTROPIC_WARD', name: 'Entropic Ward', classes: ['WARLOCK'], subclass: 'GREAT_OLD_ONE', from: 6, max: () => 1, rest: 'SHORT' },
|
||||
|
||||
{ key: 'ARCANE_RECOVERY', name: 'Arcane Recovery', classes: ['WIZARD'], max: () => 1, rest: 'LONG' },
|
||||
{ key: 'SIGNATURE_SPELLS', name: 'Signature Spells', classes: ['WIZARD'], from: 20, max: () => 2, rest: 'SHORT' },
|
||||
|
||||
{ key: 'STROKE_OF_LUCK', name: 'Stroke of Luck', classes: ['ROGUE'], from: 20, max: () => 1, rest: 'SHORT' },
|
||||
{ key: 'MYSTIC_ARCANUM', name: 'Mystic Arcanum', classes: ['WARLOCK'], from: 11, max: ({ level }) => (level >= 17 ? 4 : level >= 15 ? 3 : level >= 13 ? 2 : 1), rest: 'LONG' },
|
||||
|
||||
{ key: 'FLASH_OF_GENIUS', name: 'Flash of Genius', classes: ['ARTIFICER'], from: 7, max: ({ mods }) => atLeastOne(mods.INT), rest: 'LONG' },
|
||||
{ key: 'ILLUSORY_SELF', name: 'Illusory Self', classes: ['WIZARD'], subclass: 'ILLUSION', from: 10, max: () => 1, rest: 'SHORT' },
|
||||
];
|
||||
|
||||
// The counters a character has, with how many of each are spent and left:
|
||||
// [{ key, name, max, used, remaining, restoresOn }]. `used` is the stored
|
||||
// tally, which may name counters the character no longer has or hold more
|
||||
// than they now allow.
|
||||
function resourceState({ characterClass, subclass = null, level = 1, resourcesUsed = {} }, abilities, profBonus) {
|
||||
const mods = Object.fromEntries(Object.entries(abilities).map(([ability, detail]) => [ability, detail.modifier]));
|
||||
const context = { level, mods, profBonus };
|
||||
const tally = resourcesUsed && typeof resourcesUsed === 'object' ? resourcesUsed : {};
|
||||
return RESOURCES.filter(
|
||||
(resource) =>
|
||||
resource.classes.includes(characterClass) &&
|
||||
level >= (resource.from || 1) &&
|
||||
level <= (resource.until || Infinity) &&
|
||||
(!resource.subclass || resource.subclass === subclass)
|
||||
).map((resource) => {
|
||||
const max = resource.max(context);
|
||||
const used = Math.min(Math.max(Math.round(Number(tally[resource.key]) || 0), 0), max);
|
||||
return {
|
||||
key: resource.key,
|
||||
name: resource.name,
|
||||
max,
|
||||
used,
|
||||
remaining: max - used,
|
||||
restoresOn: typeof resource.rest === 'function' ? resource.rest(context) : resource.rest,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// The tally to store, from a character's counters: only what is spent.
|
||||
function resourceTally(resources) {
|
||||
return Object.fromEntries(resources.filter((resource) => resource.used > 0).map((resource) => [resource.key, resource.used]));
|
||||
}
|
||||
|
||||
// What a rest gives back: the tally afterwards, and the names of the counters
|
||||
// that were refilled. A long rest refills every counter; a short rest those
|
||||
// that restore on one.
|
||||
function restResources(resources, restType) {
|
||||
const refills = (resource) => resource.used > 0 && (restType === 'LONG' || resource.restoresOn === 'SHORT');
|
||||
return {
|
||||
resourcesUsed: resourceTally(resources.filter((resource) => !refills(resource))),
|
||||
restored: resources.filter(refills).map((resource) => resource.name),
|
||||
};
|
||||
}
|
||||
|
||||
const MAX_EXHAUSTION = 6;
|
||||
|
||||
module.exports = { RESOURCES, resourceState, resourceTally, restResources, MAX_EXHAUSTION };
|
||||
@@ -0,0 +1,60 @@
|
||||
const { RESOURCES, resourceState, resourceTally, restResources } = require('./classResources');
|
||||
const { computeCharacterSheet } = require('./calculations');
|
||||
const { CLASSES } = require('./data/classes');
|
||||
const { findSubclass } = require('./data/subclasses');
|
||||
|
||||
const of = (character) => computeCharacterSheet({ level: 1, ...character }).resources;
|
||||
const named = (resources) => Object.fromEntries(resources.map((r) => [r.key, r.max]));
|
||||
|
||||
describe('class counters', () => {
|
||||
test('every counter belongs to a real class and, where it names one, a real subclass', () => {
|
||||
for (const resource of RESOURCES) {
|
||||
for (const cls of resource.classes) {
|
||||
expect(CLASSES[cls]).toBeDefined();
|
||||
if (resource.subclass) expect(findSubclass(cls, resource.subclass)).not.toBeNull();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('come from class and level', () => {
|
||||
expect(named(of({ characterClass: 'BARBARIAN' }))).toEqual({ RAGE: 2 });
|
||||
expect(named(of({ characterClass: 'BARBARIAN', level: 6 }))).toEqual({ RAGE: 4 });
|
||||
expect(named(of({ characterClass: 'FIGHTER' }))).toEqual({ SECOND_WIND: 1 });
|
||||
expect(named(of({ characterClass: 'FIGHTER', level: 9 }))).toEqual({ SECOND_WIND: 1, ACTION_SURGE: 1, INDOMITABLE: 1 });
|
||||
expect(named(of({ characterClass: 'MONK' }))).toEqual({});
|
||||
expect(named(of({ characterClass: 'MONK', level: 4 }))).toEqual({ KI: 4 });
|
||||
expect(named(of({ characterClass: 'PALADIN', level: 3, chaScore: 10 }))).toEqual({ CHANNEL_DIVINITY: 1, LAY_ON_HANDS: 15, DIVINE_SENSE: 1 });
|
||||
expect(of({ characterClass: 'ROGUE', level: 10 })).toEqual([]);
|
||||
expect(of({ characterClass: null })).toEqual([]);
|
||||
});
|
||||
|
||||
test('some follow an ability modifier, never below one', () => {
|
||||
expect(named(of({ characterClass: 'BARD', chaScore: 16 })).BARDIC_INSPIRATION).toBe(3);
|
||||
expect(named(of({ characterClass: 'BARD', chaScore: 6 })).BARDIC_INSPIRATION).toBe(1);
|
||||
});
|
||||
|
||||
test('a subclass adds its own', () => {
|
||||
expect(named(of({ characterClass: 'FIGHTER', level: 3 })).SUPERIORITY_DICE).toBeUndefined();
|
||||
expect(named(of({ characterClass: 'FIGHTER', level: 3, subclass: 'BATTLE_MASTER' })).SUPERIORITY_DICE).toBe(4);
|
||||
expect(named(of({ characterClass: 'FIGHTER', level: 7, subclass: 'BATTLE_MASTER' })).SUPERIORITY_DICE).toBe(5);
|
||||
expect(named(of({ characterClass: 'DRUID', level: 2, subclass: 'LAND' }))).toEqual({ WILD_SHAPE: 2, NATURAL_RECOVERY: 1 });
|
||||
});
|
||||
|
||||
test('a bard\'s inspiration comes back on a short rest from level 5', () => {
|
||||
expect(of({ characterClass: 'BARD', level: 4 })[0].restoresOn).toBe('LONG');
|
||||
expect(of({ characterClass: 'BARD', level: 5 })[0].restoresOn).toBe('SHORT');
|
||||
});
|
||||
|
||||
test('the stored tally is squared up with what the character has', () => {
|
||||
const resources = of({ characterClass: 'MONK', level: 4, resourcesUsed: { KI: 9, RAGE: 1 } });
|
||||
expect(resources).toEqual([{ key: 'KI', name: 'Ki', max: 4, used: 4, remaining: 0, restoresOn: 'SHORT' }]);
|
||||
expect(resourceTally(resources)).toEqual({ KI: 4 });
|
||||
expect(resourceState({ characterClass: 'MONK', level: 4, resourcesUsed: null }, { WIS: { modifier: 0 } }, 2)[0].used).toBe(0);
|
||||
});
|
||||
|
||||
test('a short rest refills what restores on one; a long rest everything', () => {
|
||||
const resources = of({ characterClass: 'FIGHTER', level: 9, resourcesUsed: { SECOND_WIND: 1, INDOMITABLE: 1 } });
|
||||
expect(restResources(resources, 'SHORT')).toEqual({ resourcesUsed: { INDOMITABLE: 1 }, restored: ['Second Wind'] });
|
||||
expect(restResources(resources, 'LONG')).toEqual({ resourcesUsed: {}, restored: ['Second Wind', 'Indomitable'] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
// Combat: how an attack or a spell is resolved in a battle. An "action" is
|
||||
// one attack or spell from being declared to its damage landing
|
||||
// (EncounterAction): who it is aimed at, the d20 rolled against each target
|
||||
// (or each target's saving throw), and the damage. Pure: no DB calls. The
|
||||
// random source can be passed in for tests.
|
||||
|
||||
const { parseDice, leadingDice, rollExpression, rollCritical, rollDie } = require('./dice');
|
||||
|
||||
// What an attack roll comes to against a target. A natural 20 is a critical
|
||||
// hit and a natural 1 a miss, whatever the numbers; otherwise the d20 plus the
|
||||
// bonus has to reach the AC (with any area-attack penalty added).
|
||||
function attackOutcome(d20, attackBonus, ac, penalty = 0) {
|
||||
if (d20 === 20) return 'CRIT';
|
||||
if (d20 === 1) return 'FUMBLE';
|
||||
return d20 + attackBonus >= ac + penalty ? 'HIT' : 'MISS';
|
||||
}
|
||||
|
||||
// Whether a saving throw succeeds: the d20 plus the bonus reaches the DC.
|
||||
const saveSucceeds = (d20, saveBonus, dc) => d20 + saveBonus >= dc;
|
||||
|
||||
const lands = (outcome) => outcome === 'HIT' || outcome === 'CRIT';
|
||||
|
||||
// A target as the dice have it (or as the DM has overruled them), with the
|
||||
// damage it takes. `outcome` and `damage` on the target are the DM's
|
||||
// overrides; null leaves it to the dice.
|
||||
// ATTACK: total, outcome HIT | MISS | CRIT | FUMBLE (null until a d20 is in).
|
||||
// SAVE: total, outcome SAVED | FAILED (null until the save is in).
|
||||
// AUTO: outcome HIT.
|
||||
// `finalDamage` is null until it can be known.
|
||||
function settleTarget(action, target) {
|
||||
const { kind, detail } = action;
|
||||
const base = action.damage ? action.damage.total : null;
|
||||
const crit = action.damage && action.damage.crit ? action.damage.crit.total : null;
|
||||
const noDamage = !detail.damageDice && base == null;
|
||||
let total = null;
|
||||
let rolled = null; // what the dice say, before any override
|
||||
if (kind === 'ATTACK') {
|
||||
if (target.d20 != null) {
|
||||
total = target.d20 + (detail.attackBonus || 0);
|
||||
rolled = attackOutcome(target.d20, detail.attackBonus || 0, target.ac ?? 10, target.penalty || 0);
|
||||
}
|
||||
} else if (kind === 'SAVE') {
|
||||
if (target.d20 != null) {
|
||||
total = target.d20 + (target.saveBonus || 0);
|
||||
rolled = saveSucceeds(target.d20, target.saveBonus || 0, detail.saveDC || 10) ? 'SAVED' : 'FAILED';
|
||||
}
|
||||
} else {
|
||||
rolled = 'HIT';
|
||||
}
|
||||
const outcome = target.outcome || rolled;
|
||||
|
||||
let finalDamage = null;
|
||||
if (target.damage != null) finalDamage = target.damage;
|
||||
else if (outcome === 'MISS' || outcome === 'FUMBLE') finalDamage = 0;
|
||||
else if (noDamage) finalDamage = outcome ? 0 : null;
|
||||
else if (outcome && base != null) {
|
||||
if (outcome === 'CRIT') finalDamage = crit != null ? crit : base;
|
||||
else if (outcome === 'SAVED') finalDamage = detail.halfOnSave ? Math.floor(base / 2) : 0;
|
||||
else finalDamage = base;
|
||||
}
|
||||
return { ...target, total, rolled, outcome, overruled: Boolean(target.outcome) && target.outcome !== rolled, finalDamage };
|
||||
}
|
||||
|
||||
// An action with every target settled, and what it is still waiting for:
|
||||
// `needsRolls` (targets with no outcome yet), `needsDamage` (someone is hit
|
||||
// and the damage is not known), `needsCrit` (someone is critically hit and the
|
||||
// critical damage has not been rolled), and `ready` when none of those.
|
||||
function settle(action) {
|
||||
const targets = (action.targets || []).map((target) => settleTarget(action, target));
|
||||
const needsRolls = targets.filter((t) => !t.outcome).length;
|
||||
const hurts = targets.some((t) => t.damage == null && (lands(t.outcome) || t.outcome === 'FAILED' || (t.outcome === 'SAVED' && action.detail.halfOnSave)));
|
||||
const hasDice = Boolean(action.detail.damageDice);
|
||||
const needsDamage = hasDice && hurts && !action.damage;
|
||||
const needsCrit = hasDice && Boolean(action.damage) && !action.damage.crit && !action.damage.entered && targets.some((t) => t.outcome === 'CRIT' && t.damage == null);
|
||||
return { ...action, targets, needsRolls, needsDamage, needsCrit, ready: needsRolls === 0 && !needsDamage && targets.length > 0 };
|
||||
}
|
||||
|
||||
// Rolls an action's damage: its dice plus its bonus, and, when a target is
|
||||
// critically hit, the critical damage by the campaign's rule. Null for an
|
||||
// action with no dice (or dice that can't be read).
|
||||
function rollDamage(detail, { critical = false, critRule = 'DOUBLE_DICE', roll = rollDie } = {}) {
|
||||
const dice = leadingDice(detail.damageDice || '');
|
||||
const parsed = dice ? parseDice(dice) : null;
|
||||
if (!parsed) return null;
|
||||
const withBonus = { dice: parsed.dice, flat: parsed.flat + (detail.damageBonus || 0) };
|
||||
const normal = rollExpression(withBonus, { roll });
|
||||
return {
|
||||
total: Math.max(0, normal.total),
|
||||
dice: normal.dice,
|
||||
modifier: normal.modifier,
|
||||
crit: critical ? critOf(withBonus, critRule, roll) : null,
|
||||
};
|
||||
}
|
||||
|
||||
function critOf(parsed, critRule, roll) {
|
||||
const crit = rollCritical(parsed, critRule, { roll });
|
||||
return { total: Math.max(0, crit.total), dice: crit.dice, modifier: crit.modifier };
|
||||
}
|
||||
|
||||
// The critical damage alone, for an action whose normal damage is already rolled.
|
||||
function rollCritDamage(detail, { critRule = 'DOUBLE_DICE', roll = rollDie } = {}) {
|
||||
const dice = leadingDice(detail.damageDice || '');
|
||||
const parsed = dice ? parseDice(dice) : null;
|
||||
if (!parsed) return null;
|
||||
return critOf({ dice: parsed.dice, flat: parsed.flat + (detail.damageBonus || 0) }, critRule, roll);
|
||||
}
|
||||
|
||||
// Which side a combatant fights on: the party (characters and friendly NPCs),
|
||||
// its enemies (monsters and hostile NPCs), or neither (a neutral NPC).
|
||||
// Takes { kind: 'CHARACTER' | 'MONSTER' | 'NPC', disposition? }.
|
||||
function sideOf(combatant) {
|
||||
if (combatant.kind === 'CHARACTER') return 'PARTY';
|
||||
if (combatant.kind === 'MONSTER') return 'ENEMY';
|
||||
if (combatant.disposition === 'FRIENDLY') return 'PARTY';
|
||||
if (combatant.disposition === 'HOSTILE') return 'ENEMY';
|
||||
return 'NEUTRAL';
|
||||
}
|
||||
|
||||
// Who a combatant acting by itself could go for: everyone standing on the
|
||||
// other side. A neutral has no enemies.
|
||||
function opponentsOf(actor, combatants) {
|
||||
const side = sideOf(actor);
|
||||
if (side === 'NEUTRAL') return [];
|
||||
return combatants.filter((c) => c.id !== actor.id && !c.fallen && sideOf(c) !== 'NEUTRAL' && sideOf(c) !== side);
|
||||
}
|
||||
|
||||
// How likely each opponent is to be picked, relative to the others. Everyone
|
||||
// starts equal; whoever the actor went for last, and whoever has hurt it,
|
||||
// count for more (a creature keeps at what it is fighting), and so, a little,
|
||||
// does someone easier to hit.
|
||||
function targetWeights(candidates, { lastTargetId = null, hurtBy = [] } = {}) {
|
||||
return candidates.map((c) => {
|
||||
let weight = 2;
|
||||
if (c.id === lastTargetId) weight += 3;
|
||||
if (hurtBy.includes(c.id)) weight += 3;
|
||||
weight += Math.max(0, Math.min(2, (16 - (c.ac ?? 12)) / 3));
|
||||
return weight;
|
||||
});
|
||||
}
|
||||
|
||||
// Picks one opponent at random by those weights; null when there is nobody.
|
||||
// `random` gives a number from 0 (inclusive) to 1 (exclusive).
|
||||
function pickTarget(candidates, context = {}, random = Math.random) {
|
||||
if (candidates.length === 0) return null;
|
||||
const weights = targetWeights(candidates, context);
|
||||
let at = random() * weights.reduce((sum, w) => sum + w, 0);
|
||||
for (let i = 0; i < candidates.length; i++) {
|
||||
at -= weights[i];
|
||||
if (at < 0) return candidates[i];
|
||||
}
|
||||
return candidates[candidates.length - 1];
|
||||
}
|
||||
|
||||
// The attacks a monster or NPC makes on its turn, one entry per attack made
|
||||
// (a multiattack's `count` is spread out): [{ name, attackBonus, damageDice,
|
||||
// damageType }]. A monster's named `attacks` when it has any, otherwise its
|
||||
// single attack; an NPC's single attack. Empty for one with nothing to hit with.
|
||||
function attacksOf({ monster = null, npc = null }) {
|
||||
const named = monster && Array.isArray(monster.attacks) ? monster.attacks.filter((a) => a && a.name) : [];
|
||||
if (named.length > 0) {
|
||||
return named.flatMap((a) =>
|
||||
Array.from({ length: Math.max(1, Math.min(10, Number(a.count) || 1)) }, () => ({
|
||||
name: a.name,
|
||||
attackBonus: Number(a.attackBonus) || 0,
|
||||
damageDice: a.damageDice || null,
|
||||
damageType: a.damageType || null,
|
||||
}))
|
||||
);
|
||||
}
|
||||
const stats = monster || npc;
|
||||
if (!stats || (stats.attackBonus == null && !stats.damageDice)) return [];
|
||||
return [{ name: 'Attack', attackBonus: stats.attackBonus || 0, damageDice: stats.damageDice || null, damageType: null }];
|
||||
}
|
||||
|
||||
// Highest initiative first; ties keep the order combatants were added in.
|
||||
// Anyone who has not rolled yet waits at the bottom.
|
||||
function inTurnOrder(participants) {
|
||||
const rolled = (p) => (p.initiativeRoll == null ? 0 : 1);
|
||||
return [...participants].sort((a, b) => rolled(b) - rolled(a) || b.initiative - a.initiative || (a.id < b.id ? -1 : 1));
|
||||
}
|
||||
|
||||
// Whether a combatant may change the weapon in their hand in a battle that
|
||||
// is under way. There are two moments for it: as the battle begins, before
|
||||
// anyone has made a move (round 1, still the first combatant's turn, nothing
|
||||
// landed yet), and on their own turn once their attack has landed, before the
|
||||
// turn passes. `applied` is the battle's landed actions: [{ round,
|
||||
// actorParticipantId }]. `firstId` is whoever went first. `declared` is true
|
||||
// while somebody's attack or spell is declared and still being resolved: that
|
||||
// is a move being made.
|
||||
function weaponSwapOpen({ round, activeId, firstId, participantId, applied = [], declared = false }) {
|
||||
if (activeId == null) return true; // no turn has started
|
||||
const opening = round === 1 && activeId === firstId && applied.length === 0 && !declared;
|
||||
const afterOwnAttack = activeId === participantId && applied.some((a) => a.round === round && a.actorParticipantId === participantId);
|
||||
return opening || afterOwnAttack;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
attackOutcome,
|
||||
saveSucceeds,
|
||||
lands,
|
||||
settleTarget,
|
||||
settle,
|
||||
rollDamage,
|
||||
rollCritDamage,
|
||||
sideOf,
|
||||
opponentsOf,
|
||||
targetWeights,
|
||||
pickTarget,
|
||||
attacksOf,
|
||||
inTurnOrder,
|
||||
weaponSwapOpen,
|
||||
};
|
||||
@@ -0,0 +1,175 @@
|
||||
const { attackOutcome, saveSucceeds, settle, rollDamage, rollCritDamage, sideOf, opponentsOf, targetWeights, pickTarget, attacksOf } = require('./combat');
|
||||
|
||||
const fixed = (...faces) => {
|
||||
let i = 0;
|
||||
return () => faces[i++ % faces.length];
|
||||
};
|
||||
|
||||
describe('an attack roll', () => {
|
||||
test('hits when the d20 plus the bonus reaches the AC', () => {
|
||||
expect(attackOutcome(10, 5, 15)).toBe('HIT');
|
||||
expect(attackOutcome(9, 5, 15)).toBe('MISS');
|
||||
});
|
||||
|
||||
test('a natural 20 always hits, critically, and a natural 1 always misses', () => {
|
||||
expect(attackOutcome(20, -5, 30)).toBe('CRIT');
|
||||
expect(attackOutcome(1, 20, 5)).toBe('FUMBLE');
|
||||
});
|
||||
|
||||
test('an area attack counts each AC higher', () => {
|
||||
expect(attackOutcome(10, 5, 15, 2)).toBe('MISS');
|
||||
expect(attackOutcome(12, 5, 15, 2)).toBe('HIT');
|
||||
});
|
||||
});
|
||||
|
||||
test('a saving throw succeeds on the DC or more', () => {
|
||||
expect(saveSucceeds(12, 3, 15)).toBe(true);
|
||||
expect(saveSucceeds(11, 3, 15)).toBe(false);
|
||||
});
|
||||
|
||||
describe('settling an action', () => {
|
||||
const attack = (targets, damage = null) => ({ kind: 'ATTACK', detail: { attackBonus: 5, damageDice: '1d8', damageBonus: 3 }, targets, damage });
|
||||
|
||||
test('waits for a d20 for each target, then for the damage', () => {
|
||||
const waiting = settle(attack([{ participantId: 'a', ac: 15, d20: null }]));
|
||||
expect(waiting).toMatchObject({ needsRolls: 1, ready: false });
|
||||
const hit = settle(attack([{ participantId: 'a', ac: 15, d20: 12 }]));
|
||||
expect(hit.targets[0]).toMatchObject({ total: 17, outcome: 'HIT', finalDamage: null });
|
||||
expect(hit).toMatchObject({ needsRolls: 0, needsDamage: true, ready: false });
|
||||
const done = settle(attack([{ participantId: 'a', ac: 15, d20: 12 }], { total: 7 }));
|
||||
expect(done.targets[0].finalDamage).toBe(7);
|
||||
expect(done.ready).toBe(true);
|
||||
});
|
||||
|
||||
test('a miss needs no damage at all', () => {
|
||||
const miss = settle(attack([{ participantId: 'a', ac: 15, d20: 4 }]));
|
||||
expect(miss.targets[0]).toMatchObject({ outcome: 'MISS', finalDamage: 0 });
|
||||
expect(miss).toMatchObject({ needsDamage: false, ready: true });
|
||||
});
|
||||
|
||||
test('a critical hit takes the critical damage, once it is rolled', () => {
|
||||
const crit = settle(attack([{ participantId: 'a', ac: 15, d20: 20 }], { total: 7 }));
|
||||
expect(crit.needsCrit).toBe(true);
|
||||
expect(settle(attack([{ participantId: 'a', ac: 15, d20: 20 }], { total: 7, crit: { total: 13 } })).targets[0].finalDamage).toBe(13);
|
||||
});
|
||||
|
||||
test('the DM can overrule the dice, and set a target’s damage by hand', () => {
|
||||
const overruled = settle(attack([{ participantId: 'a', ac: 15, d20: 4, outcome: 'HIT' }, { participantId: 'b', ac: 12, d20: 15, damage: 2 }], { total: 9 }));
|
||||
expect(overruled.targets[0]).toMatchObject({ rolled: 'MISS', outcome: 'HIT', overruled: true, finalDamage: 9 });
|
||||
expect(overruled.targets[1]).toMatchObject({ outcome: 'HIT', overruled: false, finalDamage: 2 });
|
||||
});
|
||||
|
||||
test('a save spell deals full damage on a failure, half or none on a success', () => {
|
||||
const spell = (halfOnSave) =>
|
||||
settle({
|
||||
kind: 'SAVE',
|
||||
detail: { saveAbility: 'DEX', saveDC: 15, halfOnSave, damageDice: '8d6' },
|
||||
targets: [{ participantId: 'a', saveBonus: 2, d20: 13 }, { participantId: 'b', saveBonus: 2, d20: 12 }, { participantId: 'c', saveBonus: 0, d20: null }],
|
||||
damage: { total: 27 },
|
||||
});
|
||||
const fireball = spell(true);
|
||||
expect(fireball.targets.map((t) => [t.outcome, t.finalDamage])).toEqual([['SAVED', 13], ['FAILED', 27], [null, null]]);
|
||||
expect(fireball).toMatchObject({ needsRolls: 1, ready: false });
|
||||
expect(spell(false).targets[0].finalDamage).toBe(0);
|
||||
});
|
||||
|
||||
test('something that just lands hits everyone it is aimed at', () => {
|
||||
const missile = settle({ kind: 'AUTO', detail: { damageDice: '3d4+3' }, targets: [{ participantId: 'a' }], damage: { total: 10 } });
|
||||
expect(missile.targets[0]).toMatchObject({ outcome: 'HIT', finalDamage: 10 });
|
||||
expect(missile.ready).toBe(true);
|
||||
// With no dice at all (a utility spell) it is ready as it stands.
|
||||
expect(settle({ kind: 'AUTO', detail: {}, targets: [{ participantId: 'a' }], damage: null })).toMatchObject({ ready: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('damage', () => {
|
||||
test('is the dice plus the bonus', () => {
|
||||
expect(rollDamage({ damageDice: '1d8', damageBonus: 3 }, { roll: fixed(5) })).toMatchObject({ total: 8, crit: null });
|
||||
expect(rollDamage({ damageDice: '2d6+1 fire', damageBonus: 0 }, { roll: fixed(2, 3) }).total).toBe(6);
|
||||
expect(rollDamage({ damageDice: 'a nasty bite' })).toBeNull();
|
||||
});
|
||||
|
||||
test('a critical hit doubles the dice, never the bonus', () => {
|
||||
const rolled = rollDamage({ damageDice: '1d8', damageBonus: 3 }, { critical: true, roll: fixed(5, 4, 6) });
|
||||
expect(rolled.total).toBe(8);
|
||||
expect(rolled.crit.total).toBe(4 + 6 + 3);
|
||||
expect(rollCritDamage({ damageDice: '1d8', damageBonus: 3 }, { critRule: 'MAX_PLUS_ROLL', roll: fixed(2) }).total).toBe(8 + 2 + 3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sides', () => {
|
||||
const aria = { id: 'aria', kind: 'CHARACTER', ac: 16 };
|
||||
const bo = { id: 'bo', kind: 'CHARACTER', ac: 12 };
|
||||
const goblin = { id: 'goblin', kind: 'MONSTER', ac: 13 };
|
||||
const guard = { id: 'guard', kind: 'NPC', disposition: 'FRIENDLY', ac: 14 };
|
||||
const thug = { id: 'thug', kind: 'NPC', disposition: 'HOSTILE', ac: 11 };
|
||||
const baker = { id: 'baker', kind: 'NPC', disposition: 'NEUTRAL', ac: 10 };
|
||||
const everyone = [aria, bo, goblin, guard, thug, baker];
|
||||
|
||||
test('characters and friendly NPCs against monsters and hostile NPCs', () => {
|
||||
expect(everyone.map(sideOf)).toEqual(['PARTY', 'PARTY', 'ENEMY', 'PARTY', 'ENEMY', 'NEUTRAL']);
|
||||
expect(opponentsOf(goblin, everyone).map((c) => c.id)).toEqual(['aria', 'bo', 'guard']);
|
||||
expect(opponentsOf(guard, everyone).map((c) => c.id)).toEqual(['goblin', 'thug']);
|
||||
expect(opponentsOf(baker, everyone)).toEqual([]);
|
||||
});
|
||||
|
||||
test('the fallen are nobody’s target', () => {
|
||||
expect(opponentsOf(goblin, [aria, { ...bo, fallen: true }]).map((c) => c.id)).toEqual(['aria']);
|
||||
});
|
||||
|
||||
test('a creature favours who it fought last, who hurt it, and the easier mark', () => {
|
||||
const [ariaWeight, boWeight] = targetWeights([aria, bo]);
|
||||
expect(boWeight).toBeGreaterThan(ariaWeight); // lower AC
|
||||
const [again] = targetWeights([aria, bo], { lastTargetId: 'aria', hurtBy: ['aria'] });
|
||||
expect(again).toBeGreaterThan(boWeight);
|
||||
});
|
||||
|
||||
test('picks by weight, and nobody when there is nobody', () => {
|
||||
expect(pickTarget([aria, bo], {}, () => 0).id).toBe('aria');
|
||||
expect(pickTarget([aria, bo], {}, () => 0.999).id).toBe('bo');
|
||||
expect(pickTarget([], {})).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('what a creature attacks with', () => {
|
||||
test('its single attack, or each of its named attacks as often as it makes it', () => {
|
||||
expect(attacksOf({ monster: { attackBonus: 4, damageDice: '1d6+2', attacks: [] } })).toEqual([{ name: 'Attack', attackBonus: 4, damageDice: '1d6+2', damageType: null }]);
|
||||
const owlbear = attacksOf({ monster: { attackBonus: 7, damageDice: '2d8+5', attacks: [{ name: 'Claw', attackBonus: 7, damageDice: '2d8+5', damageType: 'slashing', count: 2 }, { name: 'Beak', attackBonus: 7, damageDice: '1d10+5' }] } });
|
||||
expect(owlbear.map((a) => a.name)).toEqual(['Claw', 'Claw', 'Beak']);
|
||||
expect(attacksOf({ npc: { attackBonus: 3, damageDice: '1d6' } })).toHaveLength(1);
|
||||
expect(attacksOf({ npc: { attackBonus: null, damageDice: null } })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('changing weapons in a battle', () => {
|
||||
const { inTurnOrder, weaponSwapOpen } = require('./combat');
|
||||
const base = { round: 1, activeId: 'a', firstId: 'a', participantId: 'b', applied: [] };
|
||||
|
||||
test('the turn order is by initiative, the unrolled last', () => {
|
||||
const order = inTurnOrder([
|
||||
{ id: '1', initiativeRoll: null, initiative: 0 },
|
||||
{ id: '2', initiativeRoll: 5, initiative: 7 },
|
||||
{ id: '3', initiativeRoll: 12, initiative: 12 },
|
||||
]);
|
||||
expect(order.map((p) => p.id)).toEqual(['3', '2', '1']);
|
||||
});
|
||||
|
||||
test('anyone may as the battle begins, before a move is made', () => {
|
||||
expect(weaponSwapOpen(base)).toBe(true);
|
||||
expect(weaponSwapOpen({ ...base, activeId: null })).toBe(true);
|
||||
// The first turn has passed, or something has landed: the moment is gone.
|
||||
expect(weaponSwapOpen({ ...base, activeId: 'b', participantId: 'c' })).toBe(false);
|
||||
expect(weaponSwapOpen({ ...base, applied: [{ round: 1, actorParticipantId: 'a' }] })).toBe(false);
|
||||
expect(weaponSwapOpen({ ...base, round: 2 })).toBe(false);
|
||||
expect(weaponSwapOpen({ ...base, declared: true })).toBe(false); // an attack is being resolved
|
||||
});
|
||||
|
||||
test('after that, only on their own turn once their attack has landed', () => {
|
||||
const later = { round: 2, activeId: 'b', firstId: 'a', participantId: 'b' };
|
||||
expect(weaponSwapOpen({ ...later, applied: [] })).toBe(false);
|
||||
expect(weaponSwapOpen({ ...later, applied: [{ round: 1, actorParticipantId: 'b' }] })).toBe(false); // last round's
|
||||
expect(weaponSwapOpen({ ...later, applied: [{ round: 2, actorParticipantId: 'b' }] })).toBe(true);
|
||||
// Somebody else's turn, even though they attacked earlier this round.
|
||||
expect(weaponSwapOpen({ ...later, activeId: 'c', applied: [{ round: 2, actorParticipantId: 'b' }] })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -60,6 +60,202 @@ const SPECIES_TRAITS = {
|
||||
{ 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.' },
|
||||
],
|
||||
AASIMAR: [
|
||||
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
|
||||
{ name: 'Celestial Resistance', text: 'Necrotic and radiant damage against you is halved.' },
|
||||
{ name: 'Healing Hands', text: 'Once per long rest, touch a creature and restore hit points: roll a d4 for each point of your proficiency bonus.' },
|
||||
{ name: 'Light Bearer', text: 'You know the Light cantrip (the DM grants it).' },
|
||||
{ name: 'Celestial Revelation', text: 'From level 3, once per long rest, transform for a minute (bonus action), choosing: spectral wings (fly at your speed), an inner radiance (light, and radiant damage to those near you each turn) or a fearful shroud (enemies nearby make a Charisma save or are frightened). While transformed, one hit each turn deals extra damage equal to your proficiency bonus.' },
|
||||
],
|
||||
GOLIATH: [
|
||||
{ name: 'Giant Ancestry', text: 'Choose a giant with your DM; use its gift your proficiency bonus times per long rest. Cloud: bonus-action teleport 30 ft. Fire: +1d10 fire on a hit. Frost: +1d6 cold on a hit and the target is slowed by 10 ft. Hill: knock a Large or smaller target you hit prone. Stone: reaction, reduce damage you take by 1d12 + Constitution modifier. Storm: reaction, deal 1d8 thunder to a creature that damaged you.' },
|
||||
{ name: 'Large Form', text: 'From level 5, once per long rest, grow Large for 10 minutes (bonus action): advantage on Strength checks and +10 ft speed.' },
|
||||
{ name: 'Powerful Build', text: 'You count as one size larger when working out what you can carry, push, drag or lift.' },
|
||||
],
|
||||
AARAKOCRA: [
|
||||
{ name: 'Flight', text: 'You can fly at your walking speed, but not while wearing medium or heavy armor.' },
|
||||
{ name: 'Talons', text: 'Your unarmed strikes deal 1d6 + Strength modifier slashing damage.' },
|
||||
{ name: 'Wind Caller', text: 'From level 3, cast Gust of Wind once per long rest without a spell slot.' },
|
||||
],
|
||||
BUGBEAR: [
|
||||
{ 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: 'Long-Limbed', text: 'On your turn, your melee attacks reach 5 feet further than normal.' },
|
||||
{ name: 'Powerful Build', text: 'You count as one size larger when working out what you can carry, push, drag or lift.' },
|
||||
{ name: 'Sneaky', text: 'You are proficient in Stealth (add the bonus by hand) and can squeeze through spaces made for Small creatures.' },
|
||||
{ name: 'Surprise Attack', text: 'Hit a creature that has not yet taken a turn in the fight: it takes an extra 2d6 damage (once per combat).' },
|
||||
],
|
||||
CENTAUR: [
|
||||
{ name: 'Charge', text: 'Move at least 30 feet straight toward a target and hit it with a melee attack: make a Hooves attack against it as a bonus action.' },
|
||||
{ name: 'Equine Build', text: 'You count as one size larger for carrying, pushing and dragging. Climbing costs 4 extra feet for each foot you climb.' },
|
||||
{ name: 'Hooves', text: 'Your unarmed strikes deal 1d6 + Strength modifier bludgeoning damage.' },
|
||||
{ name: 'Natural Affinity', text: 'You are proficient in one of Animal Handling, Medicine, Nature or Survival (agree it with your DM).' },
|
||||
],
|
||||
CHANGELING: [
|
||||
{ name: 'Shapechanger', text: 'Action: change your appearance and voice (height, features, hair, skin) to look like another humanoid of your size. Your gear does not change.' },
|
||||
{ name: 'Changeling Instincts', text: 'You are proficient in two of Deception, Insight, Intimidation, Performance and Persuasion (agree them with your DM).' },
|
||||
],
|
||||
DEEP_GNOME: [
|
||||
{ name: 'Darkvision', text: 'See in dim light within 120 feet as if it were bright, and in darkness as if it were dim.' },
|
||||
{ name: 'Gnomish Magic Resistance', text: 'Advantage on Intelligence, Wisdom and Charisma saves against spells.' },
|
||||
{ name: 'Svirfneblin Camouflage', text: 'Your proficiency bonus times per long rest, give yourself advantage on a Stealth check.' },
|
||||
{ name: 'Gift of the Svirfneblin', text: 'From level 3, cast Disguise Self once per long rest; from level 5, Nondetection on yourself once per long rest.' },
|
||||
],
|
||||
DUERGAR: [
|
||||
{ name: 'Darkvision', text: 'See in dim light within 120 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.' },
|
||||
{ name: 'Psionic Fortitude', text: 'Advantage on saves against being charmed or stunned.' },
|
||||
{ name: 'Duergar Magic', text: 'From level 3, cast Enlarge/Reduce on yourself once per long rest; from level 5, Invisibility on yourself once per long rest.' },
|
||||
],
|
||||
ELADRIN: [
|
||||
{ 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.' },
|
||||
{ name: 'Keen Senses', text: 'You are proficient in Perception (add the bonus by hand).' },
|
||||
{ name: 'Fey Step', text: 'Your proficiency bonus times per long rest, bonus action: teleport up to 30 feet. From level 3 it also has your season’s effect (agree it with your DM): autumn charms, winter frightens, spring lets you teleport an ally instead, summer burns those nearby.' },
|
||||
],
|
||||
FAIRY: [
|
||||
{ name: 'Flight', text: 'You can fly at your walking speed, but not while wearing medium or heavy armor.' },
|
||||
{ name: 'Fairy Magic', text: 'You know Druidcraft. From level 3 cast Faerie Fire, and from level 5 Enlarge/Reduce, each once per long rest without a slot.' },
|
||||
{ name: 'Small', text: 'You are Small: heavy weapons are hard for you to wield (disadvantage).' },
|
||||
],
|
||||
FIRBOLG: [
|
||||
{ name: 'Firbolg Magic', text: 'Cast Detect Magic and Disguise Self, each once per long rest without a slot.' },
|
||||
{ name: 'Hidden Step', text: 'Your proficiency bonus times per long rest, bonus action: turn invisible until the start of your next turn or until you attack.' },
|
||||
{ name: 'Powerful Build', text: 'You count as one size larger when working out what you can carry, push, drag or lift.' },
|
||||
{ name: 'Speech of Beast and Leaf', text: 'Beasts and plants understand the meaning of your words, and you have advantage on Charisma checks to influence them.' },
|
||||
],
|
||||
AIR_GENASI: [
|
||||
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
|
||||
{ name: 'Unending Breath', text: 'You can hold your breath indefinitely.' },
|
||||
{ name: 'Lightning Resistance', text: 'Lightning damage against you is halved.' },
|
||||
{ name: 'Mingle with the Wind', text: 'You know Shocking Grasp. From level 3 cast Feather Fall, and from level 5 Levitate, each once per long rest without a slot.' },
|
||||
],
|
||||
EARTH_GENASI: [
|
||||
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
|
||||
{ name: 'Earth Walk', text: 'Difficult terrain made of earth or stone does not slow you.' },
|
||||
{ name: 'Merge with Stone', text: 'You know Blade Ward and can cast it as a bonus action your proficiency bonus times per long rest. From level 5 cast Pass without Trace once per long rest without a slot.' },
|
||||
],
|
||||
FIRE_GENASI: [
|
||||
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
|
||||
{ name: 'Fire Resistance', text: 'Fire damage against you is halved.' },
|
||||
{ name: 'Reach to the Blaze', text: 'You know Produce Flame. From level 3 cast Burning Hands, and from level 5 Flame Blade, each once per long rest without a slot.' },
|
||||
],
|
||||
WATER_GENASI: [
|
||||
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
|
||||
{ name: 'Acid Resistance', text: 'Acid damage against you is halved.' },
|
||||
{ name: 'Amphibious', text: 'You can breathe air and water, and you have a swimming speed equal to your walking speed.' },
|
||||
{ name: 'Call to the Wave', text: 'You know Acid Splash. From level 3 cast Create or Destroy Water, and from level 5 Water Walk, each once per long rest without a slot.' },
|
||||
],
|
||||
GITHYANKI: [
|
||||
{ name: 'Astral Knowledge', text: 'After each long rest, pick one skill and one weapon or tool to be proficient in until the next (agree them with your DM).' },
|
||||
{ name: 'Githyanki Psionics', text: 'You know Mage Hand (and the hand is invisible). From level 3 cast Jump, and from level 5 Misty Step, each once per long rest without a slot.' },
|
||||
{ name: 'Psychic Resilience', text: 'Psychic damage against you is halved.' },
|
||||
],
|
||||
GITHZERAI: [
|
||||
{ name: 'Mental Discipline', text: 'Advantage on saves against being charmed or frightened.' },
|
||||
{ name: 'Githzerai Psionics', text: 'You know Mage Hand (and the hand is invisible). From level 3 cast Shield, and from level 5 Detect Thoughts, each once per long rest without a slot.' },
|
||||
{ name: 'Psychic Resilience', text: 'Psychic damage against you is halved.' },
|
||||
],
|
||||
GOBLIN: [
|
||||
{ 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: 'Fury of the Small', text: 'Your proficiency bonus times per long rest, when you hit a creature larger than you, deal extra damage equal to your proficiency bonus.' },
|
||||
{ name: 'Nimble Escape', text: 'Bonus action: Disengage or Hide.' },
|
||||
{ name: 'Small', text: 'You are Small: heavy weapons are hard for you to wield (disadvantage).' },
|
||||
],
|
||||
HARENGON: [
|
||||
{ name: 'Hare-Trigger', text: 'Add your proficiency bonus to your initiative rolls.' },
|
||||
{ name: 'Leporine Senses', text: 'You are proficient in Perception (add the bonus by hand).' },
|
||||
{ name: 'Lucky Footwork', text: 'Reaction, when you fail a Dexterity save: add a d4 to it, which may turn it into a success.' },
|
||||
{ name: 'Rabbit Hop', text: 'Your proficiency bonus times per long rest, bonus action: jump 5 × your proficiency bonus feet without provoking opportunity attacks.' },
|
||||
],
|
||||
HOBGOBLIN: [
|
||||
{ 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: 'Fey Gift', text: 'Your proficiency bonus times per long rest, take the Help action as a bonus action. From level 3 it also gives temporary HP, speed, or makes the target’s next attack against you harder (agree which with your DM).' },
|
||||
{ name: 'Fortune from the Many', text: 'Once per long rest, when you miss an attack or fail a check or save, add +1 for each ally you can see within 30 feet (up to +3).' },
|
||||
],
|
||||
KENKU: [
|
||||
{ name: 'Expert Duplication', text: 'Advantage on checks to copy handwriting or craftwork.' },
|
||||
{ name: 'Kenku Recall', text: 'You are proficient in two skills of your choice. Your proficiency bonus times per long rest, give yourself advantage on a check with a skill you are proficient in.' },
|
||||
{ name: 'Mimicry', text: 'You can copy any sound or voice you have heard; telling it apart takes an Insight check against yours.' },
|
||||
],
|
||||
KOBOLD: [
|
||||
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
|
||||
{ name: 'Draconic Cry', text: 'Your proficiency bonus times per long rest, bonus action: until the start of your next turn, you and your allies have advantage on attacks against enemies within 10 feet of you.' },
|
||||
{ name: 'Kobold Legacy', text: 'Choose one with your DM: Craftiness (proficiency in Arcana, Investigation, Medicine, Sleight of Hand or Survival), Defiance (advantage on saves against being frightened), or Draconic Sorcery (one sorcerer cantrip).' },
|
||||
{ name: 'Small', text: 'You are Small: heavy weapons are hard for you to wield (disadvantage).' },
|
||||
],
|
||||
LIZARDFOLK: [
|
||||
{ name: 'Bite', text: 'Your unarmed strikes can be bites: 1d6 + Strength modifier piercing damage.' },
|
||||
{ name: 'Hold Breath', text: 'You can hold your breath for up to 15 minutes, and you swim at your walking speed.' },
|
||||
{ name: 'Hungry Jaws', text: 'Your proficiency bonus times per long rest, bonus action: a Bite attack that, on a hit, gives you temporary HP equal to your proficiency bonus.' },
|
||||
{ name: 'Natural Armor', text: 'Without armor your AC is 13 + your Dexterity modifier (ask your DM to set your armor bonus). A shield still adds.' },
|
||||
{ name: 'Nature’s Intuition', text: 'You are proficient in two of Animal Handling, Medicine, Nature, Perception, Stealth and Survival (agree them with your DM; add the bonus by hand).' },
|
||||
],
|
||||
MINOTAUR: [
|
||||
{ name: 'Horns', text: 'Your unarmed strikes can gore: 1d6 + Strength modifier piercing damage.' },
|
||||
{ name: 'Goring Rush', text: 'Right after you Dash and move at least 20 feet, make one Horns attack as a bonus action.' },
|
||||
{ name: 'Hammering Horns', text: 'After you hit with a melee attack as part of the Attack action, shove the target up to 10 feet away as a bonus action (Strength save to resist).' },
|
||||
{ name: 'Labyrinthine Recall', text: 'You always know which way is north, and you have advantage on checks to navigate or track.' },
|
||||
],
|
||||
SEA_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.' },
|
||||
{ name: 'Child of the Sea', text: 'You breathe air and water, swim at your walking speed, and cold damage against you is halved.' },
|
||||
{ name: 'Friend of the Sea', text: 'You can share simple ideas with beasts that breathe water.' },
|
||||
],
|
||||
SHADAR_KAI: [
|
||||
{ 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.' },
|
||||
{ name: 'Necrotic Resistance', text: 'Necrotic damage against you is halved.' },
|
||||
{ name: 'Blessing of the Raven Queen', text: 'Your proficiency bonus times per long rest, bonus action: teleport up to 30 feet. From level 3 you also halve all damage against you until the start of your next turn.' },
|
||||
],
|
||||
SHIFTER: [
|
||||
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
|
||||
{ name: 'Bestial Instincts', text: 'You are proficient in one of Acrobatics, Athletics, Intimidation or Survival (agree it with your DM).' },
|
||||
{ name: 'Shifting', text: 'Your proficiency bonus times per long rest, bonus action: shift for one minute and gain 2 × your proficiency bonus temporary HP, plus your kind’s benefit (agree it with your DM): Beasthide +1 AC, Longtooth a bonus-action bite, Swiftstride +10 ft speed, Wildhunt advantage on Wisdom checks.' },
|
||||
],
|
||||
TABAXI: [
|
||||
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
|
||||
{ name: 'Cat’s Claws', text: 'Your unarmed strikes deal 1d6 + Strength modifier slashing damage, and you climb at your walking speed.' },
|
||||
{ name: 'Cat’s Talent', text: 'You are proficient in Perception and Stealth (add the bonus by hand).' },
|
||||
{ name: 'Feline Agility', text: 'On your turn, double your speed until the end of the turn. You can do it again after a turn in which you do not move.' },
|
||||
],
|
||||
TORTLE: [
|
||||
{ name: 'Claws', text: 'Your unarmed strikes deal 1d6 + Strength modifier slashing damage.' },
|
||||
{ name: 'Hold Breath', text: 'You can hold your breath for up to an hour.' },
|
||||
{ name: 'Natural Armor', text: 'Your shell gives you AC 17, whatever your Dexterity; you cannot wear armor, but a shield still adds (ask your DM to set your armor bonus).' },
|
||||
{ name: 'Shell Defense', text: 'Action: withdraw into your shell: +4 AC and advantage on Strength and Constitution saves, but speed 0, disadvantage on Dexterity saves and no reactions, until you come out (bonus action).' },
|
||||
{ name: 'Nature’s Intuition', text: 'You are proficient in two of Animal Handling, Medicine, Nature, Perception, Stealth and Survival (agree them with your DM; add the bonus by hand).' },
|
||||
],
|
||||
TRITON: [
|
||||
{ name: 'Amphibious', text: 'You can breathe air and water, and you have a swimming speed equal to your walking speed.' },
|
||||
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
|
||||
{ name: 'Control Air and Water', text: 'Cast Fog Cloud; from level 3 Gust of Wind, and from level 5 Water Walk, each once per long rest without a slot.' },
|
||||
{ name: 'Emissary of the Sea', text: 'You can share simple ideas with beasts, elementals and monstrosities that breathe water.' },
|
||||
{ name: 'Guardian of the Depths', text: 'Cold damage against you is halved.' },
|
||||
],
|
||||
YUAN_TI: [
|
||||
{ name: 'Darkvision', text: 'See in dim light within 60 feet as if it were bright, and in darkness as if it were dim.' },
|
||||
{ name: 'Magic Resistance', text: 'Advantage on saves against spells.' },
|
||||
{ name: 'Poison Resilience', text: 'Advantage on saves against being poisoned, and poison damage against you is halved.' },
|
||||
{ name: 'Serpentine Spellcasting', text: 'You know Poison Spray, and you can cast Animal Friendship on snakes at will. From level 3 cast Suggestion once per long rest without a slot.' },
|
||||
],
|
||||
OWLIN: [
|
||||
{ name: 'Darkvision', text: 'See in dim light within 120 feet as if it were bright, and in darkness as if it were dim.' },
|
||||
{ name: 'Flight', text: 'You can fly at your walking speed, but not while wearing medium or heavy armor.' },
|
||||
{ name: 'Silent Feathers', text: 'You are proficient in Stealth (add the bonus by hand).' },
|
||||
],
|
||||
SATYR: [
|
||||
{ name: 'Ram', text: 'Your unarmed strikes can headbutt: 1d6 + Strength modifier bludgeoning damage.' },
|
||||
{ name: 'Magic Resistance', text: 'Advantage on saves against spells.' },
|
||||
{ name: 'Mirthful Leaps', text: 'Whenever you jump, roll a d8 and add it to the distance in feet.' },
|
||||
{ name: 'Reveler', text: 'You are proficient in Performance and Persuasion (add the bonus by hand).' },
|
||||
],
|
||||
};
|
||||
|
||||
// Granted automatically by class, at level 1.
|
||||
@@ -70,7 +266,7 @@ const CLASS_FEATURES = {
|
||||
],
|
||||
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).' },
|
||||
{ name: 'Unarmored Defense', text: 'Without armor, add your Constitution modifier to your AC (counted on your sheet). A shield still adds.' },
|
||||
],
|
||||
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.' },
|
||||
@@ -110,7 +306,11 @@ const CLASS_FEATURES = {
|
||||
],
|
||||
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).' },
|
||||
{ name: 'Unarmored Defense', text: 'Without armor or a shield, add your Wisdom modifier to your AC (counted on your sheet).' },
|
||||
],
|
||||
ARTIFICER: [
|
||||
{ name: 'Magical Tinkering', text: 'Touch a tiny object to give it a small magic: it shines, plays a recorded message, gives off a smell or sound, or shows a picture. You can keep as many going as your Intelligence modifier.' },
|
||||
{ name: 'Spellcasting', text: 'You cast artificer spells through tools: thieves’ tools, artisan’s tools or an infused item serve as your focus.' },
|
||||
],
|
||||
};
|
||||
|
||||
|
||||
@@ -71,6 +71,11 @@ const CLASSES = {
|
||||
saveProficiencies: ['STR', 'DEX'], spellcastingAbility: null,
|
||||
skillChoices: { count: 2, options: ['ACROBATICS', 'ATHLETICS', 'HISTORY', 'INSIGHT', 'RELIGION', 'STEALTH'] },
|
||||
},
|
||||
ARTIFICER: {
|
||||
key: 'ARTIFICER', name: 'Artificer', hitDie: 8, primaryAbility: 'Int',
|
||||
saveProficiencies: ['CON', 'INT'], spellcastingAbility: 'INT',
|
||||
skillChoices: { count: 2, options: ['ARCANA', 'HISTORY', 'INVESTIGATION', 'MEDICINE', 'NATURE', 'PERCEPTION', 'SLEIGHT_OF_HAND'] },
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = { CLASSES };
|
||||
|
||||
@@ -3,13 +3,15 @@
|
||||
// matches the `Item` Prisma model minus `id`/`campaignId`, plus a stable `key`
|
||||
// for "add to campaign" lookups and a `category` for the library picker.
|
||||
//
|
||||
// Armor here is a flat bonus to AC on top of 10 + Dexterity, because that is
|
||||
// how gear effects work (game/calculations.js, GEAR_STATS): the standard
|
||||
// rules' "replaces 10 + DEX" and "DEX bonus capped at 2" are not modelled.
|
||||
// Each suit's bonus is its standard AC less 10, and what the bonus cannot say
|
||||
// is in the note. A DM who wants it stricter edits the copy in their campaign.
|
||||
// Armor's AC is a bonus on top of 10 + Dexterity, because that is how gear
|
||||
// effects work (game/calculations.js, GEAR_STATS): each suit's bonus is its
|
||||
// standard AC less 10. What kind of armor it is (armorType, from the category)
|
||||
// tells the sheet how much Dexterity counts in it: all of it in light armor,
|
||||
// at most +2 in medium, none in heavy (calculations.js, armorDexterity).
|
||||
// What neither can say (a Strength requirement, Stealth) is in the note.
|
||||
|
||||
const STEALTH = 'Disadvantage on Stealth checks.';
|
||||
const ARMOR_TYPE = { 'Light Armor': 'LIGHT', 'Medium Armor': 'MEDIUM', 'Heavy Armor': 'HEAVY', Shields: 'SHIELD' };
|
||||
const armor = (key, name, category, ac, description, note = null, more = []) => ({
|
||||
key,
|
||||
name,
|
||||
@@ -18,6 +20,8 @@ const armor = (key, name, category, ac, description, note = null, more = []) =>
|
||||
damageDice: null,
|
||||
effects: [{ stat: 'AC', amount: ac }, ...more],
|
||||
effectNote: note,
|
||||
// What kind it is: the sheet goes by this for Unarmored Defense and the like.
|
||||
armorType: ARMOR_TYPE[category],
|
||||
});
|
||||
const gear = (key, name, category, description, effects = [], effectNote = null, damageDice = null) => ({
|
||||
key,
|
||||
@@ -36,17 +40,17 @@ const ITEM_LIBRARY = [
|
||||
armor('studded-leather', 'Studded Leather', 'Light Armor', 2, 'Tough leather set with close rivets and spikes.'),
|
||||
|
||||
// Medium armor
|
||||
armor('hide-armor', 'Hide Armor', 'Medium Armor', 2, 'Thick furs and pelts.', 'Standard rules: counts at most +2 from Dexterity.'),
|
||||
armor('chain-shirt', 'Chain Shirt', 'Medium Armor', 3, 'Interlocking rings worn between layers of clothing.', 'Standard rules: counts at most +2 from Dexterity.'),
|
||||
armor('scale-mail', 'Scale Mail', 'Medium Armor', 4, 'A coat and leggings of leather covered in overlapping metal scales.', `${STEALTH} Standard rules: counts at most +2 from Dexterity.`),
|
||||
armor('breastplate', 'Breastplate', 'Medium Armor', 4, 'A fitted metal chest piece worn with supple leather.', 'Standard rules: counts at most +2 from Dexterity.'),
|
||||
armor('half-plate', 'Half Plate', 'Medium Armor', 5, 'Shaped metal plates covering most of the body.', `${STEALTH} Standard rules: counts at most +2 from Dexterity.`),
|
||||
armor('hide-armor', 'Hide Armor', 'Medium Armor', 2, 'Thick furs and pelts.', 'Medium armor: at most +2 from Dexterity counts (worked out on the sheet).'),
|
||||
armor('chain-shirt', 'Chain Shirt', 'Medium Armor', 3, 'Interlocking rings worn between layers of clothing.', 'Medium armor: at most +2 from Dexterity counts (worked out on the sheet).'),
|
||||
armor('scale-mail', 'Scale Mail', 'Medium Armor', 4, 'A coat and leggings of leather covered in overlapping metal scales.', `${STEALTH} Medium armor: at most +2 from Dexterity counts (worked out on the sheet).`),
|
||||
armor('breastplate', 'Breastplate', 'Medium Armor', 4, 'A fitted metal chest piece worn with supple leather.', 'Medium armor: at most +2 from Dexterity counts (worked out on the sheet).'),
|
||||
armor('half-plate', 'Half Plate', 'Medium Armor', 5, 'Shaped metal plates covering most of the body.', `${STEALTH} Medium armor: at most +2 from Dexterity counts (worked out on the sheet).`),
|
||||
|
||||
// Heavy armor: slow, loud, and in the standard rules it ignores Dexterity.
|
||||
armor('ring-mail', 'Ring Mail', 'Heavy Armor', 4, 'Leather armor with heavy rings sewn into it.', `${STEALTH} Standard rules: adds no Dexterity.`),
|
||||
armor('chain-mail', 'Chain Mail', 'Heavy Armor', 6, 'Interlocking metal rings over a layer of quilted fabric, with gauntlets.', `${STEALTH} Standard rules: adds no Dexterity, and needs Strength 13.`, [{ stat: 'SPEED', amount: -10 }]),
|
||||
armor('splint-armor', 'Splint Armor', 'Heavy Armor', 7, 'Narrow vertical strips of metal riveted to a leather backing.', `${STEALTH} Standard rules: adds no Dexterity, and needs Strength 15.`, [{ stat: 'SPEED', amount: -10 }]),
|
||||
armor('plate-armor', 'Plate Armor', 'Heavy Armor', 8, 'Shaped, interlocking metal plates covering the whole body.', `${STEALTH} Standard rules: adds no Dexterity, and needs Strength 15.`, [{ stat: 'SPEED', amount: -10 }]),
|
||||
armor('ring-mail', 'Ring Mail', 'Heavy Armor', 4, 'Leather armor with heavy rings sewn into it.', `${STEALTH} Heavy armor: Dexterity does not count (worked out on the sheet).`),
|
||||
armor('chain-mail', 'Chain Mail', 'Heavy Armor', 6, 'Interlocking metal rings over a layer of quilted fabric, with gauntlets.', `${STEALTH} Heavy armor: Dexterity does not count (worked out on the sheet). Standard rules: needs Strength 13.`, [{ stat: 'SPEED', amount: -10 }]),
|
||||
armor('splint-armor', 'Splint Armor', 'Heavy Armor', 7, 'Narrow vertical strips of metal riveted to a leather backing.', `${STEALTH} Heavy armor: Dexterity does not count (worked out on the sheet). Standard rules: needs Strength 15.`, [{ stat: 'SPEED', amount: -10 }]),
|
||||
armor('plate-armor', 'Plate Armor', 'Heavy Armor', 8, 'Shaped, interlocking metal plates covering the whole body.', `${STEALTH} Heavy armor: Dexterity does not count (worked out on the sheet). Standard rules: needs Strength 15.`, [{ stat: 'SPEED', amount: -10 }]),
|
||||
|
||||
// Shields
|
||||
armor('shield', 'Shield', 'Shields', 2, 'Wood or metal, carried in one hand.'),
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
// What each class gains at each level after the first: the "Levelling-Up
|
||||
// Checklist" tables of the Hollowcrown book (Rules Cheat Sheet) for levels 2
|
||||
// to 10, carried on to level 20 in the same spirit. These are the features every member of the class gets; what a subclass
|
||||
// adds is in subclasses.js. Level 1 features are in characterOptions.js and
|
||||
// are written by the builder.
|
||||
//
|
||||
// Each entry becomes a line of the character's special abilities, "Name —
|
||||
// text". An `upgrade` rewrites the line that already has that name (Sneak
|
||||
// Attack growing a die); anything else is added as a new line. `{ boon: true }`
|
||||
// is a Boon: the DM picks one from BOONS below.
|
||||
//
|
||||
// None of this feeds the calculation engine: like the level 1 features, these
|
||||
// are table rules in plain words.
|
||||
|
||||
const BOON = { boon: true };
|
||||
|
||||
const rage = (uses, damage) => ({
|
||||
name: 'Rage',
|
||||
text: `${uses} per day, for one minute: +${damage} melee damage, advantage on Strength checks and saves, and physical damage against you is halved.`,
|
||||
upgrade: true,
|
||||
});
|
||||
|
||||
const sneakAttack = (dice) => ({
|
||||
name: 'Sneak Attack',
|
||||
text: `Once per turn, deal an extra ${dice} damage to a target you have advantage against, or that has one of your allies next to it.`,
|
||||
upgrade: true,
|
||||
});
|
||||
|
||||
const bardicInspiration = (die) => ({
|
||||
name: 'Bardic Inspiration',
|
||||
text: `A few times per day, as a bonus action, give an ally a ${die} to add to one attack, check or save.`,
|
||||
upgrade: true,
|
||||
});
|
||||
|
||||
const wildShape = (limit) => ({
|
||||
name: 'Wild Shape',
|
||||
text: `Twice per short rest, become a beast you have seen of ${limit}, for up to half your level in hours. Use the beast's HP; when it hits 0 you return to your own form.`,
|
||||
upgrade: true,
|
||||
});
|
||||
|
||||
const EXTRA_ATTACK = { name: 'Extra Attack', text: 'Attack twice when you take the Attack action.' };
|
||||
const EVASION = { name: 'Evasion', text: 'On a Dexterity save for half damage, take none on a success and half on a failure.' };
|
||||
const LANDS_STRIDE = { name: 'Land’s Stride', text: 'Ordinary difficult terrain and plants do not slow you.' };
|
||||
|
||||
const INVOCATIONS =
|
||||
'Agonizing Blast (add your Charisma modifier to each Eldritch Blast hit), Devil’s Sight (see normally in darkness, even magical darkness, to 120 ft), Repelling Blast (Eldritch Blast hits push the target 10 ft away), Mask of Many Faces (cast Disguise Self at will), Beguiling Influence (proficiency in Deception and Persuasion, added by hand), Eyes of the Rune Keeper (read any writing)';
|
||||
const invocations = (total) => ({
|
||||
name: 'Eldritch Invocations',
|
||||
text: `Choose one more with your DM (${total} in all). From level 5 the list adds Thirsting Blade (Pact of the Blade: attack twice with your pact weapon) and One with Shadows (become invisible while standing still in dim light or darkness).`,
|
||||
});
|
||||
|
||||
const LEVEL_FEATURES = {
|
||||
BARBARIAN: {
|
||||
2: [
|
||||
{ name: 'Reckless Attack', text: 'On your first attack each turn you may attack with advantage; attacks against you have advantage until your next turn.' },
|
||||
{ name: 'Danger Sense', text: 'Advantage on Dexterity saves against effects you can see (traps, breath, spells).' },
|
||||
],
|
||||
3: [rage('Three times', 2)],
|
||||
4: [BOON],
|
||||
5: [EXTRA_ATTACK, { name: 'Fast Movement', text: '+10 ft speed when not in heavy armor (counted on your sheet).' }],
|
||||
6: [rage('Four times', 2)],
|
||||
7: [{ name: 'Feral Instinct', text: 'Advantage on initiative; you can act normally in a surprise round if you rage first.' }],
|
||||
8: [BOON],
|
||||
9: [{ name: 'Brutal Critical', text: 'Roll one extra weapon damage die on a critical hit.' }, rage('Four times', 3)],
|
||||
11: [{ name: 'Relentless Rage', text: 'While raging, when you drop to 0 HP but are not killed outright, make a DC 10 Constitution save to drop to 1 HP instead. The DC rises by 5 each time, back to 10 after a rest.' }],
|
||||
12: [BOON, rage('Five times', 3)],
|
||||
13: [{ name: 'Brutal Critical', text: 'Roll two extra weapon damage dice on a critical hit.', upgrade: true }],
|
||||
15: [{ name: 'Persistent Rage', text: 'Your rage only ends early if you fall unconscious or choose to end it.' }],
|
||||
16: [BOON, rage('Five times', 4)],
|
||||
17: [{ name: 'Brutal Critical', text: 'Roll three extra weapon damage dice on a critical hit.', upgrade: true }, rage('Six times', 4)],
|
||||
18: [{ name: 'Indomitable Might', text: 'If a Strength check comes up lower than your Strength score, use the score instead.' }],
|
||||
19: [BOON],
|
||||
20: [
|
||||
{ name: 'Primal Champion', text: 'Your Strength and Constitution each count 4 higher (to 24 at most): add +2 to those modifiers by hand.' },
|
||||
{ name: 'Rage', text: 'As often as you like, for one minute: +4 melee damage, advantage on Strength checks and saves, and physical damage against you is halved.', upgrade: true },
|
||||
],
|
||||
},
|
||||
BARD: {
|
||||
2: [
|
||||
{ name: 'Jack of All Trades', text: 'Add half your proficiency bonus (round down) to any check you are not proficient in (counted on your sheet for skills and initiative).' },
|
||||
{ name: 'Song of Rest', text: 'During a short rest, allies who spend Hit Dice heal an extra 1d6.' },
|
||||
],
|
||||
3: [
|
||||
{ name: 'Expertise', text: 'Double proficiency on two proficient skills (add by hand).' },
|
||||
],
|
||||
4: [BOON],
|
||||
5: [bardicInspiration('d8'), { name: 'Font of Inspiration', text: 'Regain Bardic Inspiration on a short rest.' }],
|
||||
6: [
|
||||
{ name: 'Countercharm', text: 'Action: allies within 30 ft get advantage on saves against fear and charm until your next turn.' },
|
||||
],
|
||||
8: [BOON],
|
||||
9: [{ name: 'Song of Rest', text: 'During a short rest, allies who spend Hit Dice heal an extra 1d8.', upgrade: true }],
|
||||
10: [
|
||||
bardicInspiration('d10'),
|
||||
{ name: 'Expertise', text: 'Double proficiency on four proficient skills (add by hand).', upgrade: true },
|
||||
{ name: 'Magical Secrets', text: 'Learn two more spells from any class (the DM grants them within the unlock schedule).' },
|
||||
],
|
||||
12: [BOON],
|
||||
13: [{ name: 'Song of Rest', text: 'During a short rest, allies who spend Hit Dice heal an extra 1d10.', upgrade: true }],
|
||||
14: [{ name: 'Magical Secrets', text: 'Learn four spells from any class in all (the DM grants two more within the unlock schedule).', upgrade: true }],
|
||||
15: [bardicInspiration('d12')],
|
||||
16: [BOON],
|
||||
17: [{ name: 'Song of Rest', text: 'During a short rest, allies who spend Hit Dice heal an extra 1d12.', upgrade: true }],
|
||||
18: [{ name: 'Magical Secrets', text: 'Learn six spells from any class in all (the DM grants two more within the unlock schedule).', upgrade: true }],
|
||||
19: [BOON],
|
||||
20: [{ name: 'Superior Inspiration', text: 'When you roll initiative with no Bardic Inspiration left, you get one back.' }],
|
||||
},
|
||||
CLERIC: {
|
||||
2: [
|
||||
{ name: 'Channel Divinity', text: 'Once per short rest, use Turn Undead or your domain’s Channel Divinity.' },
|
||||
{ name: 'Turn Undead', text: 'Channel Divinity. Action: undead within 30 ft make a Wisdom save or flee from you for 1 minute.' },
|
||||
],
|
||||
4: [BOON],
|
||||
5: [{ name: 'Destroy Undead', text: 'Undead of CR 1/2 or lower that fail against your Turn Undead are destroyed.' }],
|
||||
6: [
|
||||
{ name: 'Channel Divinity', text: 'Twice per short rest, use Turn Undead or your domain’s Channel Divinity.', upgrade: true },
|
||||
],
|
||||
8: [
|
||||
BOON,
|
||||
{ name: 'Destroy Undead', text: 'Undead of CR 1 or lower that fail against your Turn Undead are destroyed.', upgrade: true },
|
||||
],
|
||||
10: [{ name: 'Divine Intervention', text: 'Once per week, call on your god: roll d100; if you roll your level or lower, the god helps (the DM decides how).' }],
|
||||
11: [{ name: 'Destroy Undead', text: 'Undead of CR 2 or lower that fail against your Turn Undead are destroyed.', upgrade: true }],
|
||||
12: [BOON],
|
||||
14: [{ name: 'Destroy Undead', text: 'Undead of CR 3 or lower that fail against your Turn Undead are destroyed.', upgrade: true }],
|
||||
16: [BOON],
|
||||
17: [{ name: 'Destroy Undead', text: 'Undead of CR 4 or lower that fail against your Turn Undead are destroyed.', upgrade: true }],
|
||||
18: [{ name: 'Channel Divinity', text: 'Three times per short rest, use Turn Undead or your domain’s Channel Divinity.', upgrade: true }],
|
||||
19: [BOON],
|
||||
20: [{ name: 'Divine Intervention', text: 'Once per week, call on your god and it answers: no roll needed (the DM decides how it helps).', upgrade: true }],
|
||||
},
|
||||
DRUID: {
|
||||
2: [
|
||||
wildShape('CR 1/4 or less (no flying or swimming)'),
|
||||
],
|
||||
4: [BOON, wildShape('CR 1/2 or less (it may swim, not fly)')],
|
||||
8: [BOON, wildShape('CR 1 or less (it may swim or fly)')],
|
||||
12: [BOON],
|
||||
16: [BOON],
|
||||
18: [
|
||||
{ name: 'Timeless Body', text: 'You age one year for every ten that pass.' },
|
||||
{ name: 'Beast Spells', text: 'You can cast spells while in Wild Shape (anything that needs no costly material).' },
|
||||
],
|
||||
19: [BOON],
|
||||
20: [{ name: 'Archdruid', text: 'Wild Shape as often as you like, and cast druid spells without words, gestures or simple materials.' }],
|
||||
},
|
||||
FIGHTER: {
|
||||
2: [{ name: 'Action Surge', text: 'Once per short rest, take one extra action on your turn.' }],
|
||||
4: [BOON],
|
||||
5: [EXTRA_ATTACK],
|
||||
6: [BOON],
|
||||
8: [BOON],
|
||||
9: [{ name: 'Indomitable', text: 'Once per long rest, reroll a failed saving throw.' }],
|
||||
11: [{ name: 'Extra Attack', text: 'Attack three times when you take the Attack action.', upgrade: true }],
|
||||
12: [BOON],
|
||||
13: [{ name: 'Indomitable', text: 'Twice per long rest, reroll a failed saving throw.', upgrade: true }],
|
||||
14: [BOON],
|
||||
16: [BOON],
|
||||
17: [
|
||||
{ name: 'Action Surge', text: 'Twice per short rest (but once per turn), take one extra action on your turn.', upgrade: true },
|
||||
{ name: 'Indomitable', text: 'Three times per long rest, reroll a failed saving throw.', upgrade: true },
|
||||
],
|
||||
19: [BOON],
|
||||
20: [{ name: 'Extra Attack', text: 'Attack four times when you take the Attack action.', upgrade: true }],
|
||||
},
|
||||
MONK: {
|
||||
2: [
|
||||
{ name: 'Ki', text: 'Points equal to your level; they come back on a short rest. Ki save DC is 8 + proficiency bonus + Wisdom modifier.' },
|
||||
{ name: 'Flurry of Blows', text: '1 ki: two unarmed strikes as a bonus action.' },
|
||||
{ name: 'Patient Defense', text: '1 ki: Dodge as a bonus action.' },
|
||||
{ name: 'Step of the Wind', text: '1 ki: Dash or Disengage as a bonus action, jump distance doubled.' },
|
||||
{ name: 'Unarmored Movement', text: '+10 ft speed without armor (counted on your sheet).' },
|
||||
],
|
||||
3: [
|
||||
{ name: 'Deflect Missiles', text: 'Reaction: reduce ranged weapon damage by 1d10 + Dexterity modifier + your level.' },
|
||||
],
|
||||
4: [BOON, { name: 'Slow Fall', text: 'Reaction: reduce falling damage by 5 × your level.' }],
|
||||
5: [
|
||||
EXTRA_ATTACK,
|
||||
{ name: 'Stunning Strike', text: '1 ki after a melee hit: the target makes a Constitution save or is stunned until your next turn.' },
|
||||
{ name: 'Martial Arts', text: 'Your unarmed strikes deal 1d6 damage and can use Dexterity. After attacking, make one unarmed strike as a bonus action.', upgrade: true },
|
||||
],
|
||||
6: [
|
||||
{ name: 'Ki-Empowered Strikes', text: 'Your unarmed strikes count as magical.' },
|
||||
{ name: 'Unarmored Movement', text: '+15 ft speed without armor (counted on your sheet).', upgrade: true },
|
||||
],
|
||||
7: [EVASION, { name: 'Stillness of Mind', text: 'Action: end charm or fear on yourself.' }],
|
||||
8: [BOON],
|
||||
9: [{ name: 'Unarmored Movement', text: '+15 ft speed without armor (counted on your sheet). You can run along walls and across water during your move.', upgrade: true }],
|
||||
10: [
|
||||
{ name: 'Purity of Body', text: 'Immune to poison and disease.' },
|
||||
{ name: 'Unarmored Movement', text: '+20 ft speed without armor (counted on your sheet). You can run along walls and across water during your move.', upgrade: true },
|
||||
],
|
||||
11: [{ name: 'Martial Arts', text: 'Your unarmed strikes deal 1d8 damage and can use Dexterity. After attacking, make one unarmed strike as a bonus action.', upgrade: true }],
|
||||
12: [BOON],
|
||||
13: [{ name: 'Tongue of the Sun and Moon', text: 'You understand every spoken language, and anyone who speaks one understands you.' }],
|
||||
14: [
|
||||
{ name: 'Diamond Soul', text: 'You are proficient in every saving throw (counted on your sheet); 1 ki rerolls a failed save.' },
|
||||
{ name: 'Unarmored Movement', text: '+25 ft speed without armor (counted on your sheet). You can run along walls and across water during your move.', upgrade: true },
|
||||
],
|
||||
15: [{ name: 'Timeless Body', text: 'You need no food or water and suffer none of the frailty of old age.' }],
|
||||
16: [BOON],
|
||||
17: [{ name: 'Martial Arts', text: 'Your unarmed strikes deal 1d10 damage and can use Dexterity. After attacking, make one unarmed strike as a bonus action.', upgrade: true }],
|
||||
18: [
|
||||
{ name: 'Empty Body', text: '4 ki: invisible for one minute, and all damage but force against you is halved. 8 ki: cast Astral Projection on yourself.' },
|
||||
{ name: 'Unarmored Movement', text: '+30 ft speed without armor (counted on your sheet). You can run along walls and across water during your move.', upgrade: true },
|
||||
],
|
||||
19: [BOON],
|
||||
20: [{ name: 'Perfect Self', text: 'When you roll initiative with no ki left, regain 4 ki.' }],
|
||||
},
|
||||
PALADIN: {
|
||||
2: [
|
||||
{ name: 'Divine Smite', text: 'After a melee hit, spend a spell slot to deal +2d8 radiant (+1d8 per slot level above 1st; +1d8 more against undead and fiends).' },
|
||||
{ name: 'Fighting Style', text: 'Choose one with your DM: +1 AC in armor (the DM raises Extra AC by 1), +2 damage with a one-handed weapon, or protect an adjacent ally (impose disadvantage on an attack as a reaction).' },
|
||||
{ name: 'Spellcasting', text: 'Paladin spells unlock: you now have spell slots.' },
|
||||
],
|
||||
3: [
|
||||
{ name: 'Divine Health', text: 'Immune to disease.' },
|
||||
],
|
||||
4: [BOON],
|
||||
5: [EXTRA_ATTACK],
|
||||
6: [{ name: 'Aura of Protection', text: 'You and allies within 10 ft add your Charisma modifier to all saving throws while you are conscious (yours is counted on your sheet).' }],
|
||||
8: [BOON],
|
||||
10: [{ name: 'Aura of Courage', text: 'You and allies within 10 ft can’t be frightened.' }],
|
||||
11: [{ name: 'Improved Divine Smite', text: 'Every melee weapon hit deals an extra 1d8 radiant damage.' }],
|
||||
12: [BOON],
|
||||
14: [{ name: 'Cleansing Touch', text: 'A few times per day (your Charisma modifier, at least once), action: end one spell on yourself or a willing creature you touch.' }],
|
||||
16: [BOON],
|
||||
18: [
|
||||
{ name: 'Aura of Protection', text: 'You and allies within 30 ft add your Charisma modifier to all saving throws while you are conscious (yours is counted on your sheet).', upgrade: true },
|
||||
{ name: 'Aura of Courage', text: 'You and allies within 30 ft can’t be frightened.', upgrade: true },
|
||||
],
|
||||
19: [BOON],
|
||||
},
|
||||
RANGER: {
|
||||
2: [
|
||||
{ name: 'Fighting Style', text: 'Choose one with your DM: +2 to ranged attacks, +1 AC in armor (the DM raises Extra AC by 1), or add your ability modifier again to a paired weapon’s damage (added by hand).' },
|
||||
{ name: 'Spellcasting', text: 'Ranger spells unlock: you now have spell slots.' },
|
||||
],
|
||||
3: [
|
||||
{ name: 'Primeval Awareness', text: 'Spend a spell slot: sense aberrations, dragons, fey, fiends, undead and elementals within 1 mile for 1 minute per slot level.' },
|
||||
],
|
||||
4: [BOON],
|
||||
5: [EXTRA_ATTACK],
|
||||
6: [
|
||||
{ name: 'Favored Enemy', text: 'Choose a second favored enemy with your DM.' },
|
||||
{ name: 'Natural Explorer', text: 'Choose a second favored terrain with your DM.' },
|
||||
],
|
||||
8: [BOON, LANDS_STRIDE],
|
||||
10: [
|
||||
{ name: 'Hide in Plain Sight', text: 'Spend 1 minute camouflaging: +10 to Stealth while you stay still.' },
|
||||
{ name: 'Natural Explorer', text: 'Choose a third favored terrain with your DM.' },
|
||||
],
|
||||
12: [BOON],
|
||||
14: [
|
||||
{ name: 'Vanish', text: 'Hide as a bonus action, and you can’t be tracked by non-magical means unless you choose to leave a trail.' },
|
||||
{ name: 'Favored Enemy', text: 'Choose a third favored enemy with your DM.', upgrade: true },
|
||||
],
|
||||
16: [BOON],
|
||||
18: [{ name: 'Feral Senses', text: 'Within 30 ft, invisibility gives no advantage against you, and you know where invisible creatures are.' }],
|
||||
19: [BOON],
|
||||
20: [{ name: 'Foe Slayer', text: 'Once per turn, add your Wisdom modifier to the attack or damage roll against a favored enemy.' }],
|
||||
},
|
||||
ROGUE: {
|
||||
2: [{ name: 'Cunning Action', text: 'Bonus action: Dash, Disengage or Hide.' }],
|
||||
3: [sneakAttack('2d6')],
|
||||
4: [BOON],
|
||||
5: [sneakAttack('3d6'), { name: 'Uncanny Dodge', text: 'Reaction: halve the damage of an attack that hits you.' }],
|
||||
6: [{ name: 'Expertise', text: 'Double proficiency on two more proficient skills (add by hand).' }],
|
||||
7: [sneakAttack('4d6'), EVASION],
|
||||
8: [BOON],
|
||||
9: [sneakAttack('5d6')],
|
||||
10: [BOON],
|
||||
11: [sneakAttack('6d6'), { name: 'Reliable Talent', text: 'On a check with a skill you are proficient in, treat a d20 roll of 9 or lower as a 10.' }],
|
||||
12: [BOON],
|
||||
13: [sneakAttack('7d6')],
|
||||
14: [{ name: 'Blindsense', text: 'If you can hear, you know where any hidden or invisible creature within 10 ft is.' }],
|
||||
15: [sneakAttack('8d6'), { name: 'Slippery Mind', text: 'You are proficient in Wisdom saves (counted on your sheet).' }],
|
||||
16: [BOON],
|
||||
17: [sneakAttack('9d6')],
|
||||
18: [{ name: 'Elusive', text: 'No attack against you has advantage while you are not incapacitated.' }],
|
||||
19: [BOON, sneakAttack('10d6')],
|
||||
20: [{ name: 'Stroke of Luck', text: 'Once per short rest, turn a missed attack into a hit, or a failed check into a 20.' }],
|
||||
},
|
||||
SORCERER: {
|
||||
2: [{ name: 'Font of Magic', text: 'Sorcery points equal to your level; they come back on a long rest. Bonus action: turn points into a spell slot (2 points = 1st, 3 = 2nd, 5 = 3rd, 6 = 4th, 7 = 5th), or a spell slot into points equal to its level.' }],
|
||||
3: [{ name: 'Metamagic', text: 'Choose two with your DM: Quickened Spell (2 points: cast an action spell as a bonus action), Twinned Spell (points = spell level: hit a second target with a single-target spell), Careful Spell (1 point: allies auto-succeed on your spell’s save), Subtle Spell (1 point: cast without words or gestures), Extended Spell (1 point: double duration), Heightened Spell (3 points: one target has disadvantage on its first save).' }],
|
||||
4: [BOON],
|
||||
8: [BOON],
|
||||
10: [{ name: 'Metamagic', text: 'Choose a third option with your DM.' }],
|
||||
12: [BOON],
|
||||
16: [BOON],
|
||||
17: [{ name: 'Metamagic', text: 'Choose a fourth option with your DM.' }],
|
||||
19: [BOON],
|
||||
20: [{ name: 'Sorcerous Restoration', text: 'Regain 4 sorcery points after each short rest.' }],
|
||||
},
|
||||
WARLOCK: {
|
||||
2: [{ name: 'Eldritch Invocations', text: `Choose two with your DM: ${INVOCATIONS}.` }],
|
||||
3: [{ name: 'Pact Boon', text: 'Choose one with your DM: Pact of the Blade (summon a weapon of your choice as an action; it counts as magical), Pact of the Chain (gain a small familiar spirit: an imp, a sprite or a cat-shaped shadow), or Pact of the Tome (a book of three extra cantrips from any class, which the DM grants).' }],
|
||||
4: [BOON],
|
||||
5: [invocations('three')],
|
||||
7: [invocations('four')],
|
||||
8: [BOON],
|
||||
9: [invocations('five')],
|
||||
11: [{ name: 'Mystic Arcanum', text: 'Choose a 6th-level warlock spell with your DM: cast it once per long rest without a slot. One more spell is added at 13 (7th), 15 (8th) and 17 (9th).' }],
|
||||
12: [BOON, invocations('six')],
|
||||
13: [{ name: 'Mystic Arcanum', text: 'Choose a 7th-level spell too: each arcanum spell is cast once per long rest without a slot.', upgrade: true }],
|
||||
15: [{ name: 'Mystic Arcanum', text: 'Choose an 8th-level spell too: each arcanum spell is cast once per long rest without a slot.', upgrade: true }, invocations('seven')],
|
||||
16: [BOON],
|
||||
17: [{ name: 'Mystic Arcanum', text: 'Choose a 9th-level spell too: each arcanum spell (6th to 9th) is cast once per long rest without a slot.', upgrade: true }],
|
||||
18: [invocations('eight')],
|
||||
19: [BOON],
|
||||
20: [{ name: 'Eldritch Master', text: 'Once per long rest, spend a minute pleading with your patron to regain all your pact slots.' }],
|
||||
},
|
||||
WIZARD: {
|
||||
4: [BOON],
|
||||
8: [BOON],
|
||||
12: [BOON],
|
||||
16: [BOON],
|
||||
18: [{ name: 'Spell Mastery', text: 'Choose a 1st- and a 2nd-level spell in your book with your DM: cast them at their lowest level without a slot.' }],
|
||||
19: [BOON],
|
||||
20: [{ name: 'Signature Spells', text: 'Choose two 3rd-level spells with your DM: each can be cast once per short rest without a slot.' }],
|
||||
},
|
||||
ARTIFICER: {
|
||||
2: [{ name: 'Infuse Item', text: 'After a long rest, infuse up to two items with magic (you know four infusions; choose them with your DM): an enhanced weapon (+1 to hit and damage), enhanced armor (+1 AC), a bag of holding, a glowing focus (+1 spell attacks), and more.' }],
|
||||
3: [{ name: 'The Right Tool for the Job', text: 'With an hour’s work and thieves’ or artisan’s tools, make any set of artisan’s tools you need.' }],
|
||||
4: [BOON],
|
||||
6: [
|
||||
{ name: 'Tool Expertise', text: 'Double your proficiency bonus on any check that uses a tool (add it by hand).' },
|
||||
{ name: 'Infuse Item', text: 'You know six infusions and keep up to three infused items at once.', upgrade: true },
|
||||
],
|
||||
7: [{ name: 'Flash of Genius', text: 'A few times per long rest (your Intelligence modifier, at least once), reaction: add your Intelligence modifier to a check or save made by you or a creature within 30 ft.' }],
|
||||
8: [BOON],
|
||||
10: [
|
||||
{ name: 'Magic Item Adept', text: 'Attune to four magic items, and craft common or uncommon ones in a quarter of the time for half the gold.' },
|
||||
{ name: 'Infuse Item', text: 'You know eight infusions and keep up to four infused items at once.', upgrade: true },
|
||||
],
|
||||
11: [{ name: 'Spell-Storing Item', text: 'After a long rest, store a 1st- or 2nd-level artificer spell in an item. Whoever holds it can cast it from the item, twice your Intelligence modifier times.' }],
|
||||
12: [BOON],
|
||||
14: [
|
||||
{ name: 'Magic Item Savant', text: 'Attune to five magic items, and ignore class, species, spell and level requirements on them.' },
|
||||
{ name: 'Infuse Item', text: 'You know ten infusions and keep up to five infused items at once.', upgrade: true },
|
||||
],
|
||||
16: [BOON],
|
||||
18: [
|
||||
{ name: 'Magic Item Master', text: 'Attune to six magic items.' },
|
||||
{ name: 'Infuse Item', text: 'You know twelve infusions and keep up to six infused items at once.', upgrade: true },
|
||||
],
|
||||
19: [BOON],
|
||||
20: [{ name: 'Soul of Artifice', text: '+1 to every saving throw for each magic item you are attuned to. When you drop to 0 HP, end one of your infusions to drop to 1 instead.' }],
|
||||
},
|
||||
};
|
||||
|
||||
// The class tables above go this far; so does a character.
|
||||
const MAX_FEATURE_LEVEL = 20;
|
||||
|
||||
// From level 5 a damaging cantrip rolls twice the dice the site shows. Written
|
||||
// onto the sheet of every class that casts, so nobody forgets.
|
||||
const CANTRIP_LEVEL = 5;
|
||||
const CANTRIP_FEATURE = {
|
||||
name: 'Cantrips',
|
||||
text: 'Double dice. Roll twice the damage dice the site shows for a damaging cantrip (Eldritch Blast becomes two beams, each with its own attack roll).',
|
||||
};
|
||||
|
||||
// Boons stand in for ability score increases, which the site does not have
|
||||
// (every number on the sheet comes from the scores rolled at the build). Each
|
||||
// is worth what +2 to a best ability would be. `max` is how often one can be
|
||||
// taken; `per` is what each taking adds, and `text` the line for that many.
|
||||
const BOONS = [
|
||||
{
|
||||
key: 'WEAPON_MASTERY',
|
||||
name: 'Weapon Mastery',
|
||||
max: 2,
|
||||
per: 1,
|
||||
text: (amount) => `+${amount} to attack and damage rolls with weapons (add it to the numbers the site shows).`,
|
||||
},
|
||||
{
|
||||
key: 'ARCANE_FOCUS',
|
||||
name: 'Arcane Focus',
|
||||
max: 2,
|
||||
per: 1,
|
||||
text: (amount) => `+${amount} to spell save DC and spell attack bonus (add it to the numbers the site shows).`,
|
||||
},
|
||||
// AC is the most powerful number in the game, so this one is taken once.
|
||||
{ key: 'TOUGHENED', name: 'Toughened', max: 1, per: 1, text: (amount) => `+${amount} AC (counted in your Extra AC).` },
|
||||
// The site works max HP out itself, so the extra lives in Temp HP.
|
||||
{ key: 'HARDY', name: 'Hardy', max: 2, per: 5, text: (amount) => `+${amount} maximum HP: gain ${amount} Temp HP after each long rest.` },
|
||||
// Past level 10 a class can have more Boons than the four above allow.
|
||||
{ key: 'RESOLVE', name: 'Resolve', max: 2, per: 1, text: (amount) => `+${amount} to every saving throw (add it to the numbers the site shows).` },
|
||||
];
|
||||
|
||||
module.exports = { LEVEL_FEATURES, MAX_FEATURE_LEVEL, CANTRIP_LEVEL, CANTRIP_FEATURE, BOONS };
|
||||
@@ -0,0 +1,116 @@
|
||||
// Suggested multiclass routes: well-known ways to combine classes, for a
|
||||
// player choosing where their next level goes. Each route starts from a class
|
||||
// (`from`) and lists its `steps` in order: take `class` up to `toLevel` (that
|
||||
// class's own level). `subclass` is the subclass the route assumes, if any,
|
||||
// and `why` what it buys. The requirements are checked against the character
|
||||
// when shown (game/multiclass.js); none of this is enforced.
|
||||
|
||||
const MULTICLASS_PATHS = [
|
||||
{
|
||||
key: 'HEXADIN',
|
||||
name: 'Hexadin',
|
||||
from: 'PALADIN',
|
||||
steps: [{ class: 'PALADIN', toLevel: 2 }, { class: 'WARLOCK', toLevel: 1, subclass: 'HEXBLADE' }, { class: 'PALADIN', toLevel: 18 }],
|
||||
why: 'Hexblade lets you swing with Charisma, so one ability powers attacks, smites and auras.',
|
||||
},
|
||||
{
|
||||
key: 'SORCADIN',
|
||||
name: 'Sorcadin',
|
||||
from: 'PALADIN',
|
||||
steps: [{ class: 'PALADIN', toLevel: 6 }, { class: 'SORCERER', toLevel: 14 }],
|
||||
why: 'Aura of Protection, then a deep pool of spell slots to pour into Divine Smite.',
|
||||
},
|
||||
{
|
||||
key: 'SORLOCK',
|
||||
name: 'Sorlock',
|
||||
from: 'SORCERER',
|
||||
steps: [{ class: 'SORCERER', toLevel: 2 }, { class: 'WARLOCK', toLevel: 2 }, { class: 'SORCERER', toLevel: 18 }],
|
||||
why: 'Agonizing Eldritch Blast, quickened with Metamagic, and pact slots that come back on a short rest.',
|
||||
},
|
||||
{
|
||||
key: 'GLOOM_ASSASSIN',
|
||||
name: 'Gloom Assassin',
|
||||
from: 'RANGER',
|
||||
steps: [{ class: 'RANGER', toLevel: 5, subclass: 'GLOOM_STALKER' }, { class: 'ROGUE', toLevel: 3, subclass: 'ASSASSIN' }, { class: 'RANGER', toLevel: 12 }],
|
||||
why: 'An enormous first round: extra attacks, advantage and automatic critical hits on the surprised.',
|
||||
},
|
||||
{
|
||||
key: 'FIGHTER_DIP',
|
||||
name: 'Fighter dip for anyone who swings',
|
||||
from: null,
|
||||
steps: [{ class: 'FIGHTER', toLevel: 2 }],
|
||||
why: 'Two levels give a fighting style, Second Wind and Action Surge: one huge turn per rest.',
|
||||
},
|
||||
{
|
||||
key: 'CLERIC_DIP',
|
||||
name: 'Cleric dip for armor and healing',
|
||||
from: 'WIZARD',
|
||||
steps: [{ class: 'CLERIC', toLevel: 1 }, { class: 'WIZARD', toLevel: 19 }],
|
||||
why: 'Armor and shields, healing words and a domain’s gifts on a wizard, for one level.',
|
||||
},
|
||||
{
|
||||
key: 'BLADESINGER_FIGHTER',
|
||||
name: 'Fighting wizard',
|
||||
from: 'FIGHTER',
|
||||
steps: [{ class: 'FIGHTER', toLevel: 2 }, { class: 'WIZARD', toLevel: 18, subclass: 'BLADESINGING' }],
|
||||
why: 'Starts in armor with Action Surge, then grows into a Bladesinger with real spells.',
|
||||
},
|
||||
{
|
||||
key: 'ROGUE_FIGHTER',
|
||||
name: 'Skirmisher',
|
||||
from: 'ROGUE',
|
||||
steps: [{ class: 'ROGUE', toLevel: 1 }, { class: 'FIGHTER', toLevel: 2 }, { class: 'ROGUE', toLevel: 17 }],
|
||||
why: 'Action Surge for a second Sneak Attack chance in a turn, and better armor.',
|
||||
},
|
||||
{
|
||||
key: 'MONK_CLERIC',
|
||||
name: 'Wisdom warrior',
|
||||
from: 'MONK',
|
||||
steps: [{ class: 'MONK', toLevel: 5 }, { class: 'CLERIC', toLevel: 2 }, { class: 'MONK', toLevel: 13 }],
|
||||
why: 'Stunning Strike and Extra Attack first, then Wisdom-powered healing and Channel Divinity.',
|
||||
},
|
||||
{
|
||||
key: 'BARBARIAN_FIGHTER',
|
||||
name: 'Raging champion',
|
||||
from: 'BARBARIAN',
|
||||
steps: [{ class: 'BARBARIAN', toLevel: 5 }, { class: 'FIGHTER', toLevel: 3, subclass: 'CHAMPION' }, { class: 'BARBARIAN', toLevel: 12 }],
|
||||
why: 'Reckless Attack with critical hits on 19–20: advantage makes those crits come often.',
|
||||
},
|
||||
{
|
||||
key: 'DRUID_CLERIC',
|
||||
name: 'Nature priest',
|
||||
from: 'DRUID',
|
||||
steps: [{ class: 'CLERIC', toLevel: 1, subclass: 'LIFE' }, { class: 'DRUID', toLevel: 19 }],
|
||||
why: 'One Life Domain level makes every druid healing spell heal more, and adds heavy armor.',
|
||||
},
|
||||
{
|
||||
key: 'BARD_WARLOCK',
|
||||
name: 'Eldritch bard',
|
||||
from: 'BARD',
|
||||
steps: [{ class: 'BARD', toLevel: 6 }, { class: 'WARLOCK', toLevel: 2 }, { class: 'BARD', toLevel: 12 }],
|
||||
why: 'Eldritch Blast with Agonizing Blast as a dependable attack for a support caster.',
|
||||
},
|
||||
{
|
||||
key: 'ARTIFICER_WIZARD',
|
||||
name: 'Arcane engineer',
|
||||
from: 'ARTIFICER',
|
||||
steps: [{ class: 'ARTIFICER', toLevel: 2 }, { class: 'WIZARD', toLevel: 18 }],
|
||||
why: 'Infusions and a tool focus early, then a wizard’s full spell list, all on Intelligence.',
|
||||
},
|
||||
{
|
||||
key: 'RANGER_DRUID',
|
||||
name: 'Wild warden',
|
||||
from: 'RANGER',
|
||||
steps: [{ class: 'RANGER', toLevel: 5 }, { class: 'DRUID', toLevel: 2 }, { class: 'RANGER', toLevel: 13 }],
|
||||
why: 'Extra Attack and a ranger’s toolkit, plus Wild Shape for scouting and a second health bar.',
|
||||
},
|
||||
{
|
||||
key: 'WARLOCK_PALADIN',
|
||||
name: 'Blade pact knight',
|
||||
from: 'WARLOCK',
|
||||
steps: [{ class: 'WARLOCK', toLevel: 3, subclass: 'HEXBLADE' }, { class: 'PALADIN', toLevel: 2 }, { class: 'WARLOCK', toLevel: 15 }],
|
||||
why: 'A pact weapon swung with Charisma, and short-rest slots to burn on Divine Smite.',
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = { MULTICLASS_PATHS };
|
||||
@@ -1,23 +1,76 @@
|
||||
// Generated from /seed-data/species.json — keep in sync by hand if that file changes.
|
||||
// See docs/GAME_RULES_REFERENCE.md "Species Ability Score Increases & Speed".
|
||||
//
|
||||
// `abilityBonuses` are fixed. `flexible` is a choice the player makes in the
|
||||
// builder on top of them: one of the `patterns` (+2 and +1, or +1 three
|
||||
// times...), each to a different ability, never one in `exclude`. The choice
|
||||
// is kept on the character as speciesBonusChoices, e.g. { STR: 2, WIS: 1 }.
|
||||
|
||||
const SPECIES = {
|
||||
HUMAN: { key: 'HUMAN', name: 'Human', abilityBonuses: { STR: 1, DEX: 1, CON: 1, INT: 1, WIS: 1, CHA: 1 }, speed: 30, notes: null },
|
||||
HALF_ELF: {
|
||||
key: 'HALF_ELF',
|
||||
name: 'Half-Elf',
|
||||
abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 2 },
|
||||
speed: 30,
|
||||
notes: "Fixed +2 CHA plus a flexible +1/+1 to two other abilities of the player's choice. The builder UI must prompt for this choice; do not hardcode a default.",
|
||||
},
|
||||
ELF: { key: 'ELF', name: 'Elf', abilityBonuses: { STR: 0, DEX: 2, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, notes: null },
|
||||
GNOME: { key: 'GNOME', name: 'Gnome', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 2, WIS: 0, CHA: 0 }, speed: 25, notes: null },
|
||||
DWARF: { key: 'DWARF', name: 'Dwarf', abilityBonuses: { STR: 0, DEX: 0, CON: 2, INT: 0, WIS: 0, CHA: 0 }, speed: 25, notes: null },
|
||||
HALFLING: { key: 'HALFLING', name: 'Halfling', abilityBonuses: { STR: 0, DEX: 2, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 25, notes: null },
|
||||
DRAGONBORN: { key: 'DRAGONBORN', name: 'Dragonborn', abilityBonuses: { STR: 2, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 1 }, speed: 30, notes: null },
|
||||
TIEFLING: { key: 'TIEFLING', name: 'Tiefling', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 1, WIS: 0, CHA: 2 }, speed: 30, notes: null },
|
||||
HALF_ORC: { key: 'HALF_ORC', name: 'Half-Orc', abilityBonuses: { STR: 2, DEX: 0, CON: 1, INT: 0, WIS: 0, CHA: 0 }, speed: 30, notes: null },
|
||||
ORC: { key: 'ORC', name: 'Orc', abilityBonuses: { STR: 2, DEX: 0, CON: 1, INT: 0, WIS: 0, CHA: 0 }, speed: 30, notes: null },
|
||||
HUMAN: { key: 'HUMAN', name: 'Human', abilityBonuses: { STR: 1, DEX: 1, CON: 1, INT: 1, WIS: 1, CHA: 1 }, speed: 30 },
|
||||
HALF_ELF: { key: 'HALF_ELF', name: 'Half-Elf', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 2 }, speed: 30, flexible: { patterns: [[1, 1]], exclude: ['CHA'] } },
|
||||
ELF: { key: 'ELF', name: 'Elf', abilityBonuses: { STR: 0, DEX: 2, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30 },
|
||||
GNOME: { key: 'GNOME', name: 'Gnome', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 2, WIS: 0, CHA: 0 }, speed: 25 },
|
||||
DWARF: { key: 'DWARF', name: 'Dwarf', abilityBonuses: { STR: 0, DEX: 0, CON: 2, INT: 0, WIS: 0, CHA: 0 }, speed: 25 },
|
||||
HALFLING: { key: 'HALFLING', name: 'Halfling', abilityBonuses: { STR: 0, DEX: 2, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 25 },
|
||||
DRAGONBORN: { key: 'DRAGONBORN', name: 'Dragonborn', abilityBonuses: { STR: 2, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 1 }, speed: 30 },
|
||||
TIEFLING: { key: 'TIEFLING', name: 'Tiefling', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 1, WIS: 0, CHA: 2 }, speed: 30 },
|
||||
HALF_ORC: { key: 'HALF_ORC', name: 'Half-Orc', abilityBonuses: { STR: 2, DEX: 0, CON: 1, INT: 0, WIS: 0, CHA: 0 }, speed: 30 },
|
||||
ORC: { key: 'ORC', name: 'Orc', abilityBonuses: { STR: 2, DEX: 0, CON: 1, INT: 0, WIS: 0, CHA: 0 }, speed: 30 },
|
||||
AASIMAR: { key: 'AASIMAR', name: 'Aasimar', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
GOLIATH: { key: 'GOLIATH', name: 'Goliath', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 35, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
AARAKOCRA: { key: 'AARAKOCRA', name: 'Aarakocra', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
BUGBEAR: { key: 'BUGBEAR', name: 'Bugbear', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
CENTAUR: { key: 'CENTAUR', name: 'Centaur', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 40, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
CHANGELING: { key: 'CHANGELING', name: 'Changeling', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
DEEP_GNOME: { key: 'DEEP_GNOME', name: 'Deep Gnome', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
DUERGAR: { key: 'DUERGAR', name: 'Duergar', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
ELADRIN: { key: 'ELADRIN', name: 'Eladrin', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
FAIRY: { key: 'FAIRY', name: 'Fairy', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
FIRBOLG: { key: 'FIRBOLG', name: 'Firbolg', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
AIR_GENASI: { key: 'AIR_GENASI', name: 'Air Genasi', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 35, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
EARTH_GENASI: { key: 'EARTH_GENASI', name: 'Earth Genasi', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
FIRE_GENASI: { key: 'FIRE_GENASI', name: 'Fire Genasi', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
WATER_GENASI: { key: 'WATER_GENASI', name: 'Water Genasi', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
GITHYANKI: { key: 'GITHYANKI', name: 'Githyanki', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
GITHZERAI: { key: 'GITHZERAI', name: 'Githzerai', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
GOBLIN: { key: 'GOBLIN', name: 'Goblin', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
HARENGON: { key: 'HARENGON', name: 'Harengon', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
HOBGOBLIN: { key: 'HOBGOBLIN', name: 'Hobgoblin', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
KENKU: { key: 'KENKU', name: 'Kenku', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
KOBOLD: { key: 'KOBOLD', name: 'Kobold', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
LIZARDFOLK: { key: 'LIZARDFOLK', name: 'Lizardfolk', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
MINOTAUR: { key: 'MINOTAUR', name: 'Minotaur', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
SEA_ELF: { key: 'SEA_ELF', name: 'Sea Elf', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
SHADAR_KAI: { key: 'SHADAR_KAI', name: 'Shadar-kai', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
SHIFTER: { key: 'SHIFTER', name: 'Shifter', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
TABAXI: { key: 'TABAXI', name: 'Tabaxi', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
TORTLE: { key: 'TORTLE', name: 'Tortle', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
TRITON: { key: 'TRITON', name: 'Triton', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
YUAN_TI: { key: 'YUAN_TI', name: 'Yuan-ti', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
OWLIN: { key: 'OWLIN', name: 'Owlin', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 30, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
SATYR: { key: 'SATYR', name: 'Satyr', abilityBonuses: { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }, speed: 35, flexible: { patterns: [[2, 1], [1, 1, 1]] } },
|
||||
};
|
||||
|
||||
module.exports = { SPECIES };
|
||||
const ABILITIES = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA'];
|
||||
|
||||
// What is wrong with a player's flexible bonuses for a species, or null when
|
||||
// they are fine. A species without a choice to make takes none.
|
||||
function speciesBonusProblem(speciesKey, choices) {
|
||||
const species = SPECIES[speciesKey];
|
||||
if (!species) return 'That is not a species.';
|
||||
const entries = Object.entries(choices || {}).filter(([, amount]) => amount);
|
||||
if (!species.flexible) return entries.length ? `${species.name} has no bonuses to choose.` : null;
|
||||
if (entries.some(([ability]) => !ABILITIES.includes(ability))) return 'Bonuses go to the six abilities.';
|
||||
const excluded = species.flexible.exclude || [];
|
||||
if (entries.some(([ability]) => excluded.includes(ability))) return `${species.name} cannot put a chosen bonus on ${excluded.join(' or ')}.`;
|
||||
const amounts = entries.map(([, amount]) => amount).sort((a, b) => b - a).join(',');
|
||||
const fits = species.flexible.patterns.some((pattern) => [...pattern].sort((a, b) => b - a).join(',') === amounts);
|
||||
if (!fits) {
|
||||
const options = species.flexible.patterns.map((pattern) => pattern.map((n) => `+${n}`).join('/')).join(' or ');
|
||||
return `${species.name} chooses ${options}, each to a different ability.`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
module.exports = { SPECIES, speciesBonusProblem };
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
// Spell slots by class and character level: the standard 5e tables, as the
|
||||
// Hollowcrown book's Slot Tracker prints them for levels 1 to 10. Each row is
|
||||
// how many slots there are of each slot level, 1st first.
|
||||
|
||||
// Bard, Cleric, Druid, Sorcerer, Wizard.
|
||||
const FULL_CASTER_SLOTS = [
|
||||
[2],
|
||||
[3],
|
||||
[4, 2],
|
||||
[4, 3],
|
||||
[4, 3, 2],
|
||||
[4, 3, 3],
|
||||
[4, 3, 3, 1],
|
||||
[4, 3, 3, 2],
|
||||
[4, 3, 3, 3, 1],
|
||||
[4, 3, 3, 3, 2],
|
||||
[4, 3, 3, 3, 2, 1],
|
||||
[4, 3, 3, 3, 2, 1],
|
||||
[4, 3, 3, 3, 2, 1, 1],
|
||||
[4, 3, 3, 3, 2, 1, 1],
|
||||
[4, 3, 3, 3, 2, 1, 1, 1],
|
||||
[4, 3, 3, 3, 2, 1, 1, 1],
|
||||
[4, 3, 3, 3, 2, 1, 1, 1, 1],
|
||||
[4, 3, 3, 3, 3, 1, 1, 1, 1],
|
||||
[4, 3, 3, 3, 3, 2, 1, 1, 1],
|
||||
[4, 3, 3, 3, 3, 2, 2, 1, 1],
|
||||
];
|
||||
|
||||
// Paladin, Ranger: nothing at level 1, then half a full caster's pace.
|
||||
const HALF_CASTER_SLOTS = [
|
||||
[],
|
||||
[2],
|
||||
[3],
|
||||
[3],
|
||||
[4, 2],
|
||||
[4, 2],
|
||||
[4, 3],
|
||||
[4, 3],
|
||||
[4, 3, 2],
|
||||
[4, 3, 2],
|
||||
[4, 3, 3],
|
||||
[4, 3, 3],
|
||||
[4, 3, 3, 1],
|
||||
[4, 3, 3, 1],
|
||||
[4, 3, 3, 2],
|
||||
[4, 3, 3, 2],
|
||||
[4, 3, 3, 3, 1],
|
||||
[4, 3, 3, 3, 1],
|
||||
[4, 3, 3, 3, 2],
|
||||
[4, 3, 3, 3, 2],
|
||||
];
|
||||
|
||||
// Artificer: a half caster that starts at level 1, rounding up.
|
||||
const ARTIFICER_SLOTS = [
|
||||
[2],
|
||||
[2],
|
||||
[3],
|
||||
[3],
|
||||
[4, 2],
|
||||
[4, 2],
|
||||
[4, 3],
|
||||
[4, 3],
|
||||
[4, 3, 2],
|
||||
[4, 3, 2],
|
||||
[4, 3, 3],
|
||||
[4, 3, 3],
|
||||
[4, 3, 3, 1],
|
||||
[4, 3, 3, 1],
|
||||
[4, 3, 3, 2],
|
||||
[4, 3, 3, 2],
|
||||
[4, 3, 3, 3, 1],
|
||||
[4, 3, 3, 3, 1],
|
||||
[4, 3, 3, 3, 2],
|
||||
[4, 3, 3, 3, 2],
|
||||
];
|
||||
|
||||
// Eldritch Knight, Arcane Trickster: a third of a full caster's pace, from
|
||||
// level 3 (the subclass is what casts, not the class).
|
||||
const THIRD_CASTER_SLOTS = [
|
||||
[],
|
||||
[],
|
||||
[2],
|
||||
[3],
|
||||
[3],
|
||||
[3],
|
||||
[4, 2],
|
||||
[4, 2],
|
||||
[4, 2],
|
||||
[4, 3],
|
||||
[4, 3],
|
||||
[4, 3],
|
||||
[4, 3, 2],
|
||||
[4, 3, 2],
|
||||
[4, 3, 2],
|
||||
[4, 3, 3],
|
||||
[4, 3, 3],
|
||||
[4, 3, 3],
|
||||
[4, 3, 3, 1],
|
||||
[4, 3, 3, 1],
|
||||
];
|
||||
|
||||
// Warlock: a few slots, all of one slot level. [how many, which level].
|
||||
const PACT_SLOTS = [
|
||||
[1, 1],
|
||||
[2, 1],
|
||||
[2, 2],
|
||||
[2, 2],
|
||||
[2, 3],
|
||||
[2, 3],
|
||||
[2, 4],
|
||||
[2, 4],
|
||||
[2, 5],
|
||||
[2, 5],
|
||||
[3, 5],
|
||||
[3, 5],
|
||||
[3, 5],
|
||||
[3, 5],
|
||||
[3, 5],
|
||||
[3, 5],
|
||||
[4, 5],
|
||||
[4, 5],
|
||||
[4, 5],
|
||||
[4, 5],
|
||||
];
|
||||
|
||||
// FULL and HALF casters get their slots back on a long rest; a warlock's
|
||||
// PACT slots come back on a short rest too.
|
||||
const CASTER_KIND = {
|
||||
BARD: 'FULL',
|
||||
CLERIC: 'FULL',
|
||||
DRUID: 'FULL',
|
||||
SORCERER: 'FULL',
|
||||
WIZARD: 'FULL',
|
||||
PALADIN: 'HALF',
|
||||
RANGER: 'HALF',
|
||||
ARTIFICER: 'HALF',
|
||||
WARLOCK: 'PACT',
|
||||
};
|
||||
|
||||
// A class whose slots follow its own table rather than its kind's.
|
||||
const CLASS_SLOT_TABLES = { ARTIFICER: ARTIFICER_SLOTS };
|
||||
|
||||
// Subclasses that cast in a class that otherwise does not, with Intelligence.
|
||||
const SUBCLASS_CASTER_KIND = { ELDRITCH_KNIGHT: 'THIRD', ARCANE_TRICKSTER: 'THIRD' };
|
||||
|
||||
const MAX_SLOT_LEVEL = 9;
|
||||
|
||||
module.exports = {
|
||||
FULL_CASTER_SLOTS,
|
||||
HALF_CASTER_SLOTS,
|
||||
ARTIFICER_SLOTS,
|
||||
THIRD_CASTER_SLOTS,
|
||||
PACT_SLOTS,
|
||||
CASTER_KIND,
|
||||
CLASS_SLOT_TABLES,
|
||||
SUBCLASS_CASTER_KIND,
|
||||
MAX_SLOT_LEVEL,
|
||||
};
|
||||
@@ -155,4 +155,61 @@ const SPELL_LIBRARY = [
|
||||
{ key: 'wall-of-stone', name: 'Wall of Stone', level: 5, school: 'Evocation', castingTime: '1 action', range: '120 feet', duration: 'Concentration, up to 10 minutes', description: 'A nonmagical wall of solid stone springs into existence.', classes: ['DRUID', 'SORCERER', 'WIZARD'] },
|
||||
];
|
||||
|
||||
// How each spell lands in a battle (game/combat.js): a spell attack against
|
||||
// AC, or a saving throw by each target, [ability, half damage on a success].
|
||||
// A spell in neither list simply takes effect. Written onto the entries
|
||||
// below, as `attackRoll`, `saveAbility` and `halfOnSave`.
|
||||
const SPELL_ATTACKS = ['chill-touch', 'eldritch-blast', 'fire-bolt', 'produce-flame', 'ray-of-frost', 'shocking-grasp', 'thorn-whip', 'guiding-bolt', 'witch-bolt', 'scorching-ray', 'spiritual-weapon', 'contagion'];
|
||||
const SPELL_SAVES = {
|
||||
'acid-splash': ['DEX', false],
|
||||
'poison-spray': ['CON', false],
|
||||
'sacred-flame': ['DEX', false],
|
||||
'vicious-mockery': ['WIS', false],
|
||||
'burning-hands': ['DEX', true],
|
||||
'thunderwave': ['CON', true],
|
||||
'bane': ['CHA', false],
|
||||
'charm-person': ['WIS', false],
|
||||
'command': ['WIS', false],
|
||||
'entangle': ['STR', false],
|
||||
'faerie-fire': ['DEX', false],
|
||||
'animal-friendship': ['WIS', false],
|
||||
'blindness-deafness': ['CON', false],
|
||||
'hold-person': ['WIS', false],
|
||||
'flaming-sphere': ['DEX', true],
|
||||
'moonbeam': ['CON', true],
|
||||
'shatter': ['CON', true],
|
||||
'suggestion': ['WIS', false],
|
||||
'web': ['DEX', false],
|
||||
'zone-of-truth': ['CHA', false],
|
||||
'levitate': ['CON', false],
|
||||
'gust-of-wind': ['STR', false],
|
||||
'call-lightning': ['DEX', true],
|
||||
'fear': ['WIS', false],
|
||||
'fireball': ['DEX', true],
|
||||
'lightning-bolt': ['DEX', true],
|
||||
'sleet-storm': ['DEX', false],
|
||||
'slow': ['WIS', false],
|
||||
'spirit-guardians': ['WIS', true],
|
||||
'stinking-cloud': ['CON', false],
|
||||
'banishment': ['CHA', false],
|
||||
'blight': ['CON', true],
|
||||
'confusion': ['WIS', false],
|
||||
'ice-storm': ['DEX', true],
|
||||
'polymorph': ['WIS', false],
|
||||
'wall-of-fire': ['DEX', true],
|
||||
'guardian-of-faith': ['DEX', true],
|
||||
'cloudkill': ['CON', true],
|
||||
'cone-of-cold': ['CON', true],
|
||||
'dominate-person': ['WIS', false],
|
||||
'flame-strike': ['DEX', true],
|
||||
'hold-monster': ['WIS', false],
|
||||
'insect-plague': ['CON', true],
|
||||
};
|
||||
for (const spell of SPELL_LIBRARY) {
|
||||
spell.attackRoll = SPELL_ATTACKS.includes(spell.key);
|
||||
const save = SPELL_SAVES[spell.key];
|
||||
spell.saveAbility = save ? save[0] : null;
|
||||
spell.halfOnSave = save ? save[1] : false;
|
||||
}
|
||||
|
||||
module.exports = { SPELL_LIBRARY };
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// Artificer subclasses: the specialists. The shape is described in index.js.
|
||||
|
||||
const ARTIFICER = [
|
||||
{
|
||||
key: 'ALCHEMIST',
|
||||
name: 'Alchemist',
|
||||
source: 'Eberron: Rising from the Last War',
|
||||
edition: '2014',
|
||||
summary: 'Brews elixirs and bolsters healing and acid with chemistry.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Experimental Elixir', text: 'Alchemist. After a long rest, brew an elixir (roll a d6: healing, swiftness, resilience, boldness, flight or transformation); spend a spell slot to brew more and choose.' },
|
||||
{ name: 'Tool Proficiency', text: 'You are proficient with alchemist’s supplies.' },
|
||||
],
|
||||
5: [{ name: 'Alchemical Savant', text: 'Add your Intelligence modifier to one roll of acid, fire, necrotic or poison damage, or of healing, from your spells.' }],
|
||||
9: [{ name: 'Restorative Reagents', text: 'Your elixirs give 2d6 + Intelligence modifier Temp HP, and a few times per long rest you cast Lesser Restoration without a slot.' }],
|
||||
15: [{ name: 'Chemical Mastery', text: 'Acid and poison damage against you is halved, and you are immune to being poisoned. Once per long rest each, cast Greater Restoration and Heal without a slot.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ARMORER',
|
||||
name: 'Armorer',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Wears a suit of arcane power armor: guardian or infiltrator.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Arcane Armor', text: 'Armorer. Your armor becomes your focus, covers your whole body, and you are proficient with heavy armor.' },
|
||||
{ name: 'Armor Model', text: 'Choose with your DM, changeable after a rest. Guardian: thunder gauntlets (1d8 thunder; the target has disadvantage against others) and a defensive field (bonus action, Temp HP equal to your level). Infiltrator: a lightning launcher (1d6 lightning, +1d6 once per turn), +5 ft speed and advantage on Stealth.' },
|
||||
],
|
||||
5: [{ name: 'Extra Attack', text: 'Attack twice when you take the Attack action.' }],
|
||||
9: [{ name: 'Armor Modifications', text: 'Your armor counts as four items for your infusions (helmet, chest, boots, weapon), and you can keep two more infused items.' }],
|
||||
15: [{ name: 'Perfected Armor', text: 'Guardian: reaction, pull a Huge or smaller creature 30 ft and attack it. Infiltrator: lightning hits make the target glow and give advantage on the next attack against it, plus 1d6 lightning.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ARTILLERIST',
|
||||
name: 'Artillerist',
|
||||
source: 'Eberron: Rising from the Last War',
|
||||
edition: '2014',
|
||||
summary: 'Builds an eldritch cannon that blasts, burns or shields.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Eldritch Cannon', text: 'Artillerist. Once per long rest (or by spending a spell slot), action: make a Small or Tiny cannon (the DM adds it). Bonus action: it fires a Flamethrower (2d8 fire cone), a Force Ballista (2d8 force and a push) or a Protector (1d8 + Intelligence modifier Temp HP to allies nearby).' },
|
||||
{ name: 'Tool Proficiency', text: 'You are proficient with woodcarver’s tools.' },
|
||||
],
|
||||
5: [{ name: 'Arcane Firearm', text: 'Carve a wand, staff or rod into an arcane firearm: your artificer spells cast through it add 1d8 to one damage roll.' }],
|
||||
9: [{ name: 'Explosive Cannon', text: 'Your cannon deals 1d8 more, and you can detonate it (3d8 force to creatures within 20 ft, Dexterity save for half).' }],
|
||||
15: [{ name: 'Fortified Position', text: 'You can have two cannons at once, and you and allies within 10 ft of a cannon have half cover.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'BATTLE_SMITH',
|
||||
name: 'Battle Smith',
|
||||
source: 'Eberron: Rising from the Last War',
|
||||
edition: '2014',
|
||||
summary: 'Fights with a steel defender at your side and a magic weapon in hand.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Battle Ready', text: 'Battle Smith. Proficient with martial weapons, and you can use Intelligence for attack and damage with magic weapons.' },
|
||||
{ name: 'Steel Defender', text: 'A mechanical companion fights beside you (the DM adds it): it acts on your turn, can repair itself, and uses its reaction to give an attacker disadvantage against someone near it. Bonus action: command it to attack.' },
|
||||
],
|
||||
5: [{ name: 'Extra Attack', text: 'Attack twice when you take the Attack action.' }],
|
||||
9: [{ name: 'Arcane Jolt', text: 'A few times per long rest (Intelligence modifier), when you or your defender hit: +2d6 force, or heal a creature within 30 ft 2d6.' }],
|
||||
15: [{ name: 'Improved Defender', text: 'Arcane Jolt deals or heals 4d6; your defender gains +2 AC, and when it deflects an attack the attacker takes 1d4 + Intelligence modifier force.' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = ARTIFICER;
|
||||
@@ -0,0 +1,165 @@
|
||||
// Barbarian subclasses: the primal paths. The shape is described in index.js.
|
||||
|
||||
const BARBARIAN = [
|
||||
{
|
||||
key: 'BERSERKER',
|
||||
name: 'Path of the Berserker',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Rage as pure fury: extra attacks now, exhaustion after.',
|
||||
features: {
|
||||
3: [{ name: 'Frenzy', text: 'Path of the Berserker. While raging you may make one extra melee attack as a bonus action each turn; when the rage ends, gain one level of exhaustion.' }],
|
||||
6: [{ name: 'Mindless Rage', text: 'You can’t be charmed or frightened while raging.' }],
|
||||
10: [{ name: 'Intimidating Presence', text: 'Action: one creature within 30 ft makes a Wisdom save (DC 8 + proficiency bonus + Charisma modifier) or is frightened of you until the end of your next turn.' }],
|
||||
14: [{ name: 'Retaliation', text: 'Reaction: when a creature within 5 ft damages you, make a melee weapon attack against it.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'TOTEM_WARRIOR',
|
||||
name: 'Path of the Totem Warrior',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A spirit animal walks with you and lends its strength.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Spirit Seeker', text: 'Path of the Totem Warrior. You can speak with beasts and sense what they sense, as a ritual with your DM.' },
|
||||
{ name: 'Totem Spirit', text: 'Choose one with your DM. Bear: while raging, all damage but psychic is halved. Eagle: while raging, opportunity attacks against you have disadvantage and you can Dash as a bonus action. Wolf: while raging, allies have advantage on melee attacks against enemies next to you.' },
|
||||
],
|
||||
6: [{ name: 'Aspect of the Beast', text: 'Choose one with your DM. Bear: carry twice as much, advantage on Strength checks to push, pull or lift. Eagle: see clearly up to a mile, no penalty in dim light. Wolf: track at a fast pace and move stealthily at a normal one.' }],
|
||||
10: [{ name: 'Spirit Walker', text: 'As a ritual, ask the spirits of a place for what they know (the DM answers as a nature spirit would).' }],
|
||||
14: [{ name: 'Totemic Attunement', text: 'Choose one with your DM. Bear: while raging, enemies next to you have disadvantage on attacks against anyone else. Eagle: while raging, fly at your speed for the turn. Wolf: while raging, a melee hit can knock a Large or smaller creature prone as a bonus action.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ZEALOT',
|
||||
name: 'Path of the Zealot',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A god’s fury in your blows, and death has trouble keeping you.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Divine Fury', text: 'Path of the Zealot. While raging, the first creature you hit each turn takes an extra 1d6 + half your level radiant or necrotic damage.' },
|
||||
{ name: 'Warrior of the Gods', text: 'Spells that bring you back from the dead cost nothing to cast on you.' },
|
||||
],
|
||||
6: [{ name: 'Fanatical Focus', text: 'Once per rage, reroll a saving throw you just failed.' }],
|
||||
10: [{ name: 'Zealous Presence', text: 'Once per long rest, bonus action: up to ten allies within 60 ft have advantage on attacks and saves until your next turn.' }],
|
||||
14: [{ name: 'Rage Beyond Death', text: 'While raging, dropping to 0 HP does not knock you out. You still make death saves; you die only when the rage ends with you at 0 HP.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ANCESTRAL_GUARDIAN',
|
||||
name: 'Path of the Ancestral Guardian',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Ancestor spirits shield your friends from whatever you hit.',
|
||||
features: {
|
||||
3: [{ name: 'Ancestral Protectors', text: 'Path of the Ancestral Guardian. While raging, the first creature you hit each turn has disadvantage on attacks against anyone but you, and anyone else it hits takes only half damage, until your next turn.' }],
|
||||
6: [{ name: 'Spirit Shield', text: 'While raging, reaction: when a creature within 30 ft takes damage, reduce it by 2d6 (3d6 from level 10, 4d6 from level 14).' }],
|
||||
10: [{ name: 'Consult the Spirits', text: 'Once per short rest, cast Augury or Clairvoyance without a slot, the spirits doing the seeing.' }],
|
||||
14: [{ name: 'Vengeful Ancestors', text: 'When Spirit Shield reduces damage, the attacker takes force damage equal to the amount reduced.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'BATTLERAGER',
|
||||
name: 'Path of the Battlerager',
|
||||
source: 'Sword Coast Adventurer’s Guide',
|
||||
edition: '2014',
|
||||
summary: 'Spiked armor and a reckless charge into the middle of everything.',
|
||||
features: {
|
||||
3: [{ name: 'Battlerager Armor', text: 'Path of the Battlerager. In spiked armor while raging: bonus action, a spike attack (1d4 + Strength piercing); and when you grapple a creature it takes 3 piercing damage.' }],
|
||||
6: [{ name: 'Reckless Abandon', text: 'When you attack recklessly while raging, gain Temp HP equal to your Constitution modifier.' }],
|
||||
10: [{ name: 'Battlerager Charge', text: 'While raging, you can Dash as a bonus action.' }],
|
||||
14: [{ name: 'Spiked Retribution', text: 'While raging in spiked armor, a creature within 5 ft that hits you with a melee attack takes 3 piercing damage.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'BEAST',
|
||||
name: 'Path of the Beast',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Your rage brings out claws, a bite or a lashing tail.',
|
||||
features: {
|
||||
3: [{ name: 'Form of the Beast', text: 'Path of the Beast. Each time you rage, choose a natural weapon: Bite (1d8; once per turn heal your proficiency bonus when below half HP), Claws (1d6 each; one extra claw attack when you attack with one) or Tail (1d8, 10 ft reach; reaction +1d8 to your AC against a hit).' }],
|
||||
6: [{ name: 'Bestial Soul', text: 'Your natural weapons count as magical. After a long rest choose: swim speed and water breathing, climb speed, or extra jump distance.' }],
|
||||
10: [{ name: 'Infectious Fury', text: 'A few times per long rest (proficiency bonus), when your natural weapon hits: the target makes a Wisdom save or uses its reaction to attack someone else, or takes 2d12 psychic damage.' }],
|
||||
14: [{ name: 'Call the Hunt', text: 'A few times per long rest (proficiency bonus), when you rage: up to your Constitution modifier allies gain 1d6 extra damage once per turn, and you gain 5 Temp HP for each.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'GIANT',
|
||||
name: 'Path of the Giant',
|
||||
source: 'Bigby Presents: Glory of the Giants',
|
||||
edition: '2014',
|
||||
summary: 'Grow huge in your rage, and hurl weapons and foes alike.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Giant’s Power', text: 'Path of the Giant. You speak Giant and know Druidcraft or Thaumaturgy.' },
|
||||
{ name: 'Giant’s Havoc', text: 'While raging your reach grows by 5 ft, and you can grow Large if there is room.' },
|
||||
],
|
||||
6: [{ name: 'Elemental Cleaver', text: 'While raging, your weapon carries acid, cold, fire, lightning or thunder: +1d6 of that damage, and it can be thrown 20/60 ft and flies back.' }],
|
||||
10: [{ name: 'Mighty Impel', text: 'Bonus action while raging: throw a Medium or smaller creature within reach up to 30 ft (Strength save if unwilling); it lands prone and takes 1d8 bludgeoning.' }],
|
||||
14: [{ name: 'Demiurgic Colossus', text: 'Your rage reach grows by 10 ft, you can grow Large or Huge, Mighty Impel throws Large creatures, and Elemental Cleaver deals 2d6.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'STORM_HERALD',
|
||||
name: 'Path of the Storm Herald',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A storm of desert, sea or tundra rages around you.',
|
||||
features: {
|
||||
3: [{ name: 'Storm Aura', text: 'Path of the Storm Herald. While raging, a 10 ft aura (choose with your DM). Desert: each turn, others in it take fire damage (2 at level 3, rising). Sea: each turn, one creature in it takes 1d6 lightning (Dexterity save for half). Tundra: each turn, you and allies in it gain Temp HP (2 at level 3, rising).' }],
|
||||
6: [{ name: 'Storm Soul', text: 'Desert: fire resistance. Sea: lightning resistance, breathe underwater, swim speed. Tundra: cold resistance, and you can freeze a little water.' }],
|
||||
10: [{ name: 'Shielding Storm', text: 'Allies in your Storm Aura gain the resistance your Storm Soul gives.' }],
|
||||
14: [{ name: 'Raging Storm', text: 'Desert: reaction, a creature in your aura that hits you takes fire damage of half your level. Sea: reaction, a creature you hit makes a Strength save or is knocked prone. Tundra: each turn, one creature in your aura makes a Strength save or has speed 0.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'WILD_MAGIC_BARBARIAN',
|
||||
name: 'Path of Wild Magic',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Raw magic erupts every time you rage.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Magic Awareness', text: 'Path of Wild Magic. A few times per long rest (proficiency bonus), action: sense spells and magic items within 60 ft.' },
|
||||
{ name: 'Wild Surge', text: 'When you rage, roll a d8 for a wild effect (the DM reads it): necrotic tendrils, a teleport, an exploding spirit, a magic weapon, a retaliating aura, a light that blinds, flowers and vines, or a bolt of light.' },
|
||||
],
|
||||
6: [{ name: 'Bolstering Magic', text: 'A few times per long rest (proficiency bonus), action: a creature you touch adds a d3 to attacks and checks for 10 minutes, or regains a spent spell slot of up to a d3’s level.' }],
|
||||
10: [{ name: 'Unstable Backlash', text: 'While raging, reaction when you take damage or fail a save: roll a new Wild Surge in place of the current one.' }],
|
||||
14: [{ name: 'Controlled Surge', text: 'When you roll a Wild Surge, roll twice and choose (any doubles, choose any effect).' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'WILD_HEART',
|
||||
name: 'Path of the Wild Heart',
|
||||
source: 'Player’s Handbook (2024)',
|
||||
edition: '2024',
|
||||
replaces: 'TOTEM_WARRIOR',
|
||||
summary: 'The 2024 totem path: a beast’s spirit rages with you.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Animal Speaker', text: 'Path of the Wild Heart. Cast Beast Sense and Speak with Animals as rituals.' },
|
||||
{ name: 'Rage of the Wilds', text: 'Each time you rage, choose. Bear: all damage but force, necrotic, psychic and radiant is halved. Eagle: Dash and Disengage as one bonus action when you rage and on later turns. Wolf: allies have advantage on attacks against enemies next to you.' },
|
||||
],
|
||||
6: [{ name: 'Aspect of the Wilds', text: 'After each long rest choose: Owl (darkvision 60 ft, or 60 ft more), Panther (climb speed), or Salmon (swim speed).' }],
|
||||
10: [{ name: 'Nature Speaker', text: 'Cast Commune with Nature as a ritual.' }],
|
||||
14: [{ name: 'Power of the Wilds', text: 'Each time you rage, choose. Falcon: fly at your speed. Lion: enemies next to you have disadvantage on attacks against anyone else. Ram: a melee hit can knock a Large or smaller creature prone.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'WORLD_TREE',
|
||||
name: 'Path of the World Tree',
|
||||
source: 'Player’s Handbook (2024)',
|
||||
edition: '2024',
|
||||
summary: 'The cosmic tree’s roots and branches move with you and your allies.',
|
||||
features: {
|
||||
3: [{ name: 'Vitality of the Tree', text: 'Path of the World Tree. When you rage, gain Temp HP equal to your level. While raging, at the start of each turn give an ally within 10 ft Temp HP: d6s equal to your rage damage bonus.' }],
|
||||
6: [{ name: 'Branches of the Tree', text: 'While raging, reaction: a creature within 30 ft makes a Strength save or is teleported next to you, and its speed is 0 until the turn ends.' }],
|
||||
10: [{ name: 'Battering Roots', text: 'Your reach with Heavy or Versatile melee weapons grows by 10 ft, and a hit can push the target 15 ft or knock it prone.' }],
|
||||
14: [{ name: 'Travel Along the Tree', text: 'When you rage, and as a bonus action while raging, teleport up to 60 ft. Once per rage, teleport up to 150 ft and take up to six willing creatures within 10 ft with you.' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = BARBARIAN;
|
||||
@@ -0,0 +1,147 @@
|
||||
// Bard subclasses: the colleges. The shape is described in index.js.
|
||||
|
||||
const BARD = [
|
||||
{
|
||||
key: 'LORE',
|
||||
name: 'College of Lore',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Knows a bit of everything, and a word to trip anyone up.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Cutting Words', text: 'College of Lore. Reaction: spend a Bardic Inspiration to subtract the die from an enemy’s attack, check or damage roll.' },
|
||||
{ name: 'Bonus Proficiencies', text: 'Treat three extra skills of your choice as proficient (add your proficiency bonus by hand).' },
|
||||
],
|
||||
6: [{ name: 'Additional Magical Secrets', text: 'Learn two spells from any class list (the DM grants them within the unlock schedule).' }],
|
||||
14: [{ name: 'Peerless Skill', text: 'When you make an ability check, spend a Bardic Inspiration and add the die to it.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'VALOR',
|
||||
name: 'College of Valor',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A skald in the front line, inspiring by example.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Combat Inspiration', text: 'College of Valor. A creature with your Bardic Inspiration may add the die to a weapon damage roll, or to its AC against one attack as a reaction.' },
|
||||
{ name: 'Battle Training', text: 'You fight in medium armor and with a shield (the DM raises Extra AC to match what you wear).' },
|
||||
],
|
||||
6: [{ name: 'Extra Attack', text: 'Attack twice when you take the Attack action.' }],
|
||||
14: [{ name: 'Battle Magic', text: 'When you cast a bard spell with your action, make one weapon attack as a bonus action.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SWORDS',
|
||||
name: 'College of Swords',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A blade dancer whose performance is the fight itself.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Fighting Style', text: 'College of Swords. Choose one with your DM: +2 damage with a one-handed weapon and nothing in the other hand, or add your ability modifier to the damage of a second weapon (added by hand).' },
|
||||
{ name: 'Blade Flourish', text: 'When you attack on your turn, +10 ft speed that turn. On a hit, spend a Bardic Inspiration and add the die to the damage, and choose: add it to your AC until your next turn, hit a second creature next to you for the die’s roll, or push the target 5 ft + the roll and follow it.' },
|
||||
],
|
||||
6: [{ name: 'Extra Attack', text: 'Attack twice when you take the Attack action.' }],
|
||||
14: [{ name: 'Master’s Flourish', text: 'Use a d6 for a Blade Flourish instead of spending a Bardic Inspiration.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'CREATION',
|
||||
name: 'College of Creation',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Sings things into being, and makes objects dance.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Mote of Potential', text: 'College of Creation. Your Bardic Inspiration comes with a mote: on an ability check roll the die twice and keep either; on an attack, a thunderclap hits creatures near the target for the die’s roll; on a save, gain Temp HP of the roll + your Charisma modifier.' },
|
||||
{ name: 'Performance of Creation', text: 'Once per long rest (or by spending a 2nd-level slot), action: create a non-magical object worth up to 20 × your level gold, for a few hours.' },
|
||||
],
|
||||
6: [{ name: 'Animating Performance', text: 'Once per long rest (or by spending a 3rd-level slot), action: animate a Large or smaller object as a Dancing Item that fights for you for an hour (the DM adds it as a monster).' }],
|
||||
14: [{ name: 'Creative Crescendo', text: 'Performance of Creation makes several objects at once (your Charisma modifier), and with no limit on their value.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'DANCE',
|
||||
name: 'College of Dance',
|
||||
source: 'Player’s Handbook (2024)',
|
||||
edition: '2024',
|
||||
summary: 'A whirling dancer who fights unarmored and moves the whole party.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Dazzling Footwork', text: 'College of Dance. Without armor or a shield: AC is 10 + Dexterity + Charisma (ask your DM to set it), advantage on Performance for dancing, unarmed strikes use Dexterity and deal your Bardic Inspiration die + Dexterity bludgeoning, and when you give Bardic Inspiration you may make an unarmed strike as part of it.' },
|
||||
],
|
||||
6: [
|
||||
{ name: 'Inspiring Movement', text: 'Reaction when an enemy ends its turn within 5 ft: spend a Bardic Inspiration to move half your speed, and one ally within 30 ft can do the same, without provoking.' },
|
||||
{ name: 'Tandem Footwork', text: 'When you roll initiative, spend a Bardic Inspiration: you and allies within 30 ft add the die to initiative.' },
|
||||
],
|
||||
14: [{ name: 'Leading Evasion', text: 'On a Dexterity save for half damage, take none on a success and half on a failure; allies within 5 ft making the same save get the same.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ELOQUENCE',
|
||||
name: 'College of Eloquence',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'The master orator: words that never fall flat.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Silver Tongue', text: 'College of Eloquence. Treat a Persuasion or Deception roll of 9 or lower as a 10.' },
|
||||
{ name: 'Unsettling Words', text: 'Bonus action: spend a Bardic Inspiration; a creature within 60 ft subtracts the die from its next save.' },
|
||||
],
|
||||
6: [
|
||||
{ name: 'Unfailing Inspiration', text: 'A creature that adds your Bardic Inspiration and still fails keeps the die.' },
|
||||
{ name: 'Universal Speech', text: 'Once per long rest, up to your Charisma modifier creatures understand you for an hour, whatever language you speak.' },
|
||||
],
|
||||
14: [{ name: 'Infectious Inspiration', text: 'A few times per long rest (Charisma modifier), reaction when a creature succeeds with your Bardic Inspiration: give a free Bardic Inspiration to another creature.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'GLAMOUR',
|
||||
name: 'College of Glamour',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Fey beauty that charms crowds and commands attention.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Mantle of Inspiration', text: 'College of Glamour. Bonus action, spend a Bardic Inspiration: up to your Charisma modifier creatures within 60 ft gain Temp HP (5, rising with level) and can move their speed without provoking.' },
|
||||
{ name: 'Enthralling Performance', text: 'After performing for a minute, up to your Charisma modifier listeners make a Wisdom save or are charmed by you for an hour.' },
|
||||
],
|
||||
6: [{ name: 'Mantle of Majesty', text: 'Once per long rest, bonus action: for a minute, cast Command as a bonus action each turn without a slot; a creature you charmed fails it automatically.' }],
|
||||
14: [{ name: 'Unbreakable Majesty', text: 'Once per short rest, bonus action for a minute: a creature that attacks you makes a Charisma save or must pick another target.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SPIRITS',
|
||||
name: 'College of Spirits',
|
||||
source: 'Van Richten’s Guide to Ravenloft',
|
||||
edition: '2014',
|
||||
summary: 'A storyteller who channels the tales of the dead.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Guiding Whispers', text: 'College of Spirits. You know Guidance, and it reaches 60 ft.' },
|
||||
{ name: 'Spiritual Focus', text: 'A candle, crystal ball or skull serves as your focus; from level 6, add a d6 to the damage or healing of your bard spells through it.' },
|
||||
{ name: 'Tales from Beyond', text: 'Bonus action, spend a Bardic Inspiration: roll it to learn a tale (the DM reads the effect). Bonus action later: tell it to a creature within 30 ft for its effect.' },
|
||||
],
|
||||
6: [{ name: 'Spirit Session', text: 'With an hour-long ritual, learn a divination or necromancy spell from any class for the day.' }],
|
||||
14: [{ name: 'Mystical Connection', text: 'When you roll a tale, roll twice and choose.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'WHISPERS',
|
||||
name: 'College of Whispers',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Secrets, fear and poison words: a bard who frightens.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Psychic Blades', text: 'College of Whispers. When you hit with a weapon, spend a Bardic Inspiration: +2d6 psychic damage (3d6 at level 5, 5d6 at 10, 8d6 at 15), once per turn.' },
|
||||
{ name: 'Words of Terror', text: 'Once per short rest, after a minute alone talking with a creature: Wisdom save or frightened of you or someone you name for an hour.' },
|
||||
],
|
||||
6: [{ name: 'Mantle of Whispers', text: 'Once per short rest, reaction when a humanoid dies within 30 ft: take its shadow and wear its appearance for an hour, knowing what it knew of its life.' }],
|
||||
14: [{ name: 'Shadow Lore', text: 'Once per long rest, action: whisper to a creature; it makes a Wisdom save or is charmed by you for 8 hours, believing you know its darkest secret.' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = BARD;
|
||||
@@ -0,0 +1,232 @@
|
||||
// Cleric subclasses: the divine domains. The shape is described in index.js.
|
||||
// A domain’s first-level gifts arrive with the choice, at level 2.
|
||||
|
||||
const CLERIC = [
|
||||
{
|
||||
key: 'LIFE',
|
||||
name: 'Life Domain',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'The healer: more from every cure, and healing in a burst.',
|
||||
features: {
|
||||
2: [{ name: 'Preserve Life', text: 'Channel Divinity. Action: share out healing of 5 × your level among creatures within 30 ft (up to half their max HP each).' }],
|
||||
6: [{ name: 'Blessed Healer', text: 'When you heal someone else with a spell, you heal yourself 2 + the spell’s level.' }],
|
||||
8: [{ name: 'Divine Strike', text: 'Once per turn, a weapon hit deals +1d8 radiant damage.' }],
|
||||
14: [{ name: 'Divine Strike', text: 'Once per turn, a weapon hit deals +2d8 radiant damage.', upgrade: true }],
|
||||
17: [{ name: 'Supreme Healing', text: 'Your healing spells heal the most their dice can roll, instead of rolling.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'LIGHT',
|
||||
name: 'Light Domain',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Fire and radiance: blinds attackers and burns the dark away.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Warding Flare', text: 'Light Domain. Reaction, a few times per day (your Wisdom modifier, at least once): a creature within 30 ft that attacks you has disadvantage on that attack.' },
|
||||
{ name: 'Radiance of the Dawn', text: 'Channel Divinity. Action: magical darkness within 30 ft is dispelled, and each enemy there takes 2d10 + your level radiant damage (Constitution save for half).' },
|
||||
],
|
||||
6: [{ name: 'Improved Flare', text: 'Use Warding Flare when a creature attacks someone else within 30 ft of you.' }],
|
||||
8: [{ name: 'Potent Spellcasting', text: 'Add your Wisdom modifier to the damage of your cleric cantrips.' }],
|
||||
17: [{ name: 'Corona of Light', text: 'Action: shine like the sun for a minute (60 ft bright light); enemies in it have disadvantage on saves against fire and radiant spells.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'WAR',
|
||||
name: 'War Domain',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A soldier of the faith: extra strikes and blows that land.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'War Priest', text: 'War Domain. A few times per day (your Wisdom modifier, at least once), after you take the Attack action, make one weapon attack as a bonus action.' },
|
||||
{ name: 'Guided Strike', text: 'Channel Divinity. When you make an attack roll, add +10 to it after seeing the roll.' },
|
||||
],
|
||||
6: [{ name: 'War God’s Blessing', text: 'Channel Divinity. Reaction: give +10 to an attack roll made by a creature within 30 ft.' }],
|
||||
8: [{ name: 'Divine Strike', text: 'Once per turn, a weapon hit deals +1d8 damage of the weapon’s type.' }],
|
||||
14: [{ name: 'Divine Strike', text: 'Once per turn, a weapon hit deals +2d8 damage of the weapon’s type.', upgrade: true }],
|
||||
17: [{ name: 'Avatar of Battle', text: 'Bludgeoning, piercing and slashing damage from non-magical attacks against you is halved.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ARCANA',
|
||||
name: 'Arcana Domain',
|
||||
source: 'Sword Coast Adventurer’s Guide',
|
||||
edition: '2014',
|
||||
summary: 'A scholar of the god of magic, at home with wizard spells.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Arcane Initiate', text: 'Arcana Domain. Treat Arcana as proficient (add the bonus by hand) and learn two wizard cantrips (the DM grants them).' },
|
||||
{ name: 'Arcane Abjuration', text: 'Channel Divinity. Action: a celestial, elemental, fey or fiend within 30 ft makes a Wisdom save or is turned for a minute; from level 5, weak ones are banished.' },
|
||||
],
|
||||
6: [{ name: 'Spell Breaker', text: 'When you heal an ally with a spell, also end one spell on them of a level no higher than the slot you used.' }],
|
||||
8: [{ name: 'Potent Spellcasting', text: 'Add your Wisdom modifier to the damage of your cleric cantrips.' }],
|
||||
17: [{ name: 'Arcane Mastery', text: 'Add one wizard spell of each of 6th, 7th, 8th and 9th level to your domain spells (the DM grants them).' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'DEATH',
|
||||
name: 'Death Domain',
|
||||
source: 'Dungeon Master’s Guide',
|
||||
edition: '2014',
|
||||
summary: 'A priest of endings: necrotic magic that ignores resistance.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Reaper', text: 'Death Domain. Learn a necromancy cantrip; when you cast one that targets one creature, you may target two within 5 ft of each other.' },
|
||||
{ name: 'Touch of Death', text: 'Channel Divinity. When you hit with a melee attack, deal an extra 5 + 2 × your level necrotic damage.' },
|
||||
],
|
||||
6: [{ name: 'Inescapable Destruction', text: 'Your necrotic damage ignores resistance to necrotic.' }],
|
||||
8: [{ name: 'Divine Strike', text: 'Once per turn, a weapon hit deals +1d8 necrotic damage (2d8 from level 14).' }],
|
||||
17: [{ name: 'Improved Reaper', text: 'When you cast a necromancy spell of 1st to 5th level that targets one creature, you may target a second within 5 ft of the first.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'FORGE',
|
||||
name: 'Forge Domain',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A smith-priest in heavy armor, blessing weapons and walking through fire.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Blessing of the Forge', text: 'Forge Domain. After a long rest, touch a weapon or suit of armor: it gets +1 to attack and damage, or +1 AC, until your next long rest.' },
|
||||
{ name: 'Artisan’s Blessing', text: 'Channel Divinity. An hour’s ritual creates a metal object worth up to 100 gold.' },
|
||||
],
|
||||
6: [{ name: 'Soul of the Forge', text: 'Fire damage against you is halved, and you gain +1 AC in heavy armor (the DM raises Extra AC by 1).' }],
|
||||
8: [{ name: 'Divine Strike', text: 'Once per turn, a weapon hit deals +1d8 fire damage (2d8 from level 14).' }],
|
||||
17: [{ name: 'Saint of Forge and Fire', text: 'Immune to fire, and in heavy armor non-magical weapon damage against you is halved.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'GRAVE',
|
||||
name: 'Grave Domain',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Guards the line between life and death, and pulls friends back from it.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Circle of Mortality', text: 'Grave Domain. Healing spells on a creature at 0 HP heal their maximum. You know Spare the Dying, at 30 ft, as a bonus action.' },
|
||||
{ name: 'Eyes of the Grave', text: 'A few times per long rest (Wisdom modifier), action: sense undead within 60 ft.' },
|
||||
{ name: 'Path to the Grave', text: 'Channel Divinity. Action: curse a creature within 30 ft; the next attack to hit it deals double damage.' },
|
||||
],
|
||||
6: [{ name: 'Sentinel at Death’s Door', text: 'A few times per long rest (Wisdom modifier), reaction: turn a critical hit on a creature within 30 ft into a normal hit.' }],
|
||||
8: [{ name: 'Potent Spellcasting', text: 'Add your Wisdom modifier to the damage of your cleric cantrips.' }],
|
||||
17: [{ name: 'Keeper of Souls', text: 'Once per round, when an enemy dies within 60 ft, you or an ally within 60 ft regains HP equal to its number of Hit Dice.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'KNOWLEDGE',
|
||||
name: 'Knowledge Domain',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A seeker of secrets who reads minds and past events.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Blessings of Knowledge', text: 'Knowledge Domain. Two extra languages, and expertise in two of Arcana, History, Nature or Religion (add double proficiency by hand).' },
|
||||
{ name: 'Knowledge of the Ages', text: 'Channel Divinity. For 10 minutes, be proficient with a skill or tool of your choice.' },
|
||||
],
|
||||
6: [{ name: 'Read Thoughts', text: 'Channel Divinity. Read the surface thoughts of a creature within 60 ft (Wisdom save); you may then cast Suggestion on it without a slot.' }],
|
||||
8: [{ name: 'Potent Spellcasting', text: 'Add your Wisdom modifier to the damage of your cleric cantrips.' }],
|
||||
17: [{ name: 'Visions of the Past', text: 'After a minute of meditation, see recent events around an object you hold or the place you are in.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'NATURE',
|
||||
name: 'Nature Domain',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A green priest who charms beasts and commands plants.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Acolyte of Nature', text: 'Nature Domain. Learn a druid cantrip, and treat one of Animal Handling, Nature or Survival as proficient.' },
|
||||
{ name: 'Charm Animals and Plants', text: 'Channel Divinity. Action: beasts and plant creatures within 30 ft make a Wisdom save or are charmed by you for a minute.' },
|
||||
],
|
||||
6: [{ name: 'Dampen Elements', text: 'Reaction: give yourself or a creature within 30 ft resistance to one instance of acid, cold, fire, lightning or thunder damage.' }],
|
||||
8: [{ name: 'Divine Strike', text: 'Once per turn, a weapon hit deals +1d8 cold, fire or lightning damage (2d8 from level 14).' }],
|
||||
17: [{ name: 'Master of Nature', text: 'Bonus action: command the creatures you have charmed with Charm Animals and Plants.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ORDER',
|
||||
name: 'Order Domain',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'A herald of law whose spells make allies strike.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Voice of Authority', text: 'Order Domain. When you cast a spell of 1st level or higher on an ally, they may use their reaction to make one weapon attack.' },
|
||||
{ name: 'Order’s Demand', text: 'Channel Divinity. Action: creatures of your choice within 30 ft make a Wisdom save or are charmed until your next turn and drop what they hold.' },
|
||||
],
|
||||
6: [{ name: 'Embodiment of the Law', text: 'A few times per long rest (Wisdom modifier), cast an enchantment spell of 1st level or higher as a bonus action.' }],
|
||||
8: [{ name: 'Divine Strike', text: 'Once per turn, a weapon hit deals +1d8 psychic damage (2d8 from level 14).' }],
|
||||
17: [{ name: 'Order’s Wrath', text: 'Once per turn, a creature you hit with Divine Strike is cursed: the next ally to hit it before your next turn deals +2d8 psychic.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'PEACE',
|
||||
name: 'Peace Domain',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Binds friends together so they protect one another.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Emboldening Bond', text: 'Peace Domain. A few times per long rest (proficiency bonus), bond up to your proficiency bonus creatures for 10 minutes: once per turn each may add a d4 to an attack, check or save while within 30 ft of another.' },
|
||||
{ name: 'Balm of Peace', text: 'Channel Divinity. Action: move up to your speed without provoking; each creature you pass within 5 ft of heals 2d6 + your Wisdom modifier.' },
|
||||
],
|
||||
6: [{ name: 'Protective Bond', text: 'When a bonded creature is about to take damage, another within 30 ft can teleport next to it and take the damage instead.' }],
|
||||
8: [{ name: 'Potent Spellcasting', text: 'Add your Wisdom modifier to the damage of your cleric cantrips.' }],
|
||||
17: [{ name: 'Expansive Bond', text: 'Your bonds reach 60 ft, and a creature taking damage for another resists it.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'TEMPEST',
|
||||
name: 'Tempest Domain',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Thunder and lightning at the god’s command.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Wrath of the Storm', text: 'Tempest Domain. A few times per long rest (Wisdom modifier), reaction when a creature within 5 ft hits you: it takes 2d8 lightning or thunder (Dexterity save for half).' },
|
||||
{ name: 'Destructive Wrath', text: 'Channel Divinity. When you roll lightning or thunder damage, deal the maximum instead.' },
|
||||
],
|
||||
6: [{ name: 'Thunderbolt Strike', text: 'When you deal lightning damage to a Large or smaller creature, push it up to 10 ft away.' }],
|
||||
8: [{ name: 'Divine Strike', text: 'Once per turn, a weapon hit deals +1d8 thunder damage (2d8 from level 14).' }],
|
||||
17: [{ name: 'Stormborn', text: 'You can fly at your walking speed whenever you are outdoors and not underground.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'TRICKERY',
|
||||
name: 'Trickery Domain',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A god of mischief’s agent: illusions, duplicates and blessings of stealth.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Blessing of the Trickster', text: 'Trickery Domain. Action: give a creature advantage on Stealth checks for an hour.' },
|
||||
{ name: 'Invoke Duplicity', text: 'Channel Divinity. Create an illusory double of yourself within 30 ft for a minute; you can cast spells as if from its space, and have advantage on attacks against creatures next to it.' },
|
||||
],
|
||||
6: [{ name: 'Cloak of Shadows', text: 'Channel Divinity. Action: turn invisible until the end of your next turn.' }],
|
||||
8: [{ name: 'Divine Strike', text: 'Once per turn, a weapon hit deals +1d8 poison damage (2d8 from level 14).' }],
|
||||
17: [{ name: 'Improved Duplicity', text: 'Invoke Duplicity makes up to four doubles, and you can move them all at once.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'TWILIGHT',
|
||||
name: 'Twilight Domain',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'A guardian of the night who keeps fear away and friends topped up.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Eyes of Night', text: 'Twilight Domain. You see in darkness to 300 ft, and can share it with allies for an hour.' },
|
||||
{ name: 'Vigilant Blessing', text: 'Action: a creature has advantage on its next initiative roll.' },
|
||||
{ name: 'Twilight Sanctuary', text: 'Channel Divinity. Action: a 30 ft sphere of dim light around you for a minute; each turn, a creature in it may gain 1d6 + your level Temp HP or end being charmed or frightened.' },
|
||||
],
|
||||
6: [{ name: 'Steps of Night', text: 'A few times per long rest (proficiency bonus), bonus action in dim light or darkness: fly at your speed for a minute.' }],
|
||||
8: [{ name: 'Divine Strike', text: 'Once per turn, a weapon hit deals +1d8 radiant damage (2d8 from level 14).' }],
|
||||
17: [{ name: 'Twilight Shroud', text: 'You and allies in your Twilight Sanctuary have half cover.' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = CLERIC;
|
||||
@@ -0,0 +1,125 @@
|
||||
// Druid subclasses: the circles. The shape is described in index.js.
|
||||
|
||||
const DRUID = [
|
||||
{
|
||||
key: 'LAND',
|
||||
name: 'Circle of the Land',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A keeper of old magic, at home in the wild places.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Natural Recovery', text: 'Once per day on a short rest, recover spent spell slots totalling up to half your level (rounded up).' },
|
||||
{ name: 'Bonus Cantrip', text: 'Learn one extra cantrip (the DM grants it).' },
|
||||
],
|
||||
6: [{ name: 'Land’s Stride', text: 'Ordinary difficult terrain and plants do not slow you; advantage on saves against magical plants.' }],
|
||||
10: [{ name: 'Nature’s Ward', text: 'Immune to poison and disease; you can’t be charmed or frightened by fey or elementals.' }],
|
||||
14: [{ name: 'Nature’s Sanctuary', text: 'Beasts and plant creatures must make a Wisdom save to attack you; on a failure they pick another target.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'MOON',
|
||||
name: 'Circle of the Moon',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A shapeshifter who fights as the beast.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Combat Wild Shape', text: 'Circle of the Moon. Use Wild Shape as a bonus action. While in beast form, bonus action: spend a spell slot to heal 1d8 per slot level.' },
|
||||
{ name: 'Circle Forms', text: 'Your Wild Shape can be a beast of up to CR 1; from level 6, up to CR equal to a third of your level (rounded down).' },
|
||||
],
|
||||
6: [{ name: 'Primal Strike', text: 'Your attacks in beast form count as magical.' }],
|
||||
10: [{ name: 'Elemental Wild Shape', text: 'Spend both uses of Wild Shape at once to become an air, earth, fire or water elemental.' }],
|
||||
14: [{ name: 'Thousand Forms', text: 'Cast Alter Self at will.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'STARS',
|
||||
name: 'Circle of Stars',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Reads the night sky and wears its constellations.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Star Map', text: 'Circle of Stars. You know the Guidance cantrip, and cast Guiding Bolt without a slot a number of times per day equal to your proficiency bonus (the DM grants both).' },
|
||||
{ name: 'Starry Form', text: 'Bonus action: spend a Wild Shape use to take a starry form for 10 minutes. Choose Archer (bonus action: ranged spell attack, 60 ft, 1d8 + Wisdom modifier radiant), Chalice (when you cast a healing spell, another creature within 30 ft heals 1d8 + Wisdom modifier) or Dragon (treat a roll of 9 or lower as 10 on Intelligence and Wisdom checks and on concentration saves).' },
|
||||
],
|
||||
6: [{ name: 'Cosmic Omen', text: 'After a long rest roll a die. Even (Weal): reaction, add 1d6 to a creature’s attack, check or save. Odd (Woe): reaction, subtract 1d6. Usable a number of times per day equal to your proficiency bonus, on creatures within 30 ft.' }],
|
||||
10: [{ name: 'Twinkling Constellations', text: 'Archer and Chalice use 2d8. In Dragon form you can fly 20 ft. At the start of each turn in Starry Form you may change constellation.' }],
|
||||
14: [{ name: 'Full of Stars', text: 'In Starry Form, bludgeoning, piercing and slashing damage against you is halved.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'DREAMS',
|
||||
name: 'Circle of Dreams',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Fey-touched healer who opens safe paths through the night.',
|
||||
features: {
|
||||
2: [{ name: 'Balm of the Summer Court', text: 'Circle of Dreams. A pool of d6s equal to your level per long rest. Bonus action: spend up to half your level of them to heal a creature within 120 ft, who also gains 1 Temp HP per die.' }],
|
||||
6: [{ name: 'Hearth of Moonlight and Shadow', text: 'During a rest, a 30 ft sphere around you gives +5 to Stealth and Perception checks and hides your camp’s light.' }],
|
||||
10: [{ name: 'Hidden Paths', text: 'A few times per long rest (Wisdom modifier), bonus action: teleport 60 ft, or action: teleport a willing creature you touch 30 ft.' }],
|
||||
14: [{ name: 'Walker in Dreams', text: 'Once per long rest, right after a short rest: cast Dream, Scrying or Teleportation Circle without a slot.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SEA',
|
||||
name: 'Circle of the Sea',
|
||||
source: 'Player’s Handbook (2024)',
|
||||
edition: '2024',
|
||||
summary: 'Wears the ocean’s fury as a stinging, storm-wrapped aura.',
|
||||
features: {
|
||||
2: [{ name: 'Wrath of the Sea', text: 'Circle of the Sea. Bonus action, spend a Wild Shape use: a 5 ft emanation of ocean spray for 10 minutes. Each turn, one creature in it takes cold damage (d6s equal to your Wisdom modifier, Constitution save for half) and may be pushed 15 ft.' }],
|
||||
6: [{ name: 'Aquatic Affinity', text: 'Your Wrath of the Sea grows to 10 ft, and you gain a swim speed equal to your walking speed.' }],
|
||||
10: [{ name: 'Stormborn', text: 'While Wrath of the Sea is active you fly at your speed and resist cold, lightning and thunder damage.' }],
|
||||
14: [{ name: 'Oceanic Gift', text: 'You can put your Wrath of the Sea around an ally instead, or around both of you by spending two uses.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SHEPHERD',
|
||||
name: 'Circle of the Shepherd',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A summoner whose spirits and beasts are stronger than anyone’s.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Speech of the Woods', text: 'Circle of the Shepherd. You speak Sylvan and can cast Speak with Animals at will.' },
|
||||
{ name: 'Spirit Totem', text: 'Once per short rest, bonus action: a spirit aura of 30 ft for a minute. Bear: allies gain 5 + your level Temp HP and advantage on Strength checks. Hawk: reaction, give an ally advantage on an attack. Unicorn: advantage on checks to detect creatures, and your healing spells heal everyone in it your level more.' },
|
||||
],
|
||||
6: [{ name: 'Mighty Summoner', text: 'Beasts and fey you summon have 2 extra HP per Hit Die, and their attacks count as magical.' }],
|
||||
10: [{ name: 'Guardian Spirit', text: 'Creatures you summon that end a turn in your Spirit Totem heal half your level.' }],
|
||||
14: [{ name: 'Faithful Summons', text: 'Once per long rest, when you drop to 0 HP or are incapacitated: four CR 2 beasts appear to protect you (as Conjure Animals).' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SPORES',
|
||||
name: 'Circle of Spores',
|
||||
source: 'Guildmasters’ Guide to Ravnica',
|
||||
edition: '2014',
|
||||
summary: 'Rot and fungus: poison the living and raise the fallen.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Halo of Spores', text: 'Circle of Spores. Reaction: a creature within 10 ft takes 1d4 necrotic (1d6 at level 6, 1d8 at 10, 1d10 at 14; Constitution save negates).' },
|
||||
{ name: 'Symbiotic Entity', text: 'Action, spend a Wild Shape use: gain 4 × your level Temp HP for 10 minutes; while they last your Halo of Spores dice double and your melee hits deal +1d6 necrotic.' },
|
||||
],
|
||||
6: [{ name: 'Fungal Infestation', text: 'A few times per long rest (Wisdom modifier), reaction when a beast or humanoid dies within 10 ft: it rises as a 1 HP zombie under your command for an hour.' }],
|
||||
10: [{ name: 'Spreading Spores', text: 'Bonus action while Symbiotic Entity is active: hurl your spores into a 10 ft cube up to 30 ft away, which deals your Halo damage to anyone who enters or starts there.' }],
|
||||
14: [{ name: 'Fungal Body', text: 'You can’t be blinded, deafened, frightened or poisoned, and critical hits against you are normal hits unless you are incapacitated.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'WILDFIRE',
|
||||
name: 'Circle of Wildfire',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'A fire spirit companion that burns and renews in equal measure.',
|
||||
features: {
|
||||
2: [{ name: 'Summon Wildfire Spirit', text: 'Circle of Wildfire. Action, spend a Wild Shape use: a wildfire spirit appears for an hour, dealing 2d6 fire to creatures within 10 ft of it as it arrives (the DM adds it as a monster). It can teleport allies and fight beside you.' }],
|
||||
6: [{ name: 'Enhanced Bond', text: 'While your spirit is summoned, your fire spells and healing spells add +1d8, and spells can come from the spirit’s position.' }],
|
||||
10: [{ name: 'Cauterizing Flames', text: 'A few times per long rest (proficiency bonus), when a creature dies within 30 ft of you or your spirit: a flame appears there; anyone entering it can be healed or burned 2d10 + your Wisdom modifier, your choice.' }],
|
||||
14: [{ name: 'Blazing Revival', text: 'Once per long rest, when you drop to 0 HP with your spirit within 120 ft: it vanishes and you regain half your HP and stand up.' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = DRUID;
|
||||
@@ -0,0 +1,183 @@
|
||||
// Fighter subclasses: the martial archetypes. The shape is described in index.js.
|
||||
|
||||
const FIGHTER = [
|
||||
{
|
||||
key: 'CHAMPION',
|
||||
name: 'Champion',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Simple and deadly: more critical hits, more athletic.',
|
||||
features: {
|
||||
3: [{ name: 'Improved Critical', text: 'Your weapon attacks score a critical hit on a roll of 19 or 20.' }],
|
||||
7: [{ name: 'Remarkable Athlete', text: 'Add half your proficiency bonus to Strength, Dexterity and Constitution checks you are not proficient in; long jump + Strength modifier feet.' }],
|
||||
10: [{ name: 'Additional Fighting Style', text: 'Choose a second option from your Fighting Style list. (If it is +1 AC in armor, the DM raises Extra AC by 1.)' }],
|
||||
15: [{ name: 'Superior Critical', text: 'Your weapon attacks score a critical hit on a roll of 18 to 20.' }],
|
||||
18: [{ name: 'Survivor', text: 'At the start of each turn, if you are below half HP but above 0, regain 5 + your Constitution modifier HP.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'BATTLE_MASTER',
|
||||
name: 'Battle Master',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A tactician who turns each swing into a manoeuvre.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Combat Superiority', text: 'Battle Master. Four superiority dice (d8), back on a short rest. Spend one on a manoeuvre; where a save is called for the DC is 8 + proficiency bonus + Strength or Dexterity modifier.' },
|
||||
{ name: 'Manoeuvres', text: 'Choose three with your DM: Trip Attack (add the die to damage; Strength save or prone), Disarming Attack (add the die; Strength save or it drops what it holds), Pushing Attack (add the die; Strength save or pushed 15 ft), Precision Attack (add the die to an attack roll), Riposte (reaction when a creature misses you: attack it and add the die), Parry (reaction: reduce melee damage by the die + Dexterity modifier), Rally (bonus action: an ally gains the die + Charisma modifier Temp HP), Menacing Attack (add the die; Wisdom save or frightened until your next turn).' },
|
||||
],
|
||||
7: [
|
||||
{ name: 'Know Your Enemy', text: 'After a minute watching a creature, the DM tells you whether it is your equal, better or worse in two of: Strength, Dexterity, Constitution, AC, current HP, level.' },
|
||||
{ name: 'Combat Superiority', text: 'Battle Master. Five superiority dice (d8), back on a short rest. Spend one on a manoeuvre; where a save is called for the DC is 8 + proficiency bonus + Strength or Dexterity modifier.', upgrade: true },
|
||||
{ name: 'Manoeuvres', text: 'Choose two more with your DM (five in all) from the list on your level 3 line.' },
|
||||
],
|
||||
10: [{ name: 'Combat Superiority', text: 'Battle Master. Five superiority dice (d10), back on a short rest. Spend one on a manoeuvre; where a save is called for the DC is 8 + proficiency bonus + Strength or Dexterity modifier. Choose two more manoeuvres with your DM (seven in all).', upgrade: true }],
|
||||
15: [
|
||||
{ name: 'Relentless', text: 'When you roll initiative with no superiority dice left, regain one.' },
|
||||
{ name: 'Combat Superiority', text: 'Battle Master. Six superiority dice (d10), back on a short rest. Spend one on a manoeuvre; where a save is called for the DC is 8 + proficiency bonus + Strength or Dexterity modifier. Choose two more manoeuvres with your DM (nine in all).', upgrade: true },
|
||||
],
|
||||
18: [{ name: 'Combat Superiority', text: 'Battle Master. Six superiority dice (d12), back on a short rest. Spend one on a manoeuvre; where a save is called for the DC is 8 + proficiency bonus + Strength or Dexterity modifier. Nine manoeuvres in all.', upgrade: true }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SAMURAI',
|
||||
name: 'Samurai',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Unbreakable resolve: strikes with advantage and shrugs off blows.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Fighting Spirit', text: 'Samurai. Three times per long rest, bonus action: advantage on all weapon attacks this turn and gain 5 Temp HP.' },
|
||||
{ name: 'Bonus Proficiency', text: 'Treat one of History, Insight, Performance or Persuasion as proficient (add your proficiency bonus by hand).' },
|
||||
],
|
||||
7: [{ name: 'Elegant Courtier', text: 'Add your Wisdom modifier to Persuasion checks, and treat Wisdom saves as proficient (both added by hand).' }],
|
||||
10: [
|
||||
{ name: 'Tireless Spirit', text: 'If you roll initiative with no uses of Fighting Spirit left, you regain one.' },
|
||||
{ name: 'Fighting Spirit', text: 'Samurai. Three times per long rest, bonus action: advantage on all weapon attacks this turn and gain 10 Temp HP.', upgrade: true },
|
||||
],
|
||||
15: [
|
||||
{ name: 'Rapid Strike', text: 'Once per turn, when you have advantage on an attack, give it up to make one extra attack.' },
|
||||
{ name: 'Fighting Spirit', text: 'Samurai. Three times per long rest, bonus action: advantage on all weapon attacks this turn and gain 15 Temp HP.', upgrade: true },
|
||||
],
|
||||
18: [{ name: 'Strength Before Death', text: 'Once per long rest, when you drop to 0 HP: take a full extra turn right away before you fall.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ARCANE_ARCHER',
|
||||
name: 'Arcane Archer',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Elven archery that wraps each arrow in a spell.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Arcane Archer Lore', text: 'Arcane Archer. Treat Arcana or Nature as proficient, and learn Prestidigitation or Druidcraft.' },
|
||||
{ name: 'Arcane Shot', text: 'Twice per short rest, when you hit with a bow: add an arcane effect (choose two to know, more later): Banishing, Beguiling, Bursting (2d6 force to all within 10 ft), Enfeebling, Grasping, Piercing (a 30 ft line), Seeking (finds a hidden target), Shadow (blinds).' },
|
||||
],
|
||||
7: [
|
||||
{ name: 'Magic Arrow', text: 'Your arrows count as magical.' },
|
||||
{ name: 'Curving Shot', text: 'Bonus action when you miss with a magic arrow: reroll the attack against another target within 60 ft of the first.' },
|
||||
],
|
||||
10: [{ name: 'Arcane Shot', text: 'Learn one more Arcane Shot option (three in all); damage from shots grows to 4d6 at level 18.' }],
|
||||
15: [{ name: 'Ever-Ready Shot', text: 'When you roll initiative with no Arcane Shots left, regain one.' }],
|
||||
18: [{ name: 'Arcane Shot', text: 'Your Arcane Shot effects deal their improved damage.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'CAVALIER',
|
||||
name: 'Cavalier',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A mounted guardian who holds the line and punishes anyone who ignores them.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Born to the Saddle', text: 'Cavalier. Advantage on saves against falling off your mount; mounting or dismounting costs 5 ft of movement.' },
|
||||
{ name: 'Unwavering Mark', text: 'When you hit a creature, mark it until your next turn: it has disadvantage on attacks against anyone else, and if it damages someone else you may attack it as a bonus action with advantage, adding half your level to the damage.' },
|
||||
],
|
||||
7: [{ name: 'Warding Maneuver', text: 'A few times per long rest (Constitution modifier), reaction: add 1d8 to an adjacent ally’s AC against an attack; if it still hits, it takes half damage.' }],
|
||||
10: [{ name: 'Hold the Line', text: 'Creatures provoke opportunity attacks from you when they move 5 ft or more within your reach; a hit stops them.' }],
|
||||
15: [{ name: 'Ferocious Charger', text: 'Once per turn, after moving 10 ft straight before a hit, the target makes a Strength save or is knocked prone.' }],
|
||||
18: [{ name: 'Vigilant Defender', text: 'You get a special reaction on every other creature’s turn, used only for opportunity attacks.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ECHO_KNIGHT',
|
||||
name: 'Echo Knight',
|
||||
source: 'Explorer’s Guide to Wildemount',
|
||||
edition: '2014',
|
||||
summary: 'Fights from two places at once with an echo of a possible self.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Manifest Echo', text: 'Echo Knight. Bonus action: a translucent echo of you appears within 15 ft (AC 14 + proficiency bonus, 1 HP). You can attack from its space, swap places with it (15 ft of movement), and it moves 30 ft as a bonus action.' },
|
||||
{ name: 'Unleash Incarnation', text: 'A few times per long rest (Constitution modifier), when you take the Attack action: make one extra attack from your echo’s position.' },
|
||||
],
|
||||
7: [{ name: 'Echo Avatar', text: 'Action: see and hear through your echo for 10 minutes; it can travel up to 1,000 ft away.' }],
|
||||
10: [{ name: 'Shadow Martyr', text: 'Once per short rest, reaction: your echo teleports in front of an ally and takes the attack instead.' }],
|
||||
15: [{ name: 'Reclaim Potential', text: 'A few times per long rest (Constitution modifier), when your echo is destroyed: gain 2d6 + Constitution modifier Temp HP.' }],
|
||||
18: [{ name: 'Legion of One', text: 'You can have two echoes at once, and you regain a use of Unleash Incarnation when you roll initiative with none.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ELDRITCH_KNIGHT',
|
||||
name: 'Eldritch Knight',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A warrior who weaves wizard spells between sword strokes.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Spellcasting', text: 'Eldritch Knight. You cast wizard spells (mostly abjuration and evocation) with Intelligence, as a third caster: the DM grants spells within the unlock schedule.' },
|
||||
{ name: 'Weapon Bond', text: 'Bond with up to two weapons: they can’t be disarmed from you, and you can summon one to your hand as a bonus action.' },
|
||||
],
|
||||
7: [{ name: 'War Magic', text: 'When you cast a cantrip with your action, make one weapon attack as a bonus action.' }],
|
||||
10: [{ name: 'Eldritch Strike', text: 'A creature you hit with a weapon has disadvantage on its next save against a spell you cast before the end of your next turn.' }],
|
||||
15: [{ name: 'Arcane Charge', text: 'When you use Action Surge, teleport up to 30 ft.' }],
|
||||
18: [{ name: 'Improved War Magic', text: 'When you cast a spell with your action, make one weapon attack as a bonus action.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'PSI_WARRIOR',
|
||||
name: 'Psi Warrior',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Telekinetic force behind every blow and shield.',
|
||||
features: {
|
||||
3: [{ name: 'Psionic Power', text: 'Psi Warrior. Psionic dice (twice your proficiency bonus, d6, growing to d12), back on a long rest. Protective Field: reaction, reduce damage to someone within 30 ft by a die + Intelligence modifier. Psionic Strike: +a die + Intelligence modifier force on a hit. Telekinetic Movement: move an object or ally 30 ft.' }],
|
||||
7: [{ name: 'Telekinetic Adept', text: 'Psi-Powered Leap: bonus action, fly twice your speed this turn. Telekinetic Thrust: when you use Psionic Strike, the target makes a Strength save or is pushed 10 ft or knocked prone.' }],
|
||||
10: [{ name: 'Guarded Mind', text: 'Psychic damage against you is halved; spend a psionic die to end being charmed or frightened.' }],
|
||||
15: [{ name: 'Bulwark of Force', text: 'Once per long rest, bonus action: up to your Intelligence modifier creatures gain half cover for a minute.' }],
|
||||
18: [{ name: 'Telekinetic Master', text: 'Once per long rest, cast Telekinesis without a slot; while concentrating on it, make one weapon attack as a bonus action each turn.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'PURPLE_DRAGON_KNIGHT',
|
||||
name: 'Purple Dragon Knight (Banneret)',
|
||||
source: 'Sword Coast Adventurer’s Guide',
|
||||
edition: '2014',
|
||||
summary: 'A battlefield leader whose second winds heal the whole squad.',
|
||||
features: {
|
||||
3: [{ name: 'Rallying Cry', text: 'Purple Dragon Knight. When you use Second Wind, up to three allies within 60 ft regain HP equal to your level.' }],
|
||||
7: [{ name: 'Royal Envoy', text: 'Treat Persuasion as proficient, and double your proficiency bonus on it (add by hand).' }],
|
||||
10: [{ name: 'Inspiring Surge', text: 'When you use Action Surge, one ally within 60 ft can make a weapon attack with its reaction.' }],
|
||||
15: [{ name: 'Bulwark', text: 'When you use Indomitable on an Intelligence, Wisdom or Charisma save, an ally within 60 ft who failed the same save can reroll too.' }],
|
||||
18: [{ name: 'Inspiring Surge', text: 'When you use Action Surge, two allies within 60 ft can each make a weapon attack with their reaction.', upgrade: true }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'RUNE_KNIGHT',
|
||||
name: 'Rune Knight',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Giant runes carved into your gear, and the strength to grow giant-sized.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Rune Carver', text: 'Rune Knight. Learn two runes (Cloud, Fire, Frost, Stone, Hill, Storm; more later) and inscribe them on your gear. Each has a passive gift and a once-per-short-rest power.' },
|
||||
{ name: 'Giant’s Might', text: 'A few times per long rest (proficiency bonus), bonus action for a minute: grow Large, advantage on Strength checks and saves, and +1d6 damage once per turn.' },
|
||||
],
|
||||
7: [{ name: 'Runic Shield', text: 'A few times per long rest (proficiency bonus), reaction: force an attacker to reroll its attack against an ally within 60 ft.' }],
|
||||
10: [{ name: 'Great Stature', text: 'You grow taller, and Giant’s Might deals 1d8 extra damage.' }],
|
||||
15: [{ name: 'Master of Runes', text: 'Each rune’s power can be used twice per short rest.' }],
|
||||
18: [{ name: 'Runic Juggernaut', text: 'Giant’s Might deals 1d10, lets you grow Huge, and adds 5 ft of reach.' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = FIGHTER;
|
||||
@@ -0,0 +1,84 @@
|
||||
// Subclasses: the path a character takes within their class, one file per
|
||||
// class. Every official subclass is here (2014 books, and the 2024 Player’s
|
||||
// Handbook where it brought a new one), as listed at
|
||||
// dungeonsanddragonsfan.com/all-dnd-5e-classes-subclasses-complete-guide.
|
||||
//
|
||||
// Each entry is { key, name, source, edition, replaces?, summary, features }.
|
||||
// - `key` is unique across all classes; it is what Character.subclass holds.
|
||||
// - `source` is the book, `edition` '2014' or '2024'.
|
||||
// - `replaces` names the 2014 subclass a 2024 one updates (Wild Heart for the
|
||||
// Totem Warrior). A character on the old one can switch to the new.
|
||||
// - `features` are by character level, in the same shape as LEVEL_FEATURES
|
||||
// (levelFeatures.js): each becomes a line of the special abilities, and an
|
||||
// `upgrade` rewrites the line that already has its name. A subclass's gifts
|
||||
// from before its class chooses (a cleric domain's 1st-level ones) arrive
|
||||
// with the choice. None of it feeds the calculation engine.
|
||||
//
|
||||
// The first subclass of each class is the path every character of that class
|
||||
// followed before subclasses could be chosen (the Champion fighter, the Life
|
||||
// cleric...), and the one a campaign without subclasses gives everybody. Its
|
||||
// lines are word for word what the class tables used to write, so sheets
|
||||
// written back then still match.
|
||||
|
||||
// The level at which a class chooses.
|
||||
const SUBCLASS_LEVEL = {
|
||||
ARTIFICER: 3,
|
||||
BARBARIAN: 3,
|
||||
BARD: 3,
|
||||
CLERIC: 2,
|
||||
DRUID: 2,
|
||||
FIGHTER: 3,
|
||||
MONK: 3,
|
||||
PALADIN: 3,
|
||||
RANGER: 3,
|
||||
ROGUE: 3,
|
||||
SORCERER: 3,
|
||||
WARLOCK: 3,
|
||||
WIZARD: 2,
|
||||
};
|
||||
|
||||
const SUBCLASSES = {
|
||||
ARTIFICER: require('./artificer'),
|
||||
BARBARIAN: require('./barbarian'),
|
||||
BARD: require('./bard'),
|
||||
CLERIC: require('./cleric'),
|
||||
DRUID: require('./druid'),
|
||||
FIGHTER: require('./fighter'),
|
||||
MONK: require('./monk'),
|
||||
PALADIN: require('./paladin'),
|
||||
RANGER: require('./ranger'),
|
||||
ROGUE: require('./rogue'),
|
||||
SORCERER: require('./sorcerer'),
|
||||
WARLOCK: require('./warlock'),
|
||||
WIZARD: require('./wizard'),
|
||||
};
|
||||
|
||||
function subclassesOf(characterClass) {
|
||||
return SUBCLASSES[characterClass] || [];
|
||||
}
|
||||
|
||||
// One subclass of a class by its key; null when the class has no such subclass.
|
||||
function findSubclass(characterClass, key) {
|
||||
return subclassesOf(characterClass).find((subclass) => subclass.key === key) || null;
|
||||
}
|
||||
|
||||
function subclassName(characterClass, key) {
|
||||
const subclass = findSubclass(characterClass, key);
|
||||
return subclass ? subclass.name : null;
|
||||
}
|
||||
|
||||
// The path a class followed before subclasses could be chosen.
|
||||
function defaultSubclass(characterClass) {
|
||||
return subclassesOf(characterClass)[0] || null;
|
||||
}
|
||||
|
||||
// The 2024 subclass that updates this one, if there is one.
|
||||
function newerVersionOf(characterClass, key) {
|
||||
return subclassesOf(characterClass).find((subclass) => subclass.replaces === key) || null;
|
||||
}
|
||||
|
||||
// What a list of subclasses to choose from shows of each: everything but the
|
||||
// features.
|
||||
const subclassSummary = ({ key, name, summary, source, edition, replaces = null }) => ({ key, name, summary, source, edition, replaces });
|
||||
|
||||
module.exports = { SUBCLASS_LEVEL, SUBCLASSES, subclassesOf, findSubclass, subclassName, defaultSubclass, newerVersionOf, subclassSummary };
|
||||
@@ -0,0 +1,171 @@
|
||||
// Monk subclasses: the monastic traditions. The shape is described in index.js.
|
||||
|
||||
const MONK = [
|
||||
{
|
||||
key: 'OPEN_HAND',
|
||||
name: 'Way of the Open Hand',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Pure martial arts: knocks down, pushes away, heals itself.',
|
||||
features: {
|
||||
3: [{ name: 'Open Hand Technique', text: 'Flurry hits can knock a target prone (Dexterity save), push it 15 ft (Strength save) or stop its reactions.' }],
|
||||
6: [{ name: 'Wholeness of Body', text: 'Once per long rest, heal 3 × your level as an action.' }],
|
||||
11: [{ name: 'Tranquility', text: 'After a long rest you are under Sanctuary until your next long rest or until you attack or cast on someone.' }],
|
||||
17: [{ name: 'Quivering Palm', text: '3 ki on an unarmed hit: set up vibrations. Later, as an action, end them: the target makes a Constitution save or drops to 0 HP; on a success it takes 10d10 necrotic.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SHADOW',
|
||||
name: 'Way of Shadow',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A ninja: steps between shadows and strikes unseen.',
|
||||
features: {
|
||||
3: [{ name: 'Shadow Arts', text: 'Way of Shadow. 2 ki: cast Darkness, Darkvision, Pass without Trace or Silence without a slot. You can also make a small illusion at will.' }],
|
||||
6: [{ name: 'Shadow Step', text: 'Bonus action, while in dim light or darkness: teleport up to 60 ft to another dim or dark spot you can see, and have advantage on your first melee attack this turn.' }],
|
||||
11: [{ name: 'Cloak of Shadows', text: 'Action, in dim light or darkness: turn invisible until you attack, cast or step into bright light.' }],
|
||||
17: [{ name: 'Opportunist', text: 'Reaction: when a creature within 5 ft is hit by someone else’s attack, make a melee attack against it.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'FOUR_ELEMENTS',
|
||||
name: 'Way of the Four Elements',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Bends fire, water, earth and air with ki.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Elemental Attunement', text: 'Way of the Four Elements. Action: a harmless trick of fire, water, earth or air within 30 ft (light or snuff a flame, chill or warm, shape a little earth or mist).' },
|
||||
{ name: 'Elemental Disciplines', text: 'Choose one with your DM: Fangs of the Fire Snake (1 ki: your unarmed reach is 10 ft this turn and hits deal fire damage; +1 ki for +1d10 fire), Fist of Unbroken Air (2 ki: one creature within 30 ft takes 3d10 bludgeoning, is pushed 20 ft and knocked prone; Strength save for half and no push), Water Whip (2 ki: one creature within 30 ft takes 3d10 bludgeoning and is pulled 25 ft or knocked prone; Dexterity save for half), Shape the Flowing River (1 ki: reshape or freeze water or ice in a 30 ft cube).' },
|
||||
],
|
||||
6: [{ name: 'Elemental Disciplines', text: 'Choose one more with your DM (two in all). New at this level: Gong of the Summit (3 ki: cast Shatter), Clench of the North Wind (3 ki: cast Hold Person).' }],
|
||||
11: [{ name: 'Elemental Disciplines', text: 'Choose one more with your DM (three in all). New at this level: Flames of the Phoenix (4 ki: cast Fireball), Eternal Mountain Defense (5 ki: cast Stoneskin on yourself).', upgrade: true }],
|
||||
17: [{ name: 'Elemental Disciplines', text: 'Choose one more with your DM (four in all). New at this level: Breath of Winter (6 ki: cast Cone of Cold), River of Hungry Flame (5 ki: cast Wall of Fire), Wave of Rolling Earth (6 ki: cast Wall of Stone).', upgrade: true }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ASCENDANT_DRAGON',
|
||||
name: 'Way of the Ascendant Dragon',
|
||||
source: 'Fizban’s Treasury of Dragons',
|
||||
edition: '2014',
|
||||
summary: 'Draconic breath and wings, channelled through ki.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Draconic Disciple', text: 'Way of the Ascendant Dragon. Your unarmed strikes can deal acid, cold, fire, lightning or poison damage; you can reroll a failed Intimidation or Persuasion check once per long rest.' },
|
||||
{ name: 'Breath of the Dragon', text: 'Replace one attack with a 20 ft cone or 30 ft line of draconic breath: two martial arts dice of your element (Dexterity save for half). Free a few times per long rest (proficiency bonus), then 2 ki.' },
|
||||
],
|
||||
6: [{ name: 'Wings Unfurled', text: 'When you use Step of the Wind, sprout wings and fly until the end of the turn (a few times per long rest).' }],
|
||||
11: [{ name: 'Aspect of the Wyrm', text: 'Bonus action, 3 ki: a 10 ft aura of frightful presence or elemental resistance for a minute.' }],
|
||||
17: [{ name: 'Ascendant Aspect', text: 'Blindsight 10 ft; Breath of the Dragon uses three dice; when you hit with the breath, deal extra damage to creatures in your aura.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ASTRAL_SELF',
|
||||
name: 'Way of the Astral Self',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Summons spectral arms, then a whole astral body, to fight.',
|
||||
features: {
|
||||
3: [{ name: 'Arms of the Astral Self', text: 'Way of the Astral Self. Bonus action, 1 ki: spectral arms for 10 minutes. Wisdom replaces Strength for checks and saves, your reach is 10 ft, and arm strikes deal force using Dexterity or Wisdom.' }],
|
||||
6: [{ name: 'Visage of the Astral Self', text: 'Bonus action, 1 ki: an astral mask for 10 minutes: darkvision 120 ft, advantage on Insight and Intimidation, and you can speak to one creature alone.' }],
|
||||
11: [{ name: 'Body of the Astral Self', text: 'With arms and visage summoned: reaction, reduce acid, cold, fire, force, lightning or thunder damage by 1d10 + Wisdom modifier; once per turn an arm hit deals +1 martial arts die.' }],
|
||||
17: [{ name: 'Awakened Astral Self', text: 'Bonus action, 5 ki: your whole astral self appears for 10 minutes: +2 AC, and three arm attacks when you take the Attack action.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'DRUNKEN_MASTER',
|
||||
name: 'Way of the Drunken Master',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Sways, staggers and somehow never gets hit.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Bonus Proficiencies', text: 'Way of the Drunken Master. Treat Performance as proficient, and you are proficient with brewer’s supplies.' },
|
||||
{ name: 'Drunken Technique', text: 'When you use Flurry of Blows, you also gain Disengage and +10 ft speed this turn.' },
|
||||
],
|
||||
6: [{ name: 'Tipsy Sway', text: 'Leap to Your Feet: standing up costs only 5 ft. Redirect Attack: reaction, 1 ki, when a creature misses you, turn its attack onto another creature next to you.' }],
|
||||
11: [{ name: 'Drunkard’s Luck', text: '2 ki: cancel disadvantage on a check, attack or save.' }],
|
||||
17: [{ name: 'Intoxicated Frenzy', text: 'When you use Flurry of Blows, make up to three extra attacks, each against a different creature.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'KENSEI',
|
||||
name: 'Way of the Kensei',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A weapon master who makes chosen weapons part of their martial arts.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Path of the Kensei', text: 'Way of the Kensei. Choose two kensei weapons with your DM (one melee, one ranged): they count as monk weapons. Agile Parry: after an unarmed strike, +2 AC while holding a kensei weapon. Kensei’s Shot: bonus action, +1d4 to ranged kensei weapon damage this turn.' },
|
||||
],
|
||||
6: [
|
||||
{ name: 'One with the Blade', text: 'Your kensei weapons count as magical.' },
|
||||
{ name: 'Deft Strike', text: 'Once per turn, 1 ki on a kensei weapon hit: add a martial arts die to the damage.' },
|
||||
],
|
||||
11: [{ name: 'Sharpen the Blade', text: 'Bonus action, up to 3 ki: a kensei weapon gains that much to attack and damage for a minute.' }],
|
||||
17: [{ name: 'Unerring Accuracy', text: 'Once per turn, reroll a missed monk weapon attack.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'LONG_DEATH',
|
||||
name: 'Way of the Long Death',
|
||||
source: 'Sword Coast Adventurer’s Guide',
|
||||
edition: '2014',
|
||||
summary: 'Studies death itself: feeds on the dying and refuses to fall.',
|
||||
features: {
|
||||
3: [{ name: 'Touch of Death', text: 'Way of the Long Death. When you reduce a creature within 5 ft to 0 HP, gain Temp HP equal to your Wisdom modifier + your level.' }],
|
||||
6: [{ name: 'Hour of Reaping', text: 'Action: creatures within 30 ft that can see you make a Wisdom save or are frightened of you until your next turn.' }],
|
||||
11: [{ name: 'Mastery of Death', text: 'When you drop to 0 HP, spend 1 ki to drop to 1 HP instead.' }],
|
||||
17: [{ name: 'Touch of the Long Death', text: 'Action, 1 to 10 ki: touch a creature; it takes 2d10 necrotic per ki (Constitution save for half).' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'MERCY',
|
||||
name: 'Way of Mercy',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'A masked healer whose touch mends friends and harms foes.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Implements of Mercy', text: 'Way of Mercy. Treat Insight and Medicine as proficient, and you are proficient with an herbalism kit.' },
|
||||
{ name: 'Hand of Healing', text: '1 ki (or in place of one Flurry strike): a creature you touch heals a martial arts die + Wisdom modifier.' },
|
||||
{ name: 'Hand of Harm', text: 'Once per turn, 1 ki on an unarmed hit: +a martial arts die + Wisdom modifier necrotic.' },
|
||||
],
|
||||
6: [{ name: 'Physician’s Touch', text: 'Hand of Healing also ends a disease or a condition (blinded, deafened, paralyzed, poisoned, stunned); Hand of Harm also poisons the target until your next turn.' }],
|
||||
11: [{ name: 'Flurry of Healing and Harm', text: 'Each Flurry of Blows strike can use Hand of Healing for free, and once per turn Hand of Harm for free.' }],
|
||||
17: [{ name: 'Hand of Ultimate Mercy', text: 'Once per long rest, 5 ki: return to life a creature dead no more than 24 hours, with 4d10 + Wisdom modifier HP.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SUN_SOUL',
|
||||
name: 'Way of the Sun Soul',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Hurls bolts of radiant ki from range.',
|
||||
features: {
|
||||
3: [{ name: 'Radiant Sun Bolt', text: 'Way of the Sun Soul. A ranged spell attack (30 ft) using Dexterity: a martial arts die + Dexterity radiant. It can replace your attacks, and Flurry can be bolts for 1 ki.' }],
|
||||
6: [{ name: 'Searing Arc Strike', text: 'After the Attack action, 2 ki (+1 per extra level): cast Burning Hands as a bonus action.' }],
|
||||
11: [{ name: 'Searing Sunburst', text: 'Action: a 20 ft burst of radiance within 150 ft: 2d6 radiant (Constitution save negates), +2d6 per 1 ki spent (up to 3).' }],
|
||||
17: [{ name: 'Sun Shield', text: 'Shed bright light at will; when a creature hits you with a melee attack, it takes 5 + Wisdom modifier radiant.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'WARRIOR_OF_ELEMENTS',
|
||||
name: 'Warrior of the Elements',
|
||||
source: 'Player’s Handbook (2024)',
|
||||
edition: '2024',
|
||||
replaces: 'FOUR_ELEMENTS',
|
||||
summary: 'The 2024 elemental monk: elemental reach and bursts, simpler to run.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Elemental Attunement', text: 'Warrior of the Elements. 1 ki: for 10 minutes your unarmed reach grows 10 ft, your strikes can deal acid, cold, fire, lightning or thunder, and a hit can push or pull the target 10 ft (Strength save).' },
|
||||
{ name: 'Manipulate Elements', text: 'You know Elementalism.' },
|
||||
],
|
||||
6: [{ name: 'Elemental Burst', text: 'Action, 2 ki: a 20 ft sphere within 120 ft; three martial arts dice of an element (Dexterity save for half).' }],
|
||||
11: [{ name: 'Stride of the Elements', text: 'While attuned, you have a fly and swim speed equal to your walking speed.' }],
|
||||
17: [{ name: 'Elemental Epitome', text: 'While attuned: resistance to one element, Step of the Wind adds 20 ft and damages those you pass, and once per turn a strike deals +a martial arts die.' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = MONK;
|
||||
@@ -0,0 +1,150 @@
|
||||
// Paladin subclasses: the sacred oaths. The shape is described in index.js.
|
||||
|
||||
const PALADIN = [
|
||||
{
|
||||
key: 'DEVOTION',
|
||||
name: 'Oath of Devotion',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'The shining knight: honesty, courage, a blessed blade.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Sacred Weapon', text: 'Oath of Devotion, Channel Divinity. Add your Charisma modifier to attack rolls with your weapon for 1 minute; it sheds light.' },
|
||||
{ name: 'Turn the Unholy', text: 'Channel Divinity. Fiends and undead within 30 ft make a Wisdom save or flee for 1 minute.' },
|
||||
],
|
||||
7: [{ name: 'Aura of Devotion', text: 'You and allies within 10 ft can’t be charmed.' }],
|
||||
15: [{ name: 'Purity of Spirit', text: 'You are always under Protection from Evil and Good.' }],
|
||||
20: [{ name: 'Holy Nimbus', text: 'Once per long rest, action for a minute: bright light 30 ft; enemies starting a turn in it take 10 radiant, and you have advantage on saves against fiend and undead spells.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ANCIENTS',
|
||||
name: 'Oath of the Ancients',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A green knight who guards life, light and laughter.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Nature’s Wrath', text: 'Oath of the Ancients, Channel Divinity. Spectral vines restrain a creature within 10 ft (Strength or Dexterity save; it repeats the save at the end of each of its turns).' },
|
||||
{ name: 'Turn the Faithless', text: 'Channel Divinity. Fey and fiends within 30 ft make a Wisdom save or flee for 1 minute.' },
|
||||
],
|
||||
7: [{ name: 'Aura of Warding', text: 'You and allies within 10 ft take half damage from spells.' }],
|
||||
15: [{ name: 'Undying Sentinel', text: 'Once per long rest, when you drop to 0 HP and are not killed, drop to 1 HP instead. You no longer suffer the frailty of old age.' }],
|
||||
20: [{ name: 'Elder Champion', text: 'Once per long rest, action for a minute: regain 10 HP each turn, cast paladin spells as a bonus action, and enemies within 10 ft have disadvantage on saves against your spells and Channel Divinity.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'VENGEANCE',
|
||||
name: 'Oath of Vengeance',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A relentless hunter of one sworn enemy at a time.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Vow of Enmity', text: 'Oath of Vengeance, Channel Divinity. Bonus action: for 1 minute you have advantage on attack rolls against one creature within 10 ft.' },
|
||||
{ name: 'Abjure Enemy', text: 'Channel Divinity. One creature within 60 ft makes a Wisdom save or is frightened and cannot move for 1 minute; on a success its speed is halved.' },
|
||||
],
|
||||
7: [{ name: 'Relentless Avenger', text: 'When you hit with an opportunity attack, move up to half your speed straight afterwards without provoking attacks.' }],
|
||||
15: [{ name: 'Soul of Vengeance', text: 'Reaction: when the target of your Vow of Enmity attacks, make a melee attack against it.' }],
|
||||
20: [{ name: 'Avenging Angel', text: 'Once per long rest, action for an hour: wings (fly 60 ft) and a 30 ft aura; enemies entering it make a Wisdom save or are frightened, and attacks against them have advantage.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'CONQUEST',
|
||||
name: 'Oath of Conquest',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Rules through fear: enemies who can’t run and can’t win.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Conquering Presence', text: 'Oath of Conquest, Channel Divinity. Action: creatures of your choice within 30 ft make a Wisdom save or are frightened for a minute.' },
|
||||
{ name: 'Guided Strike', text: 'Channel Divinity. Add +10 to an attack roll after seeing it.' },
|
||||
],
|
||||
7: [{ name: 'Aura of Conquest', text: 'A creature frightened of you within 10 ft has speed 0 and takes psychic damage of half your level when it starts its turn there.' }],
|
||||
15: [{ name: 'Scornful Rebuke', text: 'A creature that hits you takes psychic damage equal to your Charisma modifier.' }],
|
||||
20: [{ name: 'Invincible Conqueror', text: 'Once per long rest, action for a minute: all damage against you is halved, you attack one extra time with the Attack action, and you crit on 19–20.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'CROWN',
|
||||
name: 'Oath of the Crown',
|
||||
source: 'Sword Coast Adventurer’s Guide',
|
||||
edition: '2014',
|
||||
summary: 'A loyal protector who takes the blows meant for others.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Champion Challenge', text: 'Oath of the Crown, Channel Divinity. Bonus action: creatures of your choice within 30 ft make a Wisdom save or can’t willingly move more than 30 ft away from you.' },
|
||||
{ name: 'Turn the Tide', text: 'Channel Divinity. Bonus action: each creature of your choice within 30 ft below half HP heals 1d6 + your Charisma modifier.' },
|
||||
],
|
||||
7: [{ name: 'Divine Allegiance', text: 'Reaction: when a creature within 5 ft takes damage, take it yourself instead.' }],
|
||||
15: [{ name: 'Unyielding Spirit', text: 'Advantage on saves against being paralyzed or stunned.' }],
|
||||
20: [{ name: 'Exalted Champion', text: 'Once per long rest, action for an hour: non-magical weapon damage against you is halved, and you and allies within 30 ft have advantage on death saves and Wisdom saves.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'GLORY',
|
||||
name: 'Oath of Glory',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'A hero of legend: athletic feats and inspiring smites.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Peerless Athlete', text: 'Oath of Glory, Channel Divinity. Bonus action for 10 minutes: advantage on Athletics and Acrobatics, carry twice as much, and jump 10 ft further.' },
|
||||
{ name: 'Inspiring Smite', text: 'Channel Divinity. Right after a Divine Smite: share 2d8 + your level Temp HP among creatures within 30 ft.' },
|
||||
],
|
||||
7: [{ name: 'Aura of Alacrity', text: '+10 ft speed; allies who start their turn within 5 ft of you gain +10 ft too.' }],
|
||||
15: [{ name: 'Glorious Defense', text: 'A few times per long rest (Charisma modifier), reaction: add your Charisma modifier to the AC of someone within 10 ft against an attack; if it misses, you may attack the attacker.' }],
|
||||
20: [{ name: 'Living Legend', text: 'Once per long rest, bonus action for a minute: advantage on Charisma checks, once per turn turn a miss into a hit, and reroll a failed save.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'OATHBREAKER',
|
||||
name: 'Oathbreaker',
|
||||
source: 'Dungeon Master’s Guide',
|
||||
edition: '2014',
|
||||
summary: 'A fallen paladin who commands the undead and feeds on fear.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Control Undead', text: 'Oathbreaker, Channel Divinity. Action: an undead within 30 ft makes a Wisdom save or obeys you for 24 hours.' },
|
||||
{ name: 'Dreadful Aspect', text: 'Channel Divinity. Action: creatures of your choice within 30 ft make a Wisdom save or are frightened for a minute.' },
|
||||
],
|
||||
7: [{ name: 'Aura of Hate', text: 'You, and fiends and undead within 10 ft, add your Charisma modifier to melee weapon damage.' }],
|
||||
15: [{ name: 'Supernatural Resistance', text: 'Non-magical bludgeoning, piercing and slashing damage against you is halved.' }],
|
||||
20: [{ name: 'Dread Lord', text: 'Once per long rest, action for a minute: a 30 ft aura of gloom; enemies starting in it take 4d10 psychic, and you can attack with shadows as a bonus action (3d10 necrotic).' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'REDEMPTION',
|
||||
name: 'Oath of Redemption',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Prefers peace, and makes violence hurt the one who started it.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Emissary of Peace', text: 'Oath of Redemption, Channel Divinity. +5 to Persuasion checks for 10 minutes.' },
|
||||
{ name: 'Rebuke the Violent', text: 'Channel Divinity. Reaction: when an attacker damages someone within 30 ft, it takes radiant damage equal to the damage it dealt (Wisdom save for half).' },
|
||||
],
|
||||
7: [{ name: 'Aura of the Guardian', text: 'Reaction: when a creature within 10 ft takes damage, take it yourself instead.' }],
|
||||
15: [{ name: 'Protective Spirit', text: 'At the end of each turn, if below half HP, heal 1d6 + half your level.' }],
|
||||
20: [{ name: 'Emissary of Redemption', text: 'All damage against you is halved, and a creature that damages you takes radiant damage equal to half of it (until you attack or cast on it).' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'WATCHERS',
|
||||
name: 'Oath of the Watchers',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Guards the world from extraplanar intruders, alert to every threat.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Watcher’s Will', text: 'Oath of the Watchers, Channel Divinity. Up to your Charisma modifier creatures within 30 ft have advantage on Intelligence, Wisdom and Charisma saves for a minute.' },
|
||||
{ name: 'Abjure the Extraplanar', text: 'Channel Divinity. Aberrations, celestials, elementals, fey and fiends within 30 ft make a Wisdom save or are turned for a minute.' },
|
||||
],
|
||||
7: [{ name: 'Aura of the Sentinel', text: 'You and allies within 10 ft add your proficiency bonus to initiative.' }],
|
||||
15: [{ name: 'Vigilant Rebuke', text: 'Reaction: when someone within 30 ft succeeds on an Intelligence, Wisdom or Charisma save, the creature that forced it takes 2d8 + Charisma modifier force.' }],
|
||||
20: [{ name: 'Mortal Bulwark', text: 'Once per long rest, bonus action for a minute: truesight 120 ft, advantage on attacks against extraplanar creatures, and a hit can banish one (Charisma save).' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = PALADIN;
|
||||
@@ -0,0 +1,128 @@
|
||||
// Ranger subclasses: the ranger conclaves. The shape is described in index.js.
|
||||
|
||||
const RANGER = [
|
||||
{
|
||||
key: 'HUNTER',
|
||||
name: 'Hunter',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Brings down the biggest thing in the room.',
|
||||
features: {
|
||||
3: [{ name: 'Colossus Slayer', text: 'Hunter’s Prey. Once per turn, +1d8 damage to a creature that is already below its max HP.' }],
|
||||
7: [{ name: 'Escape the Horde', text: 'Defensive Tactics. Opportunity attacks against you have disadvantage.' }],
|
||||
11: [{ name: 'Volley', text: 'Multiattack. Action: make a ranged attack against every creature within 10 ft of a point you can see in range.' }],
|
||||
15: [{ name: 'Uncanny Dodge', text: 'Superior Hunter’s Defense. Reaction: halve the damage of an attack that hits you.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'BEAST_MASTER',
|
||||
name: 'Beast Master',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Fights beside an animal companion.',
|
||||
features: {
|
||||
3: [{ name: 'Ranger’s Companion', text: 'Beast Master. A beast of CR 1/4 or lower fights beside you (the DM adds it to encounters as a monster). It acts on your turn: it can move freely, and attacks, Dashes, Disengages or Helps when you use your action to tell it to. Add your proficiency bonus to its AC, attacks and damage. If it dies, bond with another over 8 hours.' }],
|
||||
7: [{ name: 'Exceptional Training', text: 'On a turn your companion does not attack, it can Dash, Disengage or Help as your bonus action. Its attacks count as magical.' }],
|
||||
11: [{ name: 'Bestial Fury', text: 'When you command your companion to attack, it can attack twice.' }],
|
||||
15: [{ name: 'Share Spells', text: 'When you cast a spell targeting yourself, it can also affect your companion if within 30 ft.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'GLOOM_STALKER',
|
||||
name: 'Gloom Stalker',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'An ambusher who owns the first round and the dark.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Dread Ambusher', text: 'Gloom Stalker. Add your Wisdom modifier to initiative (ask your DM to count it). On your first turn of a fight: +10 ft speed and one extra weapon attack, which deals +1d8 damage on a hit.' },
|
||||
{ name: 'Umbral Sight', text: 'You see in darkness to 60 ft, and creatures that rely on darkvision cannot see you in the dark.' },
|
||||
],
|
||||
7: [{ name: 'Iron Mind', text: 'Treat Wisdom saves as proficient (add your proficiency bonus by hand).' }],
|
||||
11: [{ name: 'Stalker’s Flurry', text: 'Once per turn, when you miss with a weapon attack, make another weapon attack.' }],
|
||||
15: [{ name: 'Shadowy Dodge', text: 'Reaction, when an attack without advantage targets you: give it disadvantage.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'DRAKEWARDEN',
|
||||
name: 'Drakewarden',
|
||||
source: 'Fizban’s Treasury of Dragons',
|
||||
edition: '2014',
|
||||
summary: 'Raises a drake that grows into a mount and a breath weapon.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Draconic Gift', text: 'Drakewarden. You speak Draconic and know Thaumaturgy.' },
|
||||
{ name: 'Drake Companion', text: 'Action: summon a drake (acid, cold, fire, lightning or poison) that fights beside you (the DM adds it as a monster). It acts on your turn and attacks when you command it with a bonus action; its bite deals an extra 1d6 of its element.' },
|
||||
],
|
||||
7: [{ name: 'Bond of Fang and Scale', text: 'Your drake grows Medium; you can ride it if you are Small, it can fly, you resist its element, and its bite counts as magical and deals +1d6 more.' }],
|
||||
11: [{ name: 'Drake’s Breath', text: 'Once per long rest (or by spending a 3rd-level slot), action: you or the drake exhale a 30 ft cone: 8d6 of its element (Dexterity save for half; 10d6 at level 15).' }],
|
||||
15: [{ name: 'Perfected Bond', text: 'Your drake grows Large and can carry you in flight; its bite deals +1d6 more; reaction, halve damage it takes or you take while near it.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'FEY_WANDERER',
|
||||
name: 'Fey Wanderer',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Fey charm and psychic strikes: the bewitching ranger.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Dreadful Strikes', text: 'Fey Wanderer. Once per turn per creature, a weapon hit deals +1d4 psychic (1d6 from level 11).' },
|
||||
{ name: 'Otherworldly Glamour', text: 'Add your Wisdom modifier to Charisma checks, and treat one of Deception, Performance or Persuasion as proficient.' },
|
||||
],
|
||||
7: [{ name: 'Beguiling Twist', text: 'Advantage on saves against being charmed or frightened. Reaction when someone near you resists one: another creature makes a Wisdom save or is charmed or frightened for a minute.' }],
|
||||
11: [{ name: 'Fey Reinforcements', text: 'Cast Summon Fey once per long rest without a slot or material, and you may skip concentration (lasting a minute).' }],
|
||||
15: [{ name: 'Misty Wanderer', text: 'A few times per long rest (Wisdom modifier), cast Misty Step without a slot, bringing one willing creature within 5 ft along.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'HORIZON_WALKER',
|
||||
name: 'Horizon Walker',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Guards the borders between worlds, stepping through space itself.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Detect Portal', text: 'Horizon Walker. Once per short rest, sense the distance and direction of the nearest planar portal within 1 mile.' },
|
||||
{ name: 'Planar Warrior', text: 'Bonus action: your next hit on a creature within 30 ft this turn deals all force damage and +1d8 (2d8 from level 11).' },
|
||||
],
|
||||
7: [{ name: 'Ethereal Step', text: 'Once per short rest, bonus action: step into the Ethereal Plane until the end of the turn.' }],
|
||||
11: [{ name: 'Distant Strike', text: 'When you take the Attack action, teleport 10 ft before each attack; hitting two different creatures gives one extra attack against a third.' }],
|
||||
15: [{ name: 'Spectral Defense', text: 'Reaction: halve the damage of an attack that hits you.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'MONSTER_SLAYER',
|
||||
name: 'Monster Slayer',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A specialist in one dangerous quarry at a time.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Hunter’s Sense', text: 'Monster Slayer. A few times per long rest (Wisdom modifier), action: learn a creature’s immunities, resistances and vulnerabilities.' },
|
||||
{ name: 'Slayer’s Prey', text: 'Bonus action: mark a creature within 60 ft; the first hit on it each turn deals +1d6.' },
|
||||
],
|
||||
7: [{ name: 'Supernatural Defense', text: 'When your prey forces you to save or tries to escape your grapple, add 1d6.' }],
|
||||
11: [{ name: 'Magic-User’s Nemesis', text: 'Once per short rest, reaction: a creature casting a spell or teleporting within 60 ft makes a Wisdom save or the attempt fails.' }],
|
||||
15: [{ name: 'Slayer’s Counter', text: 'Reaction when your prey forces a save: attack it; on a hit you succeed on the save automatically.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SWARMKEEPER',
|
||||
name: 'Swarmkeeper',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'A cloud of spirit insects or birds moves foes and lifts you.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Gathered Swarm', text: 'Swarmkeeper. Once per turn after a hit, your swarm either deals +1d6 piercing, pushes the target 15 ft (Strength save), or moves you 5 ft.' },
|
||||
{ name: 'Swarmkeeper Magic', text: 'You know Mage Hand, and gain extra spells from your swarm as you level.' },
|
||||
],
|
||||
7: [{ name: 'Writhing Tide', text: 'A few times per long rest (proficiency bonus), bonus action: your swarm lifts you to fly 10 ft for a minute.' }],
|
||||
11: [{ name: 'Mighty Swarm', text: 'Gathered Swarm deals 1d8, a pushed creature can also be knocked prone, and moving yourself gives you half cover.' }],
|
||||
15: [{ name: 'Swarming Dispersal', text: 'A few times per long rest (proficiency bonus), reaction when you take damage: halve it and teleport 30 ft.' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = RANGER;
|
||||
@@ -0,0 +1,151 @@
|
||||
// Rogue subclasses: the roguish archetypes. The shape is described in index.js.
|
||||
|
||||
const ROGUE = [
|
||||
{
|
||||
key: 'THIEF',
|
||||
name: 'Thief',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Quick fingers, rooftops and anything that can be used.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Fast Hands', text: 'Bonus action: Sleight of Hand, pick a lock, disarm a trap or Use an Object.' },
|
||||
{ name: 'Second-Story Work', text: 'Climbing costs no extra movement; running jumps + Dexterity modifier feet.' },
|
||||
],
|
||||
9: [{ name: 'Supreme Sneak', text: 'Advantage on Stealth if you move no more than half your speed.' }],
|
||||
13: [{ name: 'Use Magic Device', text: 'Ignore class, species and level requirements on magic items.' }],
|
||||
17: [{ name: 'Thief’s Reflexes', text: 'In the first round of a fight you take two turns: one at your initiative, one at your initiative − 10.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ASSASSIN',
|
||||
name: 'Assassin',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Strikes first, and the first strike is the worst.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Assassinate', text: 'Assassin. Advantage on attacks against any creature that has not yet taken a turn in this fight, and any hit on a surprised creature is a critical hit.' },
|
||||
{ name: 'Tools of the Trade', text: 'You are practised with disguises and poisons: advantage on checks to make or use them.' },
|
||||
],
|
||||
9: [{ name: 'Infiltration Expertise', text: 'With a week and 25 gold you build a false identity with papers and a history; nobody doubts it without an obvious reason.' }],
|
||||
13: [{ name: 'Impostor', text: 'After three hours of study, mimic a person’s speech, writing and manner perfectly; advantage on checks to avoid being found out.' }],
|
||||
17: [{ name: 'Death Strike', text: 'When you hit a surprised creature, it makes a Constitution save or takes double damage.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SWASHBUCKLER',
|
||||
name: 'Swashbuckler',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A duellist: in, strike, out, and a smile.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Fancy Footwork', text: 'Swashbuckler. A creature you made a melee attack against this turn cannot make opportunity attacks against you until the turn ends.' },
|
||||
{ name: 'Rakish Audacity', text: 'Add your Charisma modifier to initiative (ask your DM to count it). You can Sneak Attack a creature with nobody else next to you or it, without needing advantage.' },
|
||||
],
|
||||
9: [{ name: 'Panache', text: 'Action: Persuasion against a creature’s Insight. A hostile one has disadvantage on attacks against anyone but you for 1 minute; any other is charmed by you for 1 minute.' }],
|
||||
13: [{ name: 'Elegant Maneuver', text: 'Bonus action: advantage on your next Acrobatics or Athletics check this turn.' }],
|
||||
17: [{ name: 'Master Duelist', text: 'Once per short rest, reroll a missed attack with advantage.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ARCANE_TRICKSTER',
|
||||
name: 'Arcane Trickster',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A thief with wizard tricks and an invisible hand.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Spellcasting', text: 'Arcane Trickster. You cast wizard spells (mostly enchantment and illusion) with Intelligence, as a third caster: the DM grants spells within the unlock schedule.' },
|
||||
{ name: 'Mage Hand Legerdemain', text: 'Your Mage Hand is invisible, and can pick locks, disarm traps and pick pockets (bonus action to control it).' },
|
||||
],
|
||||
9: [{ name: 'Magical Ambush', text: 'When you cast a spell while hidden, the target has disadvantage on its save.' }],
|
||||
13: [{ name: 'Versatile Trickster', text: 'Bonus action: your Mage Hand distracts a creature within 5 ft of it, giving you advantage on attacks against it this turn.' }],
|
||||
17: [{ name: 'Spell Thief', text: 'Once per long rest, reaction when a spell targets you: the caster makes a save; on a failure the spell fails and you can cast it for 8 hours.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'INQUISITIVE',
|
||||
name: 'Inquisitive',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A detective who reads lies and finds the weak spot.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Ear for Deceit', text: 'Inquisitive. Treat an Insight roll of 7 or lower as an 8 when sensing lies.' },
|
||||
{ name: 'Eye for Detail', text: 'Bonus action: Perception to spot a hidden creature or object, or Investigation to uncover clues.' },
|
||||
{ name: 'Insightful Fighting', text: 'Bonus action: Insight against a creature’s Deception; on a success you can Sneak Attack it without advantage for a minute.' },
|
||||
],
|
||||
9: [{ name: 'Steady Eye', text: 'Advantage on Perception and Investigation if you move no more than half your speed.' }],
|
||||
13: [{ name: 'Unerring Eye', text: 'A few times per long rest (Wisdom modifier), action: sense illusions, shapechangers and other magical deceptions within 30 ft.' }],
|
||||
17: [{ name: 'Eye for Weakness', text: 'Sneak Attack deals +3d6 against a creature you have read with Insightful Fighting.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'MASTERMIND',
|
||||
name: 'Mastermind',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A schemer who helps from afar and reads everyone.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Master of Intrigue', text: 'Mastermind. Proficient with disguise and forgery kits and one gaming set; two extra languages; mimic accents perfectly.' },
|
||||
{ name: 'Master of Tactics', text: 'Help as a bonus action, and at a range of 30 ft.' },
|
||||
],
|
||||
9: [{ name: 'Insightful Manipulator', text: 'After a minute of watching or talking, learn how a creature compares to you in two of: Intelligence, Wisdom, Charisma, class levels.' }],
|
||||
13: [{ name: 'Misdirection', text: 'Reaction: when you are attacked while a creature gives you cover, the attack targets that creature instead.' }],
|
||||
17: [{ name: 'Soul of Deceit', text: 'Your thoughts can’t be read unless you allow it, you can show false thoughts, and magic can’t compel you to tell the truth.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'PHANTOM',
|
||||
name: 'Phantom',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Walks with the dead and borrows their skills.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Whispers of the Dead', text: 'Phantom. After a rest, gain proficiency in one skill or tool of your choice until your next rest.' },
|
||||
{ name: 'Wails from the Grave', text: 'A few times per long rest (proficiency bonus), right after Sneak Attack: a second creature within 30 ft takes half your Sneak Attack dice as necrotic.' },
|
||||
],
|
||||
9: [{ name: 'Tokens of the Departed', text: 'Reaction when a creature dies within 30 ft: make a soul trinket. While you carry one you have advantage on death and Constitution saves, and can spend it on a free Wails from the Grave.' }],
|
||||
13: [{ name: 'Ghost Walk', text: 'Bonus action: become spectral for 10 minutes: fly 10 ft, pass through objects, and attacks against you have disadvantage.' }],
|
||||
17: [{ name: 'Death’s Friend', text: 'Wails from the Grave hits both creatures with necrotic damage, and you always have a soul trinket after a long rest.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SCOUT',
|
||||
name: 'Scout',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A skirmisher of the wilds, always first to move.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Skirmisher', text: 'Scout. Reaction when an enemy ends its turn within 5 ft: move half your speed without provoking.' },
|
||||
{ name: 'Survivalist', text: 'Treat Nature and Survival as proficient, with double your proficiency bonus (add by hand).' },
|
||||
],
|
||||
9: [{ name: 'Superior Mobility', text: '+10 ft to your walking speed (and climb or swim speeds).' }],
|
||||
13: [{ name: 'Ambush Master', text: 'Advantage on initiative; in the first round, the first creature you hit is easier for everyone to hit until your next turn.' }],
|
||||
17: [{ name: 'Sudden Strike', text: 'After the Attack action, make one more attack as a bonus action; it can Sneak Attack even if you already have, against a different target.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SOULKNIFE',
|
||||
name: 'Soulknife',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Psychic blades conjured from the mind, and telepathy to match.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Psionic Power', text: 'Soulknife. Psionic dice (twice your proficiency bonus, d6, growing to d12), back on a long rest. Psi-Bolstered Knack: add a die to a failed proficient check. Psychic Whispers: link minds with allies for hours.' },
|
||||
{ name: 'Psychic Blades', text: 'Manifest blades: 1d6 psychic (finesse, thrown 60 ft), and a second blade as a bonus action for 1d4.' },
|
||||
],
|
||||
9: [{ name: 'Soul Blades', text: 'Homing Strikes: add a psionic die to a missed blade attack. Psychic Teleportation: bonus action, throw a blade and teleport up to 10 × the die’s roll in feet.' }],
|
||||
13: [{ name: 'Psychic Veil', text: 'Once per long rest (or by spending a psionic die), action: invisible for an hour, until you damage or force a save.' }],
|
||||
17: [{ name: 'Rend Mind', text: 'Once per long rest (or by spending three psionic dice), when your blade Sneak Attacks: the target makes a Wisdom save or is stunned for a minute.' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = ROGUE;
|
||||
@@ -0,0 +1,138 @@
|
||||
// Sorcerer subclasses: the sorcerous origins. The shape is described in index.js.
|
||||
// An origin’s first-level gifts arrive with the choice, at level 3.
|
||||
|
||||
const SORCERER = [
|
||||
{
|
||||
key: 'DRACONIC',
|
||||
name: 'Draconic Bloodline',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Dragon blood: tougher skin and one element at your call.',
|
||||
features: {
|
||||
3: [{ name: 'Dragon Ancestor', text: 'Draconic Bloodline. Choose a kind of dragon with your DM; its element is yours (red: fire, white: cold, blue: lightning, green: poison, black: acid). Thin scales make you hardier: without armor your AC is 13 + Dexterity, and you have 1 more maximum HP for each sorcerer level (both counted on your sheet).' }],
|
||||
6: [{ name: 'Elemental Affinity', text: 'Draconic Bloodline. Add your Charisma modifier to one damage roll of your dragon’s element; spend 1 sorcery point to resist that element for 1 hour.' }],
|
||||
14: [{ name: 'Dragon Wings', text: 'Bonus action: sprout dragon wings and fly at your speed until you dismiss them.' }],
|
||||
18: [{ name: 'Draconic Presence', text: 'Action, 5 sorcery points: for a minute, creatures within 60 ft make a Wisdom save or are charmed (awe) or frightened (fear) of you.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'WILD_MAGIC',
|
||||
name: 'Wild Magic',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Raw chaos: luck you can bend, and surprises you cannot.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Wild Magic Surge', text: 'Wild Magic. After you cast a sorcerer spell of 1st level or higher, the DM may have you roll a d20: on a 1, something strange happens (the DM decides, or rolls on a table of their own).' },
|
||||
{ name: 'Tides of Chaos', text: 'Once per long rest, gain advantage on one attack, check or save. The DM may give it back by calling for a Wild Magic Surge.' },
|
||||
],
|
||||
6: [{ name: 'Bend Luck', text: 'Reaction, 2 sorcery points: add or subtract 1d4 from another creature’s attack, check or save.' }],
|
||||
14: [{ name: 'Controlled Chaos', text: 'When you roll on the wild magic table, roll twice and use either.' }],
|
||||
18: [{ name: 'Spell Bombardment', text: 'Once per turn, when a spell’s damage dice roll their highest on a die, roll that die again and add it.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'STORM',
|
||||
name: 'Storm Sorcery',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Wind and lightning: never stands still for long.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Tempestuous Magic', text: 'Storm Sorcery. Bonus action, just before or after casting a spell of 1st level or higher: fly 10 ft without provoking opportunity attacks.' },
|
||||
{ name: 'Wind Speaker', text: 'You speak the tongue of air, water, earth and fire elementals.' },
|
||||
],
|
||||
6: [
|
||||
{ name: 'Heart of the Storm', text: 'You resist lightning and thunder damage. When you start casting a lightning or thunder spell of 1st level or higher, creatures of your choice within 10 ft take half your level in lightning or thunder damage.' },
|
||||
{ name: 'Storm Guide', text: 'Action: stop rain falling within 20 ft of you. Bonus action: choose which way the wind blows within 100 ft until your next turn.' },
|
||||
],
|
||||
14: [{ name: 'Storm’s Fury', text: 'Reaction when a creature hits you in melee: it takes lightning damage equal to your level and is pushed up to 20 ft (Strength save negates the push).' }],
|
||||
18: [{ name: 'Wind Soul', text: 'Immune to lightning and thunder; fly 60 ft. Once per short rest, give up to three creatures a 30 ft fly speed for an hour.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ABERRANT_MIND',
|
||||
name: 'Aberrant Mind',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'A psionic mind touched by the Far Realm.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Psionic Spells', text: 'Aberrant Mind. Learn psionic spells as you level (Arms of Hadar, Dissonant Whispers, Mind Sliver and more; the DM grants them).' },
|
||||
{ name: 'Telepathic Speech', text: 'Bonus action: speak mind to mind with a creature within 30 ft for minutes equal to your level.' },
|
||||
],
|
||||
6: [
|
||||
{ name: 'Psionic Sorcery', text: 'Cast a psionic spell with sorcery points equal to its level instead of a slot, with no words or gestures.' },
|
||||
{ name: 'Psychic Defenses', text: 'Psychic damage against you is halved; advantage on saves against being charmed or frightened.' },
|
||||
],
|
||||
14: [{ name: 'Revelation in Flesh', text: 'Bonus action, 1+ sorcery points, for 10 minutes: see invisible things, fly, breathe and swim underwater, or squeeze through tiny gaps.' }],
|
||||
18: [{ name: 'Warping Implosion', text: 'Once per long rest (or 5 sorcery points), action: teleport 120 ft; creatures within 30 ft of where you were take 3d10 force and are pulled in (Strength save for half).' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'CLOCKWORK_SOUL',
|
||||
name: 'Clockwork Soul',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'The cosmic order of Mechanus balances luck and shields friends.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Clockwork Magic', text: 'Clockwork Soul. Learn order-themed spells as you level (Alarm, Protection from Evil and Good, Aid…; the DM grants them).' },
|
||||
{ name: 'Restore Balance', text: 'A few times per long rest (proficiency bonus), reaction: cancel advantage or disadvantage on a roll within 60 ft.' },
|
||||
],
|
||||
6: [{ name: 'Bastion of Law', text: 'Action, 1 to 5 sorcery points: a ward of that many d8s on a creature within 30 ft, which it spends to reduce damage.' }],
|
||||
14: [{ name: 'Trance of Order', text: 'Once per long rest (or 5 sorcery points), bonus action for a minute: attacks against you lack advantage, and your attack rolls, checks and saves of 9 or lower count as 10.' }],
|
||||
18: [{ name: 'Clockwork Cavalcade', text: 'Once per long rest (or 7 sorcery points), action: a 30 ft cube of spirits restores 100 HP among those inside, repairs objects and ends spells of 6th level or lower.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'DIVINE_SOUL',
|
||||
name: 'Divine Soul',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A god’s spark: sorcery with the cleric’s spell list.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Divine Magic', text: 'Divine Soul. You can learn cleric spells as sorcerer spells, and gain one affinity spell (Cure Wounds, Inflict Wounds, Bless, Bane or Protection from Evil and Good).' },
|
||||
{ name: 'Favored by the Gods', text: 'Once per short rest, add 2d4 to a failed save or missed attack.' },
|
||||
],
|
||||
6: [{ name: 'Empowered Healing', text: '1 sorcery point: reroll healing dice for you or an ally within 5 ft.' }],
|
||||
14: [{ name: 'Otherworldly Wings', text: 'Bonus action: sprout feathered or bat-like wings and fly 30 ft until dismissed.' }],
|
||||
18: [{ name: 'Unearthly Recovery', text: 'Once per long rest, bonus action while below half HP: regain HP equal to half your maximum.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'LUNAR_SORCERY',
|
||||
name: 'Lunar Sorcery',
|
||||
source: 'Dragonlance: Shadow of the Dragon Queen',
|
||||
edition: '2014',
|
||||
summary: 'Draws power from the moon’s phases: full, new and crescent.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Lunar Embodiment', text: 'Lunar Sorcery. Learn moon spells as you level, and choose a phase after each long rest (full, new or crescent); once per long rest cast that phase’s 1st-level spell without a slot.' },
|
||||
{ name: 'Moon Fire', text: 'You know Sacred Flame, and can target two creatures within 5 ft of each other with it.' },
|
||||
],
|
||||
6: [{ name: 'Lunar Boons', text: 'A few times per long rest (proficiency bonus), reduce a spell’s sorcery-point cost for the current phase’s school by 1.' }],
|
||||
14: [{ name: 'Waxing and Waning', text: 'Bonus action, 1 sorcery point: change your phase.' }],
|
||||
18: [{ name: 'Lunar Phenomenon', text: 'Once per long rest, bonus action: unleash your phase (full: blinding light; new: dark cloud and invisibility; crescent: teleport and resistance).' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SHADOW_MAGIC',
|
||||
name: 'Shadow Magic',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Shadowfell-touched: darkness you can see through and a hound of ill omen.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Eyes of the Dark', text: 'Shadow Magic. Darkvision 120 ft; cast Darkness with 2 sorcery points and see through it.' },
|
||||
{ name: 'Strength of the Grave', text: 'Once per long rest, when you drop to 0 HP (not from radiant or a crit), make a Charisma save to drop to 1 HP instead.' },
|
||||
],
|
||||
6: [{ name: 'Hound of Ill Omen', text: 'Bonus action, 3 sorcery points: a shadow hound hunts a creature within 120 ft (the DM adds it); while it is near, the target has disadvantage on saves against your spells.' }],
|
||||
14: [{ name: 'Shadow Walk', text: 'Bonus action, in dim light or darkness: teleport up to 120 ft to another dim or dark spot.' }],
|
||||
18: [{ name: 'Umbral Form', text: 'Bonus action, 6 sorcery points, for a minute: become shadow, resisting all damage but force and radiant, and move through creatures and objects.' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = SORCERER;
|
||||
@@ -0,0 +1,140 @@
|
||||
// Warlock subclasses: the otherworldly patrons. The shape is described in index.js.
|
||||
// A patron’s first-level gifts arrive with the choice, at level 3.
|
||||
|
||||
const WARLOCK = [
|
||||
{
|
||||
key: 'FIEND',
|
||||
name: 'The Fiend',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A pact with something from the hells: power fed by the fallen.',
|
||||
features: {
|
||||
3: [{ name: 'Dark One’s Blessing', text: 'The Fiend. When you bring a hostile creature to 0 HP, gain Temp HP equal to your Charisma modifier + your level (the DM adds it).' }],
|
||||
6: [{ name: 'Patron’s Luck', text: 'Once per short rest, add a d10 to an ability check or saving throw after seeing the roll.' }],
|
||||
10: [{ name: 'Patron’s Resilience', text: 'After each rest, choose one damage type: you resist it until you choose another.' }],
|
||||
14: [{ name: 'Hurl Through Hell', text: 'Once per long rest, when you hit a creature: it vanishes into the lower planes until your next turn and takes 10d10 psychic (unless it is a fiend).' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ARCHFEY',
|
||||
name: 'The Archfey',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'A fey lord’s favourite: glamour, vanishing and beguilement.',
|
||||
features: {
|
||||
3: [{ name: 'Fey Presence', text: 'The Archfey. Once per short rest, action: each creature in a 10 ft cube from you makes a Wisdom save or is charmed or frightened (your choice) until the end of your next turn.' }],
|
||||
6: [{ name: 'Misty Escape', text: 'Once per short rest, reaction when you take damage: turn invisible and teleport up to 60 ft. You stay invisible until your next turn, or until you attack or cast.' }],
|
||||
10: [{ name: 'Beguiling Defenses', text: 'You can’t be charmed. When a creature tries, turn it back: it makes a Wisdom save or is charmed by you for 1 minute.' }],
|
||||
14: [{ name: 'Dark Delirium', text: 'Once per short rest, action: a creature within 60 ft makes a Wisdom save or is lost in an illusory realm for a minute, charmed or frightened by you.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'GREAT_OLD_ONE',
|
||||
name: 'The Great Old One',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Something vast and unknowable whispers through you.',
|
||||
features: {
|
||||
3: [{ name: 'Awakened Mind', text: 'The Great Old One. Speak mind to mind with any creature you can see within 30 ft; it needs no shared language, only to know one.' }],
|
||||
6: [{ name: 'Entropic Ward', text: 'Once per short rest, reaction: an attack against you has disadvantage. If it misses, your next attack against that creature has advantage.' }],
|
||||
10: [{ name: 'Thought Shield', text: 'Nobody reads your thoughts unless you allow it. You resist psychic damage, and whoever deals it to you takes the same amount.' }],
|
||||
14: [{ name: 'Create Thrall', text: 'Action: touch an incapacitated humanoid; it is charmed by you until Remove Curse is cast, and you can speak to it telepathically on the same plane.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'CELESTIAL',
|
||||
name: 'The Celestial',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A patron of light: the warlock who heals.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Bonus Cantrips', text: 'The Celestial. You know Light and Sacred Flame.' },
|
||||
{ name: 'Healing Light', text: 'A pool of d6s equal to 1 + your level per long rest. Bonus action: heal a creature within 60 ft with up to your Charisma modifier of them.' },
|
||||
],
|
||||
6: [{ name: 'Radiant Soul', text: 'Radiant damage against you is halved; add your Charisma modifier to one radiant or fire damage roll of your spells.' }],
|
||||
10: [{ name: 'Celestial Resilience', text: 'After a rest, you gain your level + Charisma modifier Temp HP, and up to five allies gain half your level + Charisma modifier.' }],
|
||||
14: [{ name: 'Searing Vengeance', text: 'Once per long rest, when you would make a death save: stand up with half your HP, and enemies within 30 ft take 2d8 + Charisma modifier radiant and are blinded until the turn ends.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'FATHOMLESS',
|
||||
name: 'The Fathomless',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'A patron of the deep sea, with a spectral tentacle at your call.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Tentacle of the Deeps', text: 'The Fathomless. A few times per long rest (proficiency bonus), bonus action: a 10 ft spectral tentacle within 60 ft for a minute; it strikes for 1d8 cold and slows by 10 ft.' },
|
||||
{ name: 'Gift of the Sea', text: 'Swim speed 40 ft, and you can breathe underwater.' },
|
||||
],
|
||||
6: [
|
||||
{ name: 'Oceanic Soul', text: 'Cold damage against you is halved; you can speak with anything underwater.' },
|
||||
{ name: 'Guardian Coil', text: 'Reaction: your tentacle reduces damage to a creature within 10 ft of it by 1d8 (2d8 from level 10).' },
|
||||
],
|
||||
10: [{ name: 'Grasping Tentacles', text: 'Learn Evard’s Black Tentacles and cast it once per long rest without a slot; while casting it you gain Temp HP equal to your level, and damage cannot break your concentration on it.' }],
|
||||
14: [{ name: 'Fathomless Plunge', text: 'Once per short rest, action: you and up to five willing creatures within 30 ft teleport to a body of water you have seen within 1 mile.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'GENIE',
|
||||
name: 'The Genie',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'A noble genie’s vassal, with a bottle to hide in.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Genie’s Vessel', text: 'The Genie. A tiny vessel serves as your focus. Bottled Respite: hide inside it for hours. Genie’s Wrath: once per turn a hit deals extra damage equal to your proficiency bonus, of your genie’s element.' },
|
||||
],
|
||||
6: [{ name: 'Elemental Gift', text: 'Resist your genie’s element, and a few times per long rest (proficiency bonus) fly 30 ft for 10 minutes as a bonus action.' }],
|
||||
10: [{ name: 'Sanctuary Vessel', text: 'Up to five willing creatures can join you in your vessel, and those who rest there for 10 minutes gain the benefits of a short rest plus extra healing.' }],
|
||||
14: [{ name: 'Limited Wish', text: 'Once every 1d4 long rests, action: ask your patron for a 6th-level or lower spell from any list, cast without material.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'HEXBLADE',
|
||||
name: 'The Hexblade',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'A sentient weapon from the Shadowfell: the warlock who melees.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Hexblade’s Curse', text: 'The Hexblade. Once per short rest, bonus action: curse a creature within 30 ft for a minute: +proficiency bonus damage against it, crit on 19–20, and you heal your level + Charisma modifier if it dies.' },
|
||||
{ name: 'Hex Warrior', text: 'Proficient with medium armor, shields and martial weapons; one-handed (later pact) weapons can use Charisma for attack and damage.' },
|
||||
],
|
||||
6: [{ name: 'Accursed Specter', text: 'Once per long rest, when you slay a humanoid: its spirit rises as a specter under your command until your next long rest.' }],
|
||||
10: [{ name: 'Armor of Hexes', text: 'When the target of your Hexblade’s Curse hits you, roll a d6: on 4 or higher, it misses.' }],
|
||||
14: [{ name: 'Master of Hexes', text: 'When the cursed creature dies, move the curse to another creature within 30 ft (no healing from that move).' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'UNDEAD',
|
||||
name: 'The Undead',
|
||||
source: 'Van Richten’s Guide to Ravenloft',
|
||||
edition: '2014',
|
||||
summary: 'A deathless patron: a terrifying form and necrotic power.',
|
||||
features: {
|
||||
3: [{ name: 'Form of Dread', text: 'The Undead. A few times per long rest (proficiency bonus), bonus action for a minute: gain 1d10 + your level Temp HP, you can’t be frightened, and once per turn a hit can frighten the target (Wisdom save).' }],
|
||||
6: [{ name: 'Grave Touched', text: 'You need no food, water or air. Once per turn, a hit can become necrotic; in Form of Dread it deals one extra die.' }],
|
||||
10: [{ name: 'Necrotic Husk', text: 'Necrotic damage against you is halved (immune in Form of Dread). Once per long rest, when you drop to 0 HP, drop to 1 and blast creatures within 30 ft with necrotic damage.' }],
|
||||
14: [{ name: 'Spirit Projection', text: 'Once per long rest, action: project your spirit for an hour; it can fly, pass through objects, and resist damage.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'UNDYING',
|
||||
name: 'The Undying',
|
||||
source: 'Sword Coast Adventurer’s Guide',
|
||||
edition: '2014',
|
||||
summary: 'A patron who cheated death, and teaches you to.',
|
||||
features: {
|
||||
3: [
|
||||
{ name: 'Among the Dead', text: 'The Undying. You know Spare the Dying; advantage on saves against disease; undead must make a Wisdom save to attack you.' },
|
||||
],
|
||||
6: [{ name: 'Defy Death', text: 'Once per long rest, when you succeed on a death save or stabilize someone with Spare the Dying, heal 1d8 + Constitution modifier.' }],
|
||||
10: [{ name: 'Undying Nature', text: 'You can hold your breath indefinitely, need no food, water or sleep, and age a tenth as fast.' }],
|
||||
14: [{ name: 'Indestructible Life', text: 'Once per short rest, bonus action: heal 1d8 + your level and reattach a severed body part.' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = WARLOCK;
|
||||
@@ -0,0 +1,213 @@
|
||||
// Wizard subclasses: the arcane traditions. The shape is described in index.js.
|
||||
|
||||
const WIZARD = [
|
||||
{
|
||||
key: 'EVOCATION',
|
||||
name: 'School of Evocation',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Blasting, with friends left standing in the middle of it.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Evocation Savant', text: 'School of Evocation. Copying evocation spells costs half the time and gold.' },
|
||||
{ name: 'Sculpt Spells', text: 'When you cast an evocation spell that hits an area, choose 1 + the spell’s level creatures to automatically save and take no damage.' },
|
||||
],
|
||||
6: [{ name: 'Potent Cantrip', text: 'Creatures that save against your damaging cantrips still take half damage.' }],
|
||||
10: [{ name: 'Empowered Evocation', text: 'Add your Intelligence modifier to the damage of your evocation spells.' }],
|
||||
14: [{ name: 'Overchannel', text: 'When you cast a damaging spell of 1st to 5th level, deal maximum damage. Doing it again before a long rest costs you necrotic damage that grows each time.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ABJURATION',
|
||||
name: 'School of Abjuration',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Wards and counters: a shield of magic that takes the hits.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Abjuration Savant', text: 'School of Abjuration. Copying abjuration spells costs half the time and gold.' },
|
||||
{ name: 'Arcane Ward', text: 'When you cast an abjuration spell of 1st level or higher, a ward appears with HP of twice your level + your Intelligence modifier; it takes damage before you do (the DM tracks it as Temp HP). It lasts until a long rest; later abjuration spells restore twice their level to it.' },
|
||||
],
|
||||
6: [{ name: 'Projected Ward', text: 'Reaction: when a creature within 30 ft takes damage, your Arcane Ward takes it instead.' }],
|
||||
10: [{ name: 'Improved Abjuration', text: 'Add your proficiency bonus to ability checks made as part of an abjuration spell (Counterspell, Dispel Magic).' }],
|
||||
14: [{ name: 'Spell Resistance', text: 'Advantage on saves against spells, and spell damage against you is halved.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ILLUSION',
|
||||
name: 'School of Illusion',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Tricks of light and sound that hold up to a second look.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Illusion Savant', text: 'School of Illusion. Copying illusion spells costs half the time and gold.' },
|
||||
{ name: 'Improved Minor Illusion', text: 'You know Minor Illusion (the DM grants it), and it makes a sound and an image with one casting.' },
|
||||
],
|
||||
6: [{ name: 'Malleable Illusions', text: 'Action: change what an illusion of yours looks like while it lasts, if it lasts a minute or more.' }],
|
||||
10: [{ name: 'Illusory Self', text: 'Once per short rest, reaction when a creature attacks you: a copy of you takes the blow and the attack misses.' }],
|
||||
14: [{ name: 'Illusory Reality', text: 'Bonus action, when you cast an illusion of 1st level or higher: make one inanimate, harmless object in it real for a minute.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'BLADESINGING',
|
||||
name: 'Bladesinging',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'An elven sword-dance: a wizard who fights up close.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Training in War and Song', text: 'Bladesinging. Proficient with light armor and one one-handed melee weapon, and treat Performance as proficient.' },
|
||||
{ name: 'Bladesong', text: 'A few times per long rest (proficiency bonus), bonus action for a minute (in light or no armor): +Intelligence modifier to AC and concentration saves, +10 ft speed, advantage on Acrobatics.' },
|
||||
],
|
||||
6: [{ name: 'Extra Attack', text: 'Attack twice when you take the Attack action; one attack can be a cantrip instead.' }],
|
||||
10: [{ name: 'Song of Defense', text: 'Reaction while in Bladesong: spend a spell slot to reduce damage by five times its level.' }],
|
||||
14: [{ name: 'Song of Victory', text: 'While in Bladesong, add your Intelligence modifier to melee weapon damage.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'CHRONURGY',
|
||||
name: 'Chronurgy Magic',
|
||||
source: 'Explorer’s Guide to Wildemount',
|
||||
edition: '2014',
|
||||
summary: 'Bends time: rerolls fate and freezes foes.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Chronal Shift', text: 'Chronurgy Magic. Twice per long rest, reaction: force a creature within 30 ft to reroll an attack, check or save.' },
|
||||
{ name: 'Temporal Awareness', text: 'Add your Intelligence modifier to initiative.' },
|
||||
],
|
||||
6: [{ name: 'Momentary Stasis', text: 'A few times per long rest (Intelligence modifier), action: a Large or smaller creature within 60 ft makes a Constitution save or is frozen in time until the end of your next turn.' }],
|
||||
10: [{ name: 'Arcane Abeyance', text: 'Once per short rest, cast a spell of 4th level or lower into a bead; anyone can release it later as an action.' }],
|
||||
14: [{ name: 'Convergent Future', text: 'Reaction: decide that an attack, check or save within 60 ft succeeds or fails; you gain a level of exhaustion each time.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'CONJURATION',
|
||||
name: 'School of Conjuration',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Summons, teleports and makes objects out of nothing.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Conjuration Savant', text: 'School of Conjuration. Copying conjuration spells costs half the time and gold.' },
|
||||
{ name: 'Minor Conjuration', text: 'Action: conjure a non-magical object up to 3 ft across and 10 lb, for an hour.' },
|
||||
],
|
||||
6: [{ name: 'Benign Transposition', text: 'Action: teleport 30 ft, or swap places with a willing creature; again after a long rest or casting a conjuration spell.' }],
|
||||
10: [{ name: 'Focused Conjuration', text: 'Damage can’t break your concentration on a conjuration spell.' }],
|
||||
14: [{ name: 'Durable Summons', text: 'Creatures you summon gain 30 Temp HP.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'DIVINATION',
|
||||
name: 'School of Divination',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Sees the future: replaces rolls with dice foretold at dawn.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Divination Savant', text: 'School of Divination. Copying divination spells costs half the time and gold.' },
|
||||
{ name: 'Portent', text: 'After a long rest roll two d20s and note them. You can swap any attack, check or save you can see for one of those rolls, before it is made.' },
|
||||
],
|
||||
6: [{ name: 'Expert Divination', text: 'Casting a divination spell of 2nd level or higher gives back a spell slot of a lower level (up to 5th).' }],
|
||||
10: [{ name: 'The Third Eye', text: 'Action, until your next rest: darkvision, see into the Ethereal, read any language, or see invisible things within 10 ft.' }],
|
||||
14: [{ name: 'Greater Portent', text: 'Roll three d20s for Portent instead of two.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'ENCHANTMENT',
|
||||
name: 'School of Enchantment',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Charm and compulsion: makes enemies forget, freeze or fight each other.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Enchantment Savant', text: 'School of Enchantment. Copying enchantment spells costs half the time and gold.' },
|
||||
{ name: 'Hypnotic Gaze', text: 'Action: a creature within 5 ft makes a Wisdom save or is charmed and incapacitated until the end of your next turn; you can extend it each turn.' },
|
||||
],
|
||||
6: [{ name: 'Instinctive Charm', text: 'Reaction when attacked: the attacker makes a Wisdom save or must attack someone else nearby (or waste the attack).' }],
|
||||
10: [{ name: 'Split Enchantment', text: 'An enchantment spell that targets one creature can target a second.' }],
|
||||
14: [{ name: 'Alter Memories', text: 'A creature you charm doesn’t know it was charmed, and can be made to forget up to a few hours of what happened (Intelligence save).' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'GRAVITURGY',
|
||||
name: 'Graviturgy Magic',
|
||||
source: 'Explorer’s Guide to Wildemount',
|
||||
edition: '2014',
|
||||
summary: 'Commands gravity: makes things heavy, light, or pulled together.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Adjust Density', text: 'Graviturgy Magic. Action: halve or double the weight of a Large or smaller creature or object within 30 ft for a minute, changing its speed and Strength rolls.' },
|
||||
],
|
||||
6: [{ name: 'Gravity Well', text: 'When you cast a spell on a creature, you can move it 5 ft to a free space.' }],
|
||||
10: [{ name: 'Violent Attraction', text: 'A few times per long rest (Intelligence modifier), reaction: +1d10 damage to a weapon hit within 60 ft, or +2d10 to a creature’s fall damage.' }],
|
||||
14: [{ name: 'Event Horizon', text: 'Once per long rest, action for a minute: hostile creatures within 30 ft take 2d10 force each turn and have speed 0 (Strength save for half and partial speed).' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'NECROMANCY',
|
||||
name: 'School of Necromancy',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Drains life to heal itself, and raises stronger undead.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Necromancy Savant', text: 'School of Necromancy. Copying necromancy spells costs half the time and gold.' },
|
||||
{ name: 'Grim Harvest', text: 'Once per turn, when your spell kills a creature, heal twice the spell’s level (three times for necromancy).' },
|
||||
],
|
||||
6: [{ name: 'Undead Thralls', text: 'Animate Dead raises one extra corpse, and your undead have extra HP (your level) and add your proficiency bonus to damage.' }],
|
||||
10: [{ name: 'Inured to Undeath', text: 'Necrotic damage against you is halved, and your maximum HP can’t be reduced.' }],
|
||||
14: [{ name: 'Command Undead', text: 'Action: an undead within 60 ft makes a Charisma save or becomes friendly and obeys you.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'SCRIBES',
|
||||
name: 'Order of Scribes',
|
||||
source: 'Tasha’s Cauldron of Everything',
|
||||
edition: '2014',
|
||||
summary: 'Your spellbook is alive, and rewrites your spells’ damage.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Wizardly Quill', text: 'Order of Scribes. A magic quill: copy spells in 2 minutes per level, and erase writing.' },
|
||||
{ name: 'Awakened Spellbook', text: 'Your book is your focus. When you cast with a slot, change the spell’s damage type to another from your book. Once per long rest, cast a ritual at normal speed.' },
|
||||
],
|
||||
6: [{ name: 'Manifest Mind', text: 'Bonus action: a spectral mind within 60 ft; see and hear through it, and cast spells from it a few times per long rest (proficiency bonus).' }],
|
||||
10: [{ name: 'Master Scrivener', text: 'After a long rest, make a scroll of a 1st- or 2nd-level spell from your book; cast from it, it counts one level higher.' }],
|
||||
14: [{ name: 'One with the Word', text: 'Advantage on Arcana. Once per long rest, reaction when you take damage with your mind manifested: take none, and instead lose spells from your book worth 3d6 spell levels until the book is restored.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'TRANSMUTATION',
|
||||
name: 'School of Transmutation',
|
||||
source: 'Player’s Handbook',
|
||||
edition: '2014',
|
||||
summary: 'Changes matter: a philosopher’s stone and shapechanging.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Transmutation Savant', text: 'School of Transmutation. Copying transmutation spells costs half the time and gold.' },
|
||||
{ name: 'Minor Alchemy', text: 'Spend 10 minutes per cubic foot to turn wood, stone, iron, copper or silver into another of them for an hour.' },
|
||||
],
|
||||
6: [{ name: 'Transmuter’s Stone', text: 'Make a stone that grants one benefit to whoever holds it: darkvision, +10 ft speed, Constitution save proficiency, or resistance to one element.' }],
|
||||
10: [{ name: 'Shapechanger', text: 'Cast Polymorph on yourself once per short rest without a slot, as a beast of CR 1 or lower.' }],
|
||||
14: [{ name: 'Master Transmuter', text: 'Destroy your stone for a great effect: transmute an object, cure all ailments, cast Raise Dead without a slot, or restore youth.' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'WAR_MAGIC',
|
||||
name: 'War Magic',
|
||||
source: 'Xanathar’s Guide to Everything',
|
||||
edition: '2014',
|
||||
summary: 'Battle wizardry: deflects attacks and surges with power.',
|
||||
features: {
|
||||
2: [
|
||||
{ name: 'Arcane Deflection', text: 'War Magic. Reaction when hit or failing a save: +2 AC or +4 to the save; you can then cast only cantrips until your next turn.' },
|
||||
{ name: 'Tactical Wit', text: 'Add your Intelligence modifier to initiative.' },
|
||||
],
|
||||
6: [{ name: 'Power Surge', text: 'Store surges (up to your Intelligence modifier): spend one to add half your level as force damage to a spell; you gain one when you end a spell with Dispel Magic or Counterspell.' }],
|
||||
10: [{ name: 'Durable Magic', text: '+2 to AC and saves while concentrating on a spell.' }],
|
||||
14: [{ name: 'Deflecting Shroud', text: 'When you use Arcane Deflection, up to three creatures within 60 ft take force damage of half your level.' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = WIZARD;
|
||||
@@ -0,0 +1,51 @@
|
||||
// Experience points: what a monster is worth by challenge rating, how hard a
|
||||
// fight is for a party, and the XP each level takes. The 5e (2014) tables.
|
||||
|
||||
// XP for defeating one monster of a challenge rating.
|
||||
const CR_XP = {
|
||||
0: 10, '1/8': 25, '1/4': 50, '1/2': 100,
|
||||
1: 200, 2: 450, 3: 700, 4: 1100, 5: 1800, 6: 2300, 7: 2900, 8: 3900, 9: 5000, 10: 5900,
|
||||
11: 7200, 12: 8400, 13: 10000, 14: 11500, 15: 13000, 16: 15000, 17: 18000, 18: 20000, 19: 22000, 20: 25000,
|
||||
21: 33000, 22: 41000, 23: 50000, 24: 62000, 25: 75000, 26: 90000, 27: 105000, 28: 120000, 29: 135000, 30: 155000,
|
||||
};
|
||||
|
||||
// What one character of a level can take on: [easy, medium, hard, deadly],
|
||||
// level 1 first. A party's thresholds are its members' added up.
|
||||
const XP_THRESHOLDS = [
|
||||
[25, 50, 75, 100],
|
||||
[50, 100, 150, 200],
|
||||
[75, 150, 225, 400],
|
||||
[125, 250, 375, 500],
|
||||
[250, 500, 750, 1100],
|
||||
[300, 600, 900, 1400],
|
||||
[350, 750, 1100, 1700],
|
||||
[450, 900, 1400, 2100],
|
||||
[550, 1100, 1600, 2400],
|
||||
[600, 1200, 1900, 2800],
|
||||
[800, 1600, 2400, 3600],
|
||||
[1000, 2000, 3000, 4500],
|
||||
[1100, 2200, 3400, 5100],
|
||||
[1250, 2500, 3800, 5700],
|
||||
[1400, 2800, 4300, 6400],
|
||||
[1600, 3200, 4800, 7200],
|
||||
[2000, 3900, 5900, 8800],
|
||||
[2100, 4200, 6300, 9500],
|
||||
[2400, 4900, 7300, 10900],
|
||||
[2800, 5700, 8500, 12700],
|
||||
];
|
||||
|
||||
// Many monsters are harder than their XP says: the total is multiplied by
|
||||
// this to judge the fight (never to award it). [at least this many, multiplier].
|
||||
const COUNT_MULTIPLIERS = [
|
||||
[15, 4],
|
||||
[11, 3],
|
||||
[7, 2.5],
|
||||
[3, 2],
|
||||
[2, 1.5],
|
||||
[1, 1],
|
||||
];
|
||||
|
||||
// Total XP at which each level is reached, level 1 first.
|
||||
const LEVEL_XP = [0, 300, 900, 2700, 6500, 14000, 23000, 34000, 48000, 64000, 85000, 100000, 120000, 140000, 165000, 195000, 225000, 265000, 305000, 355000];
|
||||
|
||||
module.exports = { CR_XP, XP_THRESHOLDS, COUNT_MULTIPLIERS, LEVEL_XP };
|
||||
@@ -0,0 +1,105 @@
|
||||
// Dice: reading an expression ("2d6+3"), rolling it, and checking dice that
|
||||
// were rolled at the table and typed in. Used by the table's dice roller
|
||||
// (POST /campaigns/:id/rolls) and by attacks in an encounter (game/combat.js).
|
||||
// Pure but for the random source, which can be passed in for tests.
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
const rollDie = (sides) => crypto.randomInt(1, sides + 1);
|
||||
|
||||
const MAX_DICE = 100;
|
||||
const MAX_SIDES = 1000;
|
||||
|
||||
// Reads the dice expressions the app writes: "1d8", "2d6", "1d6+1d8",
|
||||
// "2d4+2", "1d8 - 1". Returns { dice: [{ count, sides, sign }], flat }, or null
|
||||
// for anything else (free text is allowed where a DM types dice) and for
|
||||
// something too big to be a real roll. Mirrors parseDice in the frontend's
|
||||
// lib/diceRoller.ts.
|
||||
function parseDice(expression) {
|
||||
const terms = String(expression || '')
|
||||
.replace(/\s+/g, '')
|
||||
.replace(/[−–]/g, '-')
|
||||
.toLowerCase()
|
||||
.replace(/-/g, '+-')
|
||||
.split('+')
|
||||
.filter(Boolean);
|
||||
if (terms.length === 0) return null;
|
||||
const parsed = { dice: [], flat: 0 };
|
||||
let total = 0;
|
||||
for (const term of terms) {
|
||||
const die = /^(-?)(\d*)d(\d+)$/.exec(term);
|
||||
if (die) {
|
||||
const count = Number(die[2]) || 1;
|
||||
const sides = Number(die[3]);
|
||||
total += count;
|
||||
if (total > MAX_DICE || sides < 2 || sides > MAX_SIDES) return null;
|
||||
parsed.dice.push({ count, sides, sign: die[1] ? -1 : 1 });
|
||||
} else if (/^-?\d+$/.test(term)) {
|
||||
parsed.flat += Number(term);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return parsed.dice.length > 0 ? parsed : null;
|
||||
}
|
||||
|
||||
// The dice at the start of a line of text that says more: "2d8+3" from
|
||||
// "2d8+3 fire". Null when it does not start with dice.
|
||||
function leadingDice(text) {
|
||||
const match = /^\s*((?:\d*d\d+|\d+)(?:\s*[+\-−–]\s*(?:\d*d\d+|\d+))*)/i.exec(String(text || ''));
|
||||
return match && parseDice(match[1]) ? match[1].replace(/\s+/g, '') : null;
|
||||
}
|
||||
|
||||
// Every die of a parsed expression, one entry each, in order: [{ sides, sign }].
|
||||
function diceOf(parsed) {
|
||||
return parsed.dice.flatMap((term) => Array.from({ length: term.count }, () => ({ sides: term.sides, sign: term.sign })));
|
||||
}
|
||||
|
||||
// Whether `values` could be what these dice showed: one whole number per die,
|
||||
// each on its die.
|
||||
function validValues(dice, values) {
|
||||
return Array.isArray(values) && values.length === dice.length && dice.every((die, i) => Number.isInteger(values[i]) && values[i] >= 1 && values[i] <= die.sides);
|
||||
}
|
||||
|
||||
// Rolls a parsed expression, or takes `values` (dice rolled at the table,
|
||||
// already checked with validValues) in place of rolling. Returns
|
||||
// { dice: [{ sides, value, kept, sign }], modifier, total }.
|
||||
function rollExpression(parsed, { values = null, roll = rollDie } = {}) {
|
||||
const dice = diceOf(parsed).map((die, i) => ({ sides: die.sides, value: values ? values[i] : roll(die.sides), kept: true, sign: die.sign }));
|
||||
return { dice, modifier: parsed.flat, total: dice.reduce((sum, die) => sum + die.sign * die.value, 0) + parsed.flat };
|
||||
}
|
||||
|
||||
const D20_MODES = ['NORMAL', 'ADVANTAGE', 'DISADVANTAGE'];
|
||||
|
||||
// How many d20s a mode rolls: two with advantage or disadvantage.
|
||||
const d20Count = (mode) => (mode === 'NORMAL' ? 1 : 2);
|
||||
|
||||
// A d20 plus a modifier, as the mode has it: one die, or two with the higher
|
||||
// (advantage) or lower (disadvantage) kept. `values` as in rollExpression.
|
||||
// Returns { dice, modifier, total, natural }: `natural` is the d20 that counted.
|
||||
function rollD20(modifier = 0, mode = 'NORMAL', { values = null, roll = rollDie } = {}) {
|
||||
const rolled = Array.from({ length: d20Count(mode) }, (_, i) => (values ? values[i] : roll(20)));
|
||||
const natural = mode === 'ADVANTAGE' ? Math.max(...rolled) : mode === 'DISADVANTAGE' ? Math.min(...rolled) : rolled[0];
|
||||
// Of two equal dice only the first is marked as the one kept.
|
||||
const keptIndex = rolled.indexOf(natural);
|
||||
return {
|
||||
dice: rolled.map((value, i) => ({ sides: 20, value, kept: i === keptIndex, sign: 1 })),
|
||||
modifier,
|
||||
total: natural + modifier,
|
||||
natural,
|
||||
};
|
||||
}
|
||||
|
||||
// What a critical hit does to damage dice (Campaign.critRule). DOUBLE_DICE:
|
||||
// every die is rolled twice. MAX_PLUS_ROLL: every die counts at its maximum,
|
||||
// and is rolled once more on top. Takes and returns a parsed expression's
|
||||
// roll; the flat modifier is never doubled.
|
||||
function rollCritical(parsed, critRule = 'DOUBLE_DICE', { roll = rollDie } = {}) {
|
||||
const base = diceOf(parsed);
|
||||
const first = base.map((die) => ({ sides: die.sides, value: critRule === 'MAX_PLUS_ROLL' ? die.sides : roll(die.sides), kept: true, sign: die.sign, maxed: critRule === 'MAX_PLUS_ROLL' }));
|
||||
const second = base.map((die) => ({ sides: die.sides, value: roll(die.sides), kept: true, sign: die.sign }));
|
||||
const dice = [...first, ...second];
|
||||
return { dice, modifier: parsed.flat, total: dice.reduce((sum, die) => sum + die.sign * die.value, 0) + parsed.flat };
|
||||
}
|
||||
|
||||
module.exports = { rollDie, parseDice, leadingDice, diceOf, validValues, rollExpression, rollD20, d20Count, rollCritical, D20_MODES, MAX_DICE };
|
||||
@@ -0,0 +1,77 @@
|
||||
const { parseDice, leadingDice, diceOf, validValues, rollExpression, rollD20, rollCritical } = require('./dice');
|
||||
|
||||
// A die that always shows the same face, or the faces given in turn.
|
||||
const fixed = (...faces) => {
|
||||
let i = 0;
|
||||
return () => faces[i++ % faces.length];
|
||||
};
|
||||
|
||||
describe('parseDice', () => {
|
||||
test('reads the expressions the app writes', () => {
|
||||
expect(parseDice('2d6+3')).toEqual({ dice: [{ count: 2, sides: 6, sign: 1 }], flat: 3 });
|
||||
expect(parseDice('1d6 + 1d8 − 1')).toEqual({ dice: [{ count: 1, sides: 6, sign: 1 }, { count: 1, sides: 8, sign: 1 }], flat: -1 });
|
||||
expect(parseDice('d20')).toEqual({ dice: [{ count: 1, sides: 20, sign: 1 }], flat: 0 });
|
||||
});
|
||||
|
||||
test('refuses free text, bare numbers and absurd rolls', () => {
|
||||
expect(parseDice('a big bite')).toBeNull();
|
||||
expect(parseDice('7')).toBeNull();
|
||||
expect(parseDice('101d6')).toBeNull();
|
||||
expect(parseDice('60d6+60d6')).toBeNull();
|
||||
expect(parseDice('1d1')).toBeNull();
|
||||
});
|
||||
|
||||
test('leadingDice takes the dice off the front of a line', () => {
|
||||
expect(leadingDice('2d8+3 fire')).toBe('2d8+3');
|
||||
expect(leadingDice('fire, 2d8')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('rolling', () => {
|
||||
test('rolls every die and adds the flat part', () => {
|
||||
const roll = rollExpression(parseDice('2d6+1d4+2'), { roll: fixed(3, 5, 4) });
|
||||
expect(roll.dice.map((d) => [d.sides, d.value])).toEqual([[6, 3], [6, 5], [4, 4]]);
|
||||
expect(roll).toMatchObject({ modifier: 2, total: 14 });
|
||||
});
|
||||
|
||||
test('a subtracted die takes away', () => {
|
||||
expect(rollExpression(parseDice('1d8-1d4'), { roll: fixed(6, 2) }).total).toBe(4);
|
||||
});
|
||||
|
||||
test('dice rolled at the table are checked against each die, then used as they are', () => {
|
||||
const dice = diceOf(parseDice('1d8+1d6'));
|
||||
expect(validValues(dice, [8, 6])).toBe(true);
|
||||
expect(validValues(dice, [9, 1])).toBe(false);
|
||||
expect(validValues(dice, [3])).toBe(false);
|
||||
expect(validValues(dice, [3, 2.5])).toBe(false);
|
||||
expect(rollExpression(parseDice('1d8+1d6+1'), { values: [8, 6] }).total).toBe(15);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a d20', () => {
|
||||
test('rolls one die and adds the modifier', () => {
|
||||
expect(rollD20(5, 'NORMAL', { roll: fixed(12) })).toMatchObject({ total: 17, natural: 12, dice: [{ sides: 20, value: 12, kept: true }] });
|
||||
});
|
||||
|
||||
test('keeps the higher with advantage and the lower with disadvantage', () => {
|
||||
const adv = rollD20(2, 'ADVANTAGE', { roll: fixed(7, 15) });
|
||||
expect(adv).toMatchObject({ natural: 15, total: 17 });
|
||||
expect(adv.dice.map((d) => d.kept)).toEqual([false, true]);
|
||||
expect(rollD20(0, 'DISADVANTAGE', { roll: fixed(7, 15) }).natural).toBe(7);
|
||||
expect(rollD20(0, 'ADVANTAGE', { values: [20, 20] }).dice.map((d) => d.kept)).toEqual([true, false]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a critical hit', () => {
|
||||
test('rolls every damage die twice, and the flat part once', () => {
|
||||
const crit = rollCritical(parseDice('1d8+3'), 'DOUBLE_DICE', { roll: fixed(5, 7) });
|
||||
expect(crit.dice.map((d) => d.value)).toEqual([5, 7]);
|
||||
expect(crit.total).toBe(15);
|
||||
});
|
||||
|
||||
test('or takes the dice at their most and rolls them once more', () => {
|
||||
const crit = rollCritical(parseDice('2d6+1'), 'MAX_PLUS_ROLL', { roll: fixed(2, 3) });
|
||||
expect(crit.dice.map((d) => d.value)).toEqual([6, 6, 2, 3]);
|
||||
expect(crit.total).toBe(18);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,303 @@
|
||||
// Levelling up: the Hollowcrown book's "Levelling-Up Checklist" (Rules Cheat
|
||||
// Sheet). Works out what a character gains at a level, and rewrites their
|
||||
// special abilities to say so. Pure: no DB calls.
|
||||
|
||||
const { LEVEL_FEATURES, MAX_FEATURE_LEVEL, CANTRIP_LEVEL, CANTRIP_FEATURE, BOONS } = require('./data/levelFeatures');
|
||||
const { SUBCLASS_LEVEL, subclassesOf, findSubclass, defaultSubclass } = require('./data/subclasses');
|
||||
const { CLASS_FEATURES } = require('./data/characterOptions');
|
||||
const { CASTER_KIND } = require('./data/spellSlots');
|
||||
const { getClassSpellcastingAbility, maxSpellLevel, scaledDamageDice, MAX_GEAR_LEVEL } = require('./calculations');
|
||||
const { classLevels, classOptions, joiningFeatures } = require('./multiclass');
|
||||
|
||||
// A choice that cannot be made: the message is for whoever made it.
|
||||
class LevelUpError extends Error {}
|
||||
|
||||
// What a class gains on reaching `level`, in the order it is written down:
|
||||
// the class's own features, then those of the subclass (its key) when one is
|
||||
// given. An entry is { name, text, upgrade? } or { boon: true }.
|
||||
function featuresAt(characterClass, level, subclassKey = null) {
|
||||
const features = [...((LEVEL_FEATURES[characterClass] || {})[level] || [])];
|
||||
const subclass = findSubclass(characterClass, subclassKey);
|
||||
if (subclass) features.push(...(subclass.features[level] || []));
|
||||
if (level === CANTRIP_LEVEL && getClassSpellcastingAbility(characterClass)) features.push(CANTRIP_FEATURE);
|
||||
return features;
|
||||
}
|
||||
|
||||
// Special abilities are one per line, "Name — what it does". The builder
|
||||
// writes a long dash; a DM typing by hand may use "--".
|
||||
const featureLine = (feature) => `${feature.name} — ${feature.text}`;
|
||||
|
||||
function lineName(line) {
|
||||
const match = /^\s*(.+?)\s*(?:—|–|--)\s/.exec(line);
|
||||
return match ? match[1].toLowerCase() : null;
|
||||
}
|
||||
|
||||
const toLines = (specialAbilities) => (specialAbilities ? specialAbilities.split(/\r?\n/) : []);
|
||||
const fromLines = (lines) => lines.join('\n') || null;
|
||||
const findLine = (lines, name) => lines.findIndex((line) => lineName(line) === name.toLowerCase());
|
||||
|
||||
// Writes features into the text. An upgrade takes the place of the line with
|
||||
// its name (Sneak Attack growing a die); anything else goes on the end, unless
|
||||
// that very line is there already.
|
||||
function addFeatures(specialAbilities, features) {
|
||||
const lines = toLines(specialAbilities);
|
||||
for (const feature of features) {
|
||||
const line = featureLine(feature);
|
||||
const at = feature.upgrade ? findLine(lines, feature.name) : -1;
|
||||
if (at >= 0) lines[at] = line;
|
||||
else if (!lines.includes(line)) lines.push(line);
|
||||
}
|
||||
return fromLines(lines);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Subclasses (data/subclasses.js). A class chooses one at SUBCLASS_LEVEL. Until
|
||||
// it has, a line on the sheet says the choice is owed.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const SUBCLASS_OWED = 'Subclass';
|
||||
|
||||
// Whether a class at this level should have a subclass.
|
||||
function owesSubclass(characterClass, level) {
|
||||
return subclassesOf(characterClass).length > 0 && level >= SUBCLASS_LEVEL[characterClass];
|
||||
}
|
||||
|
||||
const subclassOwedFeature = (characterClass) => ({
|
||||
name: SUBCLASS_OWED,
|
||||
text: `Choose one of the ${subclassesOf(characterClass).length} with your DM (the level-up checklist lists them all).`,
|
||||
});
|
||||
|
||||
// Everything a subclass has given by `level`, in the order it came.
|
||||
function subclassFeaturesThrough(subclass, level) {
|
||||
return Object.keys(subclass.features)
|
||||
.map(Number)
|
||||
.filter((at) => at <= level)
|
||||
.sort((a, b) => a - b)
|
||||
.flatMap((at) => subclass.features[at]);
|
||||
}
|
||||
|
||||
// Writes a newly chosen subclass onto the sheet: everything it has given up
|
||||
// to the character's level, in place of the line saying a choice is owed.
|
||||
function withSubclass(specialAbilities, characterClass, level, subclassKey) {
|
||||
const subclass = findSubclass(characterClass, subclassKey);
|
||||
if (!subclass) throw new LevelUpError('That is not a subclass of this class.');
|
||||
const lines = toLines(specialAbilities).filter((line) => lineName(line) !== SUBCLASS_OWED.toLowerCase());
|
||||
return addFeatures(fromLines(lines), subclassFeaturesThrough(subclass, level));
|
||||
}
|
||||
|
||||
// Takes a subclass's lines back off the sheet, found by their names. A line
|
||||
// the class itself also writes under that name is left alone.
|
||||
function withoutSubclass(specialAbilities, characterClass, subclassKey) {
|
||||
const subclass = findSubclass(characterClass, subclassKey);
|
||||
if (!subclass) return specialAbilities;
|
||||
const classNames = new Set(
|
||||
[...(CLASS_FEATURES[characterClass] || []), ...Object.values(LEVEL_FEATURES[characterClass] || {}).flat()]
|
||||
.filter((feature) => feature.name)
|
||||
.map((feature) => feature.name.toLowerCase())
|
||||
);
|
||||
const names = new Set(
|
||||
Object.values(subclass.features)
|
||||
.flat()
|
||||
.map((feature) => feature.name.toLowerCase())
|
||||
.filter((name) => !classNames.has(name))
|
||||
);
|
||||
return fromLines(toLines(specialAbilities).filter((line) => !names.has(lineName(line))));
|
||||
}
|
||||
|
||||
// The DM changing (or setting, or clearing) a character's subclass after the
|
||||
// fact: the old one's lines go, the new one's are written.
|
||||
function switchSubclass(specialAbilities, characterClass, level, fromKey, toKey) {
|
||||
const cleared = withoutSubclass(specialAbilities, characterClass, fromKey);
|
||||
if (toKey) return withSubclass(cleared, characterClass, level, toKey);
|
||||
return owesSubclass(characterClass, level) ? addFeatures(cleared, [subclassOwedFeature(characterClass)]) : cleared;
|
||||
}
|
||||
|
||||
// The subclasses a character may pick from on reaching `level`, each with
|
||||
// what it would write; null when there is no choice to make (too low a level,
|
||||
// or one is chosen already).
|
||||
function subclassChoice(characterClass, level, currentKey) {
|
||||
if (!owesSubclass(characterClass, level) || findSubclass(characterClass, currentKey)) return null;
|
||||
return {
|
||||
level: SUBCLASS_LEVEL[characterClass],
|
||||
options: subclassesOf(characterClass).map((subclass) => ({
|
||||
key: subclass.key,
|
||||
name: subclass.name,
|
||||
summary: subclass.summary,
|
||||
features: subclassFeaturesThrough(subclass, level).map(({ name, text }) => ({ name, text })),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
// How many times a Boon has been taken, read off its line ("Hardy — +10
|
||||
// maximum HP…" is twice).
|
||||
function boonTaken(specialAbilities, boon) {
|
||||
const lines = toLines(specialAbilities);
|
||||
const at = findLine(lines, boon.name);
|
||||
if (at < 0) return 0;
|
||||
const amount = /\+\s*(\d+)/.exec(lines[at]);
|
||||
return Math.max(1, Math.round((amount ? Number(amount[1]) : boon.per) / boon.per));
|
||||
}
|
||||
|
||||
// Every Boon, with what taking it now would write and whether it still can be.
|
||||
function boonOptions(specialAbilities) {
|
||||
return BOONS.map((boon) => {
|
||||
const taken = boonTaken(specialAbilities, boon);
|
||||
return { key: boon.key, name: boon.name, taken, max: boon.max, available: taken < boon.max, text: boon.text((Math.min(taken, boon.max - 1) + 1) * boon.per) };
|
||||
});
|
||||
}
|
||||
|
||||
// Temp HP the Hardy Boon gives after each long rest; 0 without it.
|
||||
function hardyTempHp(specialAbilities) {
|
||||
const hardy = BOONS.find((boon) => boon.key === 'HARDY');
|
||||
return boonTaken(specialAbilities, hardy) * hardy.per;
|
||||
}
|
||||
|
||||
// What reaching `level` does to a character's special abilities. `boonKey` is
|
||||
// the Boon picked, at a level that grants one; without it the line says a
|
||||
// choice is still owed. `subclass` is { key, chosen }: the character's
|
||||
// subclass, and whether it is being picked at this very level (then everything
|
||||
// it has given so far is written). Without one, from the level the class
|
||||
// chooses at, a line says that choice is owed too. Also returns what the Boon
|
||||
// does beyond the text: how much Extra AC it adds, and the Temp HP it gives
|
||||
// straight away.
|
||||
function advance(specialAbilities, characterClass, level, boonKey, { key: subclassKey = null, chosen = false } = {}) {
|
||||
const entries = featuresAt(characterClass, level, chosen ? null : subclassKey);
|
||||
let text = addFeatures(specialAbilities, entries.filter((entry) => !entry.boon));
|
||||
if (chosen) text = withSubclass(text, characterClass, level, subclassKey);
|
||||
else if (!findSubclass(characterClass, subclassKey) && owesSubclass(characterClass, level)) text = addFeatures(text, [subclassOwedFeature(characterClass)]);
|
||||
const result = { armorBonus: 0, tempHp: 0 };
|
||||
|
||||
if (entries.some((entry) => entry.boon)) {
|
||||
if (!boonKey) {
|
||||
text = addFeatures(text, [{ name: `Boon (level ${level})`, text: `Choose one with your DM: ${BOONS.map((boon) => boon.name).join(', ')}.` }]);
|
||||
} else {
|
||||
const boon = BOONS.find((b) => b.key === boonKey);
|
||||
if (!boon) throw new LevelUpError('That is not one of the Boons.');
|
||||
const taken = boonTaken(text, boon);
|
||||
if (taken >= boon.max) {
|
||||
throw new LevelUpError(`${boon.name} can be taken ${boon.max === 1 ? 'only once' : `at most ${boon.max} times`}. Pick a different Boon.`);
|
||||
}
|
||||
const amount = (taken + 1) * boon.per;
|
||||
text = addFeatures(text, [{ name: boon.name, text: boon.text(amount), upgrade: true }]);
|
||||
if (boon.key === 'TOUGHENED') result.armorBonus = 1;
|
||||
if (boon.key === 'HARDY') result.tempHp = amount;
|
||||
}
|
||||
}
|
||||
return { specialAbilities: text, ...result };
|
||||
}
|
||||
|
||||
// The book's unlock schedule: what a caster may be granted on reaching
|
||||
// `level`. Null for a class with no spells.
|
||||
function spellsGainedAt(characterClass, level) {
|
||||
const kind = CASTER_KIND[characterClass];
|
||||
if (!kind) return null;
|
||||
const highest = maxSpellLevel(characterClass, level);
|
||||
// Half casters: two spells at level 2, then one at each odd level.
|
||||
const halfCasterSpells = level === 2 ? 2 : level > 2 && level % 2 === 1 ? 1 : 0;
|
||||
return {
|
||||
maxSpellLevel: highest,
|
||||
// Set when this level opens up a new level of spells.
|
||||
unlocksSpellLevel: highest > maxSpellLevel(characterClass, level - 1) ? highest : null,
|
||||
newSpells: kind === 'HALF' ? halfCasterSpells : characterClass === 'WIZARD' ? 2 : 1,
|
||||
newCantrips: kind !== 'HALF' && (level === 4 || level === 10) ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
// In a campaign with subclasses switched off nobody chooses: on reaching the
|
||||
// level their class would choose at, a character is put on the class's first
|
||||
// subclass. Returns that subclass's key when this is the moment, else null.
|
||||
function subclassByDefault(characterClass, level, currentKey) {
|
||||
if (!owesSubclass(characterClass, level) || findSubclass(characterClass, currentKey)) return null;
|
||||
return defaultSubclass(characterClass).key;
|
||||
}
|
||||
|
||||
// The checklist for a character's next level. Takes the character with its
|
||||
// weapons and class levels loaded (each weapon with its pool entry).
|
||||
// `subclasses` is the campaign's setting: off, there is no subclass to pick,
|
||||
// and the class's first one is taken without asking (`subclassTaken`), its
|
||||
// features listed with the rest. `multiclass` (the campaign's setting) lists
|
||||
// the classes the level could go to (`classChoice`, by the final ability
|
||||
// `scores`), and `toClass` is the one it goes to: the character's first class
|
||||
// unless another is named. Features, Boons, spells and the subclass all go by
|
||||
// that class's own level.
|
||||
function levelUpPlan(character, { subclasses = true, multiclass = false, toClass = null, scores = {} } = {}) {
|
||||
const toLevel = character.level + 1;
|
||||
const characterClass = toClass || character.characterClass;
|
||||
const entry = classLevels(character).find((e) => e.characterClass === characterClass) || { characterClass, level: 0, subclass: null };
|
||||
const classLevel = entry.level + 1;
|
||||
const joining = entry.level === 0;
|
||||
const taken = subclasses || joining ? null : subclassByDefault(characterClass, classLevel, entry.subclass);
|
||||
const entries = joining
|
||||
? joiningFeatures(characterClass)
|
||||
: [
|
||||
...featuresAt(characterClass, classLevel, taken ? null : entry.subclass),
|
||||
...(taken ? subclassFeaturesThrough(findSubclass(characterClass, taken), classLevel) : []),
|
||||
];
|
||||
return {
|
||||
fromLevel: character.level,
|
||||
toLevel,
|
||||
// The class taking the level, and its own level once it has.
|
||||
characterClass,
|
||||
classLevel,
|
||||
// True when this is the character's first level in this class.
|
||||
joining,
|
||||
classChoice: multiclass ? { options: classOptions(character, scores) } : null,
|
||||
// Set when a subclass has to be picked on the way to this level.
|
||||
subclass: subclasses ? subclassChoice(characterClass, classLevel, entry.subclass) : null,
|
||||
subclassTaken: taken,
|
||||
features: entries.filter((e) => !e.boon).map(({ name, text, upgrade }) => ({ name, text, upgrade: Boolean(upgrade) })),
|
||||
boon: entries.some((e) => e.boon) ? boonOptions(character.specialAbilities) : null,
|
||||
spells: spellsGainedAt(characterClass, classLevel),
|
||||
// The free upgrade: one weapon of standard growth goes up a level, never
|
||||
// past its holder.
|
||||
weapons: (character.weapons || [])
|
||||
.filter((cw) => cw.weapon.damageScaling === 1 && cw.level < Math.min(toLevel, MAX_GEAR_LEVEL))
|
||||
.map((cw) => ({
|
||||
weaponId: cw.weaponId,
|
||||
name: cw.weapon.name,
|
||||
equipped: cw.equipped,
|
||||
level: cw.level,
|
||||
damageDice: scaledDamageDice(cw.weapon.damageDice, cw.level, cw.weapon.damageScaling, cw.weapon.minLevel),
|
||||
nextDamageDice: scaledDamageDice(cw.weapon.damageDice, cw.level + 1, cw.weapon.damageScaling, cw.weapon.minLevel),
|
||||
})),
|
||||
// The class tables stop at level 20; past it only the numbers move.
|
||||
beyondTables: classLevel > MAX_FEATURE_LEVEL,
|
||||
};
|
||||
}
|
||||
|
||||
// What taking a planned level does to a character's special abilities (see
|
||||
// advance): a first level in a new class writes what that class grants at
|
||||
// level 1 and teaches; any other goes through advance at the class's own level.
|
||||
function advanceIn(specialAbilities, plan, boonKey, { key = null, chosen = false } = {}) {
|
||||
if (plan.joining) return { specialAbilities: addFeatures(specialAbilities, joiningFeatures(plan.characterClass)), armorBonus: 0, tempHp: 0 };
|
||||
return advance(specialAbilities, plan.characterClass, plan.classLevel, boonKey, { key, chosen });
|
||||
}
|
||||
|
||||
// The road from level 1 to 20 for a class (and subclass): what every level
|
||||
// gives, as the progression timeline shows it. Level 1 is what the builder
|
||||
// writes; a level that grants a Boon says so. `fromSubclass` marks the
|
||||
// subclass's own lines.
|
||||
function progression(characterClass, subclassKey = null) {
|
||||
const subclass = findSubclass(characterClass, subclassKey);
|
||||
const levels = [];
|
||||
for (let level = 1; level <= MAX_FEATURE_LEVEL; level++) {
|
||||
const own = level === 1 ? CLASS_FEATURES[characterClass] || [] : featuresAt(characterClass, level);
|
||||
const fromSubclass = subclass ? subclass.features[level] || [] : [];
|
||||
const slots = maxSpellLevel(characterClass, level);
|
||||
levels.push({
|
||||
level,
|
||||
features: [
|
||||
...own.filter((entry) => !entry.boon).map(({ name, text }) => ({ name, text, fromSubclass: false })),
|
||||
...fromSubclass.map(({ name, text }) => ({ name, text, fromSubclass: true })),
|
||||
],
|
||||
boon: own.some((entry) => entry.boon),
|
||||
// The level a subclass is chosen, when none is yet.
|
||||
choosesSubclass: !subclass && subclassesOf(characterClass).length > 0 && level === SUBCLASS_LEVEL[characterClass],
|
||||
// Set when this level opens up a new level of spells.
|
||||
unlocksSpellLevel: slots > (level === 1 ? 0 : maxSpellLevel(characterClass, level - 1)) ? slots : null,
|
||||
});
|
||||
}
|
||||
return levels;
|
||||
}
|
||||
|
||||
module.exports = { LevelUpError, progression, advanceIn, featuresAt, owesSubclass, subclassChoice, subclassByDefault, switchSubclass, addFeatures, boonTaken, boonOptions, hardyTempHp, advance, spellsGainedAt, levelUpPlan };
|
||||
@@ -0,0 +1,267 @@
|
||||
const { featuresAt, addFeatures, boonTaken, boonOptions, hardyTempHp, advance, spellsGainedAt, levelUpPlan, switchSubclass, progression, LevelUpError } = require('./levelUp');
|
||||
const { SUBCLASSES, SUBCLASS_LEVEL } = require('./data/subclasses');
|
||||
const { LEVEL_FEATURES, BOONS } = require('./data/levelFeatures');
|
||||
const { CLASSES } = require('./data/classes');
|
||||
const { composeSpecialAbilities } = require('./buildFlow');
|
||||
|
||||
const boon = (key) => BOONS.find((b) => b.key === key);
|
||||
const CHAMPION = { key: 'CHAMPION' };
|
||||
|
||||
describe('the class tables', () => {
|
||||
test('cover every class from level 2 to 10, with a Boon at 4 and 8', () => {
|
||||
for (const cls of Object.keys(CLASSES)) {
|
||||
expect(LEVEL_FEATURES[cls]).toBeDefined();
|
||||
for (const level of [4, 8]) expect(featuresAt(cls, level).some((f) => f.boon)).toBe(true);
|
||||
for (const level of Object.keys(LEVEL_FEATURES[cls])) expect(Number(level)).toBeGreaterThanOrEqual(2);
|
||||
}
|
||||
// Fighters get a third Boon at 6, rogues at 10.
|
||||
expect(featuresAt('FIGHTER', 6).some((f) => f.boon)).toBe(true);
|
||||
expect(featuresAt('ROGUE', 10).some((f) => f.boon)).toBe(true);
|
||||
expect(featuresAt('WIZARD', 6).some((f) => f.boon)).toBe(false);
|
||||
});
|
||||
|
||||
test('every feature has a name and a text', () => {
|
||||
for (const levels of Object.values(LEVEL_FEATURES)) {
|
||||
for (const features of Object.values(levels)) {
|
||||
for (const f of features) expect(f.boon || (f.name && f.text)).toBeTruthy();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('casters are told at level 5 that cantrips double; others are not', () => {
|
||||
expect(featuresAt('WIZARD', 5).map((f) => f.name)).toContain('Cantrips');
|
||||
expect(featuresAt('PALADIN', 5).map((f) => f.name)).toEqual(['Extra Attack', 'Cantrips']);
|
||||
expect(featuresAt('FIGHTER', 5).map((f) => f.name)).toEqual(['Extra Attack']);
|
||||
});
|
||||
|
||||
test('the tables go on to level 20', () => {
|
||||
expect(featuresAt('FIGHTER', 11).map((f) => f.name)).toEqual(['Extra Attack']);
|
||||
expect(featuresAt('FIGHTER', 20).map((f) => f.name)).toEqual(['Extra Attack']);
|
||||
expect(featuresAt('ROGUE', 19).map((f) => f.boon || f.name)).toEqual([true, 'Sneak Attack']);
|
||||
expect(featuresAt('ARTIFICER', 7).map((f) => f.name)).toEqual(['Flash of Genius']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addFeatures', () => {
|
||||
test('adds a new feature as a line of its own, once', () => {
|
||||
const once = addFeatures('Second Wind — heal.', [{ name: 'Action Surge', text: 'One extra action.' }]);
|
||||
expect(once).toBe('Second Wind — heal.\nAction Surge — One extra action.');
|
||||
expect(addFeatures(once, [{ name: 'Action Surge', text: 'One extra action.' }])).toBe(once);
|
||||
});
|
||||
|
||||
test('an upgrade takes the place of the line with its name, however the dash was typed', () => {
|
||||
const upgrade = { name: 'Sneak Attack', text: '2d6.', upgrade: true };
|
||||
expect(addFeatures('Sneak Attack — 1d6.\nThieves’ Cant — slang.', [upgrade])).toBe('Sneak Attack — 2d6.\nThieves’ Cant — slang.');
|
||||
expect(addFeatures('sneak attack -- 1d6.', [upgrade])).toBe('Sneak Attack — 2d6.');
|
||||
// With no line to rewrite it is simply added.
|
||||
expect(addFeatures(null, [upgrade])).toBe('Sneak Attack — 2d6.');
|
||||
});
|
||||
|
||||
test('a feature that is not an upgrade leaves a line of the same name alone', () => {
|
||||
const text = addFeatures('Favored Enemy — Undead.', [{ name: 'Favored Enemy', text: 'Choose a second.' }]);
|
||||
expect(text).toBe('Favored Enemy — Undead.\nFavored Enemy — Choose a second.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('advance', () => {
|
||||
test('a rogue reaching level 3 has a bigger Sneak Attack and two new features', () => {
|
||||
const level1 = composeSpecialAbilities('HUMAN', 'ROGUE', []);
|
||||
const { specialAbilities } = advance(advance(level1, 'ROGUE', 2).specialAbilities, 'ROGUE', 3, undefined, { key: 'THIEF', chosen: true });
|
||||
const lines = specialAbilities.split('\n');
|
||||
expect(lines.filter((l) => l.startsWith('Sneak Attack'))).toEqual([expect.stringContaining('2d6')]);
|
||||
expect(lines.some((l) => l.startsWith('Cunning Action — '))).toBe(true);
|
||||
expect(lines.some((l) => l.startsWith('Fast Hands — '))).toBe(true);
|
||||
expect(lines.some((l) => l.startsWith('Versatile — '))).toBe(true); // what was there stays
|
||||
});
|
||||
|
||||
test('a Boon is written down, and says what it does beyond the text', () => {
|
||||
expect(advance(null, 'FIGHTER', 4, 'TOUGHENED', CHAMPION)).toEqual({ specialAbilities: 'Toughened — +1 AC (counted in your Extra AC).', armorBonus: 1, tempHp: 0 });
|
||||
const hardy = advance(null, 'FIGHTER', 4, 'HARDY', CHAMPION);
|
||||
expect(hardy).toMatchObject({ armorBonus: 0, tempHp: 5 });
|
||||
// Taken again, its one line grows.
|
||||
const twice = advance(hardy.specialAbilities, 'FIGHTER', 6, 'HARDY', CHAMPION);
|
||||
expect(twice.specialAbilities).toBe('Hardy — +10 maximum HP: gain 10 Temp HP after each long rest.');
|
||||
expect(twice.tempHp).toBe(10);
|
||||
expect(hardyTempHp(twice.specialAbilities)).toBe(10);
|
||||
});
|
||||
|
||||
test('a Boon cannot be taken more often than it allows', () => {
|
||||
const toughened = advance(null, 'FIGHTER', 4, 'TOUGHENED', CHAMPION).specialAbilities;
|
||||
expect(() => advance(toughened, 'FIGHTER', 6, 'TOUGHENED')).toThrow(LevelUpError);
|
||||
const mastery = advance(advance(null, 'FIGHTER', 4, 'WEAPON_MASTERY').specialAbilities, 'FIGHTER', 6, 'WEAPON_MASTERY').specialAbilities;
|
||||
expect(boonTaken(mastery, boon('WEAPON_MASTERY'))).toBe(2);
|
||||
expect(() => advance(mastery, 'FIGHTER', 8, 'WEAPON_MASTERY')).toThrow(LevelUpError);
|
||||
expect(() => advance(null, 'FIGHTER', 4, 'FLIGHT')).toThrow(LevelUpError);
|
||||
expect(boonOptions(mastery).find((o) => o.key === 'WEAPON_MASTERY').available).toBe(false);
|
||||
expect(boonOptions(mastery).find((o) => o.key === 'HARDY')).toMatchObject({ available: true, taken: 0 });
|
||||
});
|
||||
|
||||
test('with no Boon picked the line says one is owed', () => {
|
||||
const { specialAbilities, armorBonus } = advance(null, 'WIZARD', 4, undefined, { key: 'EVOCATION' });
|
||||
expect(specialAbilities).toBe('Boon (level 4) — Choose one with your DM: Weapon Mastery, Arcane Focus, Toughened, Hardy, Resolve.');
|
||||
expect(armorBonus).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('spellsGainedAt', () => {
|
||||
test('follows the unlock schedule', () => {
|
||||
expect(spellsGainedAt('FIGHTER', 3)).toBeNull();
|
||||
expect(spellsGainedAt('WIZARD', 3)).toEqual({ maxSpellLevel: 2, unlocksSpellLevel: 2, newSpells: 2, newCantrips: 0 });
|
||||
expect(spellsGainedAt('CLERIC', 4)).toEqual({ maxSpellLevel: 2, unlocksSpellLevel: null, newSpells: 1, newCantrips: 1 });
|
||||
expect(spellsGainedAt('WARLOCK', 5)).toMatchObject({ maxSpellLevel: 3, unlocksSpellLevel: 3, newSpells: 1 });
|
||||
// Half casters: two spells at level 2, then one at each odd level.
|
||||
expect(spellsGainedAt('PALADIN', 2)).toEqual({ maxSpellLevel: 1, unlocksSpellLevel: 1, newSpells: 2, newCantrips: 0 });
|
||||
expect(spellsGainedAt('RANGER', 4)).toMatchObject({ newSpells: 0, newCantrips: 0 });
|
||||
expect(spellsGainedAt('RANGER', 5)).toMatchObject({ maxSpellLevel: 2, unlocksSpellLevel: 2, newSpells: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('levelUpPlan', () => {
|
||||
const held = (over) => ({ weaponId: 'w', equipped: true, level: 1, weapon: { name: 'Longsword', damageDice: '1d8', damageScaling: 1, minLevel: 1 }, ...over });
|
||||
|
||||
test('lists the features, the Boon and the weapons that can take the free upgrade', () => {
|
||||
const plan = levelUpPlan({ level: 3, characterClass: 'FIGHTER', specialAbilities: null, weapons: [held(), held({ weaponId: 'p', weapon: { name: 'Dawnblade', damageDice: '1d8', damageScaling: 2, minLevel: 1 } }), held({ weaponId: 'top', level: 4 })] });
|
||||
expect(plan).toMatchObject({ fromLevel: 3, toLevel: 4, features: [], spells: null, beyondTables: false });
|
||||
expect(plan.boon).toHaveLength(5);
|
||||
// Only standard growth, and never past the character's new level.
|
||||
expect(plan.weapons).toEqual([{ weaponId: 'w', name: 'Longsword', equipped: true, level: 1, damageDice: '1d8', nextDamageDice: '1d10' }]);
|
||||
});
|
||||
|
||||
test('has no Boon to pick at a level that grants none', () => {
|
||||
const plan = levelUpPlan({ level: 1, characterClass: 'FIGHTER', specialAbilities: null, weapons: [] });
|
||||
expect(plan.boon).toBeNull();
|
||||
expect(plan.subclass).toBeNull();
|
||||
expect(plan.features.map((f) => f.name)).toEqual(['Action Surge']);
|
||||
});
|
||||
|
||||
test('asks for a subclass at the level the class chooses, and whenever one is still owed', () => {
|
||||
const fighter = { characterClass: 'FIGHTER', specialAbilities: null, weapons: [] };
|
||||
const plan = levelUpPlan({ ...fighter, level: 2 });
|
||||
expect(plan.subclass.level).toBe(3);
|
||||
expect(plan.subclass.options.map((o) => o.key)).toEqual(['CHAMPION', 'BATTLE_MASTER', 'SAMURAI', 'ARCANE_ARCHER', 'CAVALIER', 'ECHO_KNIGHT', 'ELDRITCH_KNIGHT', 'PSI_WARRIOR', 'PURPLE_DRAGON_KNIGHT', 'RUNE_KNIGHT']);
|
||||
expect(plan.subclass.options[0].features.map((f) => f.name)).toEqual(['Improved Critical']);
|
||||
// A wizard chooses a level earlier.
|
||||
expect(levelUpPlan({ ...fighter, characterClass: 'WIZARD', level: 1 }).subclass.level).toBe(2);
|
||||
// Still owed later on: the options then carry everything missed so far.
|
||||
const late = levelUpPlan({ ...fighter, level: 6 });
|
||||
expect(late.subclass.options[0].features.map((f) => f.name)).toEqual(['Improved Critical', 'Remarkable Athlete']);
|
||||
// With one chosen there is nothing to ask, and its features are in the list.
|
||||
const chosen = levelUpPlan({ ...fighter, level: 6, subclass: 'CHAMPION' });
|
||||
expect(chosen.subclass).toBeNull();
|
||||
expect(chosen.features.map((f) => f.name)).toEqual(['Remarkable Athlete']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a campaign without subclasses', () => {
|
||||
const fighter = { characterClass: 'FIGHTER', specialAbilities: null, weapons: [] };
|
||||
|
||||
test('asks for nothing: the class takes its first subclass at the level it would have chosen', () => {
|
||||
const plan = levelUpPlan({ ...fighter, level: 2 }, { subclasses: false });
|
||||
expect(plan.subclass).toBeNull();
|
||||
expect(plan.subclassTaken).toBe('CHAMPION');
|
||||
expect(plan.features.map((f) => f.name)).toEqual(['Improved Critical']);
|
||||
// Before that level, and once it is taken, there is nothing to take.
|
||||
expect(levelUpPlan({ ...fighter, level: 1 }, { subclasses: false }).subclassTaken).toBeNull();
|
||||
const later = levelUpPlan({ ...fighter, level: 6, subclass: 'CHAMPION' }, { subclasses: false });
|
||||
expect(later.subclassTaken).toBeNull();
|
||||
expect(later.features.map((f) => f.name)).toEqual(['Remarkable Athlete']);
|
||||
});
|
||||
|
||||
test('a character who joined above that level gets everything missed so far', () => {
|
||||
const plan = levelUpPlan({ ...fighter, level: 6 }, { subclasses: false });
|
||||
expect(plan.subclassTaken).toBe('CHAMPION');
|
||||
expect(plan.features.map((f) => f.name)).toEqual(['Improved Critical', 'Remarkable Athlete']);
|
||||
});
|
||||
|
||||
test('with subclasses on, the plan takes none by default', () => {
|
||||
expect(levelUpPlan({ ...fighter, level: 2 }).subclassTaken).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('subclasses', () => {
|
||||
test('every class has its full catalogue, each with a summary, a book and features from its choice level up to 20', () => {
|
||||
const keys = new Set();
|
||||
for (const cls of Object.keys(CLASSES)) {
|
||||
expect(SUBCLASSES[cls].length).toBeGreaterThanOrEqual(4);
|
||||
for (const subclass of SUBCLASSES[cls]) {
|
||||
expect(subclass.key && subclass.name && subclass.summary && subclass.source).toBeTruthy();
|
||||
expect(['2014', '2024']).toContain(subclass.edition);
|
||||
if (subclass.replaces) expect(SUBCLASSES[cls].map((s) => s.key)).toContain(subclass.replaces);
|
||||
const levels = Object.keys(subclass.features).map(Number);
|
||||
expect(Math.min(...levels)).toBe(SUBCLASS_LEVEL[cls]);
|
||||
expect(Math.max(...levels)).toBeLessThanOrEqual(20);
|
||||
expect(Math.max(...levels)).toBeGreaterThan(10); // nobody stops at the old tables
|
||||
for (const f of Object.values(subclass.features).flat()) {
|
||||
expect(f.name && f.text).toBeTruthy();
|
||||
expect(f.name).not.toMatch(/—|–|--/); // the dash is what ends a name on the sheet
|
||||
}
|
||||
// Keys are unique across classes: a multiclass character holds one per class.
|
||||
expect(keys.has(subclass.key)).toBe(false);
|
||||
keys.add(subclass.key);
|
||||
}
|
||||
}
|
||||
expect(keys.size).toBe(123);
|
||||
});
|
||||
|
||||
test('the first subclass of each class is still the one it always followed', () => {
|
||||
const firsts = Object.fromEntries(Object.entries(SUBCLASSES).map(([cls, list]) => [cls, list[0].key]));
|
||||
expect(firsts).toMatchObject({ BARBARIAN: 'BERSERKER', BARD: 'LORE', CLERIC: 'LIFE', DRUID: 'LAND', FIGHTER: 'CHAMPION', MONK: 'OPEN_HAND', PALADIN: 'DEVOTION', RANGER: 'HUNTER', ROGUE: 'THIEF', SORCERER: 'DRACONIC', WARLOCK: 'FIEND', WIZARD: 'EVOCATION' });
|
||||
});
|
||||
|
||||
test('a subclass adds its features to the class\'s at each level', () => {
|
||||
expect(featuresAt('FIGHTER', 3).map((f) => f.name)).toEqual([]);
|
||||
expect(featuresAt('FIGHTER', 3, 'CHAMPION').map((f) => f.name)).toEqual(['Improved Critical']);
|
||||
expect(featuresAt('CLERIC', 8, 'WAR').map((f) => f.boon || f.name)).toEqual([true, 'Destroy Undead', 'Divine Strike']);
|
||||
expect(featuresAt('FIGHTER', 3, 'LIFE')).toEqual([]); // another class's subclass counts for nothing
|
||||
});
|
||||
|
||||
test('without one, from the level the class chooses at, a line says a subclass is owed', () => {
|
||||
expect(advance(null, 'FIGHTER', 2).specialAbilities).toBe('Action Surge — Once per short rest, take one extra action on your turn.');
|
||||
const owed = advance(null, 'FIGHTER', 3).specialAbilities;
|
||||
expect(owed).toBe('Subclass — Choose one of the 10 with your DM (the level-up checklist lists them all).');
|
||||
// Said once, however many levels go by.
|
||||
expect(advance(owed, 'FIGHTER', 5).specialAbilities.split('\n').filter((l) => l.startsWith('Subclass — '))).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('picking one late writes everything it has given so far, and clears the line', () => {
|
||||
const owed = advance(advance(null, 'FIGHTER', 3).specialAbilities, 'FIGHTER', 5).specialAbilities;
|
||||
const { specialAbilities } = advance(owed, 'FIGHTER', 7, undefined, { key: 'BATTLE_MASTER', chosen: true });
|
||||
const lines = specialAbilities.split('\n');
|
||||
expect(lines.some((l) => l.startsWith('Subclass — '))).toBe(false);
|
||||
// The level 7 upgrade has taken the place of the level 3 line.
|
||||
expect(lines.filter((l) => l.startsWith('Combat Superiority — '))).toEqual([expect.stringContaining('Five superiority dice (d8)')]);
|
||||
expect(lines.filter((l) => l.startsWith('Manoeuvres — '))).toHaveLength(2);
|
||||
expect(lines.some((l) => l.startsWith('Know Your Enemy — '))).toBe(true);
|
||||
expect(() => advance(owed, 'FIGHTER', 7, undefined, { key: 'LIFE', chosen: true })).toThrow(LevelUpError);
|
||||
});
|
||||
|
||||
test('switching takes the old subclass\'s lines off and writes the new one\'s', () => {
|
||||
const champion = advance(advance('Second Wind — heal.', 'FIGHTER', 3, undefined, { key: 'CHAMPION', chosen: true }).specialAbilities, 'FIGHTER', 5, undefined, CHAMPION).specialAbilities;
|
||||
expect(champion.split('\n').map((l) => l.split(' — ')[0])).toEqual(['Second Wind', 'Improved Critical', 'Extra Attack']);
|
||||
const samurai = switchSubclass(champion, 'FIGHTER', 5, 'CHAMPION', 'SAMURAI');
|
||||
expect(samurai.split('\n').map((l) => l.split(' — ')[0])).toEqual(['Second Wind', 'Extra Attack', 'Fighting Spirit', 'Bonus Proficiency']);
|
||||
// Cleared altogether, the choice is owed again.
|
||||
expect(switchSubclass(samurai, 'FIGHTER', 5, 'SAMURAI', null).split('\n').map((l) => l.split(' — ')[0])).toEqual(['Second Wind', 'Extra Attack', 'Subclass']);
|
||||
// A line the class also writes under the same name is not taken away.
|
||||
const valor = advance('Extra Attack — mine.', 'BARD', 6, undefined, { key: 'VALOR', chosen: true }).specialAbilities;
|
||||
expect(switchSubclass(valor, 'BARD', 6, 'VALOR', 'LORE')).not.toContain('Combat Inspiration');
|
||||
});
|
||||
});
|
||||
|
||||
describe('progression', () => {
|
||||
test('runs from level 1 to 20, with the subclass marked and the Boons and spell levels shown', () => {
|
||||
const road = progression('FIGHTER', 'CHAMPION');
|
||||
expect(road).toHaveLength(20);
|
||||
expect(road[0].features.map((f) => f.name)).toEqual(['Second Wind', 'Fighting Style']);
|
||||
expect(road[2].features).toEqual([expect.objectContaining({ name: 'Improved Critical', fromSubclass: true })]);
|
||||
expect(road[3]).toMatchObject({ boon: true, features: [] });
|
||||
expect(road[17].features.map((f) => f.name)).toEqual(['Survivor']);
|
||||
});
|
||||
|
||||
test('without a subclass, says where one is chosen; for a caster, where spell levels open', () => {
|
||||
const road = progression('WIZARD');
|
||||
expect(road[1].choosesSubclass).toBe(true);
|
||||
expect(road.map((l) => l.unlocksSpellLevel).filter(Boolean)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
expect(progression('ARTIFICER')[0].unlocksSpellLevel).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,227 @@
|
||||
// Multiclassing (the 2014 Player’s Handbook rules): a character takes a level
|
||||
// in another class instead of the one they have. Their levels add up to their
|
||||
// character level; hit dice, hit points, class features and counters go by
|
||||
// each class's own level, and spell slots by the levels of every class that
|
||||
// casts. Pure: no DB calls.
|
||||
//
|
||||
// A character's first class is Character.characterClass (with its subclass);
|
||||
// the others are CharacterClassLevel rows. The first class's own level is the
|
||||
// character level less the others'.
|
||||
|
||||
const { CLASSES } = require('./data/classes');
|
||||
const { FULL_CASTER_SLOTS, PACT_SLOTS } = require('./data/spellSlots');
|
||||
const { CLASS_FEATURES } = require('./data/characterOptions');
|
||||
const { resourceState } = require('./classResources');
|
||||
const calculations = require('./calculations');
|
||||
|
||||
// What a class asks of the scores before anyone can take a level in it (or
|
||||
// leave it for another). Each entry is a list of alternatives; every ability
|
||||
// in an alternative must be 13 or more.
|
||||
const MULTICLASS_PREREQS = {
|
||||
ARTIFICER: [['INT']],
|
||||
BARBARIAN: [['STR']],
|
||||
BARD: [['CHA']],
|
||||
CLERIC: [['WIS']],
|
||||
DRUID: [['WIS']],
|
||||
FIGHTER: [['STR'], ['DEX']],
|
||||
MONK: [['DEX', 'WIS']],
|
||||
PALADIN: [['STR', 'CHA']],
|
||||
RANGER: [['DEX', 'WIS']],
|
||||
ROGUE: [['DEX']],
|
||||
SORCERER: [['CHA']],
|
||||
WARLOCK: [['CHA']],
|
||||
WIZARD: [['INT']],
|
||||
};
|
||||
const PREREQ_SCORE = 13;
|
||||
|
||||
const ABILITY_NAMES = { STR: 'Strength', DEX: 'Dexterity', CON: 'Constitution', INT: 'Intelligence', WIS: 'Wisdom', CHA: 'Charisma' };
|
||||
|
||||
// "Strength 13 or Dexterity 13", "Dexterity 13 and Wisdom 13".
|
||||
function prereqText(characterClass) {
|
||||
return (MULTICLASS_PREREQS[characterClass] || [])
|
||||
.map((all) => all.map((ability) => `${ABILITY_NAMES[ability]} ${PREREQ_SCORE}`).join(' and '))
|
||||
.join(' or ');
|
||||
}
|
||||
|
||||
// Whether final scores ({ STR: 14, ... }) meet a class's requirement.
|
||||
function meetsPrereq(characterClass, scores) {
|
||||
return (MULTICLASS_PREREQS[characterClass] || []).some((all) => all.every((ability) => (scores[ability] || 0) >= PREREQ_SCORE));
|
||||
}
|
||||
|
||||
// What a class teaches someone who comes to it from another (the 2014
|
||||
// multiclassing table), as a line for the special abilities.
|
||||
const MULTICLASS_PROFICIENCIES = {
|
||||
ARTIFICER: 'light and medium armor, shields, thieves’ tools and tinker’s tools',
|
||||
BARBARIAN: 'shields, simple and martial weapons',
|
||||
BARD: 'light armor, one skill of your choice and one musical instrument',
|
||||
CLERIC: 'light and medium armor and shields',
|
||||
DRUID: 'light and medium armor and shields (no metal)',
|
||||
FIGHTER: 'light and medium armor, shields, simple and martial weapons',
|
||||
MONK: 'simple weapons and shortswords',
|
||||
PALADIN: 'light and medium armor, shields, simple and martial weapons',
|
||||
RANGER: 'light and medium armor, shields, simple and martial weapons, and one skill from the ranger’s list',
|
||||
ROGUE: 'light armor, one skill from the rogue’s list, and thieves’ tools',
|
||||
SORCERER: 'nothing new: a sorcerer’s magic is in the blood',
|
||||
WARLOCK: 'light armor and simple weapons',
|
||||
WIZARD: 'nothing new: a wizard’s training is the spellbook',
|
||||
};
|
||||
|
||||
// The lines a character's first level in another class writes: what the class
|
||||
// grants at level 1 (multiclassing does not bring its saves or skills), and
|
||||
// what it teaches.
|
||||
function joiningFeatures(characterClass) {
|
||||
return [
|
||||
...(CLASS_FEATURES[characterClass] || []),
|
||||
{ name: `${CLASSES[characterClass].name} Training`, text: `Multiclassing into ${CLASSES[characterClass].name} teaches ${MULTICLASS_PROFICIENCIES[characterClass]}.` },
|
||||
];
|
||||
}
|
||||
|
||||
// Every class a character has levels in, the first first:
|
||||
// [{ characterClass, level, subclass, first }]. Takes a character with its
|
||||
// classLevels (an empty list or none: a single class).
|
||||
function classLevels(character) {
|
||||
const others = [...(character.classLevels || [])]
|
||||
.filter((row) => row.level > 0 && row.characterClass !== character.characterClass)
|
||||
.sort((a, b) => new Date(a.createdAt || 0) - new Date(b.createdAt || 0));
|
||||
const elsewhere = others.reduce((sum, row) => sum + row.level, 0);
|
||||
return [
|
||||
{ characterClass: character.characterClass, level: Math.max(1, (character.level || 1) - elsewhere), subclass: character.subclass || null, first: true },
|
||||
...others.map((row) => ({ characterClass: row.characterClass, level: row.level, subclass: row.subclass || null, first: false })),
|
||||
];
|
||||
}
|
||||
|
||||
// The classes a character could put their next level in: those they have
|
||||
// (always), and those whose requirement they and every class they have meet.
|
||||
// `scores` are the final ability scores.
|
||||
function classOptions(character, scores) {
|
||||
const have = classLevels(character);
|
||||
const leaving = have.filter((entry) => !meetsPrereq(entry.characterClass, scores));
|
||||
return Object.keys(CLASSES).map((characterClass) => {
|
||||
const current = have.find((entry) => entry.characterClass === characterClass);
|
||||
if (current) return { characterClass, level: current.level, eligible: true, problems: [] };
|
||||
const problems = [];
|
||||
if (!meetsPrereq(characterClass, scores)) problems.push(`${CLASSES[characterClass].name} needs ${prereqText(characterClass)}.`);
|
||||
for (const entry of leaving) problems.push(`Leaving ${CLASSES[entry.characterClass].name} for another class needs ${prereqText(entry.characterClass)}.`);
|
||||
return { characterClass, level: 0, eligible: problems.length === 0, problems };
|
||||
});
|
||||
}
|
||||
|
||||
// The character as it would be with one more level in `characterClass`: the
|
||||
// level and the class rows moved on. For working out the sheet afterwards.
|
||||
function withLevelIn(character, characterClass, subclass = undefined) {
|
||||
const next = { ...character, level: character.level + 1 };
|
||||
if (characterClass === character.characterClass) {
|
||||
if (subclass !== undefined) next.subclass = subclass;
|
||||
return next;
|
||||
}
|
||||
const rows = [...(character.classLevels || [])];
|
||||
const at = rows.findIndex((row) => row.characterClass === characterClass);
|
||||
if (at >= 0) rows[at] = { ...rows[at], level: rows[at].level + 1, ...(subclass !== undefined ? { subclass } : {}) };
|
||||
else rows.push({ characterClass, level: 1, subclass: subclass ?? null, createdAt: new Date() });
|
||||
next.classLevels = rows;
|
||||
return next;
|
||||
}
|
||||
|
||||
// Hit points: the first class's die in full at level 1, then each level the
|
||||
// average of its own class's die (rounded up), plus Constitution every level.
|
||||
function multiclassHpMax(classes, conMod) {
|
||||
let total = 0;
|
||||
classes.forEach((entry, i) => {
|
||||
const die = calculations.getClassHitDieSize(entry.characterClass);
|
||||
const average = Math.floor(die / 2) + 1;
|
||||
const levels = entry.level;
|
||||
total += i === 0 ? die + conMod + (levels - 1) * (average + conMod) : levels * (average + conMod);
|
||||
});
|
||||
return total;
|
||||
}
|
||||
|
||||
// Hit Dice: one per level, of each class's own size. Spent ones are counted
|
||||
// together; `size` is the first class's, the one rests roll.
|
||||
function multiclassHitDice(classes, used = 0) {
|
||||
const count = classes.reduce((sum, entry) => sum + entry.level, 0);
|
||||
const spent = Math.min(Math.max(Number(used) || 0, 0), count);
|
||||
return {
|
||||
size: calculations.getClassHitDieSize(classes[0].characterClass),
|
||||
count,
|
||||
used: spent,
|
||||
remaining: count - spent,
|
||||
pools: classes.map((entry) => ({ characterClass: entry.characterClass, size: calculations.getClassHitDieSize(entry.characterClass), count: entry.level })),
|
||||
};
|
||||
}
|
||||
|
||||
// How many levels a class adds to the shared caster level: all of a full
|
||||
// caster's, half a half caster's (an artificer's rounded up), a third of a
|
||||
// casting subclass's, and none of a warlock's (pact slots stand apart).
|
||||
function casterLevelOf(entry) {
|
||||
const kind = calculations.casterKind(entry.characterClass, entry.subclass);
|
||||
if (kind === 'FULL') return entry.level;
|
||||
if (kind === 'HALF') return entry.characterClass === 'ARTIFICER' ? Math.ceil(entry.level / 2) : Math.floor(entry.level / 2);
|
||||
if (kind === 'THIRD') return Math.floor(entry.level / 3);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The spell slots of a multiclassed character (pact slots aside): a single
|
||||
// casting class keeps its own table; two or more add up to a caster level on
|
||||
// the full caster table. A character whose only casting is a warlock's has
|
||||
// those pact slots. Null for none.
|
||||
function multiclassSpellSlots(classes) {
|
||||
const casters = classes.filter((entry) => {
|
||||
const kind = calculations.casterKind(entry.characterClass, entry.subclass);
|
||||
return kind && kind !== 'PACT';
|
||||
});
|
||||
if (casters.length === 0) {
|
||||
const warlock = classes.find((entry) => calculations.casterKind(entry.characterClass) === 'PACT');
|
||||
return warlock ? calculations.spellSlotsFor('WARLOCK', warlock.level) : null;
|
||||
}
|
||||
if (casters.length === 1) return calculations.spellSlotsFor(casters[0].characterClass, casters[0].level, casters[0].subclass);
|
||||
const casterLevel = casters.reduce((sum, entry) => sum + casterLevelOf(entry), 0);
|
||||
if (casterLevel < 1) return null;
|
||||
return { kind: 'FULL', restoresOn: 'LONG', max: [...FULL_CASTER_SLOTS[Math.min(casterLevel, FULL_CASTER_SLOTS.length) - 1]] };
|
||||
}
|
||||
|
||||
// A multiclassed warlock's pact slots, kept apart from the others' (they come
|
||||
// back on a short rest): { count, slotLevel }, or null when the warlock's are
|
||||
// the only slots (they are then the sheet's spell slots) or there is none.
|
||||
function pactSlotsOf(classes) {
|
||||
const warlock = classes.find((entry) => calculations.casterKind(entry.characterClass) === 'PACT');
|
||||
if (!warlock) return null;
|
||||
const others = classes.some((entry) => {
|
||||
const kind = calculations.casterKind(entry.characterClass, entry.subclass);
|
||||
return kind && kind !== 'PACT';
|
||||
});
|
||||
if (!others) return null;
|
||||
const [count, slotLevel] = PACT_SLOTS[Math.min(warlock.level, PACT_SLOTS.length) - 1];
|
||||
return { count, slotLevel };
|
||||
}
|
||||
|
||||
// The class counters of every class, each by its own class level. Where two
|
||||
// classes give the same counter (Channel Divinity), the larger one counts.
|
||||
function multiclassResources(classes, resourcesUsed, abilities, profBonus) {
|
||||
const byKey = new Map();
|
||||
for (const entry of classes) {
|
||||
for (const resource of resourceState({ ...entry, resourcesUsed }, abilities, profBonus)) {
|
||||
const had = byKey.get(resource.key);
|
||||
if (!had || resource.max > had.max) byKey.set(resource.key, resource);
|
||||
}
|
||||
}
|
||||
return [...byKey.values()];
|
||||
}
|
||||
|
||||
// Added to (not replacing) the exports object: calculations.js holds it from
|
||||
// before this file has finished loading.
|
||||
Object.assign(module.exports, {
|
||||
MULTICLASS_PREREQS,
|
||||
PREREQ_SCORE,
|
||||
prereqText,
|
||||
meetsPrereq,
|
||||
joiningFeatures,
|
||||
classLevels,
|
||||
classOptions,
|
||||
withLevelIn,
|
||||
multiclassHpMax,
|
||||
multiclassHitDice,
|
||||
casterLevelOf,
|
||||
multiclassSpellSlots,
|
||||
pactSlotsOf,
|
||||
multiclassResources,
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
const {
|
||||
prereqText,
|
||||
meetsPrereq,
|
||||
classLevels,
|
||||
classOptions,
|
||||
withLevelIn,
|
||||
multiclassHpMax,
|
||||
multiclassSpellSlots,
|
||||
pactSlotsOf,
|
||||
casterLevelOf,
|
||||
} = require('./multiclass');
|
||||
const { computeCharacterSheet, spellSlotsFor } = require('./calculations');
|
||||
const { levelUpPlan, advanceIn } = require('./levelUp');
|
||||
const { MULTICLASS_PATHS } = require('./data/multiclassPaths');
|
||||
const { findSubclass } = require('./data/subclasses');
|
||||
|
||||
const scores = (over = {}) => ({ STR: 10, DEX: 10, CON: 10, INT: 10, WIS: 10, CHA: 10, ...over });
|
||||
|
||||
describe('requirements', () => {
|
||||
test('say what a class needs, with either-or where there is a choice', () => {
|
||||
expect(prereqText('FIGHTER')).toBe('Strength 13 or Dexterity 13');
|
||||
expect(prereqText('MONK')).toBe('Dexterity 13 and Wisdom 13');
|
||||
});
|
||||
|
||||
test('are met by final scores of 13 or more', () => {
|
||||
expect(meetsPrereq('FIGHTER', scores({ DEX: 13 }))).toBe(true);
|
||||
expect(meetsPrereq('PALADIN', scores({ STR: 15, CHA: 12 }))).toBe(false);
|
||||
});
|
||||
|
||||
test('apply to the class left as well as the one joined', () => {
|
||||
const wizard = { characterClass: 'WIZARD', level: 3, classLevels: [] };
|
||||
const options = classOptions(wizard, scores({ CHA: 14 })); // INT only 10: can't leave wizard
|
||||
const warlock = options.find((o) => o.characterClass === 'WARLOCK');
|
||||
expect(warlock.eligible).toBe(false);
|
||||
expect(warlock.problems.join(' ')).toMatch(/Leaving Wizard/);
|
||||
expect(options.find((o) => o.characterClass === 'WIZARD')).toMatchObject({ eligible: true, level: 3 });
|
||||
expect(classOptions(wizard, scores({ INT: 15, CHA: 14 })).find((o) => o.characterClass === 'WARLOCK').eligible).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('class levels', () => {
|
||||
test('the first class has the levels the others leave', () => {
|
||||
const character = { characterClass: 'PALADIN', subclass: 'DEVOTION', level: 5, classLevels: [{ characterClass: 'WARLOCK', level: 2, subclass: null }] };
|
||||
expect(classLevels(character)).toEqual([
|
||||
{ characterClass: 'PALADIN', level: 3, subclass: 'DEVOTION', first: true },
|
||||
{ characterClass: 'WARLOCK', level: 2, subclass: null, first: false },
|
||||
]);
|
||||
expect(classLevels({ characterClass: 'BARD', level: 4 })).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('a level in a class moves the character and that class on', () => {
|
||||
const character = { characterClass: 'FIGHTER', level: 2, classLevels: [] };
|
||||
const next = withLevelIn(character, 'ROGUE');
|
||||
expect(next.level).toBe(3);
|
||||
expect(classLevels(next).map((e) => [e.characterClass, e.level])).toEqual([['FIGHTER', 2], ['ROGUE', 1]]);
|
||||
expect(classLevels(withLevelIn(next, 'FIGHTER')).map((e) => e.level)).toEqual([3, 1]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hit points', () => {
|
||||
test('the first class’s die in full, then each level’s own class average', () => {
|
||||
// Fighter 1 (10) + Wizard 2 (4 + 4), Constitution +1 at each of 3 levels.
|
||||
expect(multiclassHpMax([{ characterClass: 'FIGHTER', level: 1 }, { characterClass: 'WIZARD', level: 2 }], 1)).toBe(10 + 8 + 3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('spell slots', () => {
|
||||
test('one casting class keeps its own table', () => {
|
||||
expect(multiclassSpellSlots([{ characterClass: 'FIGHTER', level: 5 }, { characterClass: 'WIZARD', level: 3 }]).max).toEqual([4, 2]);
|
||||
});
|
||||
|
||||
test('two casting classes add up to a caster level on the full table', () => {
|
||||
// Paladin 6 (3) + Sorcerer 4 (4) = caster level 7.
|
||||
expect(multiclassSpellSlots([{ characterClass: 'PALADIN', level: 6 }, { characterClass: 'SORCERER', level: 4 }]).max).toEqual([4, 3, 3, 1]);
|
||||
expect(casterLevelOf({ characterClass: 'ARTIFICER', level: 3 })).toBe(2); // rounds up
|
||||
expect(casterLevelOf({ characterClass: 'FIGHTER', level: 6, subclass: 'ELDRITCH_KNIGHT' })).toBe(2);
|
||||
});
|
||||
|
||||
test('a warlock’s pact slots stand apart', () => {
|
||||
const classes = [{ characterClass: 'SORCERER', level: 5 }, { characterClass: 'WARLOCK', level: 3 }];
|
||||
expect(multiclassSpellSlots(classes).max).toEqual([4, 3, 2]);
|
||||
expect(pactSlotsOf(classes)).toEqual({ count: 2, slotLevel: 2 });
|
||||
expect(multiclassSpellSlots([{ characterClass: 'FIGHTER', level: 4 }, { characterClass: 'WARLOCK', level: 2 }]).kind).toBe('PACT');
|
||||
});
|
||||
|
||||
test('the Eldritch Knight and Arcane Trickster cast from level 3', () => {
|
||||
expect(spellSlotsFor('FIGHTER', 3, 'ELDRITCH_KNIGHT').max).toEqual([2]);
|
||||
expect(spellSlotsFor('ROGUE', 7, 'ARCANE_TRICKSTER').max).toEqual([4, 2]);
|
||||
expect(spellSlotsFor('FIGHTER', 3, 'CHAMPION')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the sheet', () => {
|
||||
const base = { strScore: 16, dexScore: 12, conScore: 14, intScore: 10, wisScore: 10, chaScore: 14, species: 'HUMAN' };
|
||||
|
||||
test('a multiclassed character adds up hit dice, hit points, slots and counters by class', () => {
|
||||
const sheet = computeCharacterSheet({ ...base, characterClass: 'PALADIN', level: 5, classLevels: [{ characterClass: 'SORCERER', level: 2 }] });
|
||||
expect(sheet.hitDice).toMatchObject({ count: 5, pools: [{ characterClass: 'PALADIN', size: 10, count: 3 }, { characterClass: 'SORCERER', size: 6, count: 2 }] });
|
||||
expect(sheet.hp.max).toBe(10 + 2 * 6 + 2 * 4 + 5 * 2); // CON 15 (14 + 1): +2
|
||||
expect(sheet.spellSlots.levels.map((l) => l.max)).toEqual([4, 2]); // caster level 1 + 2 = 3
|
||||
expect(sheet.spellcastingByClass.map((c) => c.characterClass)).toEqual(['PALADIN', 'SORCERER']);
|
||||
expect(sheet.resources.find((r) => r.key === 'SORCERY_POINTS').max).toBe(2);
|
||||
expect(sheet.resources.find((r) => r.key === 'LAY_ON_HANDS').max).toBe(15); // 5 × paladin level 3
|
||||
});
|
||||
|
||||
test('a single class is worked out as before', () => {
|
||||
const sheet = computeCharacterSheet({ ...base, characterClass: 'FIGHTER', level: 3, subclass: 'ELDRITCH_KNIGHT' });
|
||||
expect(sheet.hitDice.pools).toBeUndefined();
|
||||
expect(sheet.spellcasting.ability).toBe('INT');
|
||||
expect(sheet.spellSlots.levels).toEqual([{ level: 1, max: 2, used: 0, remaining: 2 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('levelling up into another class', () => {
|
||||
const fighter = { characterClass: 'FIGHTER', level: 4, specialAbilities: null, weapons: [], classLevels: [] };
|
||||
|
||||
test('plans the new class at its own level 1, with what it grants and teaches', () => {
|
||||
const plan = levelUpPlan(fighter, { multiclass: true, toClass: 'ROGUE', scores: scores({ STR: 15, DEX: 14 }) });
|
||||
expect(plan).toMatchObject({ characterClass: 'ROGUE', classLevel: 1, joining: true, toLevel: 5, boon: null, subclass: null });
|
||||
expect(plan.features.map((f) => f.name)).toEqual(['Sneak Attack', 'Thieves’ Cant', 'Rogue Training']);
|
||||
expect(plan.classChoice.options.find((o) => o.characterClass === 'ROGUE').eligible).toBe(true);
|
||||
const { specialAbilities } = advanceIn(null, plan, undefined);
|
||||
expect(specialAbilities).toMatch(/^Rogue Training — /m);
|
||||
});
|
||||
|
||||
test('a class’s Boons and subclass go by its own level', () => {
|
||||
const multi = { ...fighter, level: 5, classLevels: [{ characterClass: 'ROGUE', level: 2 }] };
|
||||
const plan = levelUpPlan(multi, { multiclass: true, toClass: 'ROGUE' });
|
||||
expect(plan).toMatchObject({ classLevel: 3, joining: false });
|
||||
expect(plan.subclass.options.map((o) => o.key)).toContain('ARCANE_TRICKSTER');
|
||||
expect(levelUpPlan(multi, { multiclass: true }).characterClass).toBe('FIGHTER');
|
||||
});
|
||||
|
||||
test('without the setting there is no class to choose', () => {
|
||||
expect(levelUpPlan(fighter).classChoice).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
test('every suggested route names real classes and subclasses', () => {
|
||||
for (const path of MULTICLASS_PATHS) {
|
||||
expect(path.steps.length).toBeGreaterThan(0);
|
||||
for (const step of path.steps) {
|
||||
if (step.subclass) expect(findSubclass(step.class, step.subclass)).not.toBeNull();
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
const { spellSlotsFor, spellSlotState, maxSpellLevel, hitDiceState, computeCharacterSheet } = require('./calculations');
|
||||
|
||||
describe('spellSlotsFor', () => {
|
||||
test('full casters follow the standard table', () => {
|
||||
expect(spellSlotsFor('WIZARD', 1)).toEqual({ kind: 'FULL', restoresOn: 'LONG', max: [2] });
|
||||
expect(spellSlotsFor('CLERIC', 3).max).toEqual([4, 2]);
|
||||
expect(spellSlotsFor('BARD', 5).max).toEqual([4, 3, 2]);
|
||||
expect(spellSlotsFor('DRUID', 9).max).toEqual([4, 3, 3, 3, 1]);
|
||||
expect(spellSlotsFor('SORCERER', 10).max).toEqual([4, 3, 3, 3, 2]);
|
||||
expect(spellSlotsFor('WIZARD', 20).max).toEqual([4, 3, 3, 3, 3, 2, 2, 1, 1]);
|
||||
});
|
||||
|
||||
test('half casters start at level 2', () => {
|
||||
expect(spellSlotsFor('PALADIN', 1).max).toEqual([]);
|
||||
expect(spellSlotsFor('PALADIN', 2).max).toEqual([2]);
|
||||
expect(spellSlotsFor('RANGER', 4).max).toEqual([3]);
|
||||
expect(spellSlotsFor('RANGER', 5).max).toEqual([4, 2]);
|
||||
expect(spellSlotsFor('PALADIN', 10).max).toEqual([4, 3, 2]);
|
||||
});
|
||||
|
||||
test('a warlock has a few slots, all of one level, back on a short rest', () => {
|
||||
expect(spellSlotsFor('WARLOCK', 1)).toEqual({ kind: 'PACT', restoresOn: 'SHORT', max: [1] });
|
||||
expect(spellSlotsFor('WARLOCK', 2).max).toEqual([2]);
|
||||
expect(spellSlotsFor('WARLOCK', 3).max).toEqual([0, 2]);
|
||||
expect(spellSlotsFor('WARLOCK', 9).max).toEqual([0, 0, 0, 0, 2]);
|
||||
});
|
||||
|
||||
test('classes without spells have none', () => {
|
||||
for (const cls of ['FIGHTER', 'BARBARIAN', 'ROGUE', 'MONK', null]) expect(spellSlotsFor(cls, 10)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('spellSlotState', () => {
|
||||
test('counts what is spent against what there is', () => {
|
||||
expect(spellSlotState('WIZARD', 3, [1, 2]).levels).toEqual([
|
||||
{ level: 1, max: 4, used: 1, remaining: 3 },
|
||||
{ level: 2, max: 2, used: 2, remaining: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
test('never counts more spent than the class has, or a level it has lost', () => {
|
||||
expect(spellSlotState('WIZARD', 1, [9, 2]).levels).toEqual([{ level: 1, max: 2, used: 2, remaining: 0 }]);
|
||||
});
|
||||
|
||||
test('lists only the slot levels a warlock actually has', () => {
|
||||
expect(spellSlotState('WARLOCK', 5, [0, 0, 1])).toEqual({ kind: 'PACT', restoresOn: 'SHORT', levels: [{ level: 3, max: 2, used: 1, remaining: 1 }] });
|
||||
});
|
||||
|
||||
test('is null where there is nothing to track', () => {
|
||||
expect(spellSlotState('FIGHTER', 5, [])).toBeNull();
|
||||
expect(spellSlotState('PALADIN', 1, [])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('maxSpellLevel', () => {
|
||||
test('is the highest slot level, as in the unlock schedule', () => {
|
||||
expect([1, 3, 5, 7, 9].map((level) => maxSpellLevel('WIZARD', level))).toEqual([1, 2, 3, 4, 5]);
|
||||
expect([1, 3, 5, 7, 9].map((level) => maxSpellLevel('WARLOCK', level))).toEqual([1, 2, 3, 4, 5]);
|
||||
expect([1, 2, 5, 9].map((level) => maxSpellLevel('PALADIN', level))).toEqual([0, 1, 2, 3]);
|
||||
expect(maxSpellLevel('ROGUE', 9)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hitDiceState', () => {
|
||||
test('one die per level, of the class size, less what is spent', () => {
|
||||
expect(hitDiceState('BARBARIAN', 4, 1)).toEqual({ size: 12, count: 4, used: 1, remaining: 3 });
|
||||
expect(hitDiceState('WIZARD', 2, 9)).toEqual({ size: 6, count: 2, used: 2, remaining: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('the sheet', () => {
|
||||
test('carries the slot tracker and the Hit Dice', () => {
|
||||
const sheet = computeCharacterSheet({ characterClass: 'CLERIC', level: 3, spellSlotsUsed: [1], hitDiceUsed: 2 });
|
||||
expect(sheet.spellSlots.levels.map((s) => s.remaining)).toEqual([3, 2]);
|
||||
expect(sheet.hitDice).toEqual({ size: 8, count: 3, used: 2, remaining: 1 });
|
||||
expect(computeCharacterSheet({ characterClass: 'ROGUE', level: 3 }).spellSlots).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the artificer', () => {
|
||||
test('is a half caster from level 1, rounding up', () => {
|
||||
expect(spellSlotsFor('ARTIFICER', 1)).toEqual({ kind: 'HALF', restoresOn: 'LONG', max: [2] });
|
||||
expect(spellSlotsFor('ARTIFICER', 5).max).toEqual([4, 2]);
|
||||
expect(maxSpellLevel('ARTIFICER', 20)).toBe(5);
|
||||
expect(spellSlotsFor('PALADIN', 1).max).toEqual([]); // a paladin still waits for level 2
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
const { challengeXp, encounterDifficulty, xpProgress } = require('./calculations');
|
||||
const { CR_XP, XP_THRESHOLDS, LEVEL_XP } = require('./data/xp');
|
||||
const { MONSTER_LIBRARY } = require('./data/library');
|
||||
|
||||
describe('challengeXp', () => {
|
||||
test('reads a rating however it was typed', () => {
|
||||
expect(challengeXp('0')).toBe(10);
|
||||
expect(challengeXp('1/8')).toBe(25);
|
||||
expect(challengeXp(' 1/4 ')).toBe(50);
|
||||
expect(challengeXp('0.5')).toBe(100);
|
||||
expect(challengeXp('CR 3')).toBe(700);
|
||||
expect(challengeXp(5)).toBe(1800);
|
||||
expect(challengeXp('30')).toBe(155000);
|
||||
});
|
||||
|
||||
test('is null for what is not a rating', () => {
|
||||
for (const text of [null, undefined, '', 'boss', '31', '1/3', '-1']) expect(challengeXp(text)).toBeNull();
|
||||
});
|
||||
|
||||
test('every monster in the built-in bestiary has a rating it can read', () => {
|
||||
for (const monster of MONSTER_LIBRARY) expect(challengeXp(monster.challengeRating)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the tables', () => {
|
||||
test('cover every rating from 0 to 30 and every level from 1 to 20, always rising', () => {
|
||||
expect(Object.keys(CR_XP)).toHaveLength(34);
|
||||
expect(XP_THRESHOLDS).toHaveLength(20);
|
||||
expect(LEVEL_XP).toHaveLength(20);
|
||||
for (let level = 1; level < 20; level++) {
|
||||
expect(LEVEL_XP[level]).toBeGreaterThan(LEVEL_XP[level - 1]);
|
||||
for (let i = 0; i < 4; i++) expect(XP_THRESHOLDS[level][i]).toBeGreaterThanOrEqual(XP_THRESHOLDS[level - 1][i]);
|
||||
}
|
||||
for (const [easy, medium, hard, deadly] of XP_THRESHOLDS) expect(easy < medium && medium < hard && hard < deadly).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('encounterDifficulty', () => {
|
||||
const party = [1, 1, 1, 1]; // easy 100, medium 200, hard 300, deadly 400
|
||||
|
||||
test('adds up the party\'s thresholds and the monsters\' XP', () => {
|
||||
const one = encounterDifficulty(party, ['1/2']);
|
||||
expect(one).toEqual({ xp: 100, adjustedXp: 100, multiplier: 1, rating: 'EASY', thresholds: { easy: 100, medium: 200, hard: 300, deadly: 400 }, monsters: 1, unrated: 0 });
|
||||
expect(encounterDifficulty([3, 5], []).thresholds).toEqual({ easy: 325, medium: 650, hard: 975, deadly: 1500 });
|
||||
});
|
||||
|
||||
test('more monsters make a harder fight than their XP alone', () => {
|
||||
expect(encounterDifficulty(party, ['1/8'])).toMatchObject({ xp: 25, adjustedXp: 25, rating: 'TRIVIAL' });
|
||||
expect(encounterDifficulty(party, ['1/4', '1/4'])).toMatchObject({ xp: 100, multiplier: 1.5, adjustedXp: 150, rating: 'EASY' });
|
||||
expect(encounterDifficulty(party, ['1/4', '1/4', '1/4'])).toMatchObject({ xp: 150, multiplier: 2, adjustedXp: 300, rating: 'HARD' });
|
||||
expect(encounterDifficulty(party, ['1/4', '1/4', '1/4', '1/4'])).toMatchObject({ xp: 200, adjustedXp: 400, rating: 'DEADLY' });
|
||||
expect(encounterDifficulty(party, Array(7).fill('0')).multiplier).toBe(2.5);
|
||||
expect(encounterDifficulty(party, Array(11).fill('0')).multiplier).toBe(3);
|
||||
expect(encounterDifficulty(party, Array(15).fill('0')).multiplier).toBe(4);
|
||||
});
|
||||
|
||||
test('leaves monsters with no rating out, and says how many', () => {
|
||||
expect(encounterDifficulty(party, ['1', 'boss', null])).toMatchObject({ xp: 200, adjustedXp: 200, monsters: 1, unrated: 2, rating: 'MEDIUM' });
|
||||
});
|
||||
|
||||
test('has no rating without a party, or with nothing rated to fight', () => {
|
||||
expect(encounterDifficulty([], ['1'])).toMatchObject({ xp: 200, rating: null, thresholds: null });
|
||||
expect(encounterDifficulty(party, [])).toMatchObject({ xp: 0, rating: null });
|
||||
expect(encounterDifficulty(party, ['boss'])).toMatchObject({ rating: null, unrated: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('xpProgress', () => {
|
||||
test('says what the next level takes and whether it is due', () => {
|
||||
expect(xpProgress(0, 1)).toEqual({ nextLevelAt: 300, levelUpDue: false });
|
||||
expect(xpProgress(299, 1)).toEqual({ nextLevelAt: 300, levelUpDue: false });
|
||||
expect(xpProgress(300, 1)).toEqual({ nextLevelAt: 300, levelUpDue: true });
|
||||
expect(xpProgress(300, 2)).toEqual({ nextLevelAt: 900, levelUpDue: false });
|
||||
expect(xpProgress(999999, 20)).toEqual({ nextLevelAt: null, levelUpDue: false });
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
require('dotenv').config();
|
||||
require('dotenv').config({ quiet: true });
|
||||
const http = require('http');
|
||||
const { Server } = require('socket.io');
|
||||
const { createApp } = require('./app');
|
||||
|
||||
@@ -12,11 +12,18 @@ function requireCampaignMember() {
|
||||
return async (req, res, next) => {
|
||||
const campaignId = req.params.campaignId || req.params.id;
|
||||
try {
|
||||
const campaign = await prisma.campaign.findUnique({ where: { id: campaignId } });
|
||||
if (!campaign) return res.status(404).json({ error: 'Campaign not found' });
|
||||
|
||||
const membership = await loadCampaignMembership(req.user.id, campaignId);
|
||||
if (!membership) return res.status(403).json({ error: 'Not a member of this campaign' });
|
||||
// One query for a member, which is nearly every request. Only when it
|
||||
// finds nothing is the campaign looked up, to tell a 404 from a 403.
|
||||
const found = await prisma.campaignMember.findUnique({
|
||||
where: { campaignId_userId: { campaignId, userId: req.user.id } },
|
||||
include: { campaign: true },
|
||||
});
|
||||
if (!found) {
|
||||
const exists = await prisma.campaign.findUnique({ where: { id: campaignId }, select: { id: true } });
|
||||
if (!exists) return res.status(404).json({ error: 'Campaign not found' });
|
||||
return res.status(403).json({ error: 'Not a member of this campaign' });
|
||||
}
|
||||
const { campaign, ...membership } = found;
|
||||
|
||||
req.campaign = campaign;
|
||||
req.membership = membership;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,12 +4,19 @@ const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCampaignMember, requireDM } = require('../middleware/campaignAccess');
|
||||
const { generateInviteCode } = require('../utils/inviteCode');
|
||||
const { computeCharacterSheet, GEAR_STATS, MAX_DAMAGE_SCALING, MAX_GEAR_LEVEL } = require('../game/calculations');
|
||||
const { SHEET_INCLUDE, settleHp } = require('../utils/sheet');
|
||||
const { computeCharacterSheet, xpProgress, GEAR_STATS, MAX_DAMAGE_SCALING, MAX_GEAR_LEVEL, MAX_LEVEL } = require('../game/calculations');
|
||||
const { rollDie } = require('../game/buildFlow');
|
||||
const { SHEET_INCLUDE, sheetOf, settleHp } = require('../utils/sheet');
|
||||
const { WEAPON_LIBRARY, ITEM_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../game/data/library');
|
||||
const { visitedLocationIds } = require('../utils/locations');
|
||||
const { deathSaveInfo } = require('../utils/hp');
|
||||
const { deathSaveInfo, lifeState } = require('../utils/hp');
|
||||
const { hitDiceProblem, shortRest, longRest } = require('../utils/rest');
|
||||
const { CURRENCIES } = require('../utils/grants');
|
||||
const { subclassName } = require('../game/data/subclasses');
|
||||
const { classLevels } = require('../game/multiclass');
|
||||
const { parseDice, diceOf, validValues, rollExpression, rollD20, d20Count, D20_MODES, MAX_DICE } = require('../game/dice');
|
||||
const { findSeed, normalizeCode, CODE_LENGTH } = require('../seeds');
|
||||
const { createCampaignFromSeed } = require('../seeds/createCampaign');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -30,6 +37,17 @@ function campaignSummary(campaign, role) {
|
||||
areaAttackAcPenalty: campaign.areaAttackAcPenalty,
|
||||
maxEquipped: campaign.maxEquipped,
|
||||
maxEquippedWeapons: campaign.maxEquippedWeapons,
|
||||
subclassesEnabled: campaign.subclassesEnabled,
|
||||
multiclassEnabled: campaign.multiclassEnabled,
|
||||
diceMode: campaign.diceMode,
|
||||
autoRollMonsters: campaign.autoRollMonsters,
|
||||
autoRollNpcs: campaign.autoRollNpcs,
|
||||
trackXp: campaign.trackXp,
|
||||
hpOnLevelUp: campaign.hpOnLevelUp,
|
||||
abilityScoreMethod: campaign.abilityScoreMethod,
|
||||
rollVisibility: campaign.rollVisibility,
|
||||
hideMonsterRolls: campaign.hideMonsterRolls,
|
||||
critRule: campaign.critRule,
|
||||
ownerId: campaign.ownerId,
|
||||
archivedAt: campaign.archivedAt,
|
||||
role,
|
||||
@@ -65,6 +83,18 @@ const createCampaignSchema = z.object({
|
||||
// they are checked when something is put on.
|
||||
maxEquipped: z.number().int().min(1).max(20).optional(),
|
||||
maxEquippedWeapons: z.number().int().min(0).max(20).optional(),
|
||||
// Off: nobody chooses a subclass, and each class follows its first one.
|
||||
subclassesEnabled: z.boolean().optional(),
|
||||
multiclassEnabled: z.boolean().optional(),
|
||||
diceMode: z.enum(['DIGITAL', 'PHYSICAL', 'BOTH']).optional(),
|
||||
autoRollMonsters: z.boolean().optional(),
|
||||
autoRollNpcs: z.boolean().optional(),
|
||||
trackXp: z.boolean().optional(),
|
||||
hpOnLevelUp: z.enum(['AVERAGE', 'ROLL']).optional(),
|
||||
abilityScoreMethod: z.enum(['ROLL_4D6', 'STANDARD_ARRAY', 'POINT_BUY']).optional(),
|
||||
rollVisibility: z.enum(['ALL', 'OWN']).optional(),
|
||||
hideMonsterRolls: z.boolean().optional(),
|
||||
critRule: z.enum(['DOUBLE_DICE', 'MAX_PLUS_ROLL']).optional(),
|
||||
});
|
||||
|
||||
// POST /campaigns — create, creator becomes DM/owner
|
||||
@@ -96,6 +126,28 @@ router.post('/', async (req, res, next) => {
|
||||
}
|
||||
});
|
||||
|
||||
// POST /campaigns/from-seed — a ready-made world (a file in /backend/seeds)
|
||||
// as a new campaign, by its code. As with a blank campaign, whoever creates
|
||||
// it is its DM and owner; the same code can be used again for another copy.
|
||||
router.post('/from-seed', async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ code: z.string().max(40) }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
if (normalizeCode(parsed.data.code).length !== CODE_LENGTH) {
|
||||
return res.status(400).json({ error: `A world code is ${CODE_LENGTH} letters or numbers` });
|
||||
}
|
||||
const seed = findSeed(parsed.data.code);
|
||||
if (!seed) return res.status(404).json({ error: 'There is no world with that code' });
|
||||
|
||||
// One transaction, so a failure doesn't leave half a world behind. A big
|
||||
// world is thousands of rows, which is more than the default 5 seconds.
|
||||
const campaign = await prisma.$transaction((tx) => createCampaignFromSeed(tx, req.user, seed), { timeout: 120000, maxWait: 20000 });
|
||||
res.status(201).json({ campaign: campaignSummary(campaign, 'DM') });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// POST /campaigns/join/:inviteCode — must be before requireCampaignMember-gated routes below
|
||||
router.post('/join/:inviteCode', async (req, res, next) => {
|
||||
try {
|
||||
@@ -187,7 +239,8 @@ router.post('/:id/invite', requireCampaignMember(), requireDM(), async (req, res
|
||||
// Characters within a campaign
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function characterSummary(character) {
|
||||
// `subclasses` is the campaign's setting: off, no subclass is named.
|
||||
function characterSummary(character, subclasses = true) {
|
||||
const sheet = computeCharacterSheet(
|
||||
character,
|
||||
character.skillProficiencies || [],
|
||||
@@ -201,18 +254,46 @@ function characterSummary(character) {
|
||||
name: character.name,
|
||||
species: character.species,
|
||||
characterClass: character.characterClass,
|
||||
subclassName: subclasses ? subclassName(character.characterClass, character.subclass) : null,
|
||||
level: character.level,
|
||||
levelUpsPending: character.levelUpsPending,
|
||||
// Every class it has levels in; one entry unless it has multiclassed.
|
||||
classes: classLevels(character).map((entry) => ({
|
||||
characterClass: entry.characterClass,
|
||||
level: entry.level,
|
||||
subclassName: subclasses ? subclassName(entry.characterClass, entry.subclass) : null,
|
||||
})),
|
||||
xp: character.xp,
|
||||
// A level already approved is no longer due.
|
||||
xpProgress: xpProgress(character.xp, Math.min(MAX_LEVEL, character.level + character.levelUpsPending)),
|
||||
buildStage: character.buildStage,
|
||||
currentHp: character.currentHp,
|
||||
tempHp: character.tempHp,
|
||||
deathSaves: deathSaveInfo(character),
|
||||
inspiration: character.inspiration,
|
||||
exhaustion: character.exhaustion,
|
||||
conditions: character.conditions,
|
||||
gold: character.gold,
|
||||
silver: character.silver,
|
||||
copper: character.copper,
|
||||
cash: character.cash,
|
||||
maxHp: character.buildStage === 'COMPLETE' ? sheet.hp.max : null,
|
||||
armorClass: character.buildStage === 'COMPLETE' ? sheet.armorClass : null,
|
||||
// What the DM reads off without asking for a roll.
|
||||
passives:
|
||||
character.buildStage === 'COMPLETE'
|
||||
? { perception: sheet.passivePerception, investigation: sheet.passiveInvestigation, insight: sheet.passiveInsight }
|
||||
: null,
|
||||
spellSaveDC: character.buildStage === 'COMPLETE' && sheet.spellcasting ? sheet.spellcasting.saveDC : null,
|
||||
// What each rolls with, for a check the DM calls for from the whole party.
|
||||
checks: character.buildStage === 'COMPLETE' ? { abilities: sheet.abilities, saves: sheet.saves, skills: sheet.skills } : null,
|
||||
// What is left to spend before the next rest: the slot tracker (null for
|
||||
// a character with no spell slots) and Hit Dice, with the Constitution
|
||||
// modifier each die healed is rolled with.
|
||||
spellSlots: character.buildStage === 'COMPLETE' ? sheet.spellSlots : null,
|
||||
hitDice: character.buildStage === 'COMPLETE' ? { ...sheet.hitDice, conModifier: sheet.abilities.CON.modifier } : null,
|
||||
// The class counters (Rage, Ki...), with how many of each are left.
|
||||
resources: character.buildStage === 'COMPLETE' ? sheet.resources : [],
|
||||
currentLocationId: character.currentLocationId,
|
||||
currentLocationName: character.currentLocation ? character.currentLocation.name : null,
|
||||
};
|
||||
@@ -225,7 +306,7 @@ router.get('/:id/characters', requireCampaignMember(), async (req, res, next) =>
|
||||
include: { ...SHEET_INCLUDE, currentLocation: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
const summaries = characters.map(characterSummary);
|
||||
const summaries = characters.map((character) => characterSummary(character, req.campaign.subclassesEnabled));
|
||||
if (req.membership.role === 'DM') return res.json({ characters: summaries });
|
||||
|
||||
// A player sees the party's headline numbers, but another character's
|
||||
@@ -291,6 +372,131 @@ router.post('/:id/characters', requireCampaignMember(), async (req, res, next) =
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Level-ups — the DM approves a level for any of the party at once. Each
|
||||
// approval is a checklist waiting (Character.levelUpsPending): the
|
||||
// character's player is told and makes their own picks (POST
|
||||
// /characters/:id/level-up), so five players levelling together do not queue
|
||||
// for the DM. A character with no player is the DM's to finish.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const approveLevelUpSchema = z.object({
|
||||
characterIds: z.array(z.string()).min(1).max(200),
|
||||
// Takes an approval back (one not yet used) instead of giving one.
|
||||
revoke: z.boolean().default(false),
|
||||
});
|
||||
|
||||
router.post('/:id/level-up', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = approveLevelUpSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { revoke } = parsed.data;
|
||||
const ids = [...new Set(parsed.data.characterIds)];
|
||||
|
||||
const characters = await prisma.character.findMany({
|
||||
where: { id: { in: ids }, campaignId: req.campaign.id, buildStage: 'COMPLETE' },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
if (characters.length !== ids.length) return res.status(400).json({ error: 'Pick finished characters from this campaign.' });
|
||||
|
||||
const results = characters.map((character) => {
|
||||
const who = { characterId: character.id, name: character.name, userId: character.userId, level: character.level };
|
||||
if (revoke) {
|
||||
return character.levelUpsPending > 0
|
||||
? { ...who, levelUpsPending: character.levelUpsPending - 1, skipped: null }
|
||||
: { ...who, levelUpsPending: 0, skipped: `${character.name} has no level up waiting.` };
|
||||
}
|
||||
if (character.level + character.levelUpsPending >= MAX_LEVEL) {
|
||||
return { ...who, levelUpsPending: character.levelUpsPending, skipped: `${character.name} is already at (or approved up to) level ${MAX_LEVEL}.` };
|
||||
}
|
||||
return { ...who, levelUpsPending: character.levelUpsPending + 1, skipped: null };
|
||||
});
|
||||
|
||||
const changed = results.filter((result) => !result.skipped);
|
||||
await prisma.$transaction(
|
||||
changed.map((result) => prisma.character.update({ where: { id: result.characterId }, data: { levelUpsPending: result.levelUpsPending } }))
|
||||
);
|
||||
const io = req.app.get('io');
|
||||
for (const { characterId, userId } of changed) {
|
||||
io.to(`campaign:${req.campaign.id}`).emit('character:updated', { characterId });
|
||||
// Tells the character's player there is a level to take (ids only).
|
||||
if (!revoke) io.to(`campaign:${req.campaign.id}`).emit('character:level-up-granted', { characterId, userId });
|
||||
}
|
||||
res.json({ revoke, results });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Rests — the DM rests any of the party at once (utils/rest.js)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const restSchema = z.object({
|
||||
type: z.enum(['SHORT', 'LONG']),
|
||||
characters: z
|
||||
.array(
|
||||
z.object({
|
||||
characterId: z.string(),
|
||||
// A short rest only: how many Hit Dice this character spends, and what
|
||||
// they added up to if they were rolled at the table. Left out, the
|
||||
// dice are rolled here.
|
||||
hitDice: z.number().int().min(0).max(MAX_LEVEL).default(0),
|
||||
rolled: z.number().int().min(0).max(1000).nullable().optional(),
|
||||
})
|
||||
)
|
||||
.min(1)
|
||||
.max(200),
|
||||
});
|
||||
|
||||
// A long rest puts HP, spell slots and half the Hit Dice back. A short rest
|
||||
// spends Hit Dice to heal and gives a warlock their slots. Nothing is written
|
||||
// unless every character asked for can take the rest as asked. The answer
|
||||
// says what happened to each, in the party's order.
|
||||
router.post('/:id/rest', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = restSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { type } = parsed.data;
|
||||
const asked = new Map(parsed.data.characters.map((entry) => [entry.characterId, entry]));
|
||||
|
||||
const characters = await prisma.character.findMany({
|
||||
where: { id: { in: [...asked.keys()] }, campaignId: req.campaign.id, buildStage: 'COMPLETE' },
|
||||
include: SHEET_INCLUDE,
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
if (characters.length !== asked.size) {
|
||||
return res.status(400).json({ error: 'Pick finished characters from this campaign.' });
|
||||
}
|
||||
|
||||
const outcomes = [];
|
||||
for (const character of characters) {
|
||||
const who = { characterId: character.id, name: character.name };
|
||||
const sheet = sheetOf(character);
|
||||
if (lifeState(character) === 'DEAD') {
|
||||
outcomes.push({ ...who, skipped: `${character.name} is dead: a rest does nothing for them.` });
|
||||
} else if (type === 'LONG') {
|
||||
outcomes.push({ ...who, skipped: null, ...longRest(character, sheet) });
|
||||
} else {
|
||||
const { hitDice: dice, rolled = null } = asked.get(character.id);
|
||||
const problem = hitDiceProblem(character, sheet, dice, rolled);
|
||||
if (problem) return res.status(400).json({ error: problem });
|
||||
const rolls = dice > 0 && rolled == null ? Array.from({ length: dice }, () => rollDie(sheet.hitDice.size)) : null;
|
||||
outcomes.push({ ...who, skipped: null, ...shortRest(character, sheet, { dice, rolls, rolled }) });
|
||||
}
|
||||
}
|
||||
|
||||
const rested = outcomes.filter((outcome) => outcome.data);
|
||||
await prisma.$transaction(rested.map((outcome) => prisma.character.update({ where: { id: outcome.characterId }, data: outcome.data })));
|
||||
const io = req.app.get('io');
|
||||
for (const { characterId } of rested) io.to(`campaign:${req.campaign.id}`).emit('character:updated', { characterId });
|
||||
|
||||
res.json({ type, results: outcomes.map(({ data, result, ...who }) => ({ ...who, ...result })) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Weapons (campaign-level pool; the DM manages it and sees all of it)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -439,6 +645,11 @@ const spellSchema = z.object({
|
||||
damageDice: z.string().max(20).optional().nullable(),
|
||||
isStartingOption: z.boolean().optional(),
|
||||
revives: z.boolean().optional(), // brings back the dead
|
||||
// How it lands in a battle: a spell attack against AC, or a save by each
|
||||
// target against the caster's DC (half damage on a success when halfOnSave).
|
||||
attackRoll: z.boolean().optional(),
|
||||
saveAbility: z.enum(['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA']).optional().nullable(),
|
||||
halfOnSave: z.boolean().optional(),
|
||||
});
|
||||
|
||||
router.post('/:id/spells', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
@@ -495,6 +706,8 @@ const itemSchema = z.object({
|
||||
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(),
|
||||
// Armor and shields: what kind it is. Null for anything else.
|
||||
armorType: z.enum(['LIGHT', 'MEDIUM', 'HEAVY', 'SHIELD']).optional().nullable(),
|
||||
...gearEffects,
|
||||
});
|
||||
|
||||
@@ -566,6 +779,20 @@ const monsterSchema = z.object({
|
||||
challengeRating: z.string().max(10).optional().nullable(),
|
||||
specialTrait: z.string().max(500).optional().nullable(),
|
||||
notes: z.string().max(2000).optional().nullable(),
|
||||
// Named attacks, for a monster with more than the one above. `count` is how
|
||||
// often it is made each turn (a multiattack).
|
||||
attacks: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string().trim().min(1).max(40),
|
||||
attackBonus: z.number().int().min(-20).max(50),
|
||||
damageDice: z.string().max(60).optional().nullable(),
|
||||
damageType: z.string().max(30).optional().nullable(),
|
||||
count: z.number().int().min(1).max(10).optional(),
|
||||
})
|
||||
)
|
||||
.max(8)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
router.post('/:id/monsters', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
@@ -606,6 +833,9 @@ router.delete('/:id/monsters/:monsterId', requireCampaignMember(), requireDM(),
|
||||
// Encounters
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// The campaign's own order, which the DM arranges.
|
||||
const ENCOUNTER_ORDER = [{ sortOrder: 'asc' }, { createdAt: 'asc' }];
|
||||
|
||||
router.get('/:id/encounters', requireCampaignMember(), async (req, res, next) => {
|
||||
try {
|
||||
const isDM = req.membership.role === 'DM';
|
||||
@@ -614,7 +844,7 @@ router.get('/:id/encounters', requireCampaignMember(), async (req, res, next) =>
|
||||
const mine = { archivedAt: null, participants: { some: { character: { userId: req.user.id } } } };
|
||||
const encounters = await prisma.encounter.findMany({
|
||||
where: { campaignId: req.campaign.id, ...(isDM ? {} : mine) },
|
||||
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'desc' }],
|
||||
orderBy: ENCOUNTER_ORDER,
|
||||
});
|
||||
// dmNotes never leaves the server for a player.
|
||||
res.json({ encounters: isDM ? encounters : encounters.map(({ dmNotes, ...encounter }) => encounter) });
|
||||
@@ -625,25 +855,64 @@ router.get('/:id/encounters', requireCampaignMember(), async (req, res, next) =>
|
||||
|
||||
const createEncounterSchema = z.object({
|
||||
name: z.string().min(1).max(120),
|
||||
mode: z.enum(['BATTLE', 'QUEST']).optional(),
|
||||
mode: z.enum(['BATTLE', 'QUEST', 'FREE_ROAM']).optional(),
|
||||
description: z.string().max(4000).optional().nullable(),
|
||||
locationId: z.string().optional().nullable(),
|
||||
// Free roam: the places the party can go to, from the campaign's locations.
|
||||
placeIds: z.array(z.string()).max(50).optional(),
|
||||
// Where it goes in the campaign's order: the top, the bottom, or straight
|
||||
// after another encounter (which wins over `position`). The bottom if
|
||||
// neither is given.
|
||||
position: z.enum(['TOP', 'BOTTOM']).optional(),
|
||||
afterEncounterId: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
router.post('/:id/encounters', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = createEncounterSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
if (parsed.data.locationId) {
|
||||
const location = await prisma.location.findFirst({ where: { id: parsed.data.locationId, campaignId: req.campaign.id } });
|
||||
const { position, afterEncounterId, placeIds = [], ...fields } = parsed.data;
|
||||
if (fields.locationId) {
|
||||
const location = await prisma.location.findFirst({ where: { id: fields.locationId, campaignId: req.campaign.id } });
|
||||
if (!location) return res.status(400).json({ error: 'That location is not part of this campaign.' });
|
||||
}
|
||||
const places = [...new Set(placeIds)];
|
||||
if (places.length > 0 && (await prisma.location.count({ where: { id: { in: places }, campaignId: req.campaign.id } })) !== places.length) {
|
||||
return res.status(400).json({ error: 'Pick places from this campaign\'s locations.' });
|
||||
}
|
||||
|
||||
// A new encounter goes to the top of the campaign's order.
|
||||
const first = await prisma.encounter.aggregate({ where: { campaignId: req.campaign.id }, _min: { sortOrder: true } });
|
||||
const encounter = await prisma.encounter.create({
|
||||
data: { ...parsed.data, campaignId: req.campaign.id, sortOrder: (first._min.sortOrder ?? 1) - 1 },
|
||||
const order = await prisma.encounter.findMany({
|
||||
where: { campaignId: req.campaign.id },
|
||||
orderBy: ENCOUNTER_ORDER,
|
||||
select: { id: true, sortOrder: true },
|
||||
});
|
||||
let index = position === 'TOP' ? 0 : order.length;
|
||||
if (afterEncounterId) {
|
||||
const at = order.findIndex((e) => e.id === afterEncounterId);
|
||||
if (at === -1) return res.status(400).json({ error: 'The encounter to put this one after is not part of this campaign.' });
|
||||
index = at + 1;
|
||||
}
|
||||
|
||||
const encounter = await prisma.$transaction(async (tx) => {
|
||||
// At the bottom nothing else moves. Anywhere else, the whole order is
|
||||
// numbered afresh around the newcomer.
|
||||
if (index === order.length) {
|
||||
const last = order.length > 0 ? order[order.length - 1].sortOrder : -1;
|
||||
return tx.encounter.create({ data: { ...fields, campaignId: req.campaign.id, sortOrder: last + 1 } });
|
||||
}
|
||||
const created = await tx.encounter.create({ data: { ...fields, campaignId: req.campaign.id, sortOrder: index } });
|
||||
for (const [i, existing] of order.entries()) {
|
||||
const sortOrder = i < index ? i : i + 1;
|
||||
if (existing.sortOrder !== sortOrder) await tx.encounter.update({ where: { id: existing.id }, data: { sortOrder } });
|
||||
}
|
||||
return created;
|
||||
});
|
||||
|
||||
// A free-roam scene's places. Who is in it is the DM's to add, as with
|
||||
// any encounter: the party may be split, some of them somewhere else.
|
||||
if (encounter.mode === 'FREE_ROAM' && places.length > 0) {
|
||||
await prisma.encounterLocation.createMany({ data: places.map((locationId) => ({ encounterId: encounter.id, locationId })) });
|
||||
}
|
||||
res.status(201).json({ encounter });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
@@ -706,8 +975,16 @@ const npcSchema = z.object({
|
||||
// null for an NPC who does not change money.
|
||||
exchangeGold: z.number().int().min(1).max(1000000).optional().nullable(),
|
||||
exchangeCash: z.number().int().min(1).max(1000000).optional().nullable(),
|
||||
// Where they are usually found: met there in a free-roam scene.
|
||||
locationId: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
// Whether a location named for an NPC, a ware or a scene is one of this campaign's.
|
||||
async function locationInCampaign(locationId, campaignId) {
|
||||
return !locationId || Boolean(await prisma.location.findFirst({ where: { id: locationId, campaignId }, select: { id: true } }));
|
||||
}
|
||||
const NOT_A_PLACE = 'That location is not part of this campaign.';
|
||||
|
||||
// A rate has two sides: both are given, or both are cleared.
|
||||
function halfARate(data) {
|
||||
const sides = [data.exchangeGold, data.exchangeCash];
|
||||
@@ -727,6 +1004,7 @@ router.post('/:id/npcs', requireCampaignMember(), requireDM(), async (req, res,
|
||||
const parsed = npcSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
if (halfARate(parsed.data)) return res.status(400).json({ error: HALF_A_RATE });
|
||||
if (!(await locationInCampaign(parsed.data.locationId, req.campaign.id))) return res.status(400).json({ error: NOT_A_PLACE });
|
||||
const npc = await prisma.npc.create({ data: { ...parsed.data, campaignId: req.campaign.id } });
|
||||
res.status(201).json({ npc });
|
||||
} catch (err) {
|
||||
@@ -739,6 +1017,7 @@ router.patch('/:id/npcs/:npcId', requireCampaignMember(), requireDM(), async (re
|
||||
const parsed = npcSchema.partial().safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
if (halfARate(parsed.data)) return res.status(400).json({ error: HALF_A_RATE });
|
||||
if (!(await locationInCampaign(parsed.data.locationId, req.campaign.id))) return res.status(400).json({ error: NOT_A_PLACE });
|
||||
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' });
|
||||
emitTradeChanged(req);
|
||||
@@ -851,6 +1130,7 @@ const wareSchema = z
|
||||
.object({
|
||||
npcId: z.string().optional(),
|
||||
encounterId: z.string().optional(),
|
||||
locationId: z.string().optional(), // a shop that is always at this place
|
||||
weaponId: z.string().optional(),
|
||||
itemId: z.string().optional(),
|
||||
price: z.number().int().min(1).max(1000000),
|
||||
@@ -858,7 +1138,7 @@ const wareSchema = z
|
||||
level: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
|
||||
stock: z.number().int().min(0).max(9999).optional().nullable(), // null: no limit
|
||||
})
|
||||
.refine((data) => Boolean(data.npcId) !== Boolean(data.encounterId), { message: 'Say who sells it: an NPC or an encounter, not both' })
|
||||
.refine((data) => [data.npcId, data.encounterId, data.locationId].filter(Boolean).length === 1, { message: 'Say where it is sold: by an NPC, at an encounter, or at a location (one of them)' })
|
||||
.refine((data) => Boolean(data.weaponId) !== Boolean(data.itemId), { message: 'Pick one weapon or one item to sell' });
|
||||
|
||||
router.post('/:id/wares', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
@@ -868,7 +1148,7 @@ router.post('/:id/wares', requireCampaignMember(), requireDM(), async (req, res,
|
||||
const data = parsed.data;
|
||||
const inCampaign = async (model, id) => (id ? prisma[model].findFirst({ where: { id, campaignId: req.campaign.id } }) : null);
|
||||
|
||||
const seller = (await inCampaign('npc', data.npcId)) || (await inCampaign('encounter', data.encounterId));
|
||||
const seller = (await inCampaign('npc', data.npcId)) || (await inCampaign('encounter', data.encounterId)) || (await inCampaign('location', data.locationId));
|
||||
if (!seller) return res.status(400).json({ error: 'That seller is not part of this campaign.' });
|
||||
const entry = (await inCampaign('weapon', data.weaponId)) || (await inCampaign('item', data.itemId));
|
||||
if (!entry) return res.status(400).json({ error: `That ${data.weaponId ? 'weapon' : 'item'} is not part of this campaign.` });
|
||||
@@ -924,6 +1204,14 @@ router.delete('/:id/wares/:wareId', requireCampaignMember(), requireDM(), async
|
||||
// backend/src/game/data/{weapons,spells,monsters}Library.js for the sets.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// A library entry goes into a campaign once: it is taken for as long as the
|
||||
// pool holds a row by its name, and free again when that row is renamed or
|
||||
// deleted.
|
||||
async function inPool(model, campaignId, name) {
|
||||
const row = await prisma[model].findFirst({ where: { campaignId, name: { equals: name, mode: 'insensitive' } }, select: { id: true } });
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
router.get('/:id/library', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
res.json({ weapons: WEAPON_LIBRARY, items: ITEM_LIBRARY, spells: SPELL_LIBRARY, monsters: MONSTER_LIBRARY });
|
||||
@@ -938,6 +1226,9 @@ router.post('/:id/weapons/from-library', requireCampaignMember(), requireDM(), a
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const template = WEAPON_LIBRARY.find((w) => w.key === parsed.data.key);
|
||||
if (!template) return res.status(404).json({ error: 'Unknown library weapon.' });
|
||||
if (await inPool('weapon', req.campaign.id, template.name)) {
|
||||
return res.status(409).json({ error: `${template.name} is already in this campaign.` });
|
||||
}
|
||||
const { key, category, ...data } = template;
|
||||
const weapon = await prisma.weapon.create({ data: { ...data, campaignId: req.campaign.id } });
|
||||
res.status(201).json({ weapon });
|
||||
@@ -952,6 +1243,9 @@ router.post('/:id/items/from-library', requireCampaignMember(), requireDM(), asy
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const template = ITEM_LIBRARY.find((i) => i.key === parsed.data.key);
|
||||
if (!template) return res.status(404).json({ error: 'Unknown library item.' });
|
||||
if (await inPool('item', req.campaign.id, template.name)) {
|
||||
return res.status(409).json({ error: `${template.name} is already in this campaign.` });
|
||||
}
|
||||
const { key, category, ...data } = template;
|
||||
const item = await prisma.item.create({ data: { ...data, campaignId: req.campaign.id } });
|
||||
res.status(201).json({ item });
|
||||
@@ -966,6 +1260,9 @@ router.post('/:id/spells/from-library', requireCampaignMember(), requireDM(), as
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const template = SPELL_LIBRARY.find((s) => s.key === parsed.data.key);
|
||||
if (!template) return res.status(404).json({ error: 'Unknown library spell.' });
|
||||
if (await inPool('spell', req.campaign.id, template.name)) {
|
||||
return res.status(409).json({ error: `${template.name} is already in this campaign.` });
|
||||
}
|
||||
const { key, classes, ...data } = template;
|
||||
const spell = await prisma.spell.create({ data: { ...data, campaignId: req.campaign.id } });
|
||||
res.status(201).json({ spell });
|
||||
@@ -980,6 +1277,9 @@ router.post('/:id/monsters/from-library', requireCampaignMember(), requireDM(),
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const template = MONSTER_LIBRARY.find((m) => m.key === parsed.data.key);
|
||||
if (!template) return res.status(404).json({ error: 'Unknown library monster.' });
|
||||
if (await inPool('monster', req.campaign.id, template.name)) {
|
||||
return res.status(409).json({ error: `${template.name} is already in this campaign.` });
|
||||
}
|
||||
const { key, ...data } = template;
|
||||
const monster = await prisma.monster.create({ data: { ...data, campaignId: req.campaign.id } });
|
||||
res.status(201).json({ monster });
|
||||
@@ -988,4 +1288,128 @@ router.post('/:id/monsters/from-library', requireCampaignMember(), requireDM(),
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Dice rolls — the table's dice roller (game/dice.js). A digital roll is made
|
||||
// here, never taken from the client; a physical one is typed in and checked
|
||||
// against its dice. Every roll is kept and announced, so the table (and above
|
||||
// all the DM) sees it.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const rollSchema = z
|
||||
.object({
|
||||
label: z.string().max(120).optional().nullable(),
|
||||
// A d20 plus `modifier` (a check, a save, an attack), or a dice expression (damage).
|
||||
kind: z.enum(['check', 'dice']),
|
||||
modifier: z.number().int().min(-99).max(99).default(0),
|
||||
mode: z.enum(D20_MODES).default('NORMAL'),
|
||||
expression: z.string().max(60).optional(),
|
||||
// Dice rolled at the table: what each showed, in order. Left out, the dice are rolled here.
|
||||
values: z.array(z.number().int().min(1).max(1000)).max(MAX_DICE).optional(),
|
||||
hidden: z.boolean().default(false), // the DM's alone
|
||||
encounterId: z.string().optional().nullable(),
|
||||
})
|
||||
.refine((roll) => roll.kind === 'check' || roll.expression, { message: 'A dice roll needs its dice, like "2d6+3".' });
|
||||
|
||||
// Rolls older than this are cleared away as new ones come in.
|
||||
const ROLL_KEEP_DAYS = 14;
|
||||
|
||||
const publicRoll = ({ id, userId, rollerName, label, notation, dice, modifier, total, natural, mode, physical, hidden, encounterId, createdAt }) => ({
|
||||
id,
|
||||
userId,
|
||||
rollerName,
|
||||
label,
|
||||
notation,
|
||||
dice,
|
||||
modifier,
|
||||
total,
|
||||
natural,
|
||||
mode,
|
||||
physical,
|
||||
hidden,
|
||||
encounterId,
|
||||
createdAt,
|
||||
});
|
||||
|
||||
// Which rolls a member may see: the DM every one; a player their own, and
|
||||
// everyone's (but the DM's hidden ones) where the campaign shows all rolls.
|
||||
function visibleRolls(req) {
|
||||
if (req.membership.role === 'DM') return {};
|
||||
if (req.campaign.rollVisibility === 'OWN') return { userId: req.user.id };
|
||||
return { OR: [{ userId: req.user.id }, { hidden: false }] };
|
||||
}
|
||||
|
||||
router.post('/:id/rolls', requireCampaignMember(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = rollSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { label, kind, modifier, mode, expression, values, encounterId } = parsed.data;
|
||||
const isDM = req.membership.role === 'DM';
|
||||
|
||||
// The campaign's dice decide whether a roll is made here or typed in.
|
||||
const diceMode = req.campaign.diceMode;
|
||||
if (values && diceMode === 'DIGITAL') return res.status(400).json({ error: 'This campaign plays with digital dice: the app rolls.' });
|
||||
if (!values && diceMode === 'PHYSICAL') return res.status(400).json({ error: 'This campaign plays with physical dice: roll at the table and enter what the dice show.' });
|
||||
|
||||
let rolled;
|
||||
let notation;
|
||||
if (kind === 'check') {
|
||||
const dice = Array.from({ length: d20Count(mode) }, () => ({ sides: 20 }));
|
||||
if (values && !validValues(dice, values)) {
|
||||
return res.status(400).json({ error: `Enter ${dice.length === 1 ? 'the d20' : 'both d20s'} you rolled: whole numbers from 1 to 20.` });
|
||||
}
|
||||
rolled = rollD20(modifier, mode, { values });
|
||||
notation = `1d20${modifier ? (modifier > 0 ? `+${modifier}` : `${modifier}`) : ''}`;
|
||||
} else {
|
||||
const dice = parseDice(expression);
|
||||
if (!dice) return res.status(400).json({ error: 'Those dice cannot be read. Write them like "2d6+3".' });
|
||||
if (values && !validValues(diceOf(dice), values)) {
|
||||
return res.status(400).json({ error: 'Enter what each die showed, in order, each within its die.' });
|
||||
}
|
||||
rolled = { ...rollExpression(dice, { values }), natural: null };
|
||||
notation = expression.replace(/\s+/g, '');
|
||||
}
|
||||
|
||||
const [roll] = await prisma.$transaction([
|
||||
prisma.diceRoll.create({
|
||||
data: {
|
||||
campaignId: req.campaign.id,
|
||||
userId: req.user.id,
|
||||
rollerName: req.user.displayName || 'Someone',
|
||||
label: label || null,
|
||||
notation,
|
||||
dice: rolled.dice,
|
||||
modifier: rolled.modifier,
|
||||
total: rolled.total,
|
||||
natural: rolled.natural,
|
||||
mode: kind === 'check' ? mode : 'NORMAL',
|
||||
physical: Boolean(values),
|
||||
hidden: isDM && parsed.data.hidden, // only the DM rolls behind the screen
|
||||
encounterId: encounterId || null,
|
||||
},
|
||||
}),
|
||||
prisma.diceRoll.deleteMany({ where: { campaignId: req.campaign.id, createdAt: { lt: new Date(Date.now() - ROLL_KEEP_DAYS * 24 * 60 * 60 * 1000) } } }),
|
||||
]);
|
||||
// Ids only: each member's page asks for the roll and gets it only if it is theirs to see.
|
||||
req.app.get('io').to(`campaign:${req.campaign.id}`).emit('roll:created', { rollId: roll.id, userId: roll.userId });
|
||||
res.status(201).json({ roll: publicRoll(roll) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// GET /campaigns/:id/rolls — the latest rolls this member may see, newest first.
|
||||
router.get('/:id/rolls', requireCampaignMember(), async (req, res, next) => {
|
||||
try {
|
||||
const limit = Math.min(Math.max(Number(req.query.limit) || 30, 1), 100);
|
||||
const rolls = await prisma.diceRoll.findMany({
|
||||
where: { campaignId: req.campaign.id, ...visibleRolls(req) },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: limit,
|
||||
});
|
||||
res.json({ rolls: rolls.map(publicRoll) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -8,30 +8,49 @@ const {
|
||||
computeCharacterSheet,
|
||||
computeWeaponStats,
|
||||
getClassSaveProficiencies,
|
||||
getClassHitDieSize,
|
||||
getClassSpellcastingAbility,
|
||||
scaledDamageDice,
|
||||
canUseGear,
|
||||
spellSlotState,
|
||||
xpProgress,
|
||||
MAX_GEAR_LEVEL,
|
||||
MAX_LEVEL,
|
||||
MAX_SLOT_LEVEL,
|
||||
ABILITIES,
|
||||
} = require('../game/calculations');
|
||||
const { LevelUpError, advance, advanceIn, levelUpPlan, switchSubclass, subclassByDefault } = require('../game/levelUp');
|
||||
const { classLevels, withLevelIn } = require('../game/multiclass');
|
||||
const { CLASSES } = require('../game/data/classes');
|
||||
const { resourceTally, MAX_EXHAUSTION } = require('../game/classResources');
|
||||
const { SUBCLASS_LEVEL, SUBCLASSES, subclassesOf, findSubclass, subclassName, newerVersionOf, subclassSummary } = require('../game/data/subclasses');
|
||||
const {
|
||||
rollDie,
|
||||
rollAbilityScore,
|
||||
abilityScoreFromDice,
|
||||
speciesChoicesForRoll,
|
||||
classChoicesForRoll,
|
||||
SPECIES_ROLL_DIE,
|
||||
CLASS_ROLL_DIE,
|
||||
autoSelectSkills,
|
||||
validateManualRoll,
|
||||
validatePicks,
|
||||
composeFromPicks,
|
||||
validateTalents,
|
||||
composeSpecialAbilities,
|
||||
STANDARD_ARRAY,
|
||||
POINT_BUY_BUDGET,
|
||||
pointBuyCost,
|
||||
effectiveDiceMode,
|
||||
} = require('../game/buildFlow');
|
||||
const characterOptions = require('../game/data/characterOptions');
|
||||
const { speciesBonusProblem } = require('../game/data/species');
|
||||
const { SKILLS } = require('../game/data/skills');
|
||||
const { CURRENCIES, COINS, COIN_VALUE, COIN_COLUMN, InsufficientGoldError, adjustGold, spendCoins, worthInGold, giveGear } = require('../utils/grants');
|
||||
const { recordVisits } = require('../utils/locations');
|
||||
const { SHEET_INCLUDE, settleHp } = require('../utils/sheet');
|
||||
const { SHEET_INCLUDE, sheetOf, settleHp, bySpellLevel } = require('../utils/sheet');
|
||||
const { inTurnOrder, weaponSwapOpen } = require('../game/combat');
|
||||
const { isFallen } = require('../utils/actions');
|
||||
const { absorbDamage, NO_DEATH_SAVES, lifeState, deathSaveInfo, settleDeathSaves, changeHp, rollDeathSave } = require('../utils/hp');
|
||||
|
||||
const router = express.Router();
|
||||
@@ -48,10 +67,16 @@ async function loadFullCharacter(id) {
|
||||
weapons: { include: { weapon: true } },
|
||||
spells: { include: { spell: true } },
|
||||
currentLocation: true,
|
||||
classLevels: true,
|
||||
campaign: { select: { subclassesEnabled: true, multiclassEnabled: true, diceMode: true, hpOnLevelUp: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Whether a character's campaign uses subclasses. Takes a character loaded
|
||||
// with its campaign (loadFullCharacter).
|
||||
const usesSubclasses = (character) => !character.campaign || character.campaign.subclassesEnabled;
|
||||
|
||||
// privateNotes is a real privacy boundary, not a UI hide — it's only ever
|
||||
// included in the payload for the character's own owning player.
|
||||
//
|
||||
@@ -63,6 +88,8 @@ async function loadFullCharacter(id) {
|
||||
function serializeCharacter(character, isOwner, isDM = true) {
|
||||
const restricted = !isOwner && !isDM;
|
||||
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
|
||||
// With subclasses switched off for the campaign, none is named or offered.
|
||||
const subclasses = usesSubclasses(character);
|
||||
return {
|
||||
id: character.id,
|
||||
campaignId: character.campaignId,
|
||||
@@ -71,11 +98,29 @@ function serializeCharacter(character, isOwner, isDM = true) {
|
||||
name: character.name,
|
||||
species: character.species,
|
||||
characterClass: character.characterClass,
|
||||
subclass: subclasses ? character.subclass : null,
|
||||
subclassName: subclasses ? subclassName(character.characterClass, character.subclass) : null,
|
||||
// What the class can choose from, and the level it chooses at.
|
||||
subclassLevel: subclasses ? (SUBCLASS_LEVEL[character.characterClass] ?? null) : null,
|
||||
subclassOptions: subclasses ? subclassesOf(character.characterClass).map(subclassSummary) : [],
|
||||
// The 2024 subclass that updates the one the character follows, if any.
|
||||
subclassUpgrade: subclasses && newerVersionOf(character.characterClass, character.subclass) ? subclassSummary(newerVersionOf(character.characterClass, character.subclass)) : null,
|
||||
level: character.level,
|
||||
// Levels the DM has approved that are still to be taken (their picks made).
|
||||
levelUpsPending: character.levelUpsPending,
|
||||
// Every class the character has levels in, the first first; one entry
|
||||
// unless they have multiclassed.
|
||||
classes: classLevels(character).map((entry) => ({
|
||||
characterClass: entry.characterClass,
|
||||
level: entry.level,
|
||||
subclass: subclasses ? entry.subclass : null,
|
||||
subclassName: subclasses ? subclassName(entry.characterClass, entry.subclass) : null,
|
||||
})),
|
||||
xp: character.xp,
|
||||
// A level already approved is no longer due.
|
||||
xpProgress: xpProgress(character.xp, Math.min(MAX_LEVEL, character.level + character.levelUpsPending)),
|
||||
motivation: character.motivation,
|
||||
halfElfBonusAbility1: character.halfElfBonusAbility1,
|
||||
halfElfBonusAbility2: character.halfElfBonusAbility2,
|
||||
speciesBonusChoices: character.speciesBonusChoices || {},
|
||||
rolledScores: {
|
||||
STR: character.strScore,
|
||||
DEX: character.dexScore,
|
||||
@@ -87,12 +132,18 @@ function serializeCharacter(character, isOwner, isDM = true) {
|
||||
currentHp: character.currentHp,
|
||||
tempHp: character.tempHp,
|
||||
deathSaves: deathSaveInfo(character),
|
||||
inspiration: character.inspiration,
|
||||
exhaustion: character.exhaustion,
|
||||
conditions: character.conditions,
|
||||
armorBonus: character.armorBonus,
|
||||
specialAbilities: character.specialAbilities,
|
||||
background: character.background,
|
||||
appearance: character.appearance,
|
||||
privateNotes: isOwner ? character.privateNotes : undefined,
|
||||
diceMode: character.diceMode,
|
||||
// The dice this character rolls with, and whether that is theirs to choose
|
||||
// (the campaign leaves it to each character) or the campaign's.
|
||||
diceMode: effectiveDiceMode(character.campaign, character),
|
||||
diceModeChoosable: !character.campaign || character.campaign.diceMode === 'BOTH',
|
||||
currentLocationId: restricted ? null : character.currentLocationId,
|
||||
currentLocation: restricted ? null : character.currentLocation || null,
|
||||
gold: restricted ? null : character.gold,
|
||||
@@ -113,12 +164,18 @@ function serializeCharacter(character, isOwner, isDM = true) {
|
||||
: 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) })),
|
||||
weapons: character.weapons.map((cw) => {
|
||||
// What this character rolls with it: to hit, and on top of its dice.
|
||||
const { attackBonus, damageBonus } = computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true, cw.level);
|
||||
return {
|
||||
...cw,
|
||||
scaledDamageDice: scaledDamageDice(cw.weapon.damageDice, cw.level, cw.weapon.damageScaling, cw.weapon.minLevel),
|
||||
attackBonus,
|
||||
damageBonus,
|
||||
usable: canUseGear(character.level, cw.level),
|
||||
};
|
||||
}),
|
||||
spells: [...character.spells].sort(bySpellLevel).map((cs) => ({ ...cs, usable: canUseGear(character.level, cs.spell.level) })),
|
||||
sheet: character.buildStage === 'COMPLETE' ? sheet : null,
|
||||
};
|
||||
}
|
||||
@@ -135,6 +192,10 @@ router.get('/build/options', (req, res) => {
|
||||
talentPicks: TALENT_PICKS,
|
||||
background: BACKGROUND_GROUPS,
|
||||
appearance: APPEARANCE_GROUPS,
|
||||
// Each class's subclasses, as the builder's subclass step lists them, and
|
||||
// the level each class gets its subclass's first gifts at.
|
||||
subclasses: Object.fromEntries(Object.entries(SUBCLASSES).map(([cls, list]) => [cls, list.map(subclassSummary)])),
|
||||
subclassLevels: SUBCLASS_LEVEL,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -158,8 +219,13 @@ const patchCharacterSchema = z.object({
|
||||
appearance: z.string().max(4000).nullable().optional(),
|
||||
privateNotes: z.string().max(4000).nullable().optional(),
|
||||
currentLocationId: z.string().nullable().optional(),
|
||||
level: z.number().int().min(1).max(20).optional(),
|
||||
xp: z.number().int().min(0).optional(),
|
||||
level: z.number().int().min(1).max(MAX_LEVEL).optional(),
|
||||
subclass: z.string().max(40).nullable().optional(), // a key from game/data/subclasses.js; null clears it
|
||||
xp: z.number().int().min(0).max(10000000).optional(),
|
||||
hitDiceUsed: z.number().int().min(0).max(MAX_LEVEL).optional(),
|
||||
inspiration: z.boolean().optional(),
|
||||
exhaustion: z.number().int().min(0).max(MAX_EXHAUSTION).optional(),
|
||||
conditions: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
|
||||
});
|
||||
|
||||
// Progression and placement are the DM's call, and so is rewriting what the
|
||||
@@ -168,8 +234,11 @@ const patchCharacterSchema = z.object({
|
||||
// a player cannot heal or hurt their own character. 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). The armor bonus is the DM's
|
||||
// adjustment on top of what equipped gear gives, so it is the DM's too.
|
||||
const DM_ONLY_PATCH_FIELDS = ['currentHp', 'tempHp', 'level', 'xp', 'currentLocationId', 'speedOverride', 'armorBonus', 'specialAbilities', 'background', 'appearance'];
|
||||
// adjustment on top of what equipped gear gives, so it is the DM's too. Hit
|
||||
// Dice are spent on a rest, which the DM runs. Exhaustion and conditions are
|
||||
// the DM's to give and take away. Inspiration is the DM's to give; the player
|
||||
// may spend it (checked below).
|
||||
const DM_ONLY_PATCH_FIELDS = ['currentHp', 'tempHp', 'level', 'subclass', 'xp', 'currentLocationId', 'speedOverride', 'armorBonus', 'specialAbilities', 'background', 'appearance', 'hitDiceUsed', 'exhaustion', 'conditions'];
|
||||
|
||||
function clamp(value, min, max) {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
@@ -184,7 +253,55 @@ router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, n
|
||||
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 HP, temp HP, level, XP, speed, armor bonus, location, special abilities, background or appearance.' });
|
||||
return res.status(403).json({ error: 'Only the DM can change HP, temp HP, Hit Dice, level, subclass, XP, speed, armor bonus, location, exhaustion, conditions, special abilities, background or appearance.' });
|
||||
}
|
||||
if (!req.isDM && parsed.data.inspiration === true) {
|
||||
return res.status(403).json({ error: 'Only the DM can give inspiration. You can spend it.' });
|
||||
}
|
||||
if (parsed.data.conditions) parsed.data.conditions = [...new Set(parsed.data.conditions)];
|
||||
|
||||
const newLevel = parsed.data.level ?? req.character.level;
|
||||
if (parsed.data.level !== undefined || parsed.data.hitDiceUsed !== undefined) {
|
||||
// A character has one Hit Die per level, so none can be spent beyond that.
|
||||
parsed.data.hitDiceUsed = Math.min(parsed.data.hitDiceUsed ?? req.character.hitDiceUsed, newLevel);
|
||||
}
|
||||
if (newLevel !== req.character.level) {
|
||||
// Spent slots of a level the character no longer has are forgotten.
|
||||
const slots = spellSlotState(req.character.characterClass, newLevel, req.character.spellSlotsUsed);
|
||||
const tally = [];
|
||||
for (const slot of slots ? slots.levels : []) tally[slot.level - 1] = slot.used;
|
||||
parsed.data.spellSlotsUsed = Array.from(tally, (used) => used || 0);
|
||||
}
|
||||
const characterClass = req.character.characterClass;
|
||||
const askedSubclass = parsed.data.subclass; // before a level change may take one by default
|
||||
let abilities = parsed.data.specialAbilities === undefined ? req.character.specialAbilities : null;
|
||||
const writesAbilities = req.character.buildStage === 'COMPLETE' && parsed.data.specialAbilities === undefined;
|
||||
if (writesAbilities && newLevel > req.character.level) {
|
||||
// Setting a higher level by hand still writes down what the class and
|
||||
// subclass give on the way there. A Boon, and a subclass not yet picked,
|
||||
// are left as a line saying one is owed: picking them is part of
|
||||
// levelling up properly (POST /:id/level-up).
|
||||
let key = req.character.subclass;
|
||||
for (let level = req.character.level + 1; level <= newLevel; level++) {
|
||||
// With subclasses switched off, the class's first one is taken at the
|
||||
// level it would have been chosen.
|
||||
const taken = req.campaign.subclassesEnabled ? null : subclassByDefault(characterClass, level, key);
|
||||
abilities = advance(abilities, characterClass, level, undefined, taken ? { key: taken, chosen: true } : { key }).specialAbilities;
|
||||
if (taken) key = taken;
|
||||
}
|
||||
parsed.data.specialAbilities = abilities;
|
||||
if (key !== req.character.subclass && askedSubclass === undefined) parsed.data.subclass = key;
|
||||
}
|
||||
if (askedSubclass !== undefined && askedSubclass !== req.character.subclass) {
|
||||
if (!req.campaign.subclassesEnabled) return res.status(400).json({ error: 'Subclasses are switched off for this campaign.' });
|
||||
const picked = askedSubclass;
|
||||
if (picked !== null) {
|
||||
if (!findSubclass(characterClass, picked)) return res.status(400).json({ error: 'That is not a subclass of this character\'s class.' });
|
||||
// A path can be set before the class reaches it, as the builder does;
|
||||
// its lines are written as the levels come.
|
||||
}
|
||||
// The old subclass's lines come off the sheet and the new one's go on.
|
||||
if (writesAbilities) parsed.data.specialAbilities = switchSubclass(abilities, characterClass, newLevel, req.character.subclass, picked);
|
||||
}
|
||||
|
||||
// Damage is soaked by temp HP before it reaches real HP — unless this
|
||||
@@ -307,6 +424,331 @@ router.post('/:id/death-saves', requireCharacterAccess({ write: true }), async (
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Spell slots — the slot tracker. How many slots there are comes from class
|
||||
// and level (game/calculations.js); the character row keeps how many are spent.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const ORDINALS = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th'];
|
||||
const slotLevelSchema = z.number().int().min(1).max(MAX_SLOT_LEVEL);
|
||||
|
||||
const spellSlotSchema = z.discriminatedUnion('action', [
|
||||
// Casting a spell: one slot of that level is spent.
|
||||
z.object({ action: z.literal('use'), level: slotLevelSchema }),
|
||||
// The DM setting how many of a level are spent: giving one back, or fixing a mistake.
|
||||
z.object({ action: z.literal('set'), level: slotLevelSchema, used: z.number().int().min(0).max(9) }),
|
||||
// The DM giving every slot back.
|
||||
z.object({ action: z.literal('restore') }),
|
||||
]);
|
||||
|
||||
// The owning player spends their own slots, one at a time. Getting one back
|
||||
// is the DM's: by hand here, or for everyone with a rest
|
||||
// (POST /campaigns/:id/rest).
|
||||
router.post('/:id/spell-slots', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = spellSlotSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { character } = req;
|
||||
if (character.buildStage !== 'COMPLETE') return res.status(400).json({ error: 'Character build is not finished yet.' });
|
||||
|
||||
const input = parsed.data;
|
||||
if (input.action !== 'use' && !req.isDM) {
|
||||
return res.status(403).json({ error: 'Only the DM can give a spell slot back.' });
|
||||
}
|
||||
// By the sheet, so that a casting subclass and a multiclass count.
|
||||
const slots = sheetOf(await loadFullCharacter(character.id)).spellSlots;
|
||||
if (!slots) return res.status(400).json({ error: `${character.name} has no spell slots.` });
|
||||
|
||||
// The stored tally, squared up with what the class has at this level.
|
||||
const used = Array.from({ length: slots.levels[slots.levels.length - 1].level }, (_, i) => {
|
||||
const slot = slots.levels.find((s) => s.level === i + 1);
|
||||
return slot ? slot.used : 0;
|
||||
});
|
||||
if (input.action === 'restore') {
|
||||
used.fill(0);
|
||||
} else {
|
||||
const slot = slots.levels.find((s) => s.level === input.level);
|
||||
if (!slot) return res.status(400).json({ error: `${character.name} has no ${ORDINALS[input.level - 1]}-level spell slots.` });
|
||||
if (input.action === 'use') {
|
||||
if (slot.remaining === 0) {
|
||||
return res.status(400).json({
|
||||
error: `${character.name} has no ${ORDINALS[input.level - 1]}-level spell slots left. They come back on a ${slots.restoresOn === 'SHORT' ? 'short or long' : 'long'} rest.`,
|
||||
});
|
||||
}
|
||||
used[input.level - 1] = slot.used + 1;
|
||||
} else {
|
||||
used[input.level - 1] = Math.min(input.used, slot.max);
|
||||
}
|
||||
}
|
||||
|
||||
await prisma.character.update({ where: { id: character.id }, data: { spellSlotsUsed: used } });
|
||||
const full = await loadFullCharacter(character.id);
|
||||
emitCharacterUpdated(req);
|
||||
res.json({ character: serializeCharacter(full, req.isOwner) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Class counters — Rage, Ki, Channel Divinity and the like. Which a character
|
||||
// has, and how many, comes from class, subclass and level
|
||||
// (game/classResources.js); the character row keeps how many are spent.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const resourceKey = z.string().min(1).max(40);
|
||||
|
||||
const resourceSchema = z.discriminatedUnion('action', [
|
||||
// Using it: one is spent, or `amount` from a pool (Lay on Hands, Ki).
|
||||
z.object({ action: z.literal('use'), key: resourceKey, amount: z.number().int().min(1).max(999).default(1) }),
|
||||
// The DM setting how many are spent: giving some back, or fixing a mistake.
|
||||
z.object({ action: z.literal('set'), key: resourceKey, used: z.number().int().min(0).max(999) }),
|
||||
// The DM giving every counter back.
|
||||
z.object({ action: z.literal('restore') }),
|
||||
]);
|
||||
|
||||
// The owning player spends their own. Getting any back is the DM's: by hand
|
||||
// here, or for everyone with a rest (POST /campaigns/:id/rest).
|
||||
router.post('/:id/resources', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = resourceSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
if (req.character.buildStage !== 'COMPLETE') return res.status(400).json({ error: 'Character build is not finished yet.' });
|
||||
const input = parsed.data;
|
||||
if (input.action !== 'use' && !req.isDM) return res.status(403).json({ error: 'Only the DM can give a use back.' });
|
||||
|
||||
const character = await loadFullCharacter(req.character.id);
|
||||
const resources = sheetOf(character).resources;
|
||||
if (input.action === 'restore') {
|
||||
for (const resource of resources) resource.used = 0;
|
||||
} else {
|
||||
const resource = resources.find((r) => r.key === input.key);
|
||||
if (!resource) return res.status(400).json({ error: `${character.name} has no such counter.` });
|
||||
if (input.action === 'use') {
|
||||
if (input.amount > resource.remaining) {
|
||||
const back = resource.restoresOn === 'SHORT' ? 'short or long' : 'long';
|
||||
return res.status(400).json({
|
||||
error:
|
||||
resource.remaining === 0
|
||||
? `${character.name} has no ${resource.name} left. It comes back on a ${back} rest.`
|
||||
: `${character.name} has only ${resource.remaining} ${resource.name} left.`,
|
||||
});
|
||||
}
|
||||
resource.used += input.amount;
|
||||
} else {
|
||||
resource.used = Math.min(input.used, resource.max);
|
||||
}
|
||||
}
|
||||
|
||||
await prisma.character.update({ where: { id: character.id }, data: { resourcesUsed: resourceTally(resources) } });
|
||||
const full = await loadFullCharacter(character.id);
|
||||
emitCharacterUpdated(req);
|
||||
res.json({ character: serializeCharacter(full, req.isOwner) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Levelling up — one level at a time, with the checklist that goes with it
|
||||
// (game/levelUp.js): the new level, full HP, the class's new special
|
||||
// abilities, a Boon where the level grants one, new spells, fresh spell slots
|
||||
// and the free weapon upgrade.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Answers the request and returns false when this character cannot be levelled
|
||||
// up. The DM always can; the character's own player can once the DM has
|
||||
// approved a level for them (levelUpsPending).
|
||||
function canLevelUp(req, res, character) {
|
||||
let refusal = null;
|
||||
if (!req.isDM && !(req.isOwner && character.levelUpsPending > 0)) {
|
||||
refusal = [403, req.isOwner ? 'Your DM has not approved a level up yet.' : 'Only the DM can level a character up.'];
|
||||
} else if (character.buildStage !== 'COMPLETE') refusal = [400, 'Character build is not finished yet.'];
|
||||
else if (character.level >= MAX_LEVEL) refusal = [400, `${character.name} is already level ${MAX_LEVEL}, the highest there is.`];
|
||||
if (refusal) res.status(refusal[0]).json({ error: refusal[1] });
|
||||
return !refusal;
|
||||
}
|
||||
|
||||
// The plan for a character's next level in `toClass` (their first class when
|
||||
// not given). Answers the request and returns null when the class can't take
|
||||
// it: another class needs the campaign to allow multiclassing, and the
|
||||
// character to meet both classes' requirements.
|
||||
function planFor(req, res, character, toClass) {
|
||||
const sheet = sheetOf(character);
|
||||
const scores = Object.fromEntries(Object.entries(sheet.abilities).map(([ability, detail]) => [ability, detail.final]));
|
||||
const multiclass = Boolean(character.campaign && character.campaign.multiclassEnabled);
|
||||
if (toClass && !CLASSES[toClass]) {
|
||||
res.status(400).json({ error: 'That is not a class.' });
|
||||
return null;
|
||||
}
|
||||
const plan = levelUpPlan(character, { subclasses: usesSubclasses(character), multiclass, toClass, scores });
|
||||
if (plan.characterClass !== character.characterClass && !classLevels(character).some((e) => e.characterClass === plan.characterClass)) {
|
||||
if (!multiclass) {
|
||||
res.status(400).json({ error: 'This campaign does not allow multiclassing.' });
|
||||
return null;
|
||||
}
|
||||
const option = plan.classChoice.options.find((o) => o.characterClass === plan.characterClass);
|
||||
if (!option.eligible) {
|
||||
res.status(400).json({ error: option.problems.join(' ') });
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return { plan, sheet };
|
||||
}
|
||||
|
||||
// How the level's hit points are come by: the campaign's method, the die of
|
||||
// the class taking the level, the average it would count, and whether the
|
||||
// die is rolled at the table (physical dice) and typed in.
|
||||
function hpGain(character, plan) {
|
||||
const die = getClassHitDieSize(plan.characterClass);
|
||||
return {
|
||||
method: (character.campaign && character.campaign.hpOnLevelUp) || 'AVERAGE',
|
||||
die,
|
||||
average: Math.floor(die / 2) + 1,
|
||||
physical: effectiveDiceMode(character.campaign, character) === 'PHYSICAL',
|
||||
};
|
||||
}
|
||||
|
||||
// What the next level brings, for the DM to look over before saying yes.
|
||||
// `?class=` asks about a level in another class (multiclassing).
|
||||
router.get('/:id/level-up', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const character = await loadFullCharacter(req.character.id);
|
||||
if (!canLevelUp(req, res, character)) return;
|
||||
const planned = planFor(req, res, character, typeof req.query.class === 'string' ? req.query.class : null);
|
||||
if (!planned) return;
|
||||
const { plan, sheet } = planned;
|
||||
const after = sheetOf({ ...withLevelIn(character, plan.characterClass), spellSlotsUsed: [] });
|
||||
// The spells that could be granted now: the campaign's, of a level the
|
||||
// class can cast, that the character does not know. Sent with the plan
|
||||
// because a player otherwise sees only the spells they hold.
|
||||
const spellOptions = plan.spells
|
||||
? await prisma.spell.findMany({
|
||||
where: { campaignId: character.campaignId, level: { lte: plan.spells.maxSpellLevel }, id: { notIn: character.spells.map((held) => held.spellId) } },
|
||||
select: { id: true, name: true, level: true, school: true, description: true },
|
||||
orderBy: [{ level: 'asc' }, { name: 'asc' }],
|
||||
})
|
||||
: [];
|
||||
res.json({ plan: { ...plan, maxHp: { from: sheet.hp.max, to: after.hp.max }, hp: hpGain(character, plan), spellSlots: after.spellSlots, spellOptions } });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const levelUpSchema = z.object({
|
||||
characterClass: z.enum(Object.keys(CLASSES)).optional(), // the class taking the level; the first one when left out
|
||||
subclass: z.string().optional(), // which subclass, at the level the class chooses one
|
||||
boon: z.string().optional(), // which Boon, at a level that grants one
|
||||
weaponId: z.string().nullable().optional(), // the weapon that gets the free upgrade
|
||||
hpRoll: z.number().int().min(1).max(12).optional(), // the hit die rolled at the table, where HP is rolled with physical dice
|
||||
spellIds: z.array(z.string()).max(50).default([]), // spells newly granted
|
||||
});
|
||||
|
||||
router.post('/:id/level-up', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = levelUpSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { subclass, boon, weaponId, spellIds } = parsed.data;
|
||||
const character = await loadFullCharacter(req.character.id);
|
||||
if (!canLevelUp(req, res, character)) return;
|
||||
|
||||
const planned = planFor(req, res, character, parsed.data.characterClass || null);
|
||||
if (!planned) return;
|
||||
const { plan } = planned;
|
||||
if (plan.subclass && !subclass) return res.status(400).json({ error: `Level ${plan.toLevel} needs a subclass: pick one.` });
|
||||
if (!plan.subclass && subclass) return res.status(400).json({ error: `There is no subclass to pick at level ${plan.toLevel}.` });
|
||||
if (subclass && !plan.subclass.options.some((option) => option.key === subclass)) {
|
||||
return res.status(400).json({ error: 'That is not a subclass of this character\'s class.' });
|
||||
}
|
||||
if (plan.boon && !boon) return res.status(400).json({ error: `Level ${plan.toLevel} grants a Boon: pick one.` });
|
||||
if (!plan.boon && boon) return res.status(400).json({ error: `Level ${plan.toLevel} does not grant a Boon.` });
|
||||
if (weaponId && !plan.weapons.some((w) => w.weaponId === weaponId)) {
|
||||
return res.status(400).json({ error: 'That weapon cannot take the free upgrade: it has to be one this character holds, of standard growth, below their new level.' });
|
||||
}
|
||||
const spellsFound = await prisma.spell.count({ where: { id: { in: spellIds }, campaignId: character.campaignId } });
|
||||
if (new Set(spellIds).size !== spellIds.length || spellsFound !== spellIds.length) {
|
||||
return res.status(400).json({ error: "Pick the new spells from this campaign's spell list, each once." });
|
||||
}
|
||||
// The DM grants what they like; a player picks within what the level allows.
|
||||
if (!req.isDM && spellIds.length > 0) {
|
||||
const allowed = plan.spells ? plan.spells.newSpells + plan.spells.newCantrips : 0;
|
||||
const inReach = plan.spells ? await prisma.spell.count({ where: { id: { in: spellIds }, level: { lte: plan.spells.maxSpellLevel } } }) : 0;
|
||||
if (spellIds.length > allowed || inReach !== spellIds.length) {
|
||||
return res.status(400).json({ error: allowed > 0 ? `This level allows ${allowed} new spell${allowed === 1 ? '' : 's'}, of a level you can cast.` : 'This level grants no new spell.' });
|
||||
}
|
||||
}
|
||||
|
||||
// The subclass picked, or the one taken for them where the campaign has no choosing.
|
||||
const newSubclass = subclass || plan.subclassTaken || null;
|
||||
const first = plan.characterClass === character.characterClass;
|
||||
const heldSubclass = (classLevels(character).find((e) => e.characterClass === plan.characterClass) || {}).subclass || null;
|
||||
let gained;
|
||||
try {
|
||||
gained = advanceIn(character.specialAbilities, plan, boon, newSubclass ? { key: newSubclass, chosen: true } : { key: heldSubclass });
|
||||
} catch (err) {
|
||||
if (!(err instanceof LevelUpError)) throw err;
|
||||
return res.status(400).json({ error: err.message });
|
||||
}
|
||||
const armorBonus = clamp(character.armorBonus + gained.armorBonus, -30, 30);
|
||||
// Rolled hit points: the die is rolled here, or typed in from the table.
|
||||
const hp = hpGain(character, plan);
|
||||
let hpRolled = null;
|
||||
if (hp.method === 'ROLL') {
|
||||
if (hp.physical) {
|
||||
if (!validateManualRoll(hp.die, parsed.data.hpRoll)) {
|
||||
return res.status(400).json({ error: `Roll a d${hp.die} for hit points and enter what it shows (1 to ${hp.die}).` });
|
||||
}
|
||||
hpRolled = parsed.data.hpRoll;
|
||||
} else {
|
||||
hpRolled = rollDie(hp.die);
|
||||
}
|
||||
}
|
||||
const hpRollAdjust = character.hpRollAdjust + (hpRolled == null ? 0 : hpRolled - hp.average);
|
||||
const maxHp = sheetOf({ ...withLevelIn(character, plan.characterClass, newSubclass || undefined), armorBonus, hpRollAdjust }).hp.max;
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
if (weaponId) {
|
||||
await tx.characterWeapon.update({
|
||||
where: { characterId_weaponId: { characterId: character.id, weaponId } },
|
||||
data: { level: { increment: 1 } },
|
||||
});
|
||||
}
|
||||
await tx.characterSpell.createMany({ data: spellIds.map((spellId) => ({ characterId: character.id, spellId })), skipDuplicates: true });
|
||||
// A level in another class goes on that class's row.
|
||||
if (!first) {
|
||||
await tx.characterClassLevel.upsert({
|
||||
where: { characterId_characterClass: { characterId: character.id, characterClass: plan.characterClass } },
|
||||
create: { characterId: character.id, characterClass: plan.characterClass, level: 1, subclass: newSubclass },
|
||||
update: { level: plan.classLevel, ...(newSubclass ? { subclass: newSubclass } : {}) },
|
||||
});
|
||||
}
|
||||
await tx.character.update({
|
||||
where: { id: character.id },
|
||||
data: {
|
||||
level: plan.toLevel,
|
||||
hpRollAdjust,
|
||||
// An approved level is now taken.
|
||||
levelUpsPending: Math.max(0, character.levelUpsPending - 1),
|
||||
...(first && newSubclass ? { subclass: newSubclass } : {}),
|
||||
specialAbilities: gained.specialAbilities,
|
||||
armorBonus,
|
||||
tempHp: Math.max(character.tempHp, gained.tempHp),
|
||||
spellSlotsUsed: [],
|
||||
// The new maximum, and healed to it. Levelling does not raise the dead.
|
||||
...(lifeState(character) === 'DEAD' ? {} : { currentHp: maxHp, ...NO_DEATH_SAVES }),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const full = await loadFullCharacter(character.id);
|
||||
emitCharacterUpdated(req);
|
||||
// hpRolled: what the hit die showed, where HP is rolled (null otherwise).
|
||||
res.json({ character: serializeCharacter(full, req.isOwner, req.isDM), hpRolled });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
|
||||
@@ -414,6 +856,7 @@ router.post('/:id/copy', requireCharacterAccess(), async (req, res, next) => {
|
||||
name: source.name,
|
||||
species: source.species,
|
||||
characterClass: source.characterClass,
|
||||
subclass: source.subclass,
|
||||
level: source.level,
|
||||
xp: source.xp,
|
||||
motivation: source.motivation,
|
||||
@@ -423,8 +866,7 @@ router.post('/:id/copy', requireCharacterAccess(), async (req, res, next) => {
|
||||
intScore: source.intScore,
|
||||
wisScore: source.wisScore,
|
||||
chaScore: source.chaScore,
|
||||
halfElfBonusAbility1: source.halfElfBonusAbility1,
|
||||
halfElfBonusAbility2: source.halfElfBonusAbility2,
|
||||
speciesBonusChoices: source.speciesBonusChoices,
|
||||
currentHp: sheet.hp.max,
|
||||
armorBonus: source.armorBonus,
|
||||
speedOverride: source.speedOverride,
|
||||
@@ -440,6 +882,9 @@ router.post('/:id/copy', requireCharacterAccess(), async (req, res, next) => {
|
||||
privateNotes: req.isOwner ? source.privateNotes : null,
|
||||
diceMode: source.diceMode,
|
||||
buildStage: 'COMPLETE',
|
||||
classLevels: {
|
||||
create: (source.classLevels || []).map(({ characterClass, level, subclass }) => ({ characterClass, level, subclass })),
|
||||
},
|
||||
skillProficiencies: {
|
||||
create: source.skillProficiencies.map(({ skill, proficient, expertise }) => ({ skill, proficient, expertise })),
|
||||
},
|
||||
@@ -481,7 +926,7 @@ router.post('/:id/copy', requireCharacterAccess(), async (req, res, next) => {
|
||||
// a user-facing error string on failure, otherwise returns the value(s) in
|
||||
// the exact same shape the digital path would have produced.
|
||||
function resolveSingleRoll(character, body, sides) {
|
||||
if (character.diceMode !== 'PHYSICAL') return rollDie(sides);
|
||||
if (effectiveDiceMode(character.campaign, character) !== 'PHYSICAL') return rollDie(sides);
|
||||
const value = Number(body?.value);
|
||||
if (!validateManualRoll(sides, value)) {
|
||||
throw new Error(`Enter the d${sides} you rolled — a whole number from 1 to ${sides}.`);
|
||||
@@ -490,7 +935,11 @@ function resolveSingleRoll(character, body, sides) {
|
||||
}
|
||||
|
||||
function resolveAbilityRolls(character, body) {
|
||||
if (character.diceMode !== 'PHYSICAL') {
|
||||
// The standard array is not rolled at all: the same six scores for everyone.
|
||||
if (character.campaign.abilityScoreMethod === 'STANDARD_ARRAY') {
|
||||
return STANDARD_ARRAY.map((total) => ({ dice: [], dropped: null, total }));
|
||||
}
|
||||
if (effectiveDiceMode(character.campaign, character) !== 'PHYSICAL') {
|
||||
return Array.from({ length: 6 }, () => rollAbilityScore());
|
||||
}
|
||||
const sets = body?.abilitySets;
|
||||
@@ -511,6 +960,9 @@ router.patch('/:id/build/dice-mode', requireCharacterAccess({ write: true }), as
|
||||
const parsed = z.object({ diceMode: z.enum(['DIGITAL', 'PHYSICAL']) }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
if (req.campaign.diceMode !== 'BOTH') {
|
||||
return res.status(400).json({ error: `This campaign plays with ${req.campaign.diceMode === 'PHYSICAL' ? 'physical' : 'digital'} dice only.` });
|
||||
}
|
||||
const alreadyRolling = character.buildStage !== 'ROLLING_SPECIES' || Boolean((character.buildState || {}).speciesRoll);
|
||||
if (alreadyRolling) {
|
||||
return res.status(400).json({ error: 'Dice mode can only be chosen before the first roll of the build.' });
|
||||
@@ -536,22 +988,36 @@ router.post('/:id/build/roll', requireCharacterAccess({ write: true }), async (r
|
||||
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);
|
||||
const roll = resolveSingleRoll(character, req.body, SPECIES_ROLL_DIE);
|
||||
buildState.speciesRoll = roll;
|
||||
buildState.speciesChoices = speciesChoicesForRoll(roll);
|
||||
} else if (stage === 'ROLLING_CLASS') {
|
||||
const alreadyRolled = buildState.classChoices && buildState.classChoices.type !== 'reroll';
|
||||
if (alreadyRolled) {
|
||||
// A 7 may be rerolled once (a build from before kept a bare "reroll").
|
||||
const previous = buildState.classChoices;
|
||||
const mayReroll = previous && (previous.canReroll || previous.type === 'reroll');
|
||||
if (previous && !mayReroll) {
|
||||
return res.status(400).json({ error: 'Class die already rolled for this character — submit a choice, or reroll if the current roll allows it.' });
|
||||
}
|
||||
const roll = resolveSingleRoll(character, req.body, 8);
|
||||
const roll = resolveSingleRoll(character, req.body, CLASS_ROLL_DIE);
|
||||
buildState.classRoll = roll;
|
||||
buildState.classChoices = classChoicesForRoll(roll);
|
||||
buildState.classChoices = classChoicesForRoll(roll, { rerolled: Boolean(mayReroll) });
|
||||
delete buildState.characterClass;
|
||||
} else if (stage === 'CHOOSING_SUBCLASS') {
|
||||
// A die with a face per subclass suggests one; the player still picks freely.
|
||||
if (buildState.subclassRoll) {
|
||||
return res.status(400).json({ error: 'The subclass die was already rolled — pick from the list.' });
|
||||
}
|
||||
const options = subclassesOf(buildState.characterClass);
|
||||
const roll = resolveSingleRoll(character, req.body, options.length);
|
||||
buildState.subclassRoll = roll;
|
||||
buildState.subclassSuggestion = options[roll - 1].key;
|
||||
} else if (stage === 'ASSIGNING_SCORES') {
|
||||
if (buildState.abilityRolls) {
|
||||
return res.status(400).json({ error: 'Ability scores were already rolled for this character.' });
|
||||
}
|
||||
if (req.campaign.abilityScoreMethod === 'POINT_BUY') {
|
||||
return res.status(400).json({ error: 'This campaign uses point buy: nothing is rolled, the scores are bought.' });
|
||||
}
|
||||
buildState.abilityRolls = resolveAbilityRolls(character, req.body);
|
||||
} else {
|
||||
return res.status(400).json({ error: `No die roll is required at the "${stage}" step.` });
|
||||
@@ -567,26 +1033,34 @@ router.post('/:id/build/roll', requireCharacterAccess({ write: true }), async (r
|
||||
}
|
||||
});
|
||||
|
||||
const HALF_ELF_ELIGIBLE_ABILITIES = ABILITIES.filter((a) => a !== 'CHA');
|
||||
|
||||
const chooseSchemas = {
|
||||
// `bonusChoices` are the species' flexible bonuses, { ability: amount }.
|
||||
// `halfElfBonusAbilities` is the older way to give a Half-Elf's two +1s.
|
||||
ROLLING_SPECIES: z.object({
|
||||
species: z.string(),
|
||||
halfElfBonusAbilities: z.array(z.enum(HALF_ELF_ELIGIBLE_ABILITIES)).length(2).optional(),
|
||||
bonusChoices: z.partialRecord(z.enum(ABILITIES), z.number().int().min(0).max(2)).optional(),
|
||||
halfElfBonusAbilities: z.array(z.enum(ABILITIES)).length(2).optional(),
|
||||
}),
|
||||
ROLLING_CLASS: z.object({ characterClass: z.string() }),
|
||||
// null: decide later, at the level the class chooses.
|
||||
CHOOSING_SUBCLASS: z.object({ subclass: z.string().nullable() }),
|
||||
// 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() }),
|
||||
// Rolled scores (and the standard array) are assigned by index; point buy
|
||||
// sends the six scores themselves.
|
||||
ASSIGNING_SCORES: z.object({
|
||||
assignments: z.object({
|
||||
STR: z.number().int().min(0).max(5),
|
||||
DEX: z.number().int().min(0).max(5),
|
||||
CON: z.number().int().min(0).max(5),
|
||||
INT: z.number().int().min(0).max(5),
|
||||
WIS: z.number().int().min(0).max(5),
|
||||
CHA: z.number().int().min(0).max(5),
|
||||
}),
|
||||
pointBuy: z.record(z.enum(ABILITIES), z.number().int().min(8).max(15)).optional(),
|
||||
assignments: z
|
||||
.object({
|
||||
STR: z.number().int().min(0).max(5),
|
||||
DEX: z.number().int().min(0).max(5),
|
||||
CON: z.number().int().min(0).max(5),
|
||||
INT: z.number().int().min(0).max(5),
|
||||
WIS: z.number().int().min(0).max(5),
|
||||
CHA: z.number().int().min(0).max(5),
|
||||
})
|
||||
.optional(),
|
||||
}),
|
||||
// Skill proficiencies are now auto-generated (see autoSelectSkills, applied
|
||||
// when this stage is entered from ASSIGNING_SCORES below) — this payload is
|
||||
@@ -603,8 +1077,8 @@ 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_BACKGROUND: z.object({ picks: z.record(z.string(), z.array(z.string())) }),
|
||||
CHOOSING_APPEARANCE: z.object({ picks: z.record(z.string(), z.array(z.string())) }),
|
||||
CHOOSING_EQUIPMENT: z.object({
|
||||
weaponIds: z.array(z.string()).default([]),
|
||||
itemIds: z.array(z.string()).default([]),
|
||||
@@ -625,6 +1099,7 @@ async function allStartingOptions(model, ids, campaignId, reach) {
|
||||
const STAGE_ORDER = [
|
||||
'ROLLING_SPECIES',
|
||||
'ROLLING_CLASS',
|
||||
'CHOOSING_SUBCLASS',
|
||||
'ROLLING_MOTIVATION',
|
||||
'ASSIGNING_SCORES',
|
||||
'ASSIGNING_PROFICIENCIES',
|
||||
@@ -635,9 +1110,19 @@ const STAGE_ORDER = [
|
||||
'COMPLETE',
|
||||
];
|
||||
|
||||
function nextStage(current) {
|
||||
const idx = STAGE_ORDER.indexOf(current);
|
||||
return STAGE_ORDER[idx + 1];
|
||||
// Steps a campaign can leave out: the subclass (without subclasses) and the
|
||||
// motivation (when it skips it).
|
||||
function stageSkipped(stage, campaign) {
|
||||
if (stage === 'CHOOSING_SUBCLASS') return !campaign.subclassesEnabled;
|
||||
if (stage === 'ROLLING_MOTIVATION') return campaign.skipMotivationRoll;
|
||||
return false;
|
||||
}
|
||||
|
||||
// The next (or, with step -1, the previous) step this campaign uses.
|
||||
function nextStage(current, campaign, step = 1) {
|
||||
let idx = STAGE_ORDER.indexOf(current) + step;
|
||||
while (campaign && STAGE_ORDER[idx] && stageSkipped(STAGE_ORDER[idx], campaign)) idx += step;
|
||||
return STAGE_ORDER[idx];
|
||||
}
|
||||
|
||||
router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
@@ -651,7 +1136,7 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const buildState = { ...(character.buildState || {}) };
|
||||
let advanceTo = nextStage(stage);
|
||||
let advanceTo = nextStage(stage, req.campaign);
|
||||
|
||||
if (stage === 'ROLLING_SPECIES') {
|
||||
const choices = buildState.speciesChoices;
|
||||
@@ -660,17 +1145,18 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
|
||||
if (choices.type !== 'wildcard' && !choices.options.includes(species)) {
|
||||
return res.status(400).json({ error: `${species} was not offered by this roll.` });
|
||||
}
|
||||
if (species === 'HALF_ELF') {
|
||||
if (!halfElfBonusAbilities) {
|
||||
return res.status(400).json({ error: 'Half-Elf requires choosing two abilities (other than CHA) for the +1/+1 bonus.' });
|
||||
}
|
||||
let bonusChoices = parsed.data.bonusChoices || {};
|
||||
if (halfElfBonusAbilities) {
|
||||
if (new Set(halfElfBonusAbilities).size !== 2) {
|
||||
return res.status(400).json({ error: 'The two Half-Elf bonus abilities must be different.' });
|
||||
}
|
||||
buildState.halfElfBonusAbilities = halfElfBonusAbilities;
|
||||
} else {
|
||||
delete buildState.halfElfBonusAbilities;
|
||||
bonusChoices = Object.fromEntries(halfElfBonusAbilities.map((ability) => [ability, 1]));
|
||||
}
|
||||
bonusChoices = Object.fromEntries(Object.entries(bonusChoices).filter(([, amount]) => amount));
|
||||
const problem = speciesBonusProblem(species, bonusChoices);
|
||||
if (problem) return res.status(400).json({ error: problem });
|
||||
delete buildState.halfElfBonusAbilities;
|
||||
buildState.speciesBonusChoices = bonusChoices;
|
||||
buildState.species = species;
|
||||
} else if (stage === 'ROLLING_CLASS') {
|
||||
const choices = buildState.classChoices;
|
||||
@@ -681,19 +1167,43 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
|
||||
if (choices.type !== 'wildcard' && !choices.options.includes(characterClass)) {
|
||||
return res.status(400).json({ error: `${characterClass} was not offered by this roll.` });
|
||||
}
|
||||
buildState.characterClass = characterClass;
|
||||
if (req.campaign.skipMotivationRoll) {
|
||||
advanceTo = 'ASSIGNING_SCORES';
|
||||
buildState.motivationText = null;
|
||||
// A subclass picked for another class goes with it.
|
||||
if (buildState.characterClass !== characterClass) {
|
||||
delete buildState.subclass;
|
||||
delete buildState.subclassRoll;
|
||||
delete buildState.subclassSuggestion;
|
||||
}
|
||||
buildState.characterClass = characterClass;
|
||||
if (req.campaign.skipMotivationRoll) buildState.motivationText = null;
|
||||
} else if (stage === 'CHOOSING_SUBCLASS') {
|
||||
const { subclass } = parsed.data;
|
||||
if (subclass !== null && !findSubclass(buildState.characterClass, subclass)) {
|
||||
return res.status(400).json({ error: 'That is not a subclass of this class.' });
|
||||
}
|
||||
buildState.subclass = subclass;
|
||||
} else if (stage === 'ROLLING_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') {
|
||||
let { assignments } = parsed.data;
|
||||
if (req.campaign.abilityScoreMethod === 'POINT_BUY') {
|
||||
const scores = parsed.data.pointBuy;
|
||||
if (!scores || ABILITIES.some((ability) => scores[ability] === undefined)) {
|
||||
return res.status(400).json({ error: 'Buy a score for each of the six abilities.' });
|
||||
}
|
||||
const cost = pointBuyCost(scores);
|
||||
if (cost === null || cost > POINT_BUY_BUDGET) {
|
||||
return res.status(400).json({ error: `Those scores cost ${cost} points; you have ${POINT_BUY_BUDGET}.` });
|
||||
}
|
||||
// Kept the way rolled scores are, each assigned to its own ability.
|
||||
buildState.abilityRolls = ABILITIES.map((ability) => ({ dice: [], dropped: null, total: scores[ability] }));
|
||||
buildState.pointBuy = scores;
|
||||
assignments = Object.fromEntries(ABILITIES.map((ability, i) => [ability, i]));
|
||||
}
|
||||
if (!buildState.abilityRolls) return res.status(400).json({ error: 'Roll ability scores first.' });
|
||||
const { assignments } = parsed.data;
|
||||
if (!assignments) return res.status(400).json({ error: 'Assign each score to an ability.' });
|
||||
const usedIndexes = Object.values(assignments);
|
||||
const uniqueIndexes = new Set(usedIndexes);
|
||||
if (uniqueIndexes.size !== 6 || Math.max(...usedIndexes) > 5) {
|
||||
@@ -789,8 +1299,7 @@ router.post('/:id/build/back', requireCharacterAccess({ write: true }), async (r
|
||||
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';
|
||||
backTo = nextStage(stage, req.campaign, -1);
|
||||
}
|
||||
delete buildState.equipment;
|
||||
|
||||
@@ -821,7 +1330,9 @@ router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), asyn
|
||||
rolledScores[ability] = bs.abilityRolls[rollIndex].total;
|
||||
}
|
||||
|
||||
const [halfElfBonusAbility1, halfElfBonusAbility2] = bs.halfElfBonusAbilities || [null, null];
|
||||
// A build begun before chosen bonuses were general kept a Half-Elf's two picks on their own.
|
||||
const speciesBonusChoices =
|
||||
bs.speciesBonusChoices || Object.fromEntries((bs.halfElfBonusAbilities || []).map((ability) => [ability, 1]));
|
||||
const saveProfs = getClassSaveProficiencies(bs.characterClass);
|
||||
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
@@ -833,6 +1344,8 @@ router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), asyn
|
||||
data: {
|
||||
species: bs.species,
|
||||
characterClass: bs.characterClass,
|
||||
// Chosen now, its gifts still come at the level the class chooses at.
|
||||
subclass: req.campaign.subclassesEnabled && findSubclass(bs.characterClass, bs.subclass) ? bs.subclass : null,
|
||||
motivation: bs.motivationText || null,
|
||||
// Composed here, from the picks, so the text can only ever say what
|
||||
// the lists allow.
|
||||
@@ -845,8 +1358,7 @@ router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), asyn
|
||||
intScore: rolledScores.INT,
|
||||
wisScore: rolledScores.WIS,
|
||||
chaScore: rolledScores.CHA,
|
||||
halfElfBonusAbility1,
|
||||
halfElfBonusAbility2,
|
||||
speciesBonusChoices,
|
||||
buildStage: 'COMPLETE',
|
||||
buildState: null,
|
||||
skillProficiencies: {
|
||||
@@ -929,7 +1441,7 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
|
||||
damageDice: ii.item.damageDice ? scaledDamageDice(ii.item.damageDice, ii.level, ii.item.damageScaling, ii.item.minLevel) : null,
|
||||
...effectsOf(ii.item),
|
||||
}));
|
||||
const spells = character.spells.map((cs) => ({
|
||||
const spells = [...character.spells].sort(bySpellLevel).map((cs) => ({
|
||||
characterSpellId: cs.id,
|
||||
name: cs.spell.name,
|
||||
level: cs.spell.level,
|
||||
@@ -946,6 +1458,7 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
|
||||
level: character.level,
|
||||
species: character.species,
|
||||
characterClass: character.characterClass,
|
||||
subclassName: usesSubclasses(character) ? subclassName(character.characterClass, character.subclass) : null,
|
||||
currentHp: character.currentHp,
|
||||
maxHp: sheet.hp.max,
|
||||
tempHp: character.tempHp,
|
||||
@@ -955,8 +1468,18 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
|
||||
speed: sheet.speed,
|
||||
proficiencyBonus: sheet.proficiencyBonus,
|
||||
spellcasting: sheet.spellcasting,
|
||||
spellSlots: sheet.spellSlots,
|
||||
hitDice: sheet.hitDice,
|
||||
resources: sheet.resources,
|
||||
inspiration: character.inspiration,
|
||||
exhaustion: character.exhaustion,
|
||||
conditions: character.conditions,
|
||||
passivePerception: sheet.passivePerception,
|
||||
passiveInvestigation: sheet.passiveInvestigation,
|
||||
passiveInsight: sheet.passiveInsight,
|
||||
abilities: sheet.abilities,
|
||||
saves: sheet.saves,
|
||||
skills: sheet.skills,
|
||||
specialAbilities: character.specialAbilities,
|
||||
// What equipped gear is adding and taking away, and what else it does.
|
||||
gear: sheet.gear,
|
||||
@@ -1099,6 +1622,46 @@ function requireDmForGear(req, res) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// A weapon is not swapped in the middle of a fight. For a character in a
|
||||
// battle that is under way, the weapon in hand changes only as the battle
|
||||
// begins (before anyone has made a move) or on their own turn once their
|
||||
// attack has landed, before the turn passes (game/combat.js, weaponSwapOpen).
|
||||
// Returns what to tell the player when it is not one of those moments. The
|
||||
// DM is not held to it: they referee, and put mistakes right.
|
||||
async function weaponSwapWait(character) {
|
||||
const rows = await prisma.encounterParticipant.findMany({
|
||||
where: { characterId: character.id, encounter: { status: 'ACTIVE', mode: 'BATTLE', archivedAt: null } },
|
||||
include: { encounter: true },
|
||||
});
|
||||
for (const row of rows) {
|
||||
const { encounter } = row;
|
||||
const participants = await prisma.encounterParticipant.findMany({
|
||||
where: { encounterId: encounter.id },
|
||||
include: { character: { select: { currentHp: true, deathSaveFailures: true, stable: true } } },
|
||||
});
|
||||
const first = inTurnOrder(participants).find((p) => !isFallen(p));
|
||||
// What has landed, and whether an attack somebody declared is still being
|
||||
// resolved (one the server lined up for a monster is not a move yet).
|
||||
const actions = await prisma.encounterAction.findMany({
|
||||
where: { encounterId: encounter.id, status: { in: ['APPLIED', 'PENDING'] } },
|
||||
select: { round: true, actorParticipantId: true, status: true, auto: true },
|
||||
});
|
||||
const applied = actions.filter((a) => a.status === 'APPLIED');
|
||||
const open = weaponSwapOpen({
|
||||
round: encounter.currentRound,
|
||||
activeId: encounter.activeParticipantId,
|
||||
firstId: first ? first.id : null,
|
||||
participantId: row.id,
|
||||
applied,
|
||||
declared: actions.some((a) => a.status === 'PENDING' && !a.auto),
|
||||
});
|
||||
if (!open) {
|
||||
return `${character.name} is in a battle (${encounter.name}). A weapon can be changed as the battle begins, before anyone has made a move, or on ${character.name}'s own turn once their attack has landed. The DM can change it at any time.`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function emitCharacterUpdated(req) {
|
||||
req.app.get('io').to(`campaign:${req.character.campaignId}`).emit('character:updated', { characterId: req.character.id });
|
||||
}
|
||||
@@ -1224,6 +1787,11 @@ for (const gear of GEAR) {
|
||||
const blocked = await equipBlocked(req, gear.pool, req.params.poolId);
|
||||
if (blocked) return res.status(400).json({ error: blocked });
|
||||
}
|
||||
// Drawing or putting away a weapon in a battle waits for the right moment.
|
||||
if (gear.pool === 'weapon' && !req.isDM && parsed.data.equipped !== undefined && parsed.data.equipped !== existing.equipped) {
|
||||
const wait = await weaponSwapWait(req.character);
|
||||
if (wait) return res.status(400).json({ error: wait });
|
||||
}
|
||||
|
||||
const row = await prisma[gear.held].update({ where: whereHeld(req), data, include });
|
||||
if (gear.ownLevel) await settleHp(prisma, [req.character.id]);
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
const crypto = require('crypto');
|
||||
const express = require('express');
|
||||
const { z } = require('zod');
|
||||
const { Prisma } = require('@prisma/client');
|
||||
const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { loadCampaignMembership } = require('../middleware/campaignAccess');
|
||||
const { computeCharacterSheet, computeWeaponStats, scaledDamageDice, canUseGear, abilityModifier, MAX_GEAR_LEVEL } = require('../game/calculations');
|
||||
const { computeCharacterSheet, computeWeaponStats, scaledDamageDice, canUseGear, abilityModifier, encounterDifficulty, MAX_GEAR_LEVEL } = require('../game/calculations');
|
||||
const { CURRENCIES, InsufficientGoldError, adjustGold, spendCoins, giveGear } = require('../utils/grants');
|
||||
const { moveCharacters, visitedLocationIds } = require('../utils/locations');
|
||||
const { SHEET_INCLUDE } = require('../utils/sheet');
|
||||
const { SHEET_INCLUDE, bySpellLevel } = require('../utils/sheet');
|
||||
const { NO_DEATH_SAVES, lifeState, deathSaveInfo, changeHp } = require('../utils/hp');
|
||||
const { subclassName } = require('../game/data/subclasses');
|
||||
const { settle, rollDamage, rollCritDamage, inTurnOrder } = require('../game/combat');
|
||||
const { rollDie } = require('../game/dice');
|
||||
const { ActionError, targetRows, describeSource, autoActions } = require('../utils/actions');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -15,8 +21,10 @@ router.use(requireAuth);
|
||||
|
||||
async function requireEncounterAccess(req, res, next) {
|
||||
try {
|
||||
const encounter = await prisma.encounter.findUnique({ where: { id: req.params.id } });
|
||||
if (!encounter) return res.status(404).json({ error: 'Encounter not found' });
|
||||
const found = await prisma.encounter.findUnique({ where: { id: req.params.id }, include: { campaign: true } });
|
||||
if (!found) return res.status(404).json({ error: 'Encounter not found' });
|
||||
// The campaign rides along for its settings (req.campaign), not on the encounter.
|
||||
const { campaign, ...encounter } = found;
|
||||
|
||||
const membership = await loadCampaignMembership(req.user.id, encounter.campaignId);
|
||||
if (!membership) return res.status(403).json({ error: 'Not a member of this campaign' });
|
||||
@@ -33,6 +41,7 @@ async function requireEncounterAccess(req, res, next) {
|
||||
}
|
||||
|
||||
req.encounter = encounter;
|
||||
req.campaign = campaign;
|
||||
req.membership = membership;
|
||||
req.isDM = isDM;
|
||||
return next();
|
||||
@@ -50,13 +59,6 @@ function clamp(value, min, max) {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
}
|
||||
|
||||
// Highest initiative first; ties keep the order combatants were added in.
|
||||
// Anyone who has not rolled yet waits at the bottom.
|
||||
function inTurnOrder(participants) {
|
||||
const rolled = (p) => (p.initiativeRoll == null ? 0 : 1);
|
||||
return [...participants].sort((a, b) => rolled(b) - rolled(a) || b.initiative - a.initiative || (a.id < b.id ? -1 : 1));
|
||||
}
|
||||
|
||||
// What is added to a combatant's d20 for initiative: the sheet's initiative
|
||||
// bonus for a character, the Dexterity modifier for a monster, and nothing for
|
||||
// an NPC (they have no ability scores). Takes a participant with its
|
||||
@@ -104,6 +106,41 @@ function revivalSpell(character) {
|
||||
return character.spells.map((cs) => cs.spell).find((spell) => spell.revives && canUseGear(character.level, spell.level));
|
||||
}
|
||||
|
||||
// The rounds left on a combatant's timed conditions, squared up with the
|
||||
// conditions they are actually under: { condition: rounds }.
|
||||
function roundsFor(conditionRounds, conditions) {
|
||||
const rounds = conditionRounds && typeof conditionRounds === 'object' ? conditionRounds : {};
|
||||
return Object.fromEntries(conditions.filter((condition) => Number.isInteger(rounds[condition]) && rounds[condition] > 0).map((condition) => [condition, rounds[condition]]));
|
||||
}
|
||||
|
||||
// A new round: every timed condition has one round less to run, and those
|
||||
// that run out are removed (from the character too, when it is a character's).
|
||||
// Returns what wore off, as [{ name, condition }], for the DM to read out.
|
||||
async function tickConditions(req) {
|
||||
const participants = await prisma.encounterParticipant.findMany({
|
||||
where: { encounterId: req.encounter.id },
|
||||
include: { character: { select: { id: true, conditions: true } } },
|
||||
});
|
||||
const expired = [];
|
||||
for (const p of participants) {
|
||||
const conditions = p.character ? p.character.conditions : p.conditions;
|
||||
const before = roundsFor(p.conditionRounds, conditions);
|
||||
if (Object.keys(before).length === 0) continue;
|
||||
const after = {};
|
||||
for (const [condition, rounds] of Object.entries(before)) {
|
||||
if (rounds > 1) after[condition] = rounds - 1;
|
||||
else expired.push({ name: p.displayName, condition });
|
||||
}
|
||||
const left = conditions.filter((condition) => before[condition] === undefined || after[condition] !== undefined);
|
||||
await prisma.encounterParticipant.update({ where: { id: p.id }, data: { conditionRounds: after, conditions: left } });
|
||||
if (p.character && left.length !== conditions.length) {
|
||||
await prisma.character.update({ where: { id: p.character.id }, data: { conditions: left } });
|
||||
emitCharacterUpdated(req, p.character.id);
|
||||
}
|
||||
}
|
||||
return expired;
|
||||
}
|
||||
|
||||
const initiativeRollSchema = z.number().int().min(1, 'An initiative roll is a d20: 1 to 20').max(20, 'An initiative roll is a d20: 1 to 20');
|
||||
|
||||
// What every campaign member sees about a character in an encounter: the
|
||||
@@ -113,7 +150,7 @@ const initiativeRollSchema = z.number().int().min(1, 'An initiative roll is a d2
|
||||
// used; what is still in the pack is in the character panel, for the
|
||||
// character's own player and the DM. Uses the
|
||||
// same calculation-engine functions as the sheet, never re-deriving formulas.
|
||||
function characterCombatInfo(character) {
|
||||
function characterCombatInfo(character, subclasses = true) {
|
||||
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; so does anything not equipped.
|
||||
@@ -137,6 +174,7 @@ function characterCombatInfo(character) {
|
||||
}));
|
||||
const spells = character.spells
|
||||
.filter((cs) => canUseGear(character.level, cs.spell.level))
|
||||
.sort(bySpellLevel)
|
||||
.map((cs) => ({
|
||||
characterSpellId: cs.id,
|
||||
name: cs.spell.name,
|
||||
@@ -144,11 +182,16 @@ function characterCombatInfo(character) {
|
||||
description: cs.spell.description,
|
||||
damageDice: cs.spell.damageDice,
|
||||
prepared: cs.prepared,
|
||||
// How it lands: a spell attack, a save by each target, or neither.
|
||||
attackRoll: cs.spell.attackRoll,
|
||||
saveAbility: cs.spell.saveAbility,
|
||||
halfOnSave: cs.spell.halfOnSave,
|
||||
}));
|
||||
return {
|
||||
level: character.level,
|
||||
species: character.species,
|
||||
characterClass: character.characterClass,
|
||||
subclassName: subclasses ? subclassName(character.characterClass, character.subclass) : null,
|
||||
armorClass: sheet.armorClass,
|
||||
maxHp: sheet.hp.max,
|
||||
tempHp: character.tempHp,
|
||||
@@ -157,9 +200,16 @@ function characterCombatInfo(character) {
|
||||
speed: sheet.speed,
|
||||
initiativeBonus: sheet.initiative,
|
||||
passivePerception: sheet.passivePerception,
|
||||
passiveInvestigation: sheet.passiveInvestigation,
|
||||
passiveInsight: sheet.passiveInsight,
|
||||
proficiencyBonus: sheet.proficiencyBonus,
|
||||
abilities: sheet.abilities,
|
||||
saves: sheet.saves,
|
||||
skills: sheet.skills,
|
||||
spellSlots: sheet.spellSlots,
|
||||
resources: sheet.resources,
|
||||
inspiration: character.inspiration,
|
||||
exhaustion: character.exhaustion,
|
||||
specialAbilities: character.specialAbilities,
|
||||
// What equipped gear is adding and taking away. The numbers above already include it.
|
||||
gear: sheet.gear,
|
||||
@@ -170,6 +220,16 @@ function characterCombatInfo(character) {
|
||||
};
|
||||
}
|
||||
|
||||
// How hard the scene is for the characters in it, and what its monsters are
|
||||
// worth: every monster counts, standing or not. Takes the encounter's
|
||||
// participants with their characters and monsters loaded.
|
||||
function difficultyOf(participants) {
|
||||
return encounterDifficulty(
|
||||
participants.filter((p) => p.character).map((p) => p.character.level),
|
||||
participants.filter((p) => p.monster).map((p) => p.monster.challengeRating)
|
||||
);
|
||||
}
|
||||
|
||||
// What is for sale, oldest first, with the weapon or item itself.
|
||||
const WARES = { include: { weapon: true, item: true }, orderBy: { createdAt: 'asc' } };
|
||||
|
||||
@@ -189,7 +249,7 @@ async function serializeEncounter(encounterId, isDM, viewerId) {
|
||||
const encounter = await prisma.encounter.findUnique({
|
||||
where: { id: encounterId },
|
||||
include: {
|
||||
campaign: { select: { showMonsterHp: true } },
|
||||
campaign: { select: { showMonsterHp: true, subclassesEnabled: true } },
|
||||
location: { select: { id: true, name: true, description: true } },
|
||||
participants: {
|
||||
include: {
|
||||
@@ -224,16 +284,22 @@ async function serializeEncounter(encounterId, isDM, viewerId) {
|
||||
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);
|
||||
const { maxHp, ...combatInfo } = characterCombatInfo(character, encounter.campaign.subclassesEnabled);
|
||||
out.currentHp = character.currentHp;
|
||||
out.maxHp = maxHp;
|
||||
// Likewise their conditions: the character's own, which outlast the scene.
|
||||
out.conditions = character.conditions;
|
||||
out.character = { id: character.id, name: character.name, userId: character.userId };
|
||||
// Where each character is, is part of a free-roam scene; elsewhere it stays on their sheet.
|
||||
if (encounter.mode === 'FREE_ROAM') out.character.currentLocationId = character.currentLocationId;
|
||||
out.characterCombatInfo = combatInfo;
|
||||
}
|
||||
out.conditionRounds = roundsFor(p.conditionRounds, out.conditions);
|
||||
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;
|
||||
// Where they are usually found is the DM's to know, like their notes and stats.
|
||||
const { dmNotes, ac, maxHp, attackBonus, damageDice, locationId, campaignId, createdAt, ...publicNpc } = npc;
|
||||
out.npc = isDM ? { ...publicNpc, dmNotes, ac, maxHp, attackBonus, damageDice, locationId } : publicNpc;
|
||||
}
|
||||
if (hideHp && !character) {
|
||||
// Rounded up, so anything still standing shows a sliver of bar.
|
||||
@@ -244,17 +310,69 @@ async function serializeEncounter(encounterId, isDM, viewerId) {
|
||||
return out;
|
||||
});
|
||||
|
||||
// Attacks and spells in play: those still being resolved, and the last few
|
||||
// that landed. One the DM is keeping to themselves (a monster's auto-rolled
|
||||
// attack) is theirs alone until it is applied.
|
||||
const actionRows = await prisma.encounterAction.findMany({
|
||||
where: { encounterId, status: { in: ['PENDING', 'APPLIED'] } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 30,
|
||||
});
|
||||
const showAction = (action) => {
|
||||
const settled = settle(action);
|
||||
// A player is not told a monster's or NPC's AC.
|
||||
const targets = isDM ? settled.targets : settled.targets.map((t) => (t.kind === 'CHARACTER' ? t : { ...t, ac: null }));
|
||||
const { encounterId: _encounterId, createdById, ...rest } = settled;
|
||||
return { ...rest, targets };
|
||||
};
|
||||
const actions = actionRows
|
||||
.filter((a) => a.status === 'PENDING' && (isDM || !a.hidden))
|
||||
.reverse()
|
||||
.map(showAction);
|
||||
const recentActions = actionRows
|
||||
.filter((a) => a.status === 'APPLIED')
|
||||
.slice(0, 6)
|
||||
.map(showAction);
|
||||
|
||||
// Free roam: the places the party can go to, each with who is found there,
|
||||
// what is for sale there, and which of the characters in the scene are
|
||||
// there now. Everyone in the scene sees every place in it. An NPC's secrets
|
||||
// and stats stay with the DM, as anywhere.
|
||||
let places;
|
||||
if (encounter.mode === 'FREE_ROAM') {
|
||||
const rows = await prisma.encounterLocation.findMany({
|
||||
where: { encounterId },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
include: { location: { include: { npcs: { include: { wares: WARES }, orderBy: { name: 'asc' } }, wares: WARES } } },
|
||||
});
|
||||
places = rows.map(({ location: place }) => ({
|
||||
id: place.id,
|
||||
name: place.name,
|
||||
description: place.description,
|
||||
wares: place.wares,
|
||||
npcs: place.npcs.map(({ dmNotes: secrets, ac, maxHp, attackBonus, damageDice, locationId, campaignId, createdAt, ...publicNpc }) =>
|
||||
isDM ? { ...publicNpc, dmNotes: secrets, ac, maxHp, attackBonus, damageDice, locationId } : publicNpc
|
||||
),
|
||||
here: encounter.participants
|
||||
.filter((p) => p.character && p.character.currentLocationId === place.id)
|
||||
.map((p) => ({ characterId: p.character.id, name: p.displayName, userId: p.character.userId })),
|
||||
}));
|
||||
}
|
||||
|
||||
const { dmNotes, rewards, campaign, location, ...scene } = encounter;
|
||||
const knowsPlace = isDM || (location && (await visitedLocationIds(prisma, viewerId, encounter.campaignId)).has(location.id));
|
||||
return {
|
||||
...scene,
|
||||
locationId: knowsPlace ? scene.locationId : null,
|
||||
location: knowsPlace ? location : null,
|
||||
...(isDM ? { dmNotes } : {}),
|
||||
...(isDM ? { dmNotes, difficulty: difficultyOf(encounter.participants) } : {}),
|
||||
// A player is not told that someone they cannot see is being targeted.
|
||||
targetParticipantIds: isDM ? scene.targetParticipantIds : scene.targetParticipantIds.filter((id) => !hiddenIds.has(id)),
|
||||
participants,
|
||||
fallen,
|
||||
actions,
|
||||
recentActions,
|
||||
...(places ? { places } : {}),
|
||||
rewards: isDM ? rewards : rewards.filter((r) => r.awardedAt),
|
||||
};
|
||||
}
|
||||
@@ -277,7 +395,8 @@ async function syncCharacterLocations(req) {
|
||||
where: { id: req.encounter.id },
|
||||
include: { participants: { where: { characterId: { not: null } }, include: { character: { select: { id: true, currentLocationId: true } } } } },
|
||||
});
|
||||
if (!encounter || encounter.status !== 'ACTIVE' || !encounter.locationId) return;
|
||||
// In free roam each character goes where their player sends them.
|
||||
if (!encounter || encounter.status !== 'ACTIVE' || !encounter.locationId || encounter.mode === 'FREE_ROAM') return;
|
||||
|
||||
const elsewhere = encounter.participants.map((p) => p.character).filter((c) => c.currentLocationId !== encounter.locationId);
|
||||
await moveCharacters(prisma, elsewhere.map((c) => c.id), encounter.locationId);
|
||||
@@ -301,7 +420,7 @@ router.get('/:id', requireEncounterAccess, async (req, res, next) => {
|
||||
|
||||
const patchEncounterSchema = z.object({
|
||||
status: z.enum(['PLANNING', 'ACTIVE', 'COMPLETE']).optional(),
|
||||
mode: z.enum(['BATTLE', 'QUEST']).optional(),
|
||||
mode: z.enum(['BATTLE', 'QUEST', 'FREE_ROAM']).optional(),
|
||||
name: z.string().min(1).max(120).optional(),
|
||||
description: z.string().max(4000).nullable().optional(),
|
||||
dmNotes: z.string().max(4000).nullable().optional(),
|
||||
@@ -331,7 +450,8 @@ router.patch('/:id', requireEncounterAccess, requireDM, async (req, res, next) =
|
||||
// Targets belong to the moment; beginning, ending or reopening clears them.
|
||||
if (data.status && data.status !== req.encounter.status) data.targetParticipantIds = [];
|
||||
|
||||
await prisma.encounter.update({ where: { id: req.encounter.id }, data });
|
||||
const updated = await prisma.encounter.update({ where: { id: req.encounter.id }, data });
|
||||
if (data.status === 'ACTIVE' && req.encounter.status !== 'ACTIVE') await declareAuto(req, updated);
|
||||
await respondWithEncounter(req, res);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
@@ -361,16 +481,19 @@ const participantSchema = z
|
||||
npcId: z.string().optional(),
|
||||
displayName: z.string().min(1).max(80).optional(),
|
||||
initiativeRoll: initiativeRollSchema.optional(),
|
||||
// Several of one monster at once: "Goblin 1" to "Goblin 4".
|
||||
count: z.number().int().min(1).max(20).default(1),
|
||||
})
|
||||
.refine((data) => [data.characterId, data.monsterId, data.npcId].filter(Boolean).length === 1, {
|
||||
message: 'Provide exactly one of characterId, monsterId or npcId',
|
||||
});
|
||||
})
|
||||
.refine((data) => data.count === 1 || Boolean(data.monsterId), { message: 'Only monsters can be added several at a time' });
|
||||
|
||||
router.post('/:id/participants', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
const parsed = participantSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { characterId, monsterId, npcId, displayName, initiativeRoll } = parsed.data;
|
||||
const { characterId, monsterId, npcId, displayName, initiativeRoll, count } = parsed.data;
|
||||
|
||||
let currentHp, maxHp, resolvedName;
|
||||
let bonus = 0;
|
||||
@@ -411,22 +534,40 @@ router.post('/:id/participants', requireEncounterAccess, requireDM, async (req,
|
||||
resolvedName = displayName || npc.name;
|
||||
}
|
||||
|
||||
const participant = await prisma.encounterParticipant.create({
|
||||
data: {
|
||||
encounterId: req.encounter.id,
|
||||
characterId: characterId || null,
|
||||
monsterId: monsterId || null,
|
||||
npcId: npcId || null,
|
||||
displayName: resolvedName,
|
||||
initiativeRoll: initiativeRoll ?? null,
|
||||
initiative: initiativeRoll == null ? 0 : initiativeRoll + bonus,
|
||||
currentHp,
|
||||
maxHp,
|
||||
isMonster: Boolean(monsterId),
|
||||
},
|
||||
});
|
||||
// Several at once are numbered, carrying on from any of that name already
|
||||
// in the scene ("Goblin 3" after "Goblin 1" and "Goblin 2").
|
||||
let names = [resolvedName];
|
||||
if (count > 1) {
|
||||
const present = await prisma.encounterParticipant.findMany({ where: { encounterId: req.encounter.id }, select: { displayName: true } });
|
||||
const numbered = present
|
||||
.filter((p) => p.displayName.startsWith(`${resolvedName} `))
|
||||
.map((p) => Number(p.displayName.slice(resolvedName.length + 1)))
|
||||
.filter((n) => Number.isInteger(n) && n > 0);
|
||||
const from = Math.max(0, ...numbered);
|
||||
names = Array.from({ length: count }, (_, i) => `${resolvedName} ${from + i + 1}`.slice(-80));
|
||||
}
|
||||
|
||||
await respondWithEncounter(req, res, 201, { participant });
|
||||
const participants = [];
|
||||
for (const name of names) {
|
||||
participants.push(
|
||||
await prisma.encounterParticipant.create({
|
||||
data: {
|
||||
encounterId: req.encounter.id,
|
||||
characterId: characterId || null,
|
||||
monsterId: monsterId || null,
|
||||
npcId: npcId || null,
|
||||
displayName: name,
|
||||
initiativeRoll: initiativeRoll ?? null,
|
||||
initiative: initiativeRoll == null ? 0 : initiativeRoll + bonus,
|
||||
currentHp,
|
||||
maxHp,
|
||||
isMonster: Boolean(monsterId),
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
await respondWithEncounter(req, res, 201, { participant: participants[0], participants });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
@@ -437,6 +578,9 @@ const updateParticipantSchema = z.object({
|
||||
maxHp: z.number().int().min(1).max(100000).optional(),
|
||||
initiativeRoll: initiativeRollSchema.nullable().optional(), // null clears the roll
|
||||
conditions: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
|
||||
// Rounds left on the conditions that wear off by themselves; one left out
|
||||
// lasts until the DM removes it.
|
||||
conditionRounds: z.record(z.string().max(40), z.number().int().min(1).max(100)).optional(),
|
||||
displayName: z.string().min(1).max(80).optional(),
|
||||
});
|
||||
|
||||
@@ -467,11 +611,22 @@ router.patch('/:id/participants/:participantId', requireEncounterAccess, async (
|
||||
if (data.initiativeRoll !== undefined) {
|
||||
data.initiative = data.initiativeRoll == null ? 0 : data.initiativeRoll + initiativeBonus(existing);
|
||||
}
|
||||
if (data.conditions) data.conditions = [...new Set(data.conditions)];
|
||||
if (data.conditions !== undefined || data.conditionRounds !== undefined) {
|
||||
// A condition that goes takes its countdown with it.
|
||||
const conditions = data.conditions ?? (existing.character ? existing.character.conditions : existing.conditions);
|
||||
data.conditionRounds = roundsFor(data.conditionRounds ?? existing.conditionRounds, conditions);
|
||||
}
|
||||
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.conditions !== undefined) {
|
||||
// So do conditions: they are the character's, and stay after the scene.
|
||||
await prisma.character.update({ where: { id: character.id }, data: { conditions: data.conditions } });
|
||||
emitCharacterUpdated(req, character.id);
|
||||
}
|
||||
if (data.currentHp !== undefined) {
|
||||
if (lifeState(character) === 'DEAD' && data.currentHp > 0) {
|
||||
return res.status(400).json({ error: `${character.name} is dead. Revive them before healing.` });
|
||||
@@ -563,6 +718,25 @@ router.post('/:id/participants/:participantId/revive', requireEncounterAccess, a
|
||||
}
|
||||
});
|
||||
|
||||
// Rolls initiative for every monster and NPC that has no roll yet: a d20 each,
|
||||
// with their bonus added as when a roll is typed in. Characters are left to
|
||||
// their players.
|
||||
router.post('/:id/roll-initiative', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
const waiting = await prisma.encounterParticipant.findMany({
|
||||
where: { encounterId: req.encounter.id, characterId: null, initiativeRoll: null },
|
||||
include: { monster: true },
|
||||
});
|
||||
for (const p of waiting) {
|
||||
const roll = crypto.randomInt(1, 21);
|
||||
await prisma.encounterParticipant.update({ where: { id: p.id }, data: { initiativeRoll: roll, initiative: roll + initiativeBonus(p) } });
|
||||
}
|
||||
await respondWithEncounter(req, res, 200, { rolled: waiting.length });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Targets — who the combatant on turn is going for
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -626,7 +800,7 @@ router.post('/:id/next-turn', requireEncounterAccess, requireDM, async (req, res
|
||||
const index = order.findIndex((p) => p.id === req.encounter.activeParticipantId);
|
||||
const upNext = standingFrom(order, index + 1);
|
||||
const wrapped = index !== -1 && order.indexOf(upNext) <= index;
|
||||
await prisma.encounter.update({
|
||||
const updated = await prisma.encounter.update({
|
||||
where: { id: req.encounter.id },
|
||||
data: {
|
||||
status: 'ACTIVE',
|
||||
@@ -635,7 +809,10 @@ router.post('/:id/next-turn', requireEncounterAccess, requireDM, async (req, res
|
||||
...(wrapped ? { currentRound: { increment: 1 } } : {}),
|
||||
},
|
||||
});
|
||||
await respondWithEncounter(req, res);
|
||||
await declareAuto(req, updated);
|
||||
// What wore off as the new round began, for the DM to read out.
|
||||
const expired = wrapped ? await tickConditions(req) : [];
|
||||
await respondWithEncounter(req, res, 200, { expired });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
@@ -654,12 +831,430 @@ router.post('/:id/advance-round', requireEncounterAccess, requireDM, async (req,
|
||||
...(req.encounter.mode === 'BATTLE' ? { activeParticipantId: standingFrom(order, 0)?.id ?? null } : {}),
|
||||
},
|
||||
});
|
||||
const expired = await tickConditions(req);
|
||||
await declareAuto(req, updated);
|
||||
await syncCharacterLocations(req);
|
||||
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('encounter:round-advanced', {
|
||||
encounterId: updated.id,
|
||||
currentRound: updated.currentRound,
|
||||
});
|
||||
res.json({ encounter: await serializeEncounter(updated.id, req.isDM, req.user.id) });
|
||||
res.json({ expired, encounter: await serializeEncounter(updated.id, req.isDM, req.user.id) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Actions — an attack or a spell, from being declared to its damage landing
|
||||
// (game/combat.js, utils/actions.js). A player declares their own character's
|
||||
// on their turn and rolls for it; the DM declares anyone's, enters or
|
||||
// overrules any roll, and is the one who applies it. With the campaign's
|
||||
// auto-roll settings a monster's or NPC's turn begins with its attack already
|
||||
// declared and rolled (declareAuto), for the DM to accept, change or discard.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Everything an action needs of the scene's combatants.
|
||||
const COMBATANTS = {
|
||||
character: { include: { ...SHEET_INCLUDE, spells: { include: { spell: true } } } },
|
||||
monster: true,
|
||||
npc: true,
|
||||
};
|
||||
|
||||
// What is left of the turn before: nothing. A turn passing discards whatever
|
||||
// was still being resolved, and then, where the campaign says so, the
|
||||
// combatant now on turn (a monster, or an NPC) declares its own attacks.
|
||||
async function declareAuto(req, encounter) {
|
||||
await prisma.encounterAction.updateMany({ where: { encounterId: encounter.id, status: 'PENDING' }, data: { status: 'DISCARDED' } });
|
||||
if (encounter.mode !== 'BATTLE' || encounter.status !== 'ACTIVE' || !encounter.activeParticipantId) return;
|
||||
const { autoRollMonsters, autoRollNpcs, areaAttackAcPenalty, critRule, hideMonsterRolls } = req.campaign;
|
||||
if (!autoRollMonsters && !autoRollNpcs) return;
|
||||
|
||||
const participants = await prisma.encounterParticipant.findMany({ where: { encounterId: encounter.id }, include: COMBATANTS });
|
||||
const actor = participants.find((p) => p.id === encounter.activeParticipantId);
|
||||
if (!actor || actor.character) return;
|
||||
if (actor.npc ? !autoRollNpcs : !autoRollMonsters) return;
|
||||
|
||||
const history = await prisma.encounterAction.findMany({ where: { encounterId: encounter.id, status: 'APPLIED' }, orderBy: { appliedAt: 'desc' }, take: 40 });
|
||||
const declared = autoActions(actor, participants, { penaltyStep: areaAttackAcPenalty, critRule, history });
|
||||
for (const action of declared) {
|
||||
await prisma.encounterAction.create({ data: { ...action, encounterId: encounter.id, round: encounter.currentRound, hidden: hideMonsterRolls, createdById: null } });
|
||||
}
|
||||
}
|
||||
|
||||
const abilityEnum = z.enum(['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA']);
|
||||
|
||||
const actionSourceSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('weapon'), characterWeaponId: z.string() }),
|
||||
z.object({ type: z.literal('spell'), characterSpellId: z.string(), slotLevel: z.number().int().min(1).max(9).optional() }),
|
||||
z.object({ type: z.literal('basic'), index: z.number().int().min(0).max(20).optional() }),
|
||||
z.object({
|
||||
type: z.literal('custom'),
|
||||
name: z.string().trim().min(1).max(60),
|
||||
kind: z.enum(['ATTACK', 'SAVE', 'AUTO']),
|
||||
attackBonus: z.number().int().min(-20).max(50).optional(),
|
||||
saveAbility: abilityEnum.optional(),
|
||||
saveDC: z.number().int().min(1).max(40).optional(),
|
||||
halfOnSave: z.boolean().optional(),
|
||||
damageDice: z.string().max(60).optional().nullable(),
|
||||
damageType: z.string().max(30).optional().nullable(),
|
||||
}),
|
||||
]);
|
||||
|
||||
const createActionSchema = z.object({
|
||||
// Who is acting; whoever is on turn when left out.
|
||||
actorParticipantId: z.string().optional(),
|
||||
source: actionSourceSchema,
|
||||
// Who it is aimed at; the targets marked in the encounter when left out.
|
||||
targetIds: z.array(z.string()).max(50).optional(),
|
||||
hidden: z.boolean().optional(), // the DM's: keep it from the players until applied
|
||||
});
|
||||
|
||||
// Whether the requester's own character is this participant.
|
||||
const ownsParticipant = (req, p) => Boolean(p && p.character && p.character.userId === req.user.id);
|
||||
|
||||
router.post('/:id/actions', requireEncounterAccess, async (req, res, next) => {
|
||||
try {
|
||||
const parsed = createActionSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { source } = parsed.data;
|
||||
if (req.encounter.status !== 'ACTIVE') return res.status(400).json({ error: 'Begin the encounter before anyone attacks.' });
|
||||
|
||||
const participants = await prisma.encounterParticipant.findMany({ where: { encounterId: req.encounter.id }, include: COMBATANTS });
|
||||
const actorId = parsed.data.actorParticipantId || req.encounter.activeParticipantId;
|
||||
const actor = participants.find((p) => p.id === actorId) || null;
|
||||
if (!req.isDM) {
|
||||
// A player acts for their own character, on its turn, with what it has.
|
||||
if (!ownsParticipant(req, actor) || actor.id !== req.encounter.activeParticipantId) {
|
||||
return res.status(403).json({ error: "You can only attack on your own character's turn." });
|
||||
}
|
||||
if (source.type === 'custom' || source.type === 'basic') return res.status(403).json({ error: 'Pick one of your weapons or spells.' });
|
||||
}
|
||||
|
||||
const targetIds = [...new Set(parsed.data.targetIds || req.encounter.targetParticipantIds)];
|
||||
const targets = targetIds.map((id) => participants.find((p) => p.id === id));
|
||||
if (targets.length === 0) return res.status(400).json({ error: 'Pick a target first.' });
|
||||
if (targets.some((p) => !p)) return res.status(400).json({ error: 'Combatant not found in this encounter' });
|
||||
|
||||
let described;
|
||||
try {
|
||||
described = describeSource(actor, source);
|
||||
} catch (err) {
|
||||
if (!(err instanceof ActionError)) throw err;
|
||||
return res.status(400).json({ error: err.message });
|
||||
}
|
||||
const { kind, name, detail } = described;
|
||||
|
||||
// One thing at a time: a new action takes the place of the actor's unfinished one.
|
||||
await prisma.encounterAction.updateMany({
|
||||
where: { encounterId: req.encounter.id, status: 'PENDING', actorParticipantId: actor ? actor.id : null },
|
||||
data: { status: 'DISCARDED' },
|
||||
});
|
||||
const action = await prisma.encounterAction.create({
|
||||
data: {
|
||||
encounterId: req.encounter.id,
|
||||
round: req.encounter.currentRound,
|
||||
actorParticipantId: actor ? actor.id : null,
|
||||
actorName: actor ? actor.displayName : 'The DM',
|
||||
kind,
|
||||
name,
|
||||
detail,
|
||||
targets: targetRows(kind, detail, targets, req.campaign.areaAttackAcPenalty),
|
||||
hidden: req.isDM && Boolean(parsed.data.hidden),
|
||||
createdById: req.user.id,
|
||||
},
|
||||
});
|
||||
await respondWithEncounter(req, res, 201, { actionId: action.id });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const d20Schema = z.number().int().min(1, 'A d20 shows 1 to 20').max(20, 'A d20 shows 1 to 20');
|
||||
|
||||
const patchActionSchema = z.object({
|
||||
// A d20 typed in for a target: the attack roll against them, or their saving throw. null clears it.
|
||||
rolls: z.array(z.object({ participantId: z.string(), d20: d20Schema.nullable() })).max(50).optional(),
|
||||
// Have the server roll every d20 still missing that the requester may roll.
|
||||
rollRemaining: z.boolean().optional(),
|
||||
// The DM overruling the dice for a target; null goes back to what was rolled.
|
||||
outcomes: z.array(z.object({ participantId: z.string(), outcome: z.enum(['HIT', 'MISS', 'CRIT', 'SAVED', 'FAILED']).nullable() })).max(50).optional(),
|
||||
// The damage, typed in (dice rolled at the table), or rolled by the server.
|
||||
damage: z.number().int().min(0).max(100000).nullable().optional(),
|
||||
rollDamage: z.boolean().optional(),
|
||||
// The DM setting what one target takes; null goes back to what the action deals.
|
||||
targetDamage: z.array(z.object({ participantId: z.string(), damage: z.number().int().min(0).max(100000).nullable() })).max(50).optional(),
|
||||
// The DM aiming it at someone else: rolls already made stay with their place in the list.
|
||||
targetIds: z.array(z.string()).min(1).max(50).optional(),
|
||||
hidden: z.boolean().optional(),
|
||||
discard: z.boolean().optional(),
|
||||
});
|
||||
|
||||
// Loads a pending action of this encounter with its actor, or answers and returns null.
|
||||
async function loadAction(req, res) {
|
||||
const action = await prisma.encounterAction.findUnique({ where: { id: req.params.actionId } });
|
||||
if (!action || action.encounterId !== req.encounter.id) {
|
||||
res.status(404).json({ error: 'That attack is not part of this encounter.' });
|
||||
return null;
|
||||
}
|
||||
if (action.status !== 'PENDING') {
|
||||
res.status(400).json({ error: action.status === 'APPLIED' ? 'That attack has already landed.' : 'That attack was discarded.' });
|
||||
return null;
|
||||
}
|
||||
if (!req.isDM && action.hidden) {
|
||||
res.status(404).json({ error: 'That attack is not part of this encounter.' });
|
||||
return null;
|
||||
}
|
||||
return action;
|
||||
}
|
||||
|
||||
router.patch('/:id/actions/:actionId', requireEncounterAccess, async (req, res, next) => {
|
||||
try {
|
||||
const parsed = patchActionSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const action = await loadAction(req, res);
|
||||
if (!action) return;
|
||||
const input = parsed.data;
|
||||
|
||||
const participants = await prisma.encounterParticipant.findMany({ where: { encounterId: req.encounter.id }, include: COMBATANTS });
|
||||
const actor = participants.find((p) => p.id === action.actorParticipantId) || null;
|
||||
const actsForActor = req.isDM || ownsParticipant(req, actor);
|
||||
// Who may put in the d20 for a target: for an attack, whoever is
|
||||
// attacking; for a save, the target's own player. The DM, always.
|
||||
const mayRollFor = (target) =>
|
||||
req.isDM || (action.kind === 'ATTACK' ? actsForActor : ownsParticipant(req, participants.find((p) => p.id === target.participantId)));
|
||||
// A player follows the campaign's dice; the DM enters or rolls as they like.
|
||||
const { diceMode } = req.campaign;
|
||||
const mayType = req.isDM || diceMode !== 'DIGITAL';
|
||||
const mayAsk = req.isDM || diceMode !== 'PHYSICAL';
|
||||
|
||||
if (input.discard) {
|
||||
if (!actsForActor) return res.status(403).json({ error: 'Only the DM or whoever declared it can call it off.' });
|
||||
await prisma.encounterAction.update({ where: { id: action.id }, data: { status: 'DISCARDED' } });
|
||||
return await respondWithEncounter(req, res);
|
||||
}
|
||||
const dmOnly = input.outcomes || input.targetDamage || input.targetIds || input.hidden !== undefined;
|
||||
if (dmOnly && !req.isDM) return res.status(403).json({ error: 'Only the DM overrules a roll, sets damage by hand or changes the targets.' });
|
||||
|
||||
let targets = action.targets.map((t) => ({ ...t }));
|
||||
let damage = action.damage;
|
||||
const data = {};
|
||||
|
||||
if (input.targetIds) {
|
||||
const next = [...new Set(input.targetIds)].map((id) => participants.find((p) => p.id === id));
|
||||
if (next.some((p) => !p)) return res.status(400).json({ error: 'Combatant not found in this encounter' });
|
||||
const fresh = targetRows(action.kind, action.detail, next, req.campaign.areaAttackAcPenalty);
|
||||
// A target kept keeps its roll; a new one in an old one's place takes the
|
||||
// roll already made (the die was cast before the aim was changed).
|
||||
targets = fresh.map((row, i) => {
|
||||
const kept = targets.find((t) => t.participantId === row.participantId);
|
||||
const d20 = kept ? kept.d20 : targets[i] && !next.some((p) => p.id === targets[i].participantId) ? targets[i].d20 : null;
|
||||
return { ...row, d20: action.kind === 'SAVE' && !kept ? null : d20 };
|
||||
});
|
||||
}
|
||||
|
||||
for (const { participantId, d20 } of input.rolls || []) {
|
||||
const target = targets.find((t) => t.participantId === participantId);
|
||||
if (!target) return res.status(400).json({ error: 'That is not one of its targets.' });
|
||||
if (!mayRollFor(target)) return res.status(403).json({ error: action.kind === 'SAVE' ? 'You can only enter the save for your own character.' : 'Only the attacker (or the DM) enters the attack roll.' });
|
||||
if (!mayType) return res.status(400).json({ error: 'This campaign plays with digital dice: the app rolls.' });
|
||||
target.d20 = d20;
|
||||
}
|
||||
if (input.rollRemaining) {
|
||||
if (!mayAsk) return res.status(400).json({ error: 'This campaign plays with physical dice: roll at the table and enter what the d20 shows.' });
|
||||
for (const target of targets) if (target.d20 == null && action.kind !== 'AUTO' && mayRollFor(target)) target.d20 = rollDie(20);
|
||||
}
|
||||
for (const { participantId, outcome } of input.outcomes || []) {
|
||||
const target = targets.find((t) => t.participantId === participantId);
|
||||
if (!target) return res.status(400).json({ error: 'That is not one of its targets.' });
|
||||
const allowed = action.kind === 'SAVE' ? ['SAVED', 'FAILED'] : ['HIT', 'MISS', 'CRIT'];
|
||||
if (outcome !== null && !allowed.includes(outcome)) return res.status(400).json({ error: `For this it is ${allowed.join(', ')}.` });
|
||||
target.outcome = outcome;
|
||||
}
|
||||
for (const { participantId, damage: amount } of input.targetDamage || []) {
|
||||
const target = targets.find((t) => t.participantId === participantId);
|
||||
if (!target) return res.status(400).json({ error: 'That is not one of its targets.' });
|
||||
target.damage = amount;
|
||||
}
|
||||
|
||||
if (input.damage !== undefined) {
|
||||
if (!actsForActor) return res.status(403).json({ error: 'Only the attacker (or the DM) enters the damage.' });
|
||||
if (!mayType) return res.status(400).json({ error: 'This campaign plays with digital dice: the app rolls.' });
|
||||
damage = input.damage === null ? null : { total: input.damage, entered: true };
|
||||
}
|
||||
const settledNow = () => settle({ ...action, targets, damage });
|
||||
if (input.rollDamage) {
|
||||
if (!actsForActor) return res.status(403).json({ error: 'Only the attacker (or the DM) rolls the damage.' });
|
||||
if (!mayAsk) return res.status(400).json({ error: 'This campaign plays with physical dice: roll the damage at the table and enter the total.' });
|
||||
const critical = settledNow().targets.some((t) => t.outcome === 'CRIT');
|
||||
damage = rollDamage(action.detail, { critical, critRule: req.campaign.critRule });
|
||||
if (!damage) return res.status(400).json({ error: 'It has no damage dice to roll. Enter the damage instead.' });
|
||||
}
|
||||
// A critical hit that turns up after the damage was rolled gets its dice.
|
||||
if (damage && !damage.entered && !damage.crit && settledNow().needsCrit) {
|
||||
damage = { ...damage, crit: rollCritDamage(action.detail, { critRule: req.campaign.critRule }) };
|
||||
}
|
||||
|
||||
if (input.hidden !== undefined) data.hidden = input.hidden;
|
||||
await prisma.encounterAction.update({ where: { id: action.id }, data: { ...data, targets, damage: damage === null ? Prisma.DbNull : damage } });
|
||||
await respondWithEncounter(req, res);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// The DM lets it land: every target takes what the action comes to for them
|
||||
// (temp HP first, death saves at 0, as with any damage), a spell takes its
|
||||
// slot, and the action is done and shown to everyone. Answers with a line for
|
||||
// anyone hurt while concentrating, for the DM to call the save.
|
||||
router.post('/:id/actions/:actionId/apply', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
const action = await loadAction(req, res);
|
||||
if (!action) return;
|
||||
const settled = settle(action);
|
||||
if (!settled.ready) {
|
||||
return res.status(400).json({
|
||||
error: settled.needsRolls > 0 ? `Still waiting on ${settled.needsRolls} d20${settled.needsRolls === 1 ? '' : 's'}.` : 'The damage has not been rolled or entered yet.',
|
||||
});
|
||||
}
|
||||
|
||||
const participants = await prisma.encounterParticipant.findMany({ where: { encounterId: req.encounter.id }, include: COMBATANTS });
|
||||
const concentration = [];
|
||||
for (const target of settled.targets) {
|
||||
const p = participants.find((x) => x.id === target.participantId);
|
||||
const amount = target.finalDamage || 0;
|
||||
if (!p || amount <= 0) continue;
|
||||
const conditions = p.character ? p.character.conditions : p.conditions;
|
||||
if (conditions.includes('Concentrating')) concentration.push({ name: p.displayName, damage: amount, dc: Math.max(10, Math.floor(amount / 2)) });
|
||||
if (p.character) {
|
||||
if (lifeState(p.character) === 'DEAD') continue;
|
||||
const maxHp = computeCharacterSheet(p.character, p.character.skillProficiencies, p.character.saveProficiencies).hp.max;
|
||||
const after = changeHp(p.character, p.character.currentHp - amount, maxHp);
|
||||
await prisma.character.update({ where: { id: p.character.id }, data: after });
|
||||
await prisma.encounterParticipant.update({ where: { id: p.id }, data: { currentHp: after.currentHp, maxHp } });
|
||||
emitCharacterUpdated(req, p.character.id);
|
||||
} else if (p.maxHp > 0) {
|
||||
await prisma.encounterParticipant.update({ where: { id: p.id }, data: { currentHp: clamp(p.currentHp - amount, 0, p.maxHp) } });
|
||||
}
|
||||
}
|
||||
|
||||
// A spell takes a slot of the level it was cast at, when the caster has one left.
|
||||
let slotNote = null;
|
||||
const { characterId, slotLevel } = action.detail;
|
||||
const caster = slotLevel ? participants.map((p) => p.character).find((c) => c && c.id === characterId) : null;
|
||||
if (caster) {
|
||||
const slots = computeCharacterSheet(caster, caster.skillProficiencies, caster.saveProficiencies).spellSlots;
|
||||
const slot = slots ? slots.levels.find((l) => l.level === slotLevel) : null;
|
||||
if (slot && slot.remaining > 0) {
|
||||
const used = Array.from({ length: slots.levels[slots.levels.length - 1].level }, (_, i) => {
|
||||
const at = slots.levels.find((l) => l.level === i + 1);
|
||||
return at ? at.used + (at.level === slotLevel ? 1 : 0) : 0;
|
||||
});
|
||||
await prisma.character.update({ where: { id: caster.id }, data: { spellSlotsUsed: used } });
|
||||
emitCharacterUpdated(req, caster.id);
|
||||
} else {
|
||||
slotNote = `${caster.name} had no level ${slotLevel} spell slot left for ${action.name}: nothing was spent.`;
|
||||
}
|
||||
}
|
||||
|
||||
// Kept as it landed, so later turns know who hurt whom.
|
||||
await prisma.encounterAction.update({
|
||||
where: { id: action.id },
|
||||
data: { status: 'APPLIED', appliedAt: new Date(), hidden: false, targets: settled.targets },
|
||||
});
|
||||
await respondWithEncounter(req, res, 200, { concentration, slotNote });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Free roam — the party wanders between the places the DM has laid out for
|
||||
// the scene: to shop, to meet whoever is found there. The DM sets the places;
|
||||
// each player sends their own character to one (the DM can send anyone).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// The whole list of places; an empty one clears it.
|
||||
router.put('/:id/places', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ locationIds: z.array(z.string()).max(50) }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const locationIds = [...new Set(parsed.data.locationIds)];
|
||||
if ((await prisma.location.count({ where: { id: { in: locationIds }, campaignId: req.encounter.campaignId } })) !== locationIds.length) {
|
||||
return res.status(400).json({ error: "Pick places from this campaign's locations." });
|
||||
}
|
||||
const had = await prisma.encounterLocation.findMany({ where: { encounterId: req.encounter.id }, select: { locationId: true } });
|
||||
const keep = new Set(had.map((row) => row.locationId));
|
||||
await prisma.$transaction([
|
||||
prisma.encounterLocation.deleteMany({ where: { encounterId: req.encounter.id, locationId: { notIn: locationIds } } }),
|
||||
// Added one at a time, in the order given, so the list keeps that order.
|
||||
...locationIds.filter((id) => !keep.has(id)).map((locationId) => prisma.encounterLocation.create({ data: { encounterId: req.encounter.id, locationId } })),
|
||||
]);
|
||||
await respondWithEncounter(req, res);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// A character goes to one of the scene's places: their own player sends them, or the DM.
|
||||
router.post('/:id/visit', requireEncounterAccess, async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ characterId: z.string(), locationId: z.string() }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { characterId, locationId } = parsed.data;
|
||||
if (req.encounter.mode !== 'FREE_ROAM') return res.status(400).json({ error: 'Only a free-roam scene has places to go to.' });
|
||||
if (req.encounter.status !== 'ACTIVE') return res.status(400).json({ error: 'The scene has not begun yet.' });
|
||||
|
||||
const row = await prisma.encounterParticipant.findFirst({ where: { encounterId: req.encounter.id, characterId }, include: { character: true } });
|
||||
if (!row) return res.status(400).json({ error: 'That character is not in this scene.' });
|
||||
if (!req.isDM && row.character.userId !== req.user.id) return res.status(403).json({ error: 'You can only move your own character.' });
|
||||
if (isFallen(row)) return res.status(400).json({ error: `${row.character.name} is dead.` });
|
||||
const place = await prisma.encounterLocation.findFirst({ where: { encounterId: req.encounter.id, locationId } });
|
||||
if (!place) return res.status(400).json({ error: 'That is not one of the places in this scene.' });
|
||||
|
||||
await moveCharacters(prisma, [characterId], locationId);
|
||||
emitCharacterUpdated(req, characterId);
|
||||
await respondWithEncounter(req, res);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Experience — awarded once, shared evenly between the characters in the scene
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const awardXpSchema = z.object({ xp: z.number().int().min(1).max(10000000).optional() });
|
||||
|
||||
// The DM hands out the encounter's XP: what its monsters are worth unless
|
||||
// another amount is given, in equal shares (rounded down) to every character
|
||||
// in the scene. Nobody levels up by it; the sheet says when a level is due.
|
||||
router.post('/:id/award-xp', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
const parsed = awardXpSchema.safeParse(req.body || {});
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
if (!req.campaign.trackXp) {
|
||||
return res.status(400).json({ error: 'This campaign does not keep experience points.' });
|
||||
}
|
||||
if (req.encounter.xpAwarded != null) {
|
||||
return res.status(400).json({ error: `XP has already been awarded for this encounter (${req.encounter.xpAwarded}). Change a character's XP on their sheet.` });
|
||||
}
|
||||
|
||||
const participants = await prisma.encounterParticipant.findMany({
|
||||
where: { encounterId: req.encounter.id },
|
||||
include: { character: { select: { id: true, name: true, level: true } }, monster: { select: { challengeRating: true } } },
|
||||
});
|
||||
const characters = participants.filter((p) => p.character).map((p) => p.character);
|
||||
if (characters.length === 0) return res.status(400).json({ error: 'There are no characters in this encounter to award XP to.' });
|
||||
const xp = parsed.data.xp ?? difficultyOf(participants).xp;
|
||||
if (!(xp > 0)) return res.status(400).json({ error: 'There is no XP to award: no monster here has a challenge rating. Type an amount.' });
|
||||
|
||||
const share = Math.floor(xp / characters.length);
|
||||
await prisma.$transaction([
|
||||
prisma.character.updateMany({ where: { id: { in: characters.map((c) => c.id) } }, data: { xp: { increment: share } } }),
|
||||
prisma.encounter.update({ where: { id: req.encounter.id }, data: { xpAwarded: xp } }),
|
||||
]);
|
||||
for (const character of characters) emitCharacterUpdated(req, character.id);
|
||||
await respondWithEncounter(req, res, 200, { xp, share, awardedTo: characters.map((c) => c.name) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
@@ -814,10 +1409,18 @@ function money(amount, currency) {
|
||||
}
|
||||
|
||||
// Trading takes someone to trade with and the time to do it, so it happens
|
||||
// in a quest in progress and never in a battle.
|
||||
// in a quest or a free-roam scene in progress, and never in a battle.
|
||||
function assertTradeOpen(encounter) {
|
||||
if (encounter.mode !== 'QUEST') throw new TradeError('Trading happens in a quest, not in a battle.');
|
||||
if (encounter.status !== 'ACTIVE') throw new TradeError('Trading opens once the quest is in progress.');
|
||||
if (encounter.mode === 'BATTLE') throw new TradeError('Trading happens in a quest or while roaming, not in a battle.');
|
||||
if (encounter.status !== 'ACTIVE') throw new TradeError(`Trading opens once the ${encounter.mode === 'QUEST' ? 'quest' : 'scene'} is in progress.`);
|
||||
}
|
||||
|
||||
// In a free-roam scene a character trades where they are: the place has to
|
||||
// be one of the scene's, and they have to have gone there.
|
||||
async function assertAtPlace(req, character, locationId, what) {
|
||||
const place = locationId ? await prisma.encounterLocation.findFirst({ where: { encounterId: req.encounter.id, locationId }, include: { location: true } }) : null;
|
||||
if (!place) throw new TradeError(`${what} is not here to trade with.`);
|
||||
if (character.currentLocationId !== locationId) throw new TradeError(`${character.name} has to go to ${place.location.name} first.`);
|
||||
}
|
||||
|
||||
// The character doing the trading: in this scene, alive, and the player's
|
||||
@@ -830,8 +1433,15 @@ async function loadTrader(req, characterId) {
|
||||
return row.character;
|
||||
}
|
||||
|
||||
// An NPC to trade with has to be in the scene and still standing.
|
||||
async function loadTradingNpc(req, npcId) {
|
||||
// An NPC to trade with has to be in the scene and still standing; in a
|
||||
// free-roam scene, at one of its places, with the character there too.
|
||||
async function loadTradingNpc(req, npcId, character) {
|
||||
if (req.encounter.mode === 'FREE_ROAM') {
|
||||
const npc = await prisma.npc.findFirst({ where: { id: npcId, campaignId: req.encounter.campaignId } });
|
||||
if (!npc) throw new TradeError('That NPC is not here to trade with.');
|
||||
await assertAtPlace(req, character, npc.locationId, npc.name);
|
||||
return npc;
|
||||
}
|
||||
const row = await prisma.encounterParticipant.findFirst({ where: { encounterId: req.encounter.id, npcId }, include: { npc: true } });
|
||||
if (!row || isFallen(row)) throw new TradeError('That NPC is not here to trade with.');
|
||||
return row.npc;
|
||||
@@ -864,7 +1474,7 @@ router.post(
|
||||
const to = from === 'GOLD' ? 'CASH' : 'GOLD';
|
||||
|
||||
const character = await loadTrader(req, characterId);
|
||||
const npc = await loadTradingNpc(req, npcId);
|
||||
const npc = await loadTradingNpc(req, npcId, character);
|
||||
if (!npc.exchangeGold || !npc.exchangeCash) throw new TradeError(`${npc.name} does not change money.`);
|
||||
const rate = { GOLD: npc.exchangeGold, CASH: npc.exchangeCash };
|
||||
if (amount % rate[from] !== 0) {
|
||||
@@ -906,7 +1516,12 @@ router.post(
|
||||
if (!ware || ware.campaignId !== req.encounter.campaignId || (ware.encounterId && ware.encounterId !== req.encounter.id)) {
|
||||
throw new TradeError('That is not for sale here.', 404);
|
||||
}
|
||||
const seller = ware.npcId ? (await loadTradingNpc(req, ware.npcId)).name : null;
|
||||
// A shop at a place sells to whoever has gone there, while that place is part of the scene.
|
||||
if (ware.locationId) {
|
||||
if (req.encounter.mode !== 'FREE_ROAM') throw new TradeError('That is not for sale here.', 404);
|
||||
await assertAtPlace(req, character, ware.locationId, 'That shop');
|
||||
}
|
||||
const seller = ware.npcId ? (await loadTradingNpc(req, ware.npcId, character)).name : null;
|
||||
const kind = ware.weapon ? 'weapon' : 'item';
|
||||
const entry = ware[kind];
|
||||
const total = ware.price * quantity;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// Rules the app knows, for any signed-in user: nothing here belongs to a
|
||||
// campaign or a character.
|
||||
const express = require('express');
|
||||
const { z } = require('zod');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { CLASSES } = require('../game/data/classes');
|
||||
const { findSubclass } = require('../game/data/subclasses');
|
||||
const { progression } = require('../game/levelUp');
|
||||
const { MULTICLASS_PREREQS, PREREQ_SCORE, prereqText } = require('../game/multiclass');
|
||||
const { MULTICLASS_PATHS } = require('../game/data/multiclassPaths');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use(requireAuth);
|
||||
|
||||
// GET /reference/progression?class=FIGHTER&subclass=CHAMPION — what each
|
||||
// level from 1 to 20 gives a class, with the subclass's lines when one is
|
||||
// named. Shown as the progression timeline in the builder, on the sheet and
|
||||
// when levelling up.
|
||||
router.get('/progression', (req, res) => {
|
||||
const parsed = z.object({ class: z.enum(Object.keys(CLASSES)), subclass: z.string().optional() }).safeParse(req.query);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { class: characterClass, subclass } = parsed.data;
|
||||
if (subclass && !findSubclass(characterClass, subclass)) return res.status(400).json({ error: 'That is not a subclass of this class.' });
|
||||
res.json({ characterClass, subclass: subclass || null, levels: progression(characterClass, subclass) });
|
||||
});
|
||||
|
||||
// GET /reference/multiclass — what each class asks of the ability scores to
|
||||
// multiclass into or out of it, and the suggested routes (data/multiclassPaths.js).
|
||||
router.get('/multiclass', (req, res) => {
|
||||
res.json({
|
||||
prereqScore: PREREQ_SCORE,
|
||||
prereqs: Object.fromEntries(Object.keys(CLASSES).map((cls) => [cls, { alternatives: MULTICLASS_PREREQS[cls], text: prereqText(cls) }])),
|
||||
paths: MULTICLASS_PATHS,
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,121 @@
|
||||
// Creates one campaign, fully built, from a checked seed (seeds/index.js,
|
||||
// buildSeed), with `owner` as its DM. `db` is a transaction client, so a
|
||||
// failure leaves nothing behind.
|
||||
const { generateInviteCode } = require('../utils/inviteCode');
|
||||
|
||||
// Notes list newest-first on screen, so they are stamped a second apart,
|
||||
// backwards: the first entry in the seed is the one at the top.
|
||||
function bookOrder(index) {
|
||||
return new Date(Date.now() - index * 1000);
|
||||
}
|
||||
|
||||
function byName(rows) {
|
||||
return new Map(rows.map((row) => [row.name, row]));
|
||||
}
|
||||
|
||||
const MONEY = { gold: 'GOLD', silver: 'SILVER', copper: 'COPPER', cash: 'CASH' };
|
||||
|
||||
async function createCampaignFromSeed(db, owner, seed) {
|
||||
let inviteCode = generateInviteCode();
|
||||
while (await db.campaign.findUnique({ where: { inviteCode } })) inviteCode = generateInviteCode();
|
||||
|
||||
const campaign = await db.campaign.create({
|
||||
data: { ...seed.campaign, inviteCode, ownerId: owner.id, members: { create: { userId: owner.id, role: 'DM' } } },
|
||||
});
|
||||
const campaignId = campaign.id;
|
||||
const inCampaign = (rows) => rows.map((row) => ({ ...row, campaignId }));
|
||||
|
||||
await db.location.createMany({ data: inCampaign(seed.locations) });
|
||||
await db.weapon.createMany({ data: inCampaign(seed.weapons) });
|
||||
await db.item.createMany({ data: inCampaign(seed.items) });
|
||||
await db.spell.createMany({ data: inCampaign(seed.spells) });
|
||||
await db.monster.createMany({ data: inCampaign(seed.monsters) });
|
||||
await db.npc.createMany({ data: inCampaign(seed.npcs.map(({ wares, ...npc }) => npc)) });
|
||||
|
||||
const where = { where: { campaignId } };
|
||||
const monsters = byName(await db.monster.findMany(where));
|
||||
const npcs = byName(await db.npc.findMany(where));
|
||||
const weapons = byName(await db.weapon.findMany(where));
|
||||
const items = byName(await db.item.findMany(where));
|
||||
const locations = byName(await db.location.findMany(where));
|
||||
|
||||
// A weapon or item named in a reward or a ware, with the level it is handed
|
||||
// over at: its own starting level unless the seed asks for higher.
|
||||
const gear = ({ weapon, item, level }) => {
|
||||
const entry = weapon ? weapons.get(weapon) : items.get(item);
|
||||
return { [weapon ? 'weaponId' : 'itemId']: entry.id, level: level ?? entry.minLevel };
|
||||
};
|
||||
const wares = (list, seller) =>
|
||||
(list || []).map(({ price, currency, stock, ...ware }, i) => ({
|
||||
...seller,
|
||||
...gear(ware),
|
||||
campaignId,
|
||||
price,
|
||||
currency: currency || 'GOLD',
|
||||
stock: stock ?? null,
|
||||
createdAt: new Date(Date.now() + i), // wares list in the order written
|
||||
}));
|
||||
|
||||
for (const npc of seed.npcs) {
|
||||
if (npc.wares) await db.saleOffer.createMany({ data: wares(npc.wares, { npcId: npcs.get(npc.name).id }) });
|
||||
}
|
||||
|
||||
for (const [index, enc] of seed.encounters.entries()) {
|
||||
const participants = [];
|
||||
for (const [name, count, displayName, hp] of enc.monsters || []) {
|
||||
const monster = monsters.get(name);
|
||||
const label = displayName || monster.name;
|
||||
const maxHp = hp ?? monster.maxHp;
|
||||
for (let i = 1; i <= count; i++) {
|
||||
participants.push({
|
||||
monsterId: monster.id,
|
||||
displayName: count > 1 ? `${label} #${i}` : label,
|
||||
currentHp: maxHp,
|
||||
maxHp,
|
||||
isMonster: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const entry of enc.npcs || []) {
|
||||
const { name, hp } = typeof entry === 'string' ? { name: entry } : entry;
|
||||
const npc = npcs.get(name);
|
||||
// An NPC with no combat stats takes part with no hit points to track.
|
||||
const maxHp = hp ?? npc.maxHp ?? 0;
|
||||
participants.push({ npcId: npc.id, displayName: npc.name, currentHp: maxHp, maxHp, isMonster: false });
|
||||
}
|
||||
|
||||
// Rewards list oldest-first, so these are stamped forwards.
|
||||
const rewards = (enc.rewards || []).map(({ quantity, note, ...reward }, i) => {
|
||||
const createdAt = new Date(Date.now() + i);
|
||||
const coin = Object.keys(MONEY).find((key) => reward[key]);
|
||||
if (coin) return { type: 'GOLD', gold: reward[coin], currency: MONEY[coin], note, createdAt };
|
||||
return { type: reward.weapon ? 'WEAPON' : 'ITEM', ...gear(reward), quantity: quantity ?? 1, note, createdAt };
|
||||
});
|
||||
|
||||
const encounter = await db.encounter.create({
|
||||
data: {
|
||||
campaignId,
|
||||
name: enc.name,
|
||||
mode: enc.mode,
|
||||
description: enc.description,
|
||||
dmNotes: enc.dmNotes,
|
||||
locationId: enc.location ? locations.get(enc.location).id : null,
|
||||
sortOrder: index,
|
||||
participants: { create: participants },
|
||||
rewards: { create: rewards },
|
||||
},
|
||||
});
|
||||
if (enc.wares) await db.saleOffer.createMany({ data: wares(enc.wares, { encounterId: encounter.id }) });
|
||||
}
|
||||
|
||||
await db.note.createMany({
|
||||
data: [
|
||||
...seed.sharedNotes.map((body) => ({ body, visibility: 'SHARED' })),
|
||||
...seed.dmNotes.map((body) => ({ body, visibility: 'DM_ONLY' })),
|
||||
].map((note, i) => ({ ...note, campaignId, authorId: owner.id, createdAt: bookOrder(i) })),
|
||||
});
|
||||
|
||||
return campaign;
|
||||
}
|
||||
|
||||
module.exports = { createCampaignFromSeed };
|
||||
@@ -0,0 +1,345 @@
|
||||
// World seeds: ready-made campaigns a DM starts from by typing a code.
|
||||
//
|
||||
// Every .js file in /backend/seeds is one world (docs/SEEDS.md has the full
|
||||
// format). It exports its `code` and the campaign's content; this module
|
||||
// finds the files, checks them, and turns one into rows for
|
||||
// createCampaign.js. The folder is read again on every lookup, so a file
|
||||
// dropped in is live without a restart.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { z } = require('zod');
|
||||
const { GEAR_STATS, MAX_DAMAGE_SCALING, MAX_GEAR_LEVEL } = require('../game/calculations');
|
||||
const { WEAPON_LIBRARY, ITEM_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../game/data/library');
|
||||
const { CURRENCIES } = require('../utils/grants');
|
||||
|
||||
const SEEDS_DIR = path.join(__dirname, '..', '..', 'seeds');
|
||||
const CODE_LENGTH = 6;
|
||||
const CODE_PATTERN = /^[A-Z0-9]{6}$/;
|
||||
|
||||
// What someone types, as a seed file would have it.
|
||||
function normalizeCode(code) {
|
||||
return String(code || '').replace(/[\s-]/g, '').toUpperCase();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The shape of a seed file. Objects are strict, so a misspelt field is an
|
||||
// error rather than something silently left out of the campaign. The limits
|
||||
// are the ones the app itself enforces (routes/*.js), so whatever a seed
|
||||
// creates can still be edited on screen.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const text = (max) => z.string().trim().min(1).max(max);
|
||||
const optionalText = (max) => z.string().max(max).nullish();
|
||||
const dice = z.string().min(1).max(20).nullish();
|
||||
// A creature's damage may name its type: "1d6+2 necrotic".
|
||||
const damage = z.string().min(1).max(60).nullish();
|
||||
const score = z.number().int().min(1).max(30).optional();
|
||||
const gearLevel = z.number().int().min(1).max(MAX_GEAR_LEVEL);
|
||||
|
||||
const gear = {
|
||||
damageScaling: z.number().int().min(1).max(MAX_DAMAGE_SCALING).optional(),
|
||||
minLevel: gearLevel.optional(),
|
||||
isStartingOption: z.boolean().optional(),
|
||||
effects: z.array(z.strictObject({ stat: z.enum(GEAR_STATS), amount: z.number().int().min(-100).max(100) })).max(12).optional(),
|
||||
effectNote: optionalText(300),
|
||||
};
|
||||
|
||||
const POOLS = {
|
||||
weapons: {
|
||||
library: WEAPON_LIBRARY,
|
||||
row: z.strictObject({
|
||||
name: text(80),
|
||||
damageDice: z.string().min(1).max(20),
|
||||
damageType: text(40),
|
||||
attackAbility: z.enum(['STR', 'DEX', 'FINESSE']),
|
||||
properties: z.array(z.string()).optional(),
|
||||
rangeNormal: z.number().int().min(0).nullish(),
|
||||
rangeLong: z.number().int().min(0).nullish(),
|
||||
...gear,
|
||||
}),
|
||||
},
|
||||
items: {
|
||||
library: ITEM_LIBRARY,
|
||||
row: z.strictObject({ name: text(120), description: optionalText(2000), damageDice: dice, armorType: z.enum(['LIGHT', 'MEDIUM', 'HEAVY', 'SHIELD']).nullish(), ...gear }),
|
||||
},
|
||||
spells: {
|
||||
library: SPELL_LIBRARY,
|
||||
row: z.strictObject({
|
||||
name: text(80),
|
||||
level: z.number().int().min(0).max(9),
|
||||
damageDice: dice,
|
||||
school: optionalText(40),
|
||||
castingTime: optionalText(80),
|
||||
range: optionalText(80),
|
||||
duration: optionalText(80),
|
||||
description: optionalText(4000),
|
||||
isStartingOption: z.boolean().optional(),
|
||||
revives: z.boolean().optional(),
|
||||
// How it lands in a battle: a spell attack, or a save by each target.
|
||||
attackRoll: z.boolean().optional(),
|
||||
saveAbility: z.enum(['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA']).nullish(),
|
||||
halfOnSave: z.boolean().optional(),
|
||||
}),
|
||||
},
|
||||
monsters: {
|
||||
library: MONSTER_LIBRARY,
|
||||
row: z.strictObject({
|
||||
name: text(80),
|
||||
ac: z.number().int().min(0).max(40),
|
||||
maxHp: z.number().int().min(1).max(10000),
|
||||
speed: z.number().int().min(0).max(500).optional(),
|
||||
strScore: score,
|
||||
dexScore: score,
|
||||
conScore: score,
|
||||
intScore: score,
|
||||
wisScore: score,
|
||||
chaScore: score,
|
||||
attackBonus: z.number().int().min(-10).max(30).optional(),
|
||||
damageDice: damage,
|
||||
challengeRating: optionalText(10),
|
||||
specialTrait: optionalText(500),
|
||||
notes: optionalText(2000),
|
||||
// Named attacks, for more than the one above; `count` makes it a multiattack.
|
||||
attacks: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
name: text(40),
|
||||
attackBonus: z.number().int().min(-10).max(30),
|
||||
damageDice: damage,
|
||||
damageType: optionalText(30),
|
||||
count: z.number().int().min(1).max(10).optional(),
|
||||
})
|
||||
)
|
||||
.max(8)
|
||||
.optional(),
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
const moneyAmount = z.number().int().min(1).max(1000000);
|
||||
|
||||
// Something for sale: one weapon or one item from this seed's pools, by name.
|
||||
const wareSchema = z
|
||||
.strictObject({
|
||||
weapon: z.string().optional(),
|
||||
item: z.string().optional(),
|
||||
price: moneyAmount,
|
||||
currency: z.enum(CURRENCIES).optional(),
|
||||
level: gearLevel.nullish(),
|
||||
stock: z.number().int().min(0).max(9999).nullish(),
|
||||
})
|
||||
.refine((ware) => Boolean(ware.weapon) !== Boolean(ware.item), { message: 'A ware sells one weapon or one item' });
|
||||
|
||||
// Loot: money ({ gold: 25 }, or silver / copper / cash), a weapon or an item.
|
||||
const rewardSchema = z
|
||||
.strictObject({
|
||||
gold: moneyAmount.nullish(),
|
||||
silver: moneyAmount.nullish(),
|
||||
copper: moneyAmount.nullish(),
|
||||
cash: moneyAmount.nullish(),
|
||||
weapon: z.string().nullish(),
|
||||
item: z.string().nullish(),
|
||||
quantity: z.number().int().min(1).max(999).nullish(),
|
||||
level: gearLevel.nullish(),
|
||||
note: optionalText(200),
|
||||
})
|
||||
.refine((reward) => ['gold', 'silver', 'copper', 'cash', 'weapon', 'item'].filter((key) => reward[key] != null).length === 1, {
|
||||
message: 'A reward is one thing: gold, silver, copper, cash, a weapon or an item',
|
||||
});
|
||||
|
||||
const npcSchema = z.strictObject({
|
||||
name: text(80),
|
||||
role: optionalText(80),
|
||||
disposition: z.enum(['FRIENDLY', 'NEUTRAL', 'HOSTILE']).optional(),
|
||||
description: optionalText(2000),
|
||||
dmNotes: optionalText(4000),
|
||||
ac: z.number().int().min(0).max(40).nullish(),
|
||||
maxHp: z.number().int().min(1).max(10000).nullish(),
|
||||
attackBonus: z.number().int().min(-10).max(30).nullish(),
|
||||
damageDice: damage,
|
||||
// A money changer: exchangeGold gold for exchangeCash cash, either way.
|
||||
exchangeGold: moneyAmount.nullish(),
|
||||
exchangeCash: moneyAmount.nullish(),
|
||||
wares: z.array(wareSchema).optional(),
|
||||
});
|
||||
|
||||
const encounterSchema = z.strictObject({
|
||||
name: text(120),
|
||||
mode: z.enum(['BATTLE', 'QUEST']).optional(),
|
||||
description: optionalText(4000),
|
||||
dmNotes: optionalText(4000),
|
||||
location: z.string().nullish(),
|
||||
// [monster name, how many, display name?, max HP?]
|
||||
monsters: z
|
||||
.array(z.tuple([z.string(), z.number().int().min(1).max(50)]).rest(z.union([z.string(), z.number().int().min(1), z.null(), z.undefined()])))
|
||||
.optional(),
|
||||
npcs: z.array(z.union([z.string(), z.strictObject({ name: z.string(), hp: z.number().int().min(0).optional() })])).optional(),
|
||||
rewards: z.array(rewardSchema).optional(),
|
||||
wares: z.array(wareSchema).optional(),
|
||||
});
|
||||
|
||||
// A pool entry is a full row, or one copied from the site library: its key
|
||||
// alone, or { library: key } with fields to change on the copy. The rows
|
||||
// themselves are checked once the copies are made (resolvePool).
|
||||
const poolSchema = z.array(z.union([z.string(), z.record(z.string(), z.any())])).default([]);
|
||||
|
||||
const seedSchema = z.strictObject({
|
||||
code: z.string().regex(CODE_PATTERN, `The code is ${CODE_LENGTH} capital letters or digits`),
|
||||
campaign: z.strictObject({
|
||||
name: text(120),
|
||||
description: optionalText(2000),
|
||||
startingGold: z.number().int().min(0).max(1000000).optional(),
|
||||
startingItemCount: z.number().int().min(0).max(50).optional(),
|
||||
startingSpellCount: z.number().int().min(0).max(50).optional(),
|
||||
skipMotivationRoll: z.boolean().optional(),
|
||||
showMonsterHp: z.boolean().optional(),
|
||||
areaAttackAcPenalty: z.number().int().min(0).max(10).optional(),
|
||||
maxEquipped: z.number().int().min(1).max(20).optional(),
|
||||
maxEquippedWeapons: z.number().int().min(0).max(20).optional(),
|
||||
subclassesEnabled: z.boolean().optional(),
|
||||
multiclassEnabled: z.boolean().optional(),
|
||||
diceMode: z.enum(['DIGITAL', 'PHYSICAL', 'BOTH']).optional(),
|
||||
autoRollMonsters: z.boolean().optional(),
|
||||
autoRollNpcs: z.boolean().optional(),
|
||||
trackXp: z.boolean().optional(),
|
||||
hpOnLevelUp: z.enum(['AVERAGE', 'ROLL']).optional(),
|
||||
abilityScoreMethod: z.enum(['ROLL_4D6', 'STANDARD_ARRAY', 'POINT_BUY']).optional(),
|
||||
rollVisibility: z.enum(['ALL', 'OWN']).optional(),
|
||||
hideMonsterRolls: z.boolean().optional(),
|
||||
critRule: z.enum(['DOUBLE_DICE', 'MAX_PLUS_ROLL']).optional(),
|
||||
}),
|
||||
locations: z.array(z.strictObject({ name: text(80), description: optionalText(2000) })).default([]),
|
||||
weapons: poolSchema,
|
||||
items: poolSchema,
|
||||
spells: poolSchema,
|
||||
monsters: poolSchema,
|
||||
npcs: z.array(npcSchema).default([]),
|
||||
encounters: z.array(encounterSchema).default([]),
|
||||
// Note bodies, in reading order.
|
||||
sharedNotes: z.array(text(10000)).default([]),
|
||||
dmNotes: z.array(text(10000)).default([]),
|
||||
});
|
||||
|
||||
class SeedError extends Error {}
|
||||
|
||||
function issueList(error) {
|
||||
return error.issues.map((issue) => `${issue.path.join('.') || '(file)'}: ${issue.message}`);
|
||||
}
|
||||
|
||||
// Swaps library references for copies of the library's rows (less the key and
|
||||
// the picker-only tags) and checks every row. Problems are pushed to `problems`.
|
||||
function resolvePool(pool, entries, problems) {
|
||||
const { library, row } = POOLS[pool];
|
||||
const rows = [];
|
||||
entries.forEach((entry, index) => {
|
||||
let candidate = entry;
|
||||
if (typeof entry === 'string' || (entry && entry.library)) {
|
||||
const { library: key, ...changes } = typeof entry === 'string' ? { library: entry } : entry;
|
||||
const template = library.find((item) => item.key === key);
|
||||
if (!template) return problems.push(`${pool}.${index}: there is no "${key}" in the ${pool} library`);
|
||||
const { key: _key, category, classes, ...copy } = template;
|
||||
candidate = { ...copy, ...changes };
|
||||
}
|
||||
const parsed = row.safeParse(candidate);
|
||||
if (!parsed.success) return problems.push(...issueList(parsed.error).map((issue) => `${pool}.${index} (${candidate.name || '?'}): ${issue}`));
|
||||
rows.push(parsed.data);
|
||||
});
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Checks a seed file's export and returns it ready to create: library
|
||||
// references filled in, defaults applied. Throws a SeedError listing
|
||||
// everything wrong with it.
|
||||
function buildSeed(raw) {
|
||||
const parsed = seedSchema.safeParse(raw);
|
||||
if (!parsed.success) throw new SeedError(issueList(parsed.error).join('\n'));
|
||||
const seed = parsed.data;
|
||||
const problems = [];
|
||||
for (const pool of Object.keys(POOLS)) seed[pool] = resolvePool(pool, seed[pool], problems);
|
||||
|
||||
// Encounters, rewards and wares point at things by name, so within a pool a
|
||||
// name can only be used once.
|
||||
const names = {};
|
||||
for (const pool of ['locations', 'weapons', 'items', 'spells', 'monsters', 'npcs']) {
|
||||
names[pool] = new Set();
|
||||
for (const { name } of seed[pool]) {
|
||||
if (names[pool].has(name)) problems.push(`${pool}: "${name}" is there twice`);
|
||||
names[pool].add(name);
|
||||
}
|
||||
}
|
||||
const gearByName = { weapon: new Map(seed.weapons.map((w) => [w.name, w])), item: new Map(seed.items.map((i) => [i.name, i])) };
|
||||
const checkGear = (where, { weapon, item, level }) => {
|
||||
const kind = weapon ? 'weapon' : 'item';
|
||||
const entry = gearByName[kind].get(weapon || item);
|
||||
if (!entry) return problems.push(`${where}: there is no ${kind} called "${weapon || item}"`);
|
||||
if (level && level < (entry.minLevel || 1)) problems.push(`${where}: "${entry.name}" starts at level ${entry.minLevel}, so it can't be level ${level}`);
|
||||
};
|
||||
|
||||
for (const npc of seed.npcs) {
|
||||
if (Boolean(npc.exchangeGold) !== Boolean(npc.exchangeCash)) problems.push(`NPC "${npc.name}": an exchange rate needs both exchangeGold and exchangeCash`);
|
||||
(npc.wares || []).forEach((ware) => checkGear(`NPC "${npc.name}" wares`, ware));
|
||||
}
|
||||
for (const encounter of seed.encounters) {
|
||||
const where = `Encounter "${encounter.name}"`;
|
||||
if (encounter.location && !names.locations.has(encounter.location)) problems.push(`${where}: there is no location called "${encounter.location}"`);
|
||||
for (const [monster] of encounter.monsters || []) {
|
||||
if (!names.monsters.has(monster)) problems.push(`${where}: there is no monster called "${monster}"`);
|
||||
}
|
||||
for (const entry of encounter.npcs || []) {
|
||||
const name = typeof entry === 'string' ? entry : entry.name;
|
||||
if (!names.npcs.has(name)) problems.push(`${where}: there is no NPC called "${name}"`);
|
||||
}
|
||||
for (const reward of encounter.rewards || []) if (reward.weapon || reward.item) checkGear(`${where} rewards`, reward);
|
||||
(encounter.wares || []).forEach((ware) => checkGear(`${where} wares`, ware));
|
||||
}
|
||||
|
||||
if (problems.length) throw new SeedError(problems.join('\n'));
|
||||
return seed;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The folder
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Every seed file, good or bad: [{ file, code, seed } | { file, error }].
|
||||
// A file is only built again when it has changed on disk.
|
||||
const built = new Map();
|
||||
|
||||
function loadSeeds(dir = SEEDS_DIR) {
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
const results = [];
|
||||
const codes = new Map();
|
||||
for (const file of fs.readdirSync(dir).filter((name) => name.endsWith('.js')).sort()) {
|
||||
const fullPath = path.join(dir, file);
|
||||
const { mtimeMs } = fs.statSync(fullPath);
|
||||
let entry = built.get(fullPath);
|
||||
if (!entry || entry.mtimeMs !== mtimeMs) {
|
||||
try {
|
||||
delete require.cache[require.resolve(fullPath)];
|
||||
const seed = buildSeed(require(fullPath));
|
||||
entry = { mtimeMs, result: { file, code: seed.code, seed } };
|
||||
} catch (err) {
|
||||
entry = { mtimeMs, result: { file, error: err.message } };
|
||||
}
|
||||
built.set(fullPath, entry);
|
||||
}
|
||||
let { result } = entry;
|
||||
if (result.code && codes.has(result.code)) {
|
||||
result = { file, error: `Its code ${result.code} is already used by ${codes.get(result.code)}` };
|
||||
} else if (result.code) {
|
||||
codes.set(result.code, file);
|
||||
}
|
||||
results.push(result);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
// The world behind a code, or null. A file with something wrong in it is
|
||||
// never offered; `npm run seeds:check` says what is wrong.
|
||||
function findSeed(code, dir = SEEDS_DIR) {
|
||||
const wanted = normalizeCode(code);
|
||||
const match = loadSeeds(dir).find((result) => result.code === wanted && !result.error);
|
||||
return match ? match.seed : null;
|
||||
}
|
||||
|
||||
module.exports = { SEEDS_DIR, CODE_LENGTH, SeedError, normalizeCode, buildSeed, loadSeeds, findSeed };
|
||||
@@ -0,0 +1,138 @@
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { buildSeed, loadSeeds, findSeed, normalizeCode, SeedError } = require('./index');
|
||||
|
||||
// The smallest seed there is, with whatever a test adds or changes.
|
||||
function seedWith(extra = {}) {
|
||||
return { code: 'TEST01', campaign: { name: 'Test World' }, ...extra };
|
||||
}
|
||||
|
||||
describe('the seeds in /backend/seeds', () => {
|
||||
const results = loadSeeds();
|
||||
|
||||
test('every file is a valid world', () => {
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
for (const { file, error } of results) expect({ file, error }).toEqual({ file, error: undefined });
|
||||
});
|
||||
|
||||
test('each has its own code', () => {
|
||||
const codes = results.map((result) => result.code);
|
||||
expect(new Set(codes).size).toBe(codes.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildSeed', () => {
|
||||
test('fills in what is left out', () => {
|
||||
const seed = buildSeed(seedWith());
|
||||
expect(seed.weapons).toEqual([]);
|
||||
expect(seed.encounters).toEqual([]);
|
||||
expect(seed.sharedNotes).toEqual([]);
|
||||
});
|
||||
|
||||
test('copies library entries, with changes, and drops the library-only fields', () => {
|
||||
const seed = buildSeed(seedWith({ weapons: ['dagger', { library: 'longsword', isStartingOption: true, minLevel: 2 }], monsters: ['goblin'] }));
|
||||
expect(seed.weapons[0]).toMatchObject({ name: 'Dagger', damageDice: '1d4' });
|
||||
expect(seed.weapons[1]).toMatchObject({ name: 'Longsword', isStartingOption: true, minLevel: 2 });
|
||||
expect(seed.weapons[0]).not.toHaveProperty('key');
|
||||
expect(seed.weapons[0]).not.toHaveProperty('category');
|
||||
expect(seed.monsters[0].name).toBe('Goblin');
|
||||
});
|
||||
|
||||
test('refuses a code that is not six capital letters or digits', () => {
|
||||
for (const code of ['abc123', 'ABC12', 'ABC1234', 'ABC-12', undefined]) {
|
||||
expect(() => buildSeed(seedWith({ code }))).toThrow(SeedError);
|
||||
}
|
||||
});
|
||||
|
||||
test('refuses a misspelt field rather than leaving it out', () => {
|
||||
expect(() => buildSeed(seedWith({ npcs: [{ name: 'Mira', desciption: 'A baker' }] }))).toThrow(/desciption/);
|
||||
expect(() => buildSeed(seedWith({ items: [{ name: 'Rope', starting: true }] }))).toThrow(/starting/);
|
||||
});
|
||||
|
||||
test('refuses an unknown library key', () => {
|
||||
expect(() => buildSeed(seedWith({ spells: ['fire-bolt', 'not-a-spell'] }))).toThrow(/no "not-a-spell" in the spells library/);
|
||||
});
|
||||
|
||||
test('refuses the same name twice in a pool', () => {
|
||||
expect(() => buildSeed(seedWith({ weapons: ['dagger', 'dagger'] }))).toThrow(/"Dagger" is there twice/);
|
||||
});
|
||||
|
||||
test('refuses an encounter that points at something the seed does not have', () => {
|
||||
const encounter = (extra) => seedWith({ encounters: [{ name: 'The Bridge', ...extra }] });
|
||||
expect(() => buildSeed(encounter({ location: 'Nowhere' }))).toThrow(/no location called "Nowhere"/);
|
||||
expect(() => buildSeed(encounter({ monsters: [['Troll', 1]] }))).toThrow(/no monster called "Troll"/);
|
||||
expect(() => buildSeed(encounter({ npcs: ['Mira'] }))).toThrow(/no NPC called "Mira"/);
|
||||
expect(() => buildSeed(encounter({ rewards: [{ item: 'Rope' }] }))).toThrow(/no item called "Rope"/);
|
||||
expect(() => buildSeed(encounter({ wares: [{ weapon: 'Dagger', price: 2 }] }))).toThrow(/no weapon called "Dagger"/);
|
||||
});
|
||||
|
||||
test('a reward is exactly one thing', () => {
|
||||
const rewards = (list) => seedWith({ items: [{ name: 'Rope' }], encounters: [{ name: 'The Bridge', rewards: list }] });
|
||||
expect(buildSeed(rewards([{ gold: 5 }, { cash: 20 }, { item: 'Rope', quantity: 2 }])).encounters[0].rewards).toHaveLength(3);
|
||||
expect(() => buildSeed(rewards([{ gold: 5, item: 'Rope' }]))).toThrow(SeedError);
|
||||
expect(() => buildSeed(rewards([{ note: 'nothing' }]))).toThrow(SeedError);
|
||||
});
|
||||
|
||||
test('gear cannot be sold or handed out below its starting level', () => {
|
||||
const world = (ware) => seedWith({ items: [{ name: 'Old Crown', minLevel: 4 }], npcs: [{ name: 'Mira', wares: [ware] }] });
|
||||
expect(buildSeed(world({ item: 'Old Crown', price: 100, level: 5 })).npcs[0].wares).toHaveLength(1);
|
||||
expect(() => buildSeed(world({ item: 'Old Crown', price: 100, level: 2 }))).toThrow(/starts at level 4/);
|
||||
});
|
||||
|
||||
test('an exchange rate needs both halves', () => {
|
||||
expect(() => buildSeed(seedWith({ npcs: [{ name: 'Mira', exchangeGold: 1 }] }))).toThrow(/exchange rate/);
|
||||
expect(buildSeed(seedWith({ npcs: [{ name: 'Mira', exchangeGold: 1, exchangeCash: 20 }] })).npcs[0].exchangeCash).toBe(20);
|
||||
});
|
||||
|
||||
test('an effect has to be on a number the sheet has', () => {
|
||||
const item = (effects) => seedWith({ items: [{ name: 'Shield', effects }] });
|
||||
expect(buildSeed(item([{ stat: 'AC', amount: 2 }])).items[0].effects).toEqual([{ stat: 'AC', amount: 2 }]);
|
||||
expect(() => buildSeed(item([{ stat: 'LUCK', amount: 2 }]))).toThrow(SeedError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the seeds folder', () => {
|
||||
let dir;
|
||||
const drop = (file, seed) => fs.writeFileSync(path.join(dir, file), `module.exports = ${JSON.stringify(seed)};`);
|
||||
|
||||
beforeEach(() => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'seeds-'));
|
||||
});
|
||||
afterEach(() => {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test('a code finds its world however it is typed', () => {
|
||||
drop('one.js', seedWith({ code: 'AB12CD' }));
|
||||
expect(normalizeCode(' ab1-2cd ')).toBe('AB12CD');
|
||||
expect(findSeed(' ab1-2cd ', dir).campaign.name).toBe('Test World');
|
||||
expect(findSeed('ZZZZZZ', dir)).toBeNull();
|
||||
expect(findSeed('', dir)).toBeNull();
|
||||
});
|
||||
|
||||
test('a file dropped in later is picked up', () => {
|
||||
expect(findSeed('LATER1', dir)).toBeNull();
|
||||
drop('later.js', seedWith({ code: 'LATER1' }));
|
||||
expect(findSeed('LATER1', dir)).not.toBeNull();
|
||||
});
|
||||
|
||||
test('a broken file is reported and never offered, without hiding the good ones', () => {
|
||||
drop('bad.js', seedWith({ code: 'BAD001', encounters: [{ name: 'X', monsters: [['Nobody', 1]] }] }));
|
||||
drop('good.js', seedWith({ code: 'GOOD01' }));
|
||||
fs.writeFileSync(path.join(dir, 'syntax.js'), 'module.exports = {');
|
||||
const byFile = Object.fromEntries(loadSeeds(dir).map((result) => [result.file, result]));
|
||||
expect(byFile['bad.js'].error).toMatch(/no monster called "Nobody"/);
|
||||
expect(byFile['syntax.js'].error).toBeTruthy();
|
||||
expect(byFile['good.js'].error).toBeUndefined();
|
||||
expect(findSeed('BAD001', dir)).toBeNull();
|
||||
expect(findSeed('GOOD01', dir)).not.toBeNull();
|
||||
});
|
||||
|
||||
test('two files cannot share a code: the first keeps it', () => {
|
||||
drop('a.js', seedWith({ code: 'SAME01', campaign: { name: 'First' } }));
|
||||
drop('b.js', seedWith({ code: 'SAME01', campaign: { name: 'Second' } }));
|
||||
expect(loadSeeds(dir)[1].error).toMatch(/already used by a\.js/);
|
||||
expect(findSeed('SAME01', dir).campaign.name).toBe('First');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
// Battle actions against the database's shapes: reading a combatant's numbers
|
||||
// off a loaded participant, and putting together the action a weapon, a spell
|
||||
// or a creature's attack makes (EncounterAction). The rules themselves are in
|
||||
// game/combat.js. No queries here: everything is passed in loaded.
|
||||
|
||||
const crypto = require('crypto');
|
||||
const { computeCharacterSheet, computeWeaponStats, abilityModifier, canUseGear } = require('../game/calculations');
|
||||
const { attacksOf, opponentsOf, pickTarget, rollDamage, attackOutcome, lands } = require('../game/combat');
|
||||
const { rollDie } = require('../game/dice');
|
||||
const { lifeState } = require('./hp');
|
||||
|
||||
// A problem with what was asked for: the message is for whoever asked.
|
||||
class ActionError extends Error {}
|
||||
|
||||
const sheetOf = (character) => computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
|
||||
|
||||
const kindOf = (p) => (p.npc || p.npcId ? 'NPC' : p.isMonster ? 'MONSTER' : 'CHARACTER');
|
||||
|
||||
// Out of the fight: a dead character, or a monster or NPC at 0 HP.
|
||||
function isFallen(p) {
|
||||
if (p.character) return lifeState(p.character) === 'DEAD';
|
||||
return p.maxHp > 0 && p.currentHp <= 0;
|
||||
}
|
||||
|
||||
// A participant's AC: the sheet's for a character, the stat block's for a
|
||||
// monster or NPC (10 for an NPC with no combat stats).
|
||||
function armorClassOf(p) {
|
||||
if (p.character) return sheetOf(p.character).armorClass;
|
||||
if (p.monster) return p.monster.ac;
|
||||
return p.npc && p.npc.ac != null ? p.npc.ac : 10;
|
||||
}
|
||||
|
||||
// What a participant adds to a saving throw with an ability: the sheet's save
|
||||
// bonus for a character, the ability modifier for a monster, nothing for an NPC.
|
||||
function saveBonusOf(p, ability) {
|
||||
if (p.character) return sheetOf(p.character).saves[ability].bonus;
|
||||
if (p.monster) return abilityModifier(p.monster[`${ability.toLowerCase()}Score`] ?? 10);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// A participant as game/combat.js sees a combatant.
|
||||
const combatantOf = (p) => ({ id: p.id, name: p.displayName, kind: kindOf(p), disposition: p.npc ? p.npc.disposition : null, ac: armorClassOf(p), fallen: isFallen(p) });
|
||||
|
||||
const areaPenalty = (targetCount, step) => Math.max(0, targetCount - 1) * step;
|
||||
|
||||
// The targets of an action as it starts: who, and the number each roll is
|
||||
// against. `penaltyStep` is the campaign's area-attack AC penalty.
|
||||
function targetRows(kind, detail, targets, penaltyStep) {
|
||||
const penalty = kind === 'ATTACK' ? areaPenalty(targets.length, penaltyStep) : 0;
|
||||
return targets.map((p) => ({
|
||||
participantId: p.id,
|
||||
name: p.displayName,
|
||||
kind: kindOf(p),
|
||||
ac: kind === 'ATTACK' ? armorClassOf(p) : null,
|
||||
penalty,
|
||||
saveBonus: kind === 'SAVE' ? saveBonusOf(p, detail.saveAbility) : null,
|
||||
d20: null,
|
||||
outcome: null,
|
||||
damage: null,
|
||||
}));
|
||||
}
|
||||
|
||||
// What an action is made of, from what it is made with:
|
||||
// { type: 'weapon', characterWeaponId } a character's equipped weapon
|
||||
// { type: 'spell', characterSpellId, slotLevel? } a spell a character knows
|
||||
// { type: 'basic', index? } a monster's or NPC's own attack
|
||||
// { type: 'custom', name, kind, attackBonus?, saveAbility?, saveDC?, halfOnSave?, damageDice? }
|
||||
// anything else, spelled out (the DM's: a breath weapon, a trap)
|
||||
// Returns { kind, name, detail }. Throws ActionError when the actor can't.
|
||||
function describeSource(actor, source) {
|
||||
const character = actor ? actor.character : null;
|
||||
if (source.type === 'custom') {
|
||||
const kind = source.kind || 'ATTACK';
|
||||
return {
|
||||
kind,
|
||||
name: source.name || 'Attack',
|
||||
detail: {
|
||||
attackBonus: kind === 'ATTACK' ? source.attackBonus || 0 : undefined,
|
||||
saveAbility: kind === 'SAVE' ? source.saveAbility || 'DEX' : undefined,
|
||||
saveDC: kind === 'SAVE' ? source.saveDC || 10 : undefined,
|
||||
halfOnSave: kind === 'SAVE' ? Boolean(source.halfOnSave) : undefined,
|
||||
damageDice: source.damageDice || null,
|
||||
damageBonus: 0,
|
||||
damageType: source.damageType || null,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (!actor) throw new ActionError('Nobody is on turn to make that attack.');
|
||||
|
||||
if (source.type === 'basic') {
|
||||
const attacks = attacksOf({ monster: actor.monster, npc: actor.npc });
|
||||
const attack = attacks[source.index || 0];
|
||||
if (!attack) throw new ActionError(`${actor.displayName} has no attack to make. Give it an attack bonus and damage first.`);
|
||||
return { kind: 'ATTACK', name: attack.name, detail: { attackBonus: attack.attackBonus, damageDice: attack.damageDice, damageBonus: 0, damageType: attack.damageType } };
|
||||
}
|
||||
|
||||
if (!character) throw new ActionError(`${actor.displayName} fights with its own attack, not a weapon or a spell.`);
|
||||
const sheet = sheetOf(character);
|
||||
|
||||
if (source.type === 'weapon') {
|
||||
const held = character.weapons.find((cw) => cw.id === source.characterWeaponId);
|
||||
if (!held) throw new ActionError(`${character.name} does not hold that weapon.`);
|
||||
if (!held.equipped || !canUseGear(character.level, held.level)) throw new ActionError(`${held.weapon.name} has to be equipped (and within ${character.name}'s level) to be used.`);
|
||||
const stats = computeWeaponStats(held.weapon, sheet.abilities, sheet.proficiencyBonus, true, held.level);
|
||||
return {
|
||||
kind: 'ATTACK',
|
||||
name: held.weapon.name,
|
||||
detail: { attackBonus: stats.attackBonus, damageDice: stats.damageDice, damageBonus: stats.damageBonus, damageType: stats.damageType, characterId: character.id },
|
||||
};
|
||||
}
|
||||
|
||||
if (source.type === 'spell') {
|
||||
const known = character.spells.find((cs) => cs.id === source.characterSpellId);
|
||||
if (!known) throw new ActionError(`${character.name} does not know that spell.`);
|
||||
const spell = known.spell;
|
||||
if (!canUseGear(character.level, spell.level)) throw new ActionError(`${spell.name} is beyond ${character.name}'s level.`);
|
||||
const casting = sheet.spellcasting;
|
||||
// A cantrip takes no slot; any other spell takes one of its own level, or
|
||||
// the lowest one above it that is left. With none left it cannot be cast.
|
||||
// (A character with no slots at all, handed a spell by the DM, casts it freely.)
|
||||
let slotLevel = null;
|
||||
if (spell.level > 0) {
|
||||
slotLevel = Math.max(spell.level, source.slotLevel || spell.level);
|
||||
if (sheet.spellSlots) {
|
||||
const wanted = slotLevel;
|
||||
const free = sheet.spellSlots.levels.find((l) => l.level >= wanted && l.remaining > 0);
|
||||
if (!free) throw new ActionError(`${character.name} has no spell slot of level ${wanted} or higher left, so cannot cast ${spell.name}.`);
|
||||
slotLevel = free.level;
|
||||
}
|
||||
}
|
||||
const base = { damageDice: spell.damageDice || null, damageBonus: 0, damageType: null, characterId: character.id, spellLevel: spell.level, slotLevel };
|
||||
if (spell.attackRoll) return { kind: 'ATTACK', name: spell.name, detail: { ...base, attackBonus: casting ? casting.attackBonus : 0 } };
|
||||
if (spell.saveAbility) {
|
||||
return { kind: 'SAVE', name: spell.name, detail: { ...base, saveAbility: spell.saveAbility, saveDC: casting ? casting.saveDC : 10, halfOnSave: spell.halfOnSave } };
|
||||
}
|
||||
return { kind: 'AUTO', name: spell.name, detail: base };
|
||||
}
|
||||
throw new ActionError('That is not something to attack with.');
|
||||
}
|
||||
|
||||
// A fair number from 0 up to (not including) 1, for picking a target.
|
||||
const randomUnit = () => crypto.randomInt(0, 1000000) / 1000000;
|
||||
|
||||
// The attacks a monster or NPC makes by itself on its turn, each already
|
||||
// aimed and rolled: who it goes for (game/combat.js, pickTarget), the d20, and
|
||||
// the damage where it hits. `history` is the encounter's applied actions,
|
||||
// newest first, for whom it fought last and who has hurt it. Returns the
|
||||
// actions to create (without ids); empty when it has no attack or nobody to
|
||||
// go for.
|
||||
function autoActions(actor, participants, { penaltyStep = 0, critRule = 'DOUBLE_DICE', history = [] } = {}) {
|
||||
const attacks = attacksOf({ monster: actor.monster, npc: actor.npc });
|
||||
const combatants = participants.map(combatantOf);
|
||||
const opponents = opponentsOf(combatantOf(actor), combatants);
|
||||
if (attacks.length === 0 || opponents.length === 0) return [];
|
||||
|
||||
const mine = history.find((action) => action.actorParticipantId === actor.id);
|
||||
let lastTargetId = mine && mine.targets[0] ? mine.targets[0].participantId : null;
|
||||
const hurtBy = history
|
||||
.filter((action) => (action.targets || []).some((t) => t.participantId === actor.id && t.finalDamage > 0))
|
||||
.map((action) => action.actorParticipantId)
|
||||
.filter(Boolean);
|
||||
|
||||
return attacks.map((attack) => {
|
||||
const picked = pickTarget(opponents, { lastTargetId, hurtBy }, randomUnit);
|
||||
lastTargetId = picked.id; // a creature with several attacks tends to keep at one foe
|
||||
const target = participants.find((p) => p.id === picked.id);
|
||||
const detail = { attackBonus: attack.attackBonus, damageDice: attack.damageDice, damageBonus: 0, damageType: attack.damageType };
|
||||
const [row] = targetRows('ATTACK', detail, [target], penaltyStep);
|
||||
row.d20 = rollDie(20);
|
||||
const outcome = attackOutcome(row.d20, detail.attackBonus, row.ac, row.penalty);
|
||||
return {
|
||||
actorParticipantId: actor.id,
|
||||
actorName: actor.displayName,
|
||||
kind: 'ATTACK',
|
||||
name: attack.name,
|
||||
detail,
|
||||
targets: [row],
|
||||
damage: lands(outcome) ? rollDamage(detail, { critical: outcome === 'CRIT', critRule }) : null,
|
||||
auto: true,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { ActionError, kindOf, isFallen, armorClassOf, saveBonusOf, combatantOf, areaPenalty, targetRows, describeSource, autoActions };
|
||||
@@ -0,0 +1,110 @@
|
||||
// Resting (the Hollowcrown book's Rules Cheat Sheet, "Resting"). Each function
|
||||
// takes a finished character and its sheet and returns the columns to write
|
||||
// plus an account of what happened, for the DM to read. Pure: no DB calls.
|
||||
//
|
||||
// Short rest (an hour): spend Hit Dice to heal, each one the class's die plus
|
||||
// the Constitution modifier. A warlock's spell slots come back.
|
||||
// Class counters that restore on a short rest come back.
|
||||
// Long rest (a night): all HP, all spell slots, every class counter, Hit Dice
|
||||
// up to half the level (at least one), one level of exhaustion less, and temp
|
||||
// HP is gone, except what the Hardy Boon gives.
|
||||
|
||||
const { changeHp, lifeState, NO_DEATH_SAVES } = require('./hp');
|
||||
const { hardyTempHp } = require('../game/levelUp');
|
||||
const { restResources } = require('../game/classResources');
|
||||
|
||||
// Once a day on a short rest a wizard or a Land druid (from level 2) gets some
|
||||
// spent slots back. Which ones is the player's choice, so the DM puts them
|
||||
// back on the sheet; this is the reminder, or null when it does not apply.
|
||||
function recoveryNote(character, sheet) {
|
||||
const feature = character.characterClass === 'WIZARD' ? 'Arcane Recovery' : character.characterClass === 'DRUID' && character.level >= 2 && character.subclass === 'LAND' ? 'Natural Recovery' : null;
|
||||
if (!feature || !sheet.spellSlots || !sheet.spellSlots.levels.some((slot) => slot.used > 0)) return null;
|
||||
const budget = Math.ceil(character.level / 2);
|
||||
return `${feature}: once per day, ${character.name} can regain spent slots adding up to ${budget} slot level${budget === 1 ? '' : 's'} (none of 6th level or higher). Put them back on the sheet.`;
|
||||
}
|
||||
|
||||
// The class counters a rest refills: the tally to store and a line for the DM.
|
||||
function refill(sheet, restType) {
|
||||
const { resourcesUsed, restored } = restResources(sheet.resources || [], restType);
|
||||
return { resourcesUsed, notes: restored.length > 0 ? [`Back: ${restored.join(', ')}.`] : [] };
|
||||
}
|
||||
|
||||
// A problem with the Hit Dice asked for, or null. `rolled` is the total the
|
||||
// dice showed, for dice rolled at the table.
|
||||
function hitDiceProblem(character, sheet, dice, rolled) {
|
||||
if (dice === 0) return null;
|
||||
const { size, remaining } = sheet.hitDice;
|
||||
if (lifeState(character) === 'DYING') return `${character.name} is dying: steady or heal them before they spend Hit Dice.`;
|
||||
if (dice > remaining) return `${character.name} has ${remaining} Hit ${remaining === 1 ? 'Die' : 'Dice'} left, not ${dice}.`;
|
||||
if (rolled != null && (rolled < dice || rolled > dice * size)) {
|
||||
return `${character.name}: ${dice}d${size} adds up to between ${dice} and ${dice * size}, not ${rolled}.`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// `rolls` is what each Hit Die showed, or `rolled` their total when they were
|
||||
// rolled at the table. The Constitution modifier is added once per die, and
|
||||
// the rest never takes HP away.
|
||||
function shortRest(character, sheet, { dice = 0, rolls = null, rolled = null } = {}) {
|
||||
const total = dice === 0 ? 0 : rolls ? rolls.reduce((sum, roll) => sum + roll, 0) : rolled;
|
||||
const conBonus = dice * sheet.abilities.CON.modifier;
|
||||
const healed = Math.max(0, total + conBonus);
|
||||
const pact = Boolean(sheet.spellSlots) && sheet.spellSlots.restoresOn === 'SHORT';
|
||||
const slotsRestored = pact && sheet.spellSlots.levels.some((slot) => slot.used > 0);
|
||||
|
||||
const counters = refill(sheet, 'SHORT');
|
||||
|
||||
const data = {
|
||||
...(healed > 0 ? changeHp(character, character.currentHp + healed, sheet.hp.max) : {}),
|
||||
hitDiceUsed: sheet.hitDice.used + dice,
|
||||
...(pact ? { spellSlotsUsed: [] } : {}),
|
||||
resourcesUsed: counters.resourcesUsed,
|
||||
};
|
||||
const hpAfter = data.currentHp ?? character.currentHp;
|
||||
return {
|
||||
data,
|
||||
result: {
|
||||
hpBefore: character.currentHp,
|
||||
hpAfter,
|
||||
maxHp: sheet.hp.max,
|
||||
tempHp: character.tempHp,
|
||||
hitDice: { size: sheet.hitDice.size, spent: dice, rolls, total, conBonus, healed: hpAfter - character.currentHp, left: sheet.hitDice.remaining - dice, of: sheet.hitDice.count, regained: 0 },
|
||||
slotsRestored,
|
||||
notes: [...counters.notes, recoveryNote(character, sheet)].filter(Boolean),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function longRest(character, sheet) {
|
||||
const regained = Math.min(sheet.hitDice.used, Math.max(1, Math.floor(character.level / 2)));
|
||||
const tempHp = hardyTempHp(character.specialAbilities);
|
||||
const counters = refill(sheet, 'LONG');
|
||||
const exhaustion = Math.max(0, (character.exhaustion || 0) - 1);
|
||||
const data = {
|
||||
currentHp: sheet.hp.max,
|
||||
tempHp,
|
||||
...NO_DEATH_SAVES,
|
||||
hitDiceUsed: sheet.hitDice.used - regained,
|
||||
spellSlotsUsed: [],
|
||||
resourcesUsed: counters.resourcesUsed,
|
||||
exhaustion,
|
||||
};
|
||||
return {
|
||||
data,
|
||||
result: {
|
||||
hpBefore: character.currentHp,
|
||||
hpAfter: sheet.hp.max,
|
||||
maxHp: sheet.hp.max,
|
||||
tempHp,
|
||||
hitDice: { size: sheet.hitDice.size, spent: 0, rolls: null, total: 0, conBonus: 0, healed: 0, left: sheet.hitDice.remaining + regained, of: sheet.hitDice.count, regained },
|
||||
slotsRestored: Boolean(sheet.spellSlots) && sheet.spellSlots.levels.some((slot) => slot.used > 0),
|
||||
notes: [
|
||||
...counters.notes,
|
||||
...(character.exhaustion > 0 ? [exhaustion > 0 ? `Exhaustion down to level ${exhaustion}.` : 'No longer exhausted.'] : []),
|
||||
...(tempHp > 0 ? [`Hardy: ${tempHp} Temp HP for the day.`] : []),
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { hitDiceProblem, shortRest, longRest };
|
||||
@@ -0,0 +1,125 @@
|
||||
const { hitDiceProblem, shortRest, longRest } = require('./rest');
|
||||
const { computeCharacterSheet } = require('../game/calculations');
|
||||
|
||||
const CLEAR = { deathSaveSuccesses: 0, deathSaveFailures: 0, stable: false };
|
||||
// A level 5 fighter (d10) with CON 14 (+2): 10 + 2 + 4 × (6 + 2) = 44 HP.
|
||||
const hero = (over = {}) => ({
|
||||
name: 'Aria',
|
||||
characterClass: 'FIGHTER',
|
||||
level: 5,
|
||||
conScore: 14,
|
||||
currentHp: 10,
|
||||
tempHp: 0,
|
||||
hitDiceUsed: 0,
|
||||
spellSlotsUsed: [],
|
||||
specialAbilities: null,
|
||||
...CLEAR,
|
||||
...over,
|
||||
});
|
||||
const sheet = (character) => computeCharacterSheet(character);
|
||||
|
||||
describe('shortRest', () => {
|
||||
test('spent Hit Dice heal what they rolled plus Constitution for each', () => {
|
||||
const c = hero();
|
||||
const { data, result } = shortRest(c, sheet(c), { dice: 2, rolls: [7, 4] });
|
||||
expect(data).toMatchObject({ currentHp: 25, hitDiceUsed: 2 });
|
||||
expect(result).toMatchObject({ hpBefore: 10, hpAfter: 25, maxHp: 44 });
|
||||
expect(result.hitDice).toMatchObject({ size: 10, spent: 2, total: 11, conBonus: 4, healed: 15, left: 3, of: 5 });
|
||||
});
|
||||
|
||||
test('takes a total rolled at the table, stops at max HP, and never takes HP away', () => {
|
||||
const c = hero({ currentHp: 40 });
|
||||
expect(shortRest(c, sheet(c), { dice: 1, rolled: 9 }).data.currentHp).toBe(44);
|
||||
const frail = hero({ conScore: 3, currentHp: 10 }); // CON -4
|
||||
const rest = shortRest(frail, sheet(frail), { dice: 1, rolled: 2 });
|
||||
expect(rest.data.currentHp).toBeUndefined();
|
||||
expect(rest.data.hitDiceUsed).toBe(1);
|
||||
expect(rest.result.hitDice.healed).toBe(0);
|
||||
});
|
||||
|
||||
test('with no dice spent nothing changes for a fighter', () => {
|
||||
const c = hero({ hitDiceUsed: 3 });
|
||||
expect(shortRest(c, sheet(c)).data).toEqual({ hitDiceUsed: 3, resourcesUsed: {} });
|
||||
});
|
||||
|
||||
test('gives back the class counters that restore on a short rest, and only those', () => {
|
||||
const c = hero({ level: 9, resourcesUsed: { SECOND_WIND: 1, ACTION_SURGE: 1, INDOMITABLE: 1 } });
|
||||
const { data, result } = shortRest(c, sheet(c));
|
||||
expect(data.resourcesUsed).toEqual({ INDOMITABLE: 1 });
|
||||
expect(result.notes).toEqual(['Back: Second Wind, Action Surge.']);
|
||||
});
|
||||
|
||||
test('gives a warlock their slots back, and nobody else', () => {
|
||||
const warlock = hero({ characterClass: 'WARLOCK', spellSlotsUsed: [0, 0, 2] });
|
||||
const rest = shortRest(warlock, sheet(warlock));
|
||||
expect(rest.data.spellSlotsUsed).toEqual([]);
|
||||
expect(rest.result.slotsRestored).toBe(true);
|
||||
|
||||
const wizard = hero({ characterClass: 'WIZARD', spellSlotsUsed: [2, 1] });
|
||||
const wizardRest = shortRest(wizard, sheet(wizard));
|
||||
expect(wizardRest.data.spellSlotsUsed).toBeUndefined();
|
||||
expect(wizardRest.result.slotsRestored).toBe(false);
|
||||
// ...but a wizard is reminded of Arcane Recovery: half their level, rounded up.
|
||||
expect(wizardRest.result.notes).toEqual([expect.stringContaining('Arcane Recovery')]);
|
||||
expect(wizardRest.result.notes[0]).toContain('3 slot levels');
|
||||
const fresh = hero({ characterClass: 'WIZARD' });
|
||||
expect(shortRest(fresh, sheet(fresh)).result.notes).toEqual([]);
|
||||
});
|
||||
|
||||
test('wakes a stable character who spends a Hit Die', () => {
|
||||
const c = hero({ currentHp: 0, stable: true });
|
||||
expect(shortRest(c, sheet(c), { dice: 1, rolled: 5 }).data).toMatchObject({ currentHp: 7, ...CLEAR });
|
||||
});
|
||||
});
|
||||
|
||||
describe('hitDiceProblem', () => {
|
||||
test('refuses more dice than are left, an impossible total, and the dying', () => {
|
||||
const c = hero({ hitDiceUsed: 4 });
|
||||
expect(hitDiceProblem(c, sheet(c), 0)).toBeNull();
|
||||
expect(hitDiceProblem(c, sheet(c), 1, 10)).toBeNull();
|
||||
expect(hitDiceProblem(c, sheet(c), 1)).toBeNull();
|
||||
expect(hitDiceProblem(c, sheet(c), 2)).toMatch(/1 Hit Die left/);
|
||||
expect(hitDiceProblem(c, sheet(c), 1, 11)).toMatch(/between 1 and 10/);
|
||||
expect(hitDiceProblem(c, sheet(c), 1, 0)).toMatch(/between 1 and 10/);
|
||||
const dying = hero({ currentHp: 0 });
|
||||
expect(hitDiceProblem(dying, sheet(dying), 1)).toMatch(/dying/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('longRest', () => {
|
||||
test('heals to full, gives back every slot and half the level in Hit Dice', () => {
|
||||
const c = hero({ characterClass: 'WIZARD', currentHp: 3, tempHp: 4, hitDiceUsed: 5, spellSlotsUsed: [4, 3, 2] });
|
||||
const { data, result } = longRest(c, sheet(c));
|
||||
expect(data).toEqual({ currentHp: sheet(c).hp.max, tempHp: 0, ...CLEAR, hitDiceUsed: 3, spellSlotsUsed: [], resourcesUsed: {}, exhaustion: 0 });
|
||||
expect(result.hitDice).toMatchObject({ regained: 2, left: 2, of: 5 });
|
||||
expect(result.slotsRestored).toBe(true);
|
||||
});
|
||||
|
||||
test('gives back at least one Hit Die, and no more than were spent', () => {
|
||||
const novice = hero({ level: 1, hitDiceUsed: 1 });
|
||||
expect(longRest(novice, sheet(novice)).data.hitDiceUsed).toBe(0);
|
||||
const rested = hero({ hitDiceUsed: 1 });
|
||||
expect(longRest(rested, sheet(rested)).result.hitDice).toMatchObject({ regained: 1, left: 5 });
|
||||
});
|
||||
|
||||
test('gets a dying character back on their feet', () => {
|
||||
const c = hero({ currentHp: 0, deathSaveFailures: 2, deathSaveSuccesses: 1 });
|
||||
expect(longRest(c, sheet(c)).data).toMatchObject({ currentHp: 44, ...CLEAR });
|
||||
});
|
||||
|
||||
test('gives every class counter back and takes one level of exhaustion off', () => {
|
||||
const c = hero({ level: 9, exhaustion: 2, resourcesUsed: { SECOND_WIND: 1, INDOMITABLE: 1 } });
|
||||
const { data, result } = longRest(c, sheet(c));
|
||||
expect(data).toMatchObject({ resourcesUsed: {}, exhaustion: 1 });
|
||||
expect(result.notes).toEqual(['Back: Second Wind, Indomitable.', 'Exhaustion down to level 1.']);
|
||||
const tired = hero({ exhaustion: 1 });
|
||||
expect(longRest(tired, sheet(tired)).result.notes).toEqual(['No longer exhausted.']);
|
||||
});
|
||||
|
||||
test('leaves the Hardy Boon its Temp HP', () => {
|
||||
const c = hero({ tempHp: 2, specialAbilities: 'Hardy — +10 maximum HP: gain 10 Temp HP after each long rest.' });
|
||||
const { data, result } = longRest(c, sheet(c));
|
||||
expect(data.tempHp).toBe(10);
|
||||
expect(result.notes).toEqual(['Hardy: 10 Temp HP for the day.']);
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,8 @@
|
||||
const { computeCharacterSheet } = require('../game/calculations');
|
||||
|
||||
const SHEET_INCLUDE = {
|
||||
// A multiclassed character's other classes (game/multiclass.js).
|
||||
classLevels: true,
|
||||
skillProficiencies: true,
|
||||
saveProficiencies: true,
|
||||
inventoryItems: { include: { item: true } },
|
||||
@@ -32,4 +34,8 @@ async function settleHp(db, characterIds) {
|
||||
return changed;
|
||||
}
|
||||
|
||||
module.exports = { SHEET_INCLUDE, sheetOf, settleHp };
|
||||
// A character's spells in the order they are listed everywhere: cantrips
|
||||
// first, then by spell level, then by name.
|
||||
const bySpellLevel = (a, b) => a.spell.level - b.spell.level || a.spell.name.localeCompare(b.spell.name);
|
||||
|
||||
module.exports = { SHEET_INCLUDE, sheetOf, settleHp, bySpellLevel };
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Campaign Settings
|
||||
|
||||
Each campaign has its own settings. The DM changes them on the campaign page
|
||||
under **Campaign Settings → Edit**, and players read them but can't change
|
||||
them. They are columns on the `Campaign` row (`backend/prisma/schema.prisma`),
|
||||
returned with the campaign by `GET /campaigns/:id`, and changed with
|
||||
`PATCH /campaigns/:id` (DM only). A world seed can set any of them
|
||||
([SEEDS.md](SEEDS.md)).
|
||||
|
||||
Changing a setting never rewrites what already happened. For example,
|
||||
turning XP tracking off keeps everyone's XP; it just stops showing it.
|
||||
|
||||
## Characters
|
||||
|
||||
| Setting | Default | What it does |
|
||||
|---|---|---|
|
||||
| `startingGold` | 0 | Gold every new character starts with. |
|
||||
| `startingItemCount` | 0 | How many starting weapons and items (together) the builder lets a character take. |
|
||||
| `startingSpellCount` | 0 | How many starting spells the builder lets a character take. |
|
||||
| `abilityScoreMethod` | `ROLL_4D6` | How the builder makes the six scores: `ROLL_4D6` (roll 4d6 and drop the lowest, six times, then place them), `STANDARD_ARRAY` (place 15, 14, 13, 12, 10 and 8), or `POINT_BUY` (every score starts at 8 and is raised with 27 points, to 15 at most). |
|
||||
| `skipMotivationRoll` | off | Leaves the motivation step out of the builder. |
|
||||
| `subclassesEnabled` | on | Characters choose a subclass. Off: each class follows its first subclass, unasked and unnamed. |
|
||||
| `multiclassEnabled` | off | On a level up, a character may take the level in another class whose ability requirements they meet. |
|
||||
| `maxEquipped` / `maxEquippedWeapons` | 2 / 1 | How much a character can have equipped at once, and how much of it can be weapons. |
|
||||
|
||||
## Dice and rolls
|
||||
|
||||
| Setting | Default | What it does |
|
||||
|---|---|---|
|
||||
| `diceMode` | `BOTH` | `DIGITAL`: the app rolls every die. `PHYSICAL`: everyone rolls real dice and types in what they show (the server checks each value is on the die). `BOTH`: either. In the builder each character picks one before their first roll; in the dice roller each person ticks "I roll real dice" when they want to. It covers the builder, the dice roller and the hit point roll on a level up. |
|
||||
| `rollVisibility` | `ALL` | Who sees a roll made in the dice roller. `ALL`: everyone sees every roll. `OWN`: a player sees only their own rolls. The DM always sees every roll, and can roll hidden either way. |
|
||||
| `hideMonsterRolls` | on | The DM's rolls for monsters and NPCs stay hidden from players until they are put into play. |
|
||||
|
||||
## Combat
|
||||
|
||||
| Setting | Default | What it does |
|
||||
|---|---|---|
|
||||
| `autoRollMonsters` | off | When a monster's turn comes up in a battle, the server picks its target, rolls the attack and the damage, and offers the result to the DM to accept, change or throw out. |
|
||||
| `autoRollNpcs` | off | The same for NPCs. Friendly NPCs attack monsters; hostile ones attack the party. |
|
||||
| `showMonsterHp` | on | Players see the exact HP of monsters and NPCs. Off: they see a health bar. |
|
||||
| `critRule` | `DOUBLE_DICE` | What a critical hit does to damage. `DOUBLE_DICE`: the damage dice are rolled twice. `MAX_PLUS_ROLL`: the dice count at their maximum, plus one roll of them. |
|
||||
| `areaAttackAcPenalty` | 2 | In an attack on several targets, each target's AC counts this much higher for every target after the first. 0 turns it off. |
|
||||
|
||||
## Progression
|
||||
|
||||
| Setting | Default | What it does |
|
||||
|---|---|---|
|
||||
| `trackXp` | on | Experience points are kept: on the sheets, awarded after encounters, with "level up due" shown. Off (milestone levelling): no XP is shown or awarded, and the DM decides when the party levels. |
|
||||
| `hpOnLevelUp` | `AVERAGE` | How maximum HP grows on a level up. `AVERAGE`: the hit die's average, rounded up, plus Constitution. `ROLL`: a roll of the hit die plus Constitution. |
|
||||
+1565
-53
File diff suppressed because it is too large
Load Diff
+375
-58
@@ -11,7 +11,7 @@ This describes the code as it stands. The rules live in
|
||||
## Contents
|
||||
|
||||
1. [The basics](#1-the-basics)
|
||||
2. [Battle or quest](#2-battle-or-quest)
|
||||
2. [Battle, quest or free roam](#2-battle-quest-or-free-roam)
|
||||
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)
|
||||
@@ -28,8 +28,8 @@ This describes the code as it stands. The rules live in
|
||||
|
||||
## 1. The basics
|
||||
|
||||
- An encounter is one **scene** the DM runs: a fight, or a meeting with
|
||||
people who want something.
|
||||
- An encounter is one **scene** the DM runs: a fight, a meeting with people
|
||||
who want something, or a stretch of free roaming between places.
|
||||
- Encounters belong to a campaign and are listed on the campaign page. The DM
|
||||
creates them and sees all of them.
|
||||
- A player only sees an encounter that **one of their own characters is in**.
|
||||
@@ -39,31 +39,64 @@ This describes the code as it stands. The rules live in
|
||||
- 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
|
||||
## 2. Battle, quest or free roam
|
||||
|
||||
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; once in progress, those who have had their turn move to "Next Round" at the bottom | Three groups: "People you meet", "The party", "Creatures" |
|
||||
| Rounds and turns | Yes | No |
|
||||
| Initiative | The d20 roll, typed in per combatant; the bonus is added | The same; each group lists highest first |
|
||||
| Start button | Begin Battle | Begin Quest |
|
||||
| End button | End Battle | Complete Quest |
|
||||
| Trade (section 10) | No | Yes, while in progress |
|
||||
| | Battle | NPC quest | Free roam |
|
||||
|---|---|---|---|
|
||||
| For | A fight | A scene built around people and an objective | The party wandering between places: shopping, meeting people |
|
||||
| Layout | Everyone in one list, in initiative order; once in progress, those who have had their turn move to "Next Round" at the bottom | Three groups: "People you meet", "The party", "Creatures" | A card per place, then the party |
|
||||
| Rounds and turns | Yes | No | No |
|
||||
| Initiative | The d20 roll, typed in per combatant; the bonus is added | The same; each group lists highest first | Not needed |
|
||||
| Start button | Begin Battle | Begin Quest | Begin Roaming |
|
||||
| End button | End Battle | Complete Quest | End Free Roam |
|
||||
| Trade (section 10) | No | Yes, while in progress, with the NPCs in the scene | Yes, while in progress, at the place a character has gone to |
|
||||
| Who is in it | Whoever the DM adds | Whoever the DM adds | Whoever the DM adds |
|
||||
|
||||
Everything else (hit points, conditions, rewards, the scene description, DM
|
||||
notes) works the same in both.
|
||||
notes) works the same in all three.
|
||||
|
||||
### Free roam
|
||||
|
||||
A free-roam encounter lays out **places the party can go to**: some of the
|
||||
campaign's locations, picked by the DM as the ones nearby.
|
||||
|
||||
- **Who is in it** is up to the DM, as with any encounter: nobody is added
|
||||
automatically, because the party may be split, with some of them somewhere
|
||||
else. Add the characters who are here from "Add to the scene"; a player
|
||||
sees the scene once their character is in it.
|
||||
- **Places.** On its page the DM ticks which of the campaign's locations are
|
||||
part of the scene ("Places in this scene"), and can tick more, or untick
|
||||
some, while it is in progress. Locations are made on the campaign page.
|
||||
- **Each place is a card** showing its description, who of the party is there
|
||||
now, the **NPCs found there** (name, role, description, what they sell and
|
||||
the rate they change money at), and the place's **own shop**. Everyone in
|
||||
the scene sees every place in it, whether or not they have been there.
|
||||
- **Going somewhere.** Once the DM presses Begin Roaming, a player picks their
|
||||
character and presses **Go here** on a place: the character is now there
|
||||
(it shows on their sheet too, and the place joins the ones they know). The
|
||||
DM can send anyone.
|
||||
- **Shopping.** A character buys from a place's shop, and buys from or changes
|
||||
money with an NPC found there, only while they are **at that place**. The
|
||||
Buy button says so otherwise.
|
||||
- **Setting it up (DM).** A place's own shop is stocked from its card ("Set up
|
||||
this place's own shop"): weapons and items from the campaign's pools, with a
|
||||
price and stock, exactly as an NPC's wares are. It belongs to the location,
|
||||
so it is there in every free-roam scene that includes the place. An NPC is
|
||||
put at a place with **Found at** on the NPC's pop-out
|
||||
([NPCS.md](NPCS.md)); what they sell is set there too.
|
||||
- An encounter's own location (the picker at the top) does not pull the party
|
||||
together in free roam: each character is where they were sent.
|
||||
|
||||
## 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 |
|
||||
| In progress | Being played | Begin Battle / Begin Quest / Begin Roaming, or Reopen |
|
||||
| Complete | Finished | End Battle / Complete Quest / End Free Roam |
|
||||
|
||||
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
|
||||
@@ -77,21 +110,32 @@ characters are at that location: beginning it, changing its location, or
|
||||
adding a character to it moves them there. Each place a character is moved to
|
||||
(this way or by the DM on the sheet) is remembered, and a player can see only
|
||||
the locations one of their own characters has been to — on the campaign page
|
||||
under "Places You've Been", and on the encounter itself. Archiving or deleting
|
||||
under "Places", and on the encounter itself. Archiving or deleting
|
||||
the encounter does not take a visited place away again.
|
||||
|
||||
### Order, archive and delete
|
||||
|
||||
**Order.** The campaign page lists encounters in the **campaign order**, which
|
||||
the DM arranges with the ▲ and ▼ buttons and everyone sees. A new encounter
|
||||
goes to the top. The "Sort by" menu re-sorts the list by name, status, type or
|
||||
**Order.** The campaign page lists encounters on its "Overview", under the
|
||||
characters, in the **campaign order**, which
|
||||
the DM arranges with the ▲ and ▼ buttons and everyone sees. A new encounter,
|
||||
battle or quest, goes to the **bottom** unless the DM picks otherwise in the
|
||||
menu beside the name when adding it: at the bottom, at the top, or straight
|
||||
after any encounter on the list. Top or bottom is remembered per browser. The "Sort by" menu re-sorts the list by name, status, type or
|
||||
date instead; that choice is remembered per browser and changes nothing for
|
||||
anyone else. ▲ and ▼ only show while sorting by campaign order.
|
||||
|
||||
The list shows **ten encounters a page**, with Prev and Next beneath it, and
|
||||
The list shows **ten encounters a page**, with Prev and Next beneath it (and,
|
||||
with three pages or more, a menu to jump to any page), and
|
||||
the DM's archived list is paged the same way. The order runs on across pages:
|
||||
moving the last encounter on a page down carries it to the top of the next.
|
||||
|
||||
**Completed encounters are hidden.** An encounter that is **Complete** is
|
||||
left off the list, for the DM and the players alike, so the list is what is
|
||||
still to play. A **Show completed (N)** tick box above the list brings them
|
||||
back; the choice is remembered per browser. ▲ and ▼ move an encounter past its
|
||||
neighbour on the list as shown. Opening a completed encounter from a link
|
||||
still works, and nothing about it changes.
|
||||
|
||||
**Archive.** "Archive" (on the list or the encounter page) puts an encounter
|
||||
away without changing it. It moves to the DM's "Archived" section and
|
||||
disappears from the players' list; a player whose character is in it can still
|
||||
@@ -121,30 +165,76 @@ The DM adds people from the "Add to the scene" panel.
|
||||
| Monster | The campaign's monster list ([MONSTERS.md](MONSTERS.md)) | Yes |
|
||||
| NPC | The campaign's NPC list ([NPCS.md](NPCS.md)) | No |
|
||||
|
||||
**Finding your own character.** A player's own characters stand out: their
|
||||
cards have a blue border and background and say "★ Your character", and a row
|
||||
of buttons at the top of the page names each one with its HP ("★ Aria · 12/12
|
||||
HP", plus "your turn" when it is) and scrolls to its card. The DM sees the
|
||||
same for any character of their own.
|
||||
**Several monsters at once.** With "Monster" chosen there is a number beside
|
||||
Add, 1 to 20. More than one adds that many copies, numbered: "Goblin 1" to
|
||||
"Goblin 4". Adding more later carries on from the highest number in the scene
|
||||
("Goblin 5"). One on its own keeps the plain name. An initiative roll typed
|
||||
in is given to all of them; left empty, each can be rolled separately
|
||||
(section 7).
|
||||
|
||||
**Inventory.** A character's card has an "🎒 Inventory" button for the DM and
|
||||
for that character's own player. It opens the character panel on that
|
||||
character: everything they hold, what is equipped and what each thing does
|
||||
**The turn strip.** With two or more in the scene, a row of small buttons
|
||||
runs across the top of the page, one per combatant, in the order they act. It
|
||||
stays under the top bar while the cards scroll (on a phone it scrolls
|
||||
sideways). Each button has the name, HP where the viewer may see the numbers
|
||||
(otherwise the initiative total), a thin health bar and "⚑" with the number of
|
||||
conditions. Whoever is on turn is gold and marked ▶, a target is red and
|
||||
marked 🎯, the viewer's own characters are blue and marked ★, and in a battle
|
||||
those who have acted this round are dimmed. A click scrolls to that card. The
|
||||
fallen are not on it.
|
||||
|
||||
**Finding your own character.** A player's own characters stand out: their
|
||||
cards have a blue border and background and say "★ Your character", and their
|
||||
buttons on the turn strip are blue and starred. The DM sees the same for any
|
||||
character of their own.
|
||||
|
||||
**Sheet.** A character's card has a "📋 Sheet" button for the DM and for that
|
||||
character's own player. It opens the character panel on that character,
|
||||
beside the encounter: saving throws, every skill, passive scores, special
|
||||
abilities, everything they hold, what is equipped and what each thing does
|
||||
([CHARACTERS.md](CHARACTERS.md), section 14). The floating 🧙 button opens the
|
||||
same panel from anywhere. A card's details also list what the character's
|
||||
equipped gear is doing; the AC, speed and other numbers on the card already
|
||||
include it.
|
||||
|
||||
**The spotlight.** On a wide screen the column beside the cards starts with
|
||||
one combatant's whole stat block: whoever is **on turn** in a battle. It is
|
||||
everything their card has under "details", so the DM reads the attacker's
|
||||
numbers there while scrolling to a target. **📌 Pin** on any card with details
|
||||
puts that combatant there instead (in a quest too, where nobody is on turn);
|
||||
"✕ Unpin" or a second click on Pin goes back to whoever is on turn. Pinning is
|
||||
for the viewer's own screen only. The side column stays in view and scrolls
|
||||
on its own. On a screen narrower than 960px there is no spotlight and no Pin:
|
||||
the list is one column and the card on turn is at its top.
|
||||
|
||||
**Rolling.** The underlined numbers on a card and in the spotlight roll when
|
||||
clicked: a character's saves, skills, ability checks, initiative, attacks and
|
||||
damage, and for the DM a monster's or NPC's attack and damage and a monster's
|
||||
ability scores. "🎲 Call for a roll…" in the header (DM) rolls one check or
|
||||
save for all the characters in the scene at once
|
||||
([CHARACTERS.md](CHARACTERS.md), "Rolling from the sheet").
|
||||
|
||||
**Keys (DM, battle in progress).** **N** is Next Turn. **S** opens the sheet of
|
||||
the character on turn, or pins the monster or NPC on turn to the spotlight.
|
||||
Keys do nothing while the cursor is in a field.
|
||||
|
||||
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 weapon and items the character has **equipped**
|
||||
(with attack and damage numbers), the spells they can cast, and special
|
||||
abilities. A weapon that is not equipped is not on the card and cannot be
|
||||
used; "No weapon equipped" shows when there is none. Equipping is changed
|
||||
from "🎒 Inventory", at any point in the scene. The name links to the
|
||||
character sheet.
|
||||
ability scores, the weapon and items the character has **equipped**
|
||||
(with attack and damage numbers), spellcasting numbers with the spell slots
|
||||
left, the spells they can cast, **saving throws and all eighteen skills**
|
||||
(● proficient, ◆ expertise) with passive Perception, Investigation and
|
||||
Insight, and special abilities. A weapon that is not equipped is not on the
|
||||
card and cannot be used; "No weapon equipped" shows when there is none.
|
||||
Equipping is changed from "📋 Sheet". In a **battle in progress** a player
|
||||
can change the weapon in their character's hand (equip or unequip) at two
|
||||
moments only: **as the battle begins**, before anyone has made a move
|
||||
(round 1, still the first combatant's turn, nothing declared or landed),
|
||||
and **on their own turn once their attack has landed**, before the turn
|
||||
passes. At any other moment the sheet refuses and says why. The DM is not
|
||||
held to this and can change it at any time; items are not affected, and
|
||||
neither is a quest or free roam. 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,
|
||||
@@ -254,22 +344,42 @@ Initiative is entered in battles and quests alike. Turns and rounds are for
|
||||
battles only.
|
||||
|
||||
- Each combatant has an **initiative roll** field. Type what the d20 showed,
|
||||
1 to 20; the field accepts nothing else. The app does not roll the die, but
|
||||
it adds the bonus for you and shows the total, which can go past 20 (a 20 on
|
||||
1 to 20; the field accepts nothing else. The app adds the bonus for you and
|
||||
shows the total, which can go past 20 (a 20 on
|
||||
the die with a +3 bonus is 23): a character's initiative
|
||||
bonus from their sheet, a monster's Dexterity modifier, nothing for an NPC.
|
||||
- The DM can enter the roll for anyone, when adding them or on the card. A
|
||||
player can enter the roll for **their own character** on its card.
|
||||
- **🎲 Roll initiative for N monsters and NPCs**, in "Add to the scene" while
|
||||
any of them has no roll, rolls a d20 for each of those and adds their
|
||||
bonus. Monsters added together each get their own roll. Rolls already
|
||||
entered are left alone, and characters are left to their players.
|
||||
- The list is ordered by the total, highest first; ties keep the order they
|
||||
were added in. Anyone who has not rolled yet waits at the bottom.
|
||||
- The bonus is worked out when the roll is entered. If a character's sheet
|
||||
changes afterwards, enter the roll again to pick up the new bonus.
|
||||
- **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
|
||||
highlighted, the header names them, and their stats fill the spotlight
|
||||
(section 5).
|
||||
- **Next Turn** (or the **N** key) 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.
|
||||
- Anyone out of the fight (section 6, "The fallen") is passed over.
|
||||
- **The turn-order track.** While a battle is in progress a line of names
|
||||
stays at the top of the screen: whoever is on turn first (larger, with ▶),
|
||||
then everyone still to act this round, then a **🏁 Round N+1** flag where
|
||||
the round ends, then the whole order again for the round after. It is names
|
||||
only, coloured by what each is: **blue** for a player character, **green**
|
||||
for an NPC, **red** for a monster. A struck-through name is dying. The DM
|
||||
can read off who is next, and who follows the end of the round, at a glance.
|
||||
Before the battle begins the older strip (names with HP) is shown instead.
|
||||
- **What now.** Under the track the DM gets one line saying what the scene is
|
||||
waiting on: "Aria's turn: waiting for them to pick a target", "Aria's
|
||||
Longsword: enter the d20 against Goblin 1 (AC 15)", "Fireball: 3 saving
|
||||
throws to enter (DEX, DC 14)", "Goblin 2's Attack is ready (Aria: hit for
|
||||
5). Accept, change or discard it." A player gets the same line for what is
|
||||
theirs to do: "Your turn! Pick a target", "Roll your d20 for Longsword",
|
||||
"make a DEX saving throw and enter your d20".
|
||||
- **The list follows the turn.** While a battle is in progress, whoever is on
|
||||
turn is at the top of "Initiative order" with those still to act this round
|
||||
beneath them. Each combatant whose turn has passed moves down to a **Next
|
||||
@@ -284,8 +394,10 @@ Combatants can be marked as **targets**: whoever is being attacked (or
|
||||
healed) right now. One target is an ordinary attack; more than one is an
|
||||
**area attack**.
|
||||
|
||||
- Click **🎯 Target** beside a combatant's name to mark them; click it again
|
||||
to unmark. Each one marked is added to the targets.
|
||||
- Three ways to mark someone, each a toggle: click their **name on the
|
||||
turn-order track**; click **🎯 Target** beside their name on their card; or
|
||||
press **1 to 9** for the first nine combatants in turn order (leaving out
|
||||
whoever is on turn). Each one marked is added to the targets.
|
||||
- The **DM** can mark anyone at any time, in a battle or a quest. A **player**
|
||||
can while their own character is on turn in a battle, so they can show the
|
||||
DM who they are going for. A player cannot mark someone who is out of the
|
||||
@@ -295,8 +407,13 @@ healed) right now. One target is an ordinary attack; more than one is an
|
||||
on their own turn, use the buttons on their card.
|
||||
- A target's card is outlined in red for everyone and reads "Targeted by
|
||||
<whoever is on turn>".
|
||||
- While anyone is marked the DM gets an **attack bar** above the list, which
|
||||
stays in view while scrolling. It shows who is attacking whom, each target's
|
||||
- **In hand.** The card of whoever is on turn, and of every target, shows a
|
||||
highlighted "In hand" line: the weapons the character has equipped, with
|
||||
their to-hit and damage (or, for the DM, a creature's attacks). So both
|
||||
sides of an exchange show what they are fighting with.
|
||||
- While anyone is marked the DM also gets a quick **damage bar** above the
|
||||
list, for changing HP by hand without an attack (below). It shows who is
|
||||
attacking whom, each target's
|
||||
AC and HP, and the attacker's attacks: a character's equipped weapons (none,
|
||||
if nothing is equipped) and damaging spells, or a monster's or NPC's
|
||||
attack and damage. The amount box is ready to type in; **Damage** (or
|
||||
@@ -332,20 +449,136 @@ An attack on several targets is harder to land and its damage is shared.
|
||||
is applied.
|
||||
- A target with no hit points to track is left out of the sharing.
|
||||
|
||||
The app does not roll the attack or decide whether it hits: the DM compares
|
||||
the roll with the AC shown and types the damage.
|
||||
The damage bar does not roll or decide anything: it is for when the DM
|
||||
already knows the number. An attack that is to be rolled and judged goes
|
||||
through **Attacks and spells**, next.
|
||||
|
||||
### Attacks and spells
|
||||
|
||||
An attack or a spell is **declared**, **rolled**, and then **applied** by the
|
||||
DM. The app works out whether it hits (or whether each target saves) from the
|
||||
d20 that is entered, and the DM can overrule it at every step.
|
||||
|
||||
**1. Declare.** Once a target is marked, a box "<whoever is on turn> attacks
|
||||
with…" lists what they can use, one button each:
|
||||
|
||||
- a character's **equipped weapons** (outlined, so the weapon in hand stands
|
||||
out), each with its to-hit and damage;
|
||||
- the **spells** they know, each saying how it lands: a spell attack ("+6 to
|
||||
hit"), a saving throw ("DC 14 DEX save"), or no roll;
|
||||
- for the DM, a monster's or NPC's **own attacks**;
|
||||
- for the DM, **✎ Something else…**: an attack roll, a saving throw or an
|
||||
effect spelled out on the spot (a trap, a breath weapon, a monster's spell):
|
||||
its name, bonus or DC and ability, and damage dice.
|
||||
|
||||
A **player** declares for their own character, on its turn. The **DM**
|
||||
declares for anyone. Declaring replaces that combatant's unfinished action.
|
||||
|
||||
**2. Roll.** The action appears as a card for everyone, with a row per target:
|
||||
|
||||
| The action is | Each target's row asks for | And says |
|
||||
|---|---|---|
|
||||
| An attack (a weapon, a spell attack, a creature's attack) | The attacker's **d20** against that target | "17 vs AC 15": **HIT**, **MISS**, **CRITICAL HIT** on a natural 20, a miss on a natural 1 |
|
||||
| A saving throw spell | That target's **d20** for the save; their save bonus is filled in | "14 vs DC 14": **SAVED** or **FAILED** |
|
||||
| Something that just lands (Magic Missile) | Nothing | It hits |
|
||||
|
||||
- The d20 is **typed in** (press Enter or click away) or **rolled by the
|
||||
app** with "🎲 Roll the d20". A player follows the campaign's dice setting;
|
||||
the DM can always do either. With several targets an attack takes one d20
|
||||
per target, and the area-attack AC penalty is counted in.
|
||||
- The attacker's player enters the attack rolls; a player enters the **save
|
||||
for their own character** when a spell or trap is aimed at them; the DM can
|
||||
enter anything.
|
||||
- **Damage**: once something hits (or someone fails a save), "🎲 Roll damage"
|
||||
rolls the dice shown, or the total rolled at the table is typed in. On a
|
||||
**critical hit** the app rolls the critical damage as well, by the
|
||||
campaign's rule (the dice twice, or the dice at their most plus one roll),
|
||||
and that target takes it. A save that succeeds takes half, or nothing,
|
||||
as the spell says.
|
||||
|
||||
**3. Overrule (DM).** Beside each target the DM has **Hit / Miss / Crit** (or
|
||||
**Saved / Failed**) buttons that rule the outcome whatever the dice say (a
|
||||
ruling shows a ✎; pressing it again goes back to the dice), and a **dmg** box
|
||||
to set what that one target takes. "Aim it at" moves a single-target action
|
||||
to someone else, keeping the d20 already rolled.
|
||||
|
||||
**4. Apply (DM).** **✔ Apply** (or the **A** key) lets it land: each target
|
||||
loses what the card says, with temp HP, death saves and the fallen handled as
|
||||
for any damage; a spell spends the slot it was declared with from its caster
|
||||
(a cantrip spends nothing); anyone hurt while
|
||||
Concentrating gets a line telling the DM the save to call for. The card then
|
||||
moves to **⚔ What just happened** in the side column, where the last few
|
||||
actions stay for everyone to read. **✕ Discard** throws it away; a player can
|
||||
call off their own.
|
||||
|
||||
Passing the turn discards whatever was left unfinished.
|
||||
|
||||
### Auto-rolled monster and NPC attacks
|
||||
|
||||
With **Auto-roll monster attacks** (and, separately, **Auto-roll NPC
|
||||
attacks**) on in the campaign settings, a monster's or NPC's turn begins with
|
||||
its attack **already declared and rolled** by the server:
|
||||
|
||||
- **Who it goes for.** Monsters and hostile NPCs attack the party (characters
|
||||
and friendly NPCs); friendly NPCs attack monsters and hostile NPCs; a
|
||||
neutral NPC attacks nobody. Among those still standing the target is drawn
|
||||
at random, weighted: whoever it attacked last and whoever has hurt it count
|
||||
for more, and so, a little, does a lower AC. A creature with several
|
||||
attacks tends to keep at one foe.
|
||||
- **What is rolled.** The d20 against that target's AC, and, on a hit, the
|
||||
damage (critical damage on a natural 20). A monster with **named attacks**
|
||||
([MONSTERS.md](MONSTERS.md), section 2) makes each of them, as many times
|
||||
as its multiattack says: one card each.
|
||||
- **The DM decides.** The card reads, for example, "🤖 Goblin 2: Attack → Aria:
|
||||
17 vs AC 15, HIT, −5 HP". **✔ Accept** applies it; or change the target,
|
||||
the d20, the outcome or the damage first; or **✕ Discard** it and run the
|
||||
turn by hand.
|
||||
- **Players do not see it until it is accepted**, when the campaign keeps the
|
||||
DM's monster rolls hidden (the default); then it appears in "What just
|
||||
happened" like any other.
|
||||
|
||||
A creature with no attack bonus or damage, or with nobody to attack, declares
|
||||
nothing.
|
||||
|
||||
## 8. Conditions
|
||||
|
||||
The DM adds a condition to any card from the "+ Condition" list, and removes
|
||||
one by clicking its ✕. Everyone sees them.
|
||||
one by clicking its ✕. Everyone sees them. **Hovering over a condition shows
|
||||
its rule** (on the card, in the spotlight, on the sheet and on the party
|
||||
overview).
|
||||
|
||||
**A character's conditions are the character's own.** One given on an
|
||||
encounter card is on their sheet and in their panel too, is still there when
|
||||
the encounter ends, and shows on their card in the next one, until the DM
|
||||
removes it (from any of those places). A monster's or an NPC's conditions
|
||||
belong to that one card.
|
||||
|
||||
A character's card also shows **✨ Inspired** and **Exhaustion N** when they
|
||||
apply, and under "details" (and in the spotlight) their **class counters**:
|
||||
Rage, Ki, Channel Divinity and the rest, with a Use button for the DM and for
|
||||
that character's own player ([CHARACTERS.md](CHARACTERS.md), section 7).
|
||||
|
||||
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.
|
||||
**Timed conditions.** The "rounds" box beside "+ Condition" says how long the
|
||||
next condition added lasts. Its chip shows what is left ("Frightened 2 rd").
|
||||
Each time the **round goes up** (Next Turn past the last combatant, or Next
|
||||
Round) every timed condition loses a round, and one that reaches 0 comes off
|
||||
by itself, from the character's sheet too. The DM is told what wore off
|
||||
("Frightened wore off Aria."). Given for 1 round, a condition lasts until the
|
||||
next round begins; a condition added with the box empty stays until the DM
|
||||
removes it. The countdown belongs to the encounter: it does not run outside
|
||||
one, and removing a condition by hand drops its countdown.
|
||||
|
||||
**Concentration.** "Concentrating" marks someone holding a spell. When the DM
|
||||
applies damage to them, from their card or the attack bar, a notice gives the
|
||||
save to call for: Constitution, DC 10 or half the damage if that is higher,
|
||||
with their Constitution save bonus (a monster's Constitution modifier). The
|
||||
site does not roll it or end the spell: on a failure the DM removes the chip.
|
||||
|
||||
Conditions are reminders for the table. They do not change any numbers.
|
||||
|
||||
## 9. Rewards
|
||||
|
||||
@@ -377,10 +610,69 @@ Each can carry a short note ("Goblin chief's purse").
|
||||
Until a reward is awarded only the DM can see it. Afterwards players see what
|
||||
it was and who received it.
|
||||
|
||||
### Experience and difficulty
|
||||
|
||||
The DM's **Experience** card, above Rewards, reads the fight and hands out
|
||||
its XP. Players see none of it.
|
||||
|
||||
**What the monsters are worth.** Each monster's challenge rating
|
||||
([MONSTERS.md](MONSTERS.md)) is worth a set amount of XP, and the card adds
|
||||
them up, standing or fallen. A monster whose challenge is empty or is not a
|
||||
rating ("boss") is not counted, and the card says how many are not. NPCs have
|
||||
no challenge rating and are never counted.
|
||||
|
||||
| Challenge | XP | Challenge | XP | Challenge | XP | Challenge | XP |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| 0 | 10 | 3 | 700 | 9 | 5,000 | 15 | 13,000 |
|
||||
| 1/8 | 25 | 4 | 1,100 | 10 | 5,900 | 16 | 15,000 |
|
||||
| 1/4 | 50 | 5 | 1,800 | 11 | 7,200 | 17 | 18,000 |
|
||||
| 1/2 | 100 | 6 | 2,300 | 12 | 8,400 | 18 | 20,000 |
|
||||
| 1 | 200 | 7 | 2,900 | 13 | 10,000 | 19 | 22,000 |
|
||||
| 2 | 450 | 8 | 3,900 | 14 | 11,500 | 20 | 25,000 |
|
||||
|
||||
Ratings 21 to 30 run from 33,000 to 155,000. "0.5" is read as 1/2, and "CR 3"
|
||||
as 3.
|
||||
|
||||
**How hard it is.** Several monsters are harder than their XP says, so to
|
||||
judge the fight the total is multiplied for their number: ×1 for one, ×1.5
|
||||
for two, ×2 for 3 to 6, ×2.5 for 7 to 10, ×3 for 11 to 14, ×4 for 15 or more.
|
||||
That figure is held against what the characters in the scene can take, each
|
||||
adding their own level's thresholds:
|
||||
|
||||
| Level | Easy | Medium | Hard | Deadly |
|
||||
|---|---|---|---|---|
|
||||
| 1 | 25 | 50 | 75 | 100 |
|
||||
| 2 | 50 | 100 | 150 | 200 |
|
||||
| 3 | 75 | 150 | 225 | 400 |
|
||||
| 4 | 125 | 250 | 375 | 500 |
|
||||
| 5 | 250 | 500 | 750 | 1,100 |
|
||||
| 6 | 300 | 600 | 900 | 1,400 |
|
||||
| 7 | 350 | 750 | 1,100 | 1,700 |
|
||||
| 8 | 450 | 900 | 1,400 | 2,100 |
|
||||
| 9 | 550 | 1,100 | 1,600 | 2,400 |
|
||||
| 10 | 600 | 1,200 | 1,900 | 2,800 |
|
||||
|
||||
(Levels 11 to 20 continue to 2,800 / 5,700 / 8,500 / 12,700 at level 20.) The
|
||||
fight is **Trivial** below the party's Easy figure, then **Easy**,
|
||||
**Medium**, **Hard**, and **Deadly** from the Deadly figure up. The rating is
|
||||
a badge on the card and in the page header, beside the round, and it moves as
|
||||
monsters and characters are added. There is no rating until the scene has at
|
||||
least one character and one monster with a challenge rating.
|
||||
|
||||
**Awarding it.** "Award N XP each" shares the XP evenly between **every
|
||||
character in the encounter**, rounded down, and adds it to each one's XP. The
|
||||
amount is what the monsters are worth (not the multiplied figure) unless the
|
||||
DM types another: for a quest, a clever escape, or a scene with nothing rated
|
||||
in it. It can be awarded at any point, and **once** per encounter; the card
|
||||
then reads "✓ 75 XP awarded: 37 each". A mistake is put right on the
|
||||
characters' sheets. XP never levels anyone up by itself
|
||||
([CHARACTERS.md](CHARACTERS.md), section 6).
|
||||
|
||||
## 10. Trade
|
||||
|
||||
In an NPC quest the party can **change money** and **buy things**. Both take
|
||||
someone to deal with and the time to do it, so:
|
||||
In an NPC quest the party can **change money** and **buy things**. (In free
|
||||
roam they do the same at the place each character has gone to: section 2,
|
||||
"Free roam".) Both take someone to deal with and the time to do it, so:
|
||||
|
||||
- Trading is open only in an **NPC quest that is in progress**. Before "Begin
|
||||
Quest" and after "Complete Quest" everything on offer is still shown, but
|
||||
@@ -410,8 +702,8 @@ when there is something to trade, and always for the DM in a quest.
|
||||
holds at the level it is sold at, and uses up stock. A character below that
|
||||
level holds it but cannot use it yet.
|
||||
- Every trade is written to the character's money log.
|
||||
- **An NPC's rate and wares are set on the campaign page**, under "Trade" on
|
||||
the NPC's row, and follow the NPC into every quest they are in. **An
|
||||
- **An NPC's rate and wares are set on the campaign page**, in the NPC's
|
||||
pop-out, and follow the NPC into every quest they are in. **An
|
||||
encounter's own wares are set here**, in the DM's part of the card, and
|
||||
exist only in this encounter: a market stall, a vending machine, a chest
|
||||
with a price tag.
|
||||
@@ -425,14 +717,19 @@ when there is something to trade, and always for the DM in a quest.
|
||||
| Scene description | Yes | Yes |
|
||||
| DM notes | Yes | Never |
|
||||
| Characters | Full card | Full card |
|
||||
| A character's saves, skills and passive scores | Yes | Yes, as on the sheet |
|
||||
| A character's inspiration, exhaustion, conditions and class counters | Yes, and can change them | Yes; a player can spend their own character's counters |
|
||||
| A character's inventory, spells and purse | Yes, for everyone | Their own characters only |
|
||||
| Monsters | Full stat block | Name, HP, conditions |
|
||||
| NPCs | Everything | Name, role, attitude, description, HP bar |
|
||||
| Monsters and NPCs at 0 HP | With "Show dead" ticked, marked hidden | Nothing |
|
||||
| Dead characters | Full card with "Show dead" ticked, marked hidden | The name only, in the Fallen box |
|
||||
| Rewards | All | Only awarded ones |
|
||||
| Difficulty and the monsters' XP | Yes | Never (awarded XP shows on their own sheet) |
|
||||
| Exchange rates and things for sale | Yes | Yes, for NPCs they can see and for the scene itself |
|
||||
| Controls (add, damage, turns, rewards) | Yes | None |
|
||||
| An attack or spell being resolved | Yes, all | Yes, but not a monster's or NPC's AC, and not the DM's hidden (auto-rolled) ones until they are accepted |
|
||||
| What just happened (the last few actions) | Yes | Yes |
|
||||
| Controls (add, damage, turns, rewards) | Yes | None, apart from their own attacks and rolls |
|
||||
|
||||
The server only sends a player what the right-hand column lists, so hidden
|
||||
information cannot be dug out of the page.
|
||||
@@ -450,11 +747,24 @@ information cannot be dug out of the page.
|
||||
| Change HP or conditions | Yes | No |
|
||||
| Enter an initiative roll | Yes, for anyone | For their own character only |
|
||||
| Mark targets | Yes, any time | On their own character's turn |
|
||||
| Pick a free-roam scene's places, stock a place's shop | Yes | No |
|
||||
| Send a character to a place in free roam | Yes, anyone | Their own character |
|
||||
| Declare an attack or a spell | Yes, for anyone, and anything spelled out | For their own character, on its turn, with its weapons and spells |
|
||||
| Enter or roll an attack's d20 and damage | Yes | For their own character's attack |
|
||||
| Enter or roll a saving throw | Yes, for anyone | For their own character |
|
||||
| Overrule a roll, set a target's damage, change the target | Yes | No |
|
||||
| Apply or accept an action | Yes | No |
|
||||
| Discard an action | Yes | Their own |
|
||||
| Enter a death save, or stabilise | Yes, for anyone | For their own character only |
|
||||
| Set death-save tallies by hand | Yes | No |
|
||||
| Revive a dead character outright | Yes | No |
|
||||
| Try to revive a dead character | Yes, for the character on turn | On their own character's turn, if it has a reviving spell |
|
||||
| Advance turns and rounds | Yes | No |
|
||||
| Roll initiative for the monsters and NPCs | Yes | No |
|
||||
| Call for a roll from all the characters | Yes | No |
|
||||
| See the difficulty and what the monsters are worth; award XP | Yes | No |
|
||||
| Click a number to roll it | Yes | Yes, for what they can see |
|
||||
| Give a condition a number of rounds | Yes | No |
|
||||
| Add, remove or award rewards | Yes | No |
|
||||
| Set exchange rates, and put things up for sale | Yes | No |
|
||||
| Change money or buy, in a quest in progress | Yes, for any character in it | For their own character in it |
|
||||
@@ -463,15 +773,22 @@ People outside the campaign cannot open its encounters.
|
||||
|
||||
## 13. What is not modelled
|
||||
|
||||
- Rolling initiative, attacks, damage or saves (use the dice roller, bottom
|
||||
left of every page, or in the bottom bar on a phone)
|
||||
- Applying an attack's damage automatically
|
||||
- Rolling initiative for characters into their field (a player clicks their
|
||||
Init chip to roll it, then types what came up)
|
||||
- Advantage and disadvantage on an attack or save within an action (roll both
|
||||
d20s and enter the one that counts), resistances and vulnerabilities (set
|
||||
the target's damage by hand), and upcasting a spell for more damage
|
||||
- Healing through an action (use + Heal on the card or the damage bar)
|
||||
- A monster choosing among different attacks by itself: with auto-roll it
|
||||
makes all of its named attacks, or its single one
|
||||
- Death saves for monsters and NPCs, and prompting for a save on a dying
|
||||
character's turn
|
||||
- A roll, a spell slot or a time limit for reviving the dead
|
||||
- Conditions with durations or mechanical effects
|
||||
- The mechanical effects of conditions, durations counted in anything but
|
||||
rounds, and rolling a concentration save
|
||||
- Maps, positions, distances and areas of effect
|
||||
- Experience points and encounter difficulty
|
||||
- Adjusting difficulty for a very small or very large party, and awarding
|
||||
XP to some of the characters only or in unequal shares
|
||||
- Spells as rewards, and spells for sale
|
||||
- Selling to an NPC, haggling, and buying more than one of a thing in a
|
||||
single step
|
||||
|
||||
@@ -66,6 +66,19 @@ passivePerception = 10 + perceptionSkillBonus
|
||||
armorClass = 10 + dexModifier + armorBonus
|
||||
```
|
||||
|
||||
`dexModifier` here is as much of it as the equipped armor lets through
|
||||
(`armorDexterity`): all of it with none or light armor, at most +2 in medium
|
||||
armor, none in heavy armor. Armor is an item marked with its kind
|
||||
(`Item.armorType`); its own AC is a gear effect.
|
||||
|
||||
Without armor, a class feature can replace the `10 + dexModifier` part:
|
||||
Unarmored Defense (barbarian: `10 + DEX + CON`; monk, also without a shield:
|
||||
`10 + DEX + WIS`) and Draconic Resilience (`13 + DEX`). The best one is used,
|
||||
and only when it beats `10 + dexModifier`. These, and the other class features
|
||||
that change a sheet number (Fast Movement, Unarmored Movement, Aura of
|
||||
Protection, Diamond Soul, Slippery Mind, Jack of All Trades), live in
|
||||
`backend/src/game/classFeatures.js`; CHARACTERS.md section 8 lists them.
|
||||
|
||||
`armorBonus` is a flat number the player enters representing whatever armor/shield
|
||||
they have equipped (this matches the workbook's "Armor Bonus (from armor worn)"
|
||||
input cell). Do not try to model armor types as a lookup table unless you want to
|
||||
@@ -119,15 +132,17 @@ should hide those fields entirely rather than show them as zero/blank.
|
||||
|
||||
## Species Ability Score Increases & Speed
|
||||
|
||||
See `seed-data/species.json` for the full table (10 species). Note: Half-Elf gets
|
||||
+2 Charisma fixed, plus +1 to **two other** abilities of the player's choice — the
|
||||
seed data defaults that flexible pair to STR/INT, but the character builder UI
|
||||
must let the player pick which two abilities get the +1 during Half-Elf
|
||||
character creation (don't hardcode the default in the UI).
|
||||
See `seed-data/species.json` for the full table (43 species). Note: Half-Elf gets
|
||||
+2 Charisma fixed, plus +1 to **two other** abilities of the player's choice.
|
||||
The 2024 species (Aasimar, Goliath) and those of Monsters of the Multiverse
|
||||
have no fixed bonuses: the player chooses +2 and +1, or +1 to three
|
||||
abilities. These choices are a species' `flexible` patterns; the builder must
|
||||
ask for them (don't default them in the UI), and they are stored on the
|
||||
character as `speciesBonusChoices`.
|
||||
|
||||
## Class Quick Facts
|
||||
|
||||
See `seed-data/classes.json` for the full table (12 classes): Hit Die, Primary
|
||||
See `seed-data/classes.json` for the full table (13 classes, the Artificer included): Hit Die, Primary
|
||||
Ability, the two Saving Throw proficiencies, and Spellcasting Ability.
|
||||
|
||||
## Skill → Governing Ability
|
||||
|
||||
+49
-27
@@ -36,7 +36,11 @@ level up the same way weapons do), [SPELLS.md](SPELLS.md),
|
||||
|
||||
## 2. The item pool
|
||||
|
||||
The pool is the "Items Pool" card on the campaign page (DM only).
|
||||
The pool is the "Items" part of the campaign page (DM only). It lists each
|
||||
item as a short row: its name, then what it does, its dice and its
|
||||
description, as far as they fit on a line. The list has a search box, shows
|
||||
ten to a page, and clicking a row opens the item's **pop-out**, which shows
|
||||
everything below and is where it is changed.
|
||||
|
||||
| Field | What it is |
|
||||
|---|---|
|
||||
@@ -48,19 +52,24 @@ The pool is the "Items Pool" card on the campaign page (DM only).
|
||||
| Starting option | Whether a brand-new character may pick it in the builder (section 6) |
|
||||
| Effects | What it does to whoever has it equipped: bonuses and penalties to the sheet's numbers, and a note (section 5) |
|
||||
|
||||
- **Adding:** by hand with the "+ Add Item" form, or with "📚 From Library",
|
||||
which offers 32 ready-made items: light, medium and heavy armor, shields,
|
||||
- **Adding:** by hand with "+ Add Item", or with "📚 From Library". Both open
|
||||
in a pop-out; an item added by hand opens its own pop-out straight away, to
|
||||
set what it does, and "+ Add another item" at its top goes straight back
|
||||
to an empty form. The library offers 32 ready-made items: light, medium and heavy armor, shields,
|
||||
worn gear such as a Ring of Protection, and common supplies. Each is copied
|
||||
into the pool with its effects already set (Chain Mail: +6 AC, −10 Speed,
|
||||
and a note about Stealth), at starting level 1 and not ticked as a starting
|
||||
option. The copy is yours to change. The full list is in section 10.
|
||||
- **Effects:** the "Effects" button on an item's row. The row shows what the
|
||||
item does under its name.
|
||||
option. The copy is yours to change. The full list is in section 10. Each
|
||||
can be added once: an item the pool already has by that name is left out of
|
||||
the library list, and comes back if the pool's item is renamed or deleted.
|
||||
- **Effects:** under "While equipped" in the item's pop-out, saved with "Save
|
||||
Effects". The item's row shows what it does under its name.
|
||||
- **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**
|
||||
starting-option tick box are changed in the pop-out, and saved as they are
|
||||
changed. Name, description and dice cannot be changed on screen once
|
||||
created (the API accepts it); remove and re-add instead.
|
||||
- **Removing:** "Remove from campaign" at the foot of the pop-out, after a
|
||||
confirmation. This takes the item out of **every inventory**
|
||||
and off every encounter's reward list. There is no undo.
|
||||
|
||||
## 3. A character's inventory
|
||||
@@ -159,6 +168,19 @@ Armor, shields, rings, cloaks and the like are ordinary items that have
|
||||
**effects**. An effect is a whole number, positive for a bonus and negative
|
||||
for a penalty, on one of the sheet's numbers:
|
||||
|
||||
**Armor and shields are marked as such.** An item's pop-out has an **Armor**
|
||||
menu: not armor (the default), light, medium, heavy, or shield. Its AC is
|
||||
still an effect (+AC, its usual AC less 10); the mark says what kind of thing
|
||||
it is. The sheet counts **all** of a character's Dexterity modifier toward AC
|
||||
in light armor, **at most +2** in medium armor and **none** in heavy armor
|
||||
([CHARACTERS.md](CHARACTERS.md), section 8), so plate is +8 and comes to AC
|
||||
18 whoever wears it. Some class features depend on what is worn too: a barbarian's and a monk's Unarmored
|
||||
Defense and a draconic sorcerer's scales stop while armor is equipped, a
|
||||
monk's also stop behind a shield, and a barbarian's extra speed stops in
|
||||
heavy armor ([CHARACTERS.md](CHARACTERS.md), section 8). The library's armor
|
||||
and shield come marked; mark your own. A ring or cloak that gives +AC is not
|
||||
armor: leave it unmarked.
|
||||
|
||||
| It can change | Examples |
|
||||
|---|---|
|
||||
| AC | Chain mail +6, a shield +2, a cursed cloak −1 |
|
||||
@@ -186,8 +208,8 @@ plus a **note** for what is not a number ("Disadvantage on Stealth",
|
||||
card lists every item in force with what it is doing, and its note.
|
||||
- **Max HP can move.** If taking something off lowers a character's maximum
|
||||
HP below their current HP, current HP comes down to the new maximum.
|
||||
- **Only the DM sets effects**, with the "Effects" button on the item's row in
|
||||
the pool. Changing them changes the sheet of everyone wearing the item,
|
||||
- **Only the DM sets effects**, under "While equipped" in the item's pop-out
|
||||
on the campaign page. Changing them changes the sheet of everyone wearing the item,
|
||||
straight away.
|
||||
- The DM also has an **Extra AC** number on each sheet, added on top of gear,
|
||||
for anything an item does not cover. It can be negative.
|
||||
@@ -235,8 +257,8 @@ and [ENCOUNTERS.md](ENCOUNTERS.md), section 10.
|
||||
|
||||
## 9. What is not modelled
|
||||
|
||||
- Armor rules beyond a flat bonus: armor does not replace 10 + DEX, cap the
|
||||
DEX bonus or need a Strength score (set the AC effect to match)
|
||||
- A Strength score needed for heavy armor, armor proficiency and Stealth
|
||||
disadvantage: these are notes on the armor for the table to apply
|
||||
- Effects on attack rolls, damage, spell save DC or proficiency bonus
|
||||
- Effects that depend on something (only at night, only against undead), or
|
||||
that grow with the item's level
|
||||
@@ -256,10 +278,10 @@ and [ENCOUNTERS.md](ENCOUNTERS.md), section 10.
|
||||
Everything "📚 From Library" offers. "While equipped" is what the item does
|
||||
to the sheet of whoever has it on.
|
||||
|
||||
Armor is a flat bonus to AC on top of 10 + Dexterity: each suit's bonus is its
|
||||
standard AC less 10. What a flat bonus cannot say (heavy armor ignoring
|
||||
Dexterity, a Strength requirement, disadvantage on Stealth) is in the note,
|
||||
for the DM to apply or to build into the numbers of their own copy.
|
||||
Armor is a bonus to AC on top of 10 + Dexterity: each suit's bonus is its
|
||||
standard AC less 10, and it is marked light, medium or heavy, which sets how
|
||||
much Dexterity counts in it (section 5). What that cannot say (a Strength
|
||||
requirement, disadvantage on Stealth) is in the note, for the DM to apply.
|
||||
|
||||
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.
|
||||
|
||||
@@ -276,20 +298,20 @@ This list is written from the app's own data by `npm run docs:lists` (in `/backe
|
||||
|
||||
| Item | While equipped | Note | Dice | Description |
|
||||
|---|---|---|---|---|
|
||||
| Hide Armor | +2 AC | Standard rules: counts at most +2 from Dexterity. | — | Thick furs and pelts. |
|
||||
| Chain Shirt | +3 AC | Standard rules: counts at most +2 from Dexterity. | — | Interlocking rings worn between layers of clothing. |
|
||||
| Scale Mail | +4 AC | Disadvantage on Stealth checks. Standard rules: counts at most +2 from Dexterity. | — | A coat and leggings of leather covered in overlapping metal scales. |
|
||||
| Breastplate | +4 AC | Standard rules: counts at most +2 from Dexterity. | — | A fitted metal chest piece worn with supple leather. |
|
||||
| Half Plate | +5 AC | Disadvantage on Stealth checks. Standard rules: counts at most +2 from Dexterity. | — | Shaped metal plates covering most of the body. |
|
||||
| Hide Armor | +2 AC | Medium armor: at most +2 from Dexterity counts (worked out on the sheet). | — | Thick furs and pelts. |
|
||||
| Chain Shirt | +3 AC | Medium armor: at most +2 from Dexterity counts (worked out on the sheet). | — | Interlocking rings worn between layers of clothing. |
|
||||
| Scale Mail | +4 AC | Disadvantage on Stealth checks. Medium armor: at most +2 from Dexterity counts (worked out on the sheet). | — | A coat and leggings of leather covered in overlapping metal scales. |
|
||||
| Breastplate | +4 AC | Medium armor: at most +2 from Dexterity counts (worked out on the sheet). | — | A fitted metal chest piece worn with supple leather. |
|
||||
| Half Plate | +5 AC | Disadvantage on Stealth checks. Medium armor: at most +2 from Dexterity counts (worked out on the sheet). | — | Shaped metal plates covering most of the body. |
|
||||
|
||||
### Heavy Armor (4)
|
||||
|
||||
| Item | While equipped | Note | Dice | Description |
|
||||
|---|---|---|---|---|
|
||||
| Ring Mail | +4 AC | Disadvantage on Stealth checks. Standard rules: adds no Dexterity. | — | Leather armor with heavy rings sewn into it. |
|
||||
| Chain Mail | +6 AC, −10 Speed | Disadvantage on Stealth checks. Standard rules: adds no Dexterity, and needs Strength 13. | — | Interlocking metal rings over a layer of quilted fabric, with gauntlets. |
|
||||
| Splint Armor | +7 AC, −10 Speed | Disadvantage on Stealth checks. Standard rules: adds no Dexterity, and needs Strength 15. | — | Narrow vertical strips of metal riveted to a leather backing. |
|
||||
| Plate Armor | +8 AC, −10 Speed | Disadvantage on Stealth checks. Standard rules: adds no Dexterity, and needs Strength 15. | — | Shaped, interlocking metal plates covering the whole body. |
|
||||
| Ring Mail | +4 AC | Disadvantage on Stealth checks. Heavy armor: Dexterity does not count (worked out on the sheet). | — | Leather armor with heavy rings sewn into it. |
|
||||
| Chain Mail | +6 AC, −10 Speed | Disadvantage on Stealth checks. Heavy armor: Dexterity does not count (worked out on the sheet). Standard rules: needs Strength 13. | — | Interlocking metal rings over a layer of quilted fabric, with gauntlets. |
|
||||
| Splint Armor | +7 AC, −10 Speed | Disadvantage on Stealth checks. Heavy armor: Dexterity does not count (worked out on the sheet). Standard rules: needs Strength 15. | — | Narrow vertical strips of metal riveted to a leather backing. |
|
||||
| Plate Armor | +8 AC, −10 Speed | Disadvantage on Stealth checks. Heavy armor: Dexterity does not count (worked out on the sheet). Standard rules: needs Strength 15. | — | Shaped, interlocking metal plates covering the whole body. |
|
||||
|
||||
### Shields (2)
|
||||
|
||||
|
||||
+45
-21
@@ -40,29 +40,47 @@ This describes the code as it stands. The built-in list is
|
||||
| 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`, with the damage type if you like: `1d6+2 necrotic` |
|
||||
| Challenge rating | A rough danger rating, e.g. `1/4`, `2` |
|
||||
| Named attacks | Optional, up to 8: each a name, an attack bonus, damage dice, a damage type and **how many times it is made each turn** (a multiattack: "Claw ×2, Bite ×1"). With any listed, these are what the monster attacks with in an encounter, in place of the single attack above |
|
||||
| Challenge rating | A rough danger rating, e.g. `1/4`, `2`. It sets what the monster is worth in XP and how hard an encounter is ([ENCOUNTERS.md](ENCOUNTERS.md), section 9); a monster with none, or with text that is not a rating, is left out of both |
|
||||
| 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.
|
||||
The challenge rating feeds the XP and difficulty sums. The AC, the attack
|
||||
bonus and damage (or the named attacks) and the ability scores are used when
|
||||
an attack or a spell is resolved in an encounter: an attack roll is judged
|
||||
against the AC, a saving throw adds the ability's modifier, and with
|
||||
auto-roll on the monster's attacks are aimed and rolled for the DM
|
||||
([ENCOUNTERS.md](ENCOUNTERS.md), "Attacks and spells"). A monster's ability
|
||||
modifiers are worked out from its scores for display, for its initiative
|
||||
bonus (Dexterity) and for the rolls a click makes (section 5).
|
||||
|
||||
## 3. Managing monsters
|
||||
|
||||
The list is the "Monsters" card on the campaign page (DM only).
|
||||
The list is the "Monsters" part of the campaign page (DM only). Each monster
|
||||
is a short row: its name, challenge rating, AC, HP and attack. The list has a
|
||||
search box, shows ten to a page, and clicking a row opens the monster's
|
||||
**pop-out** with its whole stat block.
|
||||
|
||||
- **Adding by hand:** "+ Add Monster" opens the whole stat block: name,
|
||||
- **Adding by hand:** "+ Add Monster" opens a pop-out with the whole stat
|
||||
block: name,
|
||||
challenge rating, AC, HP, speed, attack bonus, damage, the six ability
|
||||
scores, special trait and notes. Only name, AC and HP must be typed; speed
|
||||
starts at 30, attack bonus at 0 and each ability score at 10.
|
||||
- **Adding from the bestiary:** "📚 From Library" copies a complete stat block.
|
||||
- **Changing:** "Edit" on a monster's row opens the same form filled in.
|
||||
- Once added by hand, the monster's own pop-out opens. "+ Add another
|
||||
monster" at its top goes straight back to an empty form.
|
||||
- **Adding from the bestiary:** "📚 From Library" opens the bestiary in a
|
||||
pop-out, and "+ Add" copies a complete stat block.
|
||||
Each monster can be added once: one the campaign already has by that name is
|
||||
left out of the list, and comes back if the campaign's monster is renamed or
|
||||
deleted.
|
||||
- **Changing:** "Edit stat block" in a monster's pop-out opens the same form
|
||||
filled in.
|
||||
Saving changes the template, and copies already in encounters show the new
|
||||
stat block straight away; their current HP is left alone.
|
||||
- The list shows each monster's full stat block: the numbers in columns, and
|
||||
its ability scores, trait and notes under its name.
|
||||
- **Removing:** the ✕ button, after a confirmation. Copies
|
||||
- The pop-out shows the full stat block: the numbers, the six ability scores,
|
||||
the trait and the notes.
|
||||
- **Removing:** "Remove from campaign" at the foot of the pop-out, after a
|
||||
confirmation. Copies
|
||||
already in encounters stay there with their name and HP, but lose their
|
||||
stat block.
|
||||
|
||||
@@ -124,11 +142,14 @@ This list is written from the app's own data by `npm run docs:lists` (in `/backe
|
||||
## 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.
|
||||
panel, picks one, says how many, and types its initiative or leaves it to be
|
||||
rolled ("🎲 Roll initiative for N monsters and NPCs" rolls a d20 plus the
|
||||
Dexterity modifier for each that has no roll).
|
||||
|
||||
- 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).
|
||||
- The same monster can be added **any number of times**, up to 20 in one go.
|
||||
Each copy has its own HP and conditions. Copies added together are numbered
|
||||
("Goblin 1" to "Goblin 4"); one added on its own has 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.
|
||||
@@ -136,7 +157,10 @@ panel, picks one, and types its initiative.
|
||||
|
||||
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.
|
||||
and its notes. **Attack, Damage and each ability score roll when clicked**: a
|
||||
d20 plus the attack bonus, the damage dice, or a d20 plus the ability's
|
||||
modifier. Of damage written with more after the dice ("2d8+3 fire") the dice
|
||||
are rolled; damage that does not start with dice is shown but does not roll.
|
||||
|
||||
## 6. What players see
|
||||
|
||||
@@ -167,10 +191,10 @@ Then they get the health bar only.
|
||||
|
||||
## 8. What is not modelled
|
||||
|
||||
- Multiple attacks, spells, legendary actions and resistances (use Notes)
|
||||
- Spells, legendary actions and resistances (use Notes; in an encounter the
|
||||
DM can spell out any attack or save on the spot)
|
||||
- Trade: monsters do not sell things or change money (NPCs do)
|
||||
- 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
|
||||
- Saving throw proficiencies and skills (on an encounter card a click on an
|
||||
ability score rolls a d20 with its modifier, for a check or a save)
|
||||
- XP typed in for a monster: it always comes from the challenge rating
|
||||
- Monster hit dice, and rolling HP rather than using the fixed value
|
||||
|
||||
+23
-9
@@ -50,20 +50,33 @@ This describes the code as it stands. Related: [ENCOUNTERS.md](ENCOUNTERS.md),
|
||||
|
||||
A new NPC is Neutral unless you choose otherwise.
|
||||
|
||||
**Found at.** An NPC can be given one of the campaign's locations as the place
|
||||
they are usually found, on their pop-out. In a **free-roam** encounter that
|
||||
includes that place, the NPC appears on its card, and a character who goes
|
||||
there can buy from them and change money with them
|
||||
([ENCOUNTERS.md](ENCOUNTERS.md), section 2, "Free roam"). It changes nothing in
|
||||
a quest or a battle, where an NPC takes part because the DM added them.
|
||||
|
||||
## 3. Managing NPCs
|
||||
|
||||
The NPC list is the "NPCs" card on the campaign page (DM only).
|
||||
The NPC list is the "NPCs" part of the campaign page (DM only). Each NPC is a
|
||||
short row: name, role, the start of their description, and badges for their
|
||||
attitude, a 💱 with their exchange rate and a 🛒 with how many things they
|
||||
have for sale. The list has a search box and shows ten to a page.
|
||||
|
||||
- **Adding:** "+ Add NPC" opens a form with every field above except the
|
||||
exchange rate and wares. Only the name is required.
|
||||
- **Trade:** the "Trade" button on an NPC's row opens their exchange rate and
|
||||
their wares (section 5). The row shows a 💱 badge with the rate and a 🛒
|
||||
badge with how many things are for sale.
|
||||
- **The pop-out:** clicking a row opens the NPC's pop-out, with everything
|
||||
above: description, DM notes, combat stats, and their trade.
|
||||
- **Adding:** "+ Add NPC" opens a pop-out with every field above except the
|
||||
exchange rate and wares. Only the name is required. Once added, the NPC's
|
||||
own pop-out opens, to set their trade; "+ Add another NPC" at its top goes
|
||||
straight back to an empty form.
|
||||
- **Trade:** the exchange rate and the wares are set in the NPC's pop-out,
|
||||
under "Changes money" and "For sale" (section 5).
|
||||
- **Changing:** there is no edit form for the other fields. To change them,
|
||||
remove the NPC and add it again (the API accepts changes, but no screen
|
||||
offers them). Removing an NPC removes their wares too.
|
||||
- **Removing:** the ✕ button, after a confirmation. This also **removes the
|
||||
NPC from every encounter** it was in.
|
||||
- **Removing:** "Remove from campaign" at the foot of the pop-out, after a
|
||||
confirmation. This also **removes the NPC from every encounter** it was in.
|
||||
|
||||
## 4. NPCs in encounters
|
||||
|
||||
@@ -113,7 +126,8 @@ another.
|
||||
- Both sides go on the character's money log, naming the NPC: "Changed with
|
||||
Vex for $45" and "Changed with Vex from 6 gold".
|
||||
- An NPC never runs out of gold or cash to change.
|
||||
- To set a rate, type both numbers under "Trade" and press "Save rate".
|
||||
- To set a rate, type both numbers under "Changes money" in the NPC's pop-out
|
||||
and press "Save rate".
|
||||
"Stop changing money" clears it. An NPC with no rate does not change money.
|
||||
|
||||
### Selling
|
||||
|
||||
+25
-14
@@ -11,23 +11,26 @@ the in-progress rolls/choices held in `Character.buildState` (JSON) until the
|
||||
build is finalized, at which point the real columns (`species`, `characterClass`,
|
||||
ability scores, proficiencies) get set and `buildStage` becomes `COMPLETE`.
|
||||
|
||||
## Step 1 — Roll Species (d6)
|
||||
## Step 1 — Roll Species (d8)
|
||||
|
||||
Tell the player: **"Roll a d6."** Then offer the choice(s) that result maps to.
|
||||
Most rolls offer 2 species to pick between; keep the flavor text short.
|
||||
Tell the player: **"Roll a d8."** Then offer the family of species that result
|
||||
maps to; keep the flavor text short.
|
||||
|
||||
| d6 Roll | Choose between |
|
||||
| d8 Roll | Choose from |
|
||||
|---|---|
|
||||
| 1 | Human or Half-Elf |
|
||||
| 2 | Elf or Gnome |
|
||||
| 3 | Dwarf or Halfling |
|
||||
| 4 | Dragonborn or Tiefling |
|
||||
| 5 | Half-Orc or Orc |
|
||||
| 6 | Wildcard — pick any species |
|
||||
| 1 | Human, Half-Elf, Elf, Half-Orc |
|
||||
| 2 | Dwarf, Gnome, Halfling, Deep Gnome, Duergar |
|
||||
| 3 | Dragonborn, Tiefling, Aasimar, Goliath |
|
||||
| 4 | Orc, Goblin, Hobgoblin, Bugbear, Kobold |
|
||||
| 5 | Eladrin, Sea Elf, Shadar-kai, Githyanki, Githzerai, Changeling |
|
||||
| 6 | Air, Earth, Fire or Water Genasi, Triton, Tortle |
|
||||
| 7 | Tabaxi, Kenku, Aarakocra, Harengon, Lizardfolk, Owlin, Minotaur, Centaur, Satyr, Shifter, Firbolg, Fairy, Yuan-ti |
|
||||
| 8 | Wildcard — pick any species |
|
||||
|
||||
If the player rolls Half-Elf, immediately prompt for which two abilities (other
|
||||
than Charisma) get the flexible +1 — this choice has to happen here, not be
|
||||
silently defaulted (see GAME_RULES_REFERENCE.md).
|
||||
If the species has chosen bonuses, immediately prompt for where they go — this
|
||||
choice has to happen here, not be silently defaulted. A Half-Elf picks two
|
||||
abilities (other than Charisma) for +1 each; the 2024 and Multiverse species
|
||||
pick +2 and +1, or +1 to three abilities.
|
||||
|
||||
## Step 2 — Roll Class (d8)
|
||||
|
||||
@@ -41,9 +44,17 @@ Tell the player: **"Roll a d8."**
|
||||
| 4 | Cleric or Paladin |
|
||||
| 5 | Bard or Warlock |
|
||||
| 6 | Druid or Monk |
|
||||
| 7 | Reroll once, keep either result |
|
||||
| 7 | Artificer, or reroll once (the reroll stands) |
|
||||
| 8 | Wildcard — pick any class |
|
||||
|
||||
## Step 2b — Choose a Subclass
|
||||
|
||||
When the campaign uses subclasses, the player now picks the path within their
|
||||
class from its full list (each with its book and a level 1–20 preview), or
|
||||
rolls a die with one face per subclass for a suggestion, or leaves it until
|
||||
the class reaches the level it chooses at. A path chosen here only starts
|
||||
giving at that level.
|
||||
|
||||
## Step 3 — Roll Motivation (d6, optional flavor)
|
||||
|
||||
Tell the player: **"Roll a d6"** (optional — DM can skip this step for the whole
|
||||
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
# World Seeds
|
||||
|
||||
A world seed is a ready-made campaign: locations, weapons, items, spells,
|
||||
monsters, NPCs with their wares, encounters with their rewards, and notes. A
|
||||
DM starts a campaign from one by typing its code.
|
||||
|
||||
This describes the code as it stands. Related: [ITEMS.md](ITEMS.md),
|
||||
[WEAPONS.md](WEAPONS.md), [SPELLS.md](SPELLS.md), [MONSTERS.md](MONSTERS.md),
|
||||
[NPCS.md](NPCS.md), [ENCOUNTERS.md](ENCOUNTERS.md).
|
||||
|
||||
## Contents
|
||||
|
||||
1. [The basics](#1-the-basics)
|
||||
2. [Starting a campaign from a code](#2-starting-a-campaign-from-a-code)
|
||||
3. [Adding a world](#3-adding-a-world)
|
||||
4. [What a seed file holds](#4-what-a-seed-file-holds)
|
||||
5. [Checking a seed](#5-checking-a-seed)
|
||||
6. [The database seed](#6-the-database-seed)
|
||||
7. [The worlds that come with the app](#7-the-worlds-that-come-with-the-app)
|
||||
|
||||
---
|
||||
|
||||
## 1. The basics
|
||||
|
||||
- Every `.js` file in `/backend/seeds` is one world. The file says what its
|
||||
**code** is: six capital letters or digits.
|
||||
- Anyone who is logged in and knows a code can create that world as a new
|
||||
campaign. They become its DM and owner, exactly as with a blank campaign.
|
||||
- The same code can be used any number of times. Each use makes a separate
|
||||
campaign with its own invite code; nothing is shared between copies.
|
||||
- A seed only says what a campaign **starts** as. Once created, the campaign
|
||||
is the DM's to change, and changing the seed file later does not touch
|
||||
campaigns already made from it.
|
||||
- The folder is read each time a code is entered, so a new file is live as
|
||||
soon as it is on the server. No restart, no migration.
|
||||
|
||||
## 2. Starting a campaign from a code
|
||||
|
||||
On the **Campaigns** page, click **+ New Campaign**. Under the form for a
|
||||
blank campaign is **Or start from a ready-made world**: type the code and
|
||||
click **Create From Code**. Capitals and spaces do not matter (`aldenf`,
|
||||
`ALDENF` and `ald-enf` are the same code).
|
||||
|
||||
The whole world is created in one go, and you land on its campaign page. If
|
||||
anything in it fails, nothing is created.
|
||||
|
||||
| Reply | Meaning |
|
||||
|---|---|
|
||||
| "A world code is 6 letters or numbers" | What was typed is not six characters long |
|
||||
| "There is no world with that code" | No valid seed file has that code |
|
||||
|
||||
The API is `POST /campaigns/from-seed` with `{ "code": "ALDENF" }`. It
|
||||
answers with the new campaign, as `POST /campaigns` does.
|
||||
|
||||
## 3. Adding a world
|
||||
|
||||
1. Write the world as a file in `/backend/seeds`, for example
|
||||
`/backend/seeds/my-world.js` (section 4).
|
||||
2. Run `npm run seeds:check` (section 5) and fix whatever it reports.
|
||||
3. Put the file on the server. The code works straight away.
|
||||
|
||||
A file with a mistake in it is never offered: its code simply answers "There
|
||||
is no world with that code" until the file is fixed. Two files cannot share a
|
||||
code; the one whose file name comes first keeps it.
|
||||
|
||||
To retire a world, delete its file. Campaigns already made from it stay.
|
||||
|
||||
## 4. What a seed file holds
|
||||
|
||||
A seed file is a JavaScript module that exports one object. Only `code` and
|
||||
`campaign.name` are required; every list can be left out.
|
||||
|
||||
```js
|
||||
module.exports = {
|
||||
code: 'MYWRLD',
|
||||
campaign: { name: 'My World', description: '...', startingGold: 20, startingItemCount: 2, startingSpellCount: 2 },
|
||||
locations: [{ name: 'The Old Mill', description: '...' }],
|
||||
weapons: [
|
||||
'dagger', // a copy from the site library
|
||||
{ library: 'longsword', isStartingOption: true }, // a copy, with changes
|
||||
{ name: 'Millstone Hammer', damageDice: '2d6', damageType: 'bludgeoning', attackAbility: 'STR', minLevel: 3 },
|
||||
],
|
||||
items: [
|
||||
{ library: 'shield', isStartingOption: true },
|
||||
{ name: 'Miller’s Charm', description: '...', effects: [{ stat: 'SKILL_PERCEPTION', amount: 1 }] },
|
||||
],
|
||||
spells: [{ library: 'fire-bolt', isStartingOption: true }, 'fireball'],
|
||||
monsters: ['goblin', { name: 'Mill Wraith', ac: 13, maxHp: 30, attackBonus: 4, damageDice: '1d8+2 necrotic' }],
|
||||
npcs: [
|
||||
{
|
||||
name: 'Old Hob', role: 'Miller', disposition: 'FRIENDLY', description: '...', dmNotes: '...',
|
||||
wares: [{ item: 'Shield', price: 10 }, { weapon: 'Dagger', price: 2, stock: 3 }],
|
||||
},
|
||||
],
|
||||
encounters: [
|
||||
{
|
||||
name: 'The Mill at Night', mode: 'BATTLE', location: 'The Old Mill', description: '...', dmNotes: '...',
|
||||
monsters: [['Goblin', 3], ['Mill Wraith', 1, 'The Miller’s Wife', 40]],
|
||||
npcs: ['Old Hob'],
|
||||
rewards: [{ gold: 25 }, { silver: 40 }, { weapon: 'Millstone Hammer', note: 'Behind the wheel' }],
|
||||
},
|
||||
],
|
||||
sharedNotes: ['Welcome to My World...'],
|
||||
dmNotes: ['The secret of the mill...'],
|
||||
};
|
||||
```
|
||||
|
||||
The file is ordinary JavaScript, so it can build its lists however it likes
|
||||
(the Hollowcrown seed adds the whole spell library with a `map`).
|
||||
|
||||
### Top level
|
||||
|
||||
| Field | What it is |
|
||||
|---|---|
|
||||
| `code` | Six capital letters or digits. What a DM types |
|
||||
| `campaign` | The campaign's settings: `name`, and optionally `description`, `startingGold`, `startingItemCount`, `startingSpellCount`, `skipMotivationRoll`, `showMonsterHp`, `areaAttackAcPenalty`, `maxEquipped`, `maxEquippedWeapons`, `subclassesEnabled`, `multiclassEnabled`, `diceMode`, `autoRollMonsters`, `autoRollNpcs`, `trackXp`, `hpOnLevelUp`, `abilityScoreMethod`, `rollVisibility`, `hideMonsterRolls`, `critRule`. Anything left out takes the app's default |
|
||||
| `locations` | `{ name, description }` |
|
||||
| `weapons`, `items`, `spells`, `monsters` | The pools. Each entry is a row or a library copy (below) |
|
||||
| `npcs` | NPC rows, each optionally with `wares` |
|
||||
| `encounters` | In the order they should list |
|
||||
| `sharedNotes`, `dmNotes` | Note bodies, in reading order: the first is shown at the top. Shared notes are for everyone, DM notes for the DM |
|
||||
|
||||
### Pool entries
|
||||
|
||||
An entry in `weapons`, `items`, `spells` or `monsters` is one of:
|
||||
|
||||
- **A library key** such as `'longsword'`: a copy of that entry from the
|
||||
site's built-in library (`src/game/data/*Library.js`).
|
||||
- **A library copy with changes**: `{ library: 'longsword', isStartingOption: true, minLevel: 2 }`.
|
||||
Any field of the row can be changed, including its name.
|
||||
- **A full row**, with the same fields the app's own forms have:
|
||||
|
||||
| Pool | Fields (required in bold) |
|
||||
|---|---|
|
||||
| Weapon | **`name`**, **`damageDice`**, **`damageType`**, **`attackAbility`** (`STR`, `DEX` or `FINESSE`), `properties`, `rangeNormal`, `rangeLong`, `damageScaling` (1 to 3), `minLevel` (1 to 9), `isStartingOption`, `effects`, `effectNote` |
|
||||
| Item | **`name`**, `description`, `damageDice`, `damageScaling`, `minLevel`, `isStartingOption`, `effects`, `effectNote` |
|
||||
| Spell | **`name`**, **`level`** (0 to 9), `damageDice`, `school`, `castingTime`, `range`, `duration`, `description`, `isStartingOption`, `revives` |
|
||||
| Monster | **`name`**, **`ac`**, **`maxHp`**, `speed`, `strScore` ... `chaScore`, `attackBonus`, `damageDice` (may name its type: `"1d6+2 necrotic"`), `challengeRating`, `specialTrait`, `notes` |
|
||||
|
||||
`effects` is a list of `{ stat, amount }`, as described in
|
||||
[ITEMS.md](ITEMS.md): armor is an item with an `AC` effect.
|
||||
|
||||
Within a pool a name can only be used once, because everything else in the
|
||||
file points at pool entries **by name**.
|
||||
|
||||
### NPCs
|
||||
|
||||
**`name`**, `role`, `disposition` (`FRIENDLY`, `NEUTRAL` or `HOSTILE`),
|
||||
`description` (what players see), `dmNotes`, and for those who might fight
|
||||
`ac`, `maxHp`, `attackBonus`, `damageDice`.
|
||||
|
||||
- **A money changer** has `exchangeGold` and `exchangeCash` together:
|
||||
`exchangeGold: 1, exchangeCash: 50` is 1 gold for $50, either way.
|
||||
- **A shopkeeper** has `wares`, a list of things for sale (below).
|
||||
|
||||
### Encounters
|
||||
|
||||
| Field | What it is |
|
||||
|---|---|
|
||||
| **`name`** | |
|
||||
| `mode` | `BATTLE` (the default) or `QUEST`. Buying and money changing only happen in a quest |
|
||||
| `description` | The scene, shown to the players in it |
|
||||
| `dmNotes` | DM only |
|
||||
| `location` | A location's name |
|
||||
| `monsters` | `[monster name, how many, display name, max HP]`. The last two are optional; more than one gets "#1", "#2"... |
|
||||
| `npcs` | NPC names, or `{ name, hp }` to set the hit points for this scene |
|
||||
| `rewards` | Lined up unawarded (below) |
|
||||
| `wares` | For sale at the scene itself, with nobody behind it: a market, a vending machine |
|
||||
|
||||
A **reward** is exactly one of `gold`, `silver`, `copper`, `cash` (an amount),
|
||||
`weapon` or `item` (a name), with an optional `note`. A weapon or item can also
|
||||
have `quantity` and `level`.
|
||||
|
||||
A **ware** is `{ weapon | item, price }` with optional `currency` (`GOLD`, the
|
||||
default, `SILVER`, `COPPER` or `CASH`), `level` and `stock` (left out: no
|
||||
limit).
|
||||
|
||||
A reward's or ware's `level` defaults to the entry's own starting level, and
|
||||
cannot be below it.
|
||||
|
||||
### Limits
|
||||
|
||||
Text fields have the same length limits as the app's forms (for example 4,000
|
||||
characters for an encounter's DM notes and 10,000 for a note), so that
|
||||
everything a seed creates can still be edited on screen. The checker says
|
||||
which field is over.
|
||||
|
||||
## 5. Checking a seed
|
||||
|
||||
```bash
|
||||
npm run seeds:check
|
||||
```
|
||||
|
||||
lists every file in `/backend/seeds` with its code and what it holds, or
|
||||
everything wrong with it:
|
||||
|
||||
```
|
||||
✓ aldenfell.js — code ALDENF — Aldenfell
|
||||
24 weapons (16 starting), 31 items (10 starting), 45 spells (30 starting), 21 locations
|
||||
15 monsters, 13 NPCs (8 wares), 38 encounters (40 rewards, 9 wares), 23 notes
|
||||
✗ my-world.js
|
||||
npcs.0.desciption: Unrecognized key: "desciption"
|
||||
Encounter "The Mill at Night": there is no monster called "Gobblin"
|
||||
```
|
||||
|
||||
It checks the things that would otherwise only show up as a half-working
|
||||
campaign:
|
||||
|
||||
- A field name that is not one of the fields above (a typo).
|
||||
- A library key that is not in the library.
|
||||
- The same name twice in one pool.
|
||||
- An encounter, reward or ware that names a location, monster, NPC, weapon or
|
||||
item the file does not have.
|
||||
- A reward that is not exactly one thing, or gear handed out below its
|
||||
starting level.
|
||||
- An exchange rate with only one half.
|
||||
|
||||
`npm test` runs the same check on every seed in the folder.
|
||||
|
||||
## 6. The database seed
|
||||
|
||||
`npx prisma db seed` creates the admin account if it is missing, and nothing
|
||||
else. It never adds a campaign: worlds come from codes, in the app. See the
|
||||
README for the account it creates and `--reset`.
|
||||
|
||||
## 7. The worlds that come with the app
|
||||
|
||||
| Code | World | From |
|
||||
|---|---|---|
|
||||
| `ALDENF` | Aldenfell | The Aldenfell Campaign Book |
|
||||
| `HOLLOW` | Hollowcrown: The Rift Between Worlds | The Hollowcrown Dungeon Master's Book (V3) |
|
||||
|
||||
Change a world's code by editing `code` in its file.
|
||||
+144
-17
@@ -17,10 +17,11 @@ This describes the code as it stands. The built-in list is
|
||||
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)
|
||||
8. [Spell slots](#8-spell-slots)
|
||||
9. [Starting spells](#9-starting-spells)
|
||||
10. [Permissions](#10-permissions)
|
||||
11. [What is not modelled](#11-what-is-not-modelled)
|
||||
12. [The complete spell library](#12-the-complete-spell-library)
|
||||
|
||||
---
|
||||
|
||||
@@ -36,7 +37,10 @@ This describes the code as it stands. The built-in list is
|
||||
|
||||
## 2. The spell list
|
||||
|
||||
The list is the "Spell List" card on the campaign page (DM only).
|
||||
The list is the "Spells" part of the campaign page (DM only). Each spell is a
|
||||
short row: its name, level, damage and the start of what it does. The list
|
||||
has a search box, shows ten to a page, and clicking a row opens the spell's
|
||||
**pop-out**, which shows everything below and is where it is changed.
|
||||
|
||||
| Field | What it is |
|
||||
|---|---|
|
||||
@@ -45,17 +49,19 @@ The list is the "Spell List" card on the campaign page (DM only).
|
||||
| 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) |
|
||||
| Starting option | Whether a brand-new character may pick it in the builder (section 9) |
|
||||
| Revives | Whether it brings back the dead. A character who can cast one may revive a dead ally on their turn in a battle ([ENCOUNTERS.md](ENCOUNTERS.md), section 6). Ticked already on the library's Revivify and Raise Dead |
|
||||
| Casting time, range, duration | Stored for library spells but not shown on any screen |
|
||||
| Casting time, range, duration | Stored for library spells. Shown to the DM in the spell's pop-out on the campaign page, and nowhere else |
|
||||
|
||||
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, what it does and the two tick boxes), or from the library.
|
||||
- **Changing:** damage (the drop-down in the table) and the Revives and
|
||||
starting-option tick boxes. Name, level, school and description cannot be changed on screen
|
||||
- **Adding:** by hand with "+ Add Spell" (name, level, school, damage, what
|
||||
it does and the two tick boxes), or from the library. Both open in a
|
||||
pop-out. A spell added by hand opens its own pop-out, and "+ Add another
|
||||
spell" at its top goes straight back to an empty form.
|
||||
- **Changing:** in the spell's pop-out: damage (the drop-down) and the Revives
|
||||
and starting-option tick boxes, saved as they are changed. 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
|
||||
@@ -84,7 +90,7 @@ Before you add one, each row shows:
|
||||
- **what it does**, in a sentence.
|
||||
|
||||
Every library spell is listed in full in
|
||||
[section 11](#11-the-complete-spell-library).
|
||||
[section 12](#12-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:
|
||||
@@ -107,6 +113,10 @@ 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.
|
||||
|
||||
Each library spell can be added once. A spell the list already has by that
|
||||
name is left out of the library list, and comes back if the campaign's spell
|
||||
is renamed or deleted.
|
||||
|
||||
## 4. Granting spells to characters
|
||||
|
||||
On a character's sheet, the DM picks a spell from the list and clicks Grant.
|
||||
@@ -154,6 +164,35 @@ 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.
|
||||
|
||||
### How a spell lands in a battle
|
||||
|
||||
Each spell says how it is resolved when it is cast in an encounter
|
||||
([ENCOUNTERS.md](ENCOUNTERS.md), "Attacks and spells"). The DM sets it under
|
||||
**In a battle** when adding a spell, or on its pop-out:
|
||||
|
||||
| Setting | In an encounter |
|
||||
|---|---|
|
||||
| It just takes effect | No roll: it lands (Magic Missile, a buff) |
|
||||
| The caster rolls a spell attack | A d20 plus the caster's spell attack bonus against each target's AC |
|
||||
| A save with an ability, half damage on a success | Each target rolls a d20 plus their save bonus against the caster's spell save DC; a success takes half (Fireball) |
|
||||
| A save with an ability, nothing on a success | The same, but a success takes nothing (Sacred Flame, Hold Person) |
|
||||
|
||||
The library's spells come already set (Fire Bolt and Guiding Bolt as spell
|
||||
attacks; Fireball, Burning Hands, Hold Person and the like as saves), and
|
||||
copies already in a campaign were marked to match when this was added.
|
||||
Casting a spell of 1st level or higher this way spends a slot when the DM
|
||||
applies it: one of the spell's own level, or, when those are gone, the lowest
|
||||
slot above it that is left. **With no slot of its level or higher left the
|
||||
spell cannot be declared**: its button is off and marked "no slot left".
|
||||
**Cantrips never take a slot** and can be cast every turn, with every slot
|
||||
the caster has spent or with none to begin with. A spell above what
|
||||
the character's level allows is not offered at all (section on levels), and a
|
||||
weapon has to be equipped and within the character's level to attack with.
|
||||
|
||||
Wherever a character's spells are listed (the sheet, the encounter card, the
|
||||
attack picker) they run **cantrips first, then by spell level**, each with
|
||||
its level beside the name.
|
||||
|
||||
## 7. Spellcasting numbers
|
||||
|
||||
Shown only for classes with a spellcasting ability:
|
||||
@@ -173,7 +212,90 @@ Shown only for classes with a spellcasting ability:
|
||||
A character without a spellcasting class can still be granted spells, but has
|
||||
no save DC or attack bonus shown.
|
||||
|
||||
## 8. Starting spells
|
||||
## 8. Spell slots
|
||||
|
||||
A spell slot is one casting of a spell of that level or lower. Cantrips never
|
||||
use one. How many slots a character has is worked out from **class and
|
||||
level**; the site keeps count of how many are spent.
|
||||
|
||||
**Where.** The tracker is in the Spellcasting card on the sheet and in the
|
||||
character panel (the 🧙 button, on every page, so it is at hand in an
|
||||
encounter). The party overview has a "Spell slots" column for the whole party.
|
||||
Each slot level is a row of diamonds: filled is a slot still there to spend,
|
||||
empty is one that is spent.
|
||||
|
||||
**Who does what.**
|
||||
|
||||
- The character's **player** (and the DM) presses **Use** on a row when a
|
||||
spell is cast: one slot of that level is spent. That is all a player can do;
|
||||
a slot once used stays used.
|
||||
- Only the **DM** gives a slot back: by clicking a diamond (it sets how many
|
||||
are left; clicking the last filled one empties it), with "All back", or with
|
||||
a rest.
|
||||
- Casting a low spell with a higher slot is spending the higher slot. Nothing
|
||||
ties a slot to a spell: the site does not check which spell was cast.
|
||||
|
||||
**Getting them back.** The DM's 🛏 Rest… button ([CHARACTERS.md](CHARACTERS.md),
|
||||
section 7): a **long rest** gives every slot back; a **short rest** gives a
|
||||
warlock theirs. Levelling up with "⬆ Level Up…" gives a fresh set. Changing
|
||||
the Level field keeps what was spent, as far as the new level has those slots.
|
||||
|
||||
An **Artificer** casts from level 1 at half a full caster's pace, rounding up
|
||||
(2 slots at levels 1 and 2, 2nd-level slots at 5). An **Eldritch Knight** or
|
||||
**Arcane Trickster** casts from level 3 at a third of the pace, with
|
||||
Intelligence. A **multiclassed** character adds their casting classes up to a
|
||||
caster level on the full caster table, with a warlock's pact slots kept apart
|
||||
([CHARACTERS.md](CHARACTERS.md), "Multiclassing").
|
||||
|
||||
**Bard, Cleric, Druid, Sorcerer, Wizard** (back on a long rest):
|
||||
|
||||
| Character level | 1st | 2nd | 3rd | 4th | 5th |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | 2 | — | — | — | — |
|
||||
| 2 | 3 | — | — | — | — |
|
||||
| 3 | 4 | 2 | — | — | — |
|
||||
| 4 | 4 | 3 | — | — | — |
|
||||
| 5 | 4 | 3 | 2 | — | — |
|
||||
| 6 | 4 | 3 | 3 | — | — |
|
||||
| 7 | 4 | 3 | 3 | 1 | — |
|
||||
| 8 | 4 | 3 | 3 | 2 | — |
|
||||
| 9 | 4 | 3 | 3 | 3 | 1 |
|
||||
| 10 | 4 | 3 | 3 | 3 | 2 |
|
||||
|
||||
**Paladin, Ranger** (back on a long rest; none at level 1):
|
||||
|
||||
| Character level | 1st | 2nd | 3rd |
|
||||
|---|---|---|---|
|
||||
| 1 | — | — | — |
|
||||
| 2 | 2 | — | — |
|
||||
| 3–4 | 3 | — | — |
|
||||
| 5–6 | 4 | 2 | — |
|
||||
| 7–8 | 4 | 3 | — |
|
||||
| 9–10 | 4 | 3 | 2 |
|
||||
|
||||
**Warlock** (back on a short or long rest). All of a warlock's slots are the
|
||||
same level, and every spell cast with one is cast at that level:
|
||||
|
||||
| Character level | Slots | Slot level |
|
||||
|---|---|---|
|
||||
| 1 | 1 | 1st |
|
||||
| 2 | 2 | 1st |
|
||||
| 3–4 | 2 | 2nd |
|
||||
| 5–6 | 2 | 3rd |
|
||||
| 7–8 | 2 | 4th |
|
||||
| 9–10 | 2 | 5th |
|
||||
|
||||
Above level 10 the tables carry on as in standard 5e, up to 9th-level slots at
|
||||
character level 17 (a warlock has 3 slots from level 11 and 4 from level 17).
|
||||
Barbarians, fighters, monks and rogues have no slots, whatever spells they are
|
||||
granted.
|
||||
|
||||
Slots do not decide what a character may **know or prepare**: that is still
|
||||
section 5. A wizard of level 3 can be granted a 3rd-level spell and prepare it,
|
||||
but has no 3rd-level slot to cast it with until level 5. Holding the players
|
||||
to that is the DM's.
|
||||
|
||||
## 9. Starting spells
|
||||
|
||||
In the builder's equipment step a new character can pick spells that are:
|
||||
|
||||
@@ -184,7 +306,7 @@ In the builder's equipment step a new character can pick spells that are:
|
||||
The number allowed is the campaign's "starting spells" setting. Starting
|
||||
spells arrive unprepared.
|
||||
|
||||
## 9. Permissions
|
||||
## 10. Permissions
|
||||
|
||||
| Action | DM | Owning player | Other players |
|
||||
|---|---|---|---|
|
||||
@@ -194,11 +316,16 @@ spells arrive unprepared.
|
||||
| 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 |
|
||||
| Spend a spell slot | Yes | Yes | No |
|
||||
| Give a spell slot back | Yes | No | No |
|
||||
| See a character's spells | Yes | Yes | Yes |
|
||||
|
||||
## 10. What is not modelled
|
||||
## 11. What is not modelled
|
||||
|
||||
- Spell slots, and casting a spell at a higher level
|
||||
- Which spell a slot was spent on, and what casting at a higher level adds
|
||||
(the player adds the extra dice)
|
||||
- Sorcery points, and Arcane or Natural Recovery (the DM gives those slots
|
||||
back by hand)
|
||||
- Cantrip damage increasing at higher character levels
|
||||
- Limits on how many spells can be prepared or known
|
||||
- Concentration, components, rituals
|
||||
@@ -207,7 +334,7 @@ spells arrive unprepared.
|
||||
shown)
|
||||
- Applying spell damage to a target automatically
|
||||
|
||||
## 11. The complete spell library
|
||||
## 12. The complete spell library
|
||||
|
||||
Every spell "📚 From Library" offers, with the damage it arrives with.
|
||||
|
||||
|
||||
+28
-11
@@ -37,7 +37,11 @@ This describes the code as it stands. The formulas live in
|
||||
|
||||
## 2. The weapon pool
|
||||
|
||||
The pool is the "Weapons Pool" card on the campaign page (DM only).
|
||||
The pool is the "Weapons" part of the campaign page (DM only). It lists each
|
||||
weapon as a short row: its name, base damage, starting level and what it does
|
||||
while equipped. The list has a search box, shows ten to a page, and clicking a
|
||||
row opens the weapon's **pop-out**, which shows everything below and is where
|
||||
it is changed.
|
||||
|
||||
| Field | What it is |
|
||||
|---|---|
|
||||
@@ -48,17 +52,23 @@ The pool is the "Weapons Pool" card on the campaign page (DM only).
|
||||
| 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 |
|
||||
| Properties, range | Stored for library weapons (light, thrown, 20/60 ft…). Shown in the weapon's pop-out, and not used anywhere |
|
||||
| Effects | What it does to whoever has it equipped: bonuses and penalties to the sheet's numbers, and a note. Works exactly as for items ([ITEMS.md](ITEMS.md), section 5) |
|
||||
|
||||
- **Adding:** by hand with the "+ Add Weapon" form, or from the library.
|
||||
- **Effects:** the "Effects" button on a weapon's row. A defending blade can
|
||||
give +1 AC, a heavy maul −5 speed. They count only while the weapon is
|
||||
equipped, and do not change its own attack or damage.
|
||||
- **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
|
||||
- **Adding:** by hand with "+ Add Weapon", or from the library. Both open in
|
||||
a pop-out. A weapon added by hand opens its own pop-out straight away, to
|
||||
set what it does; "+ Add another weapon" at its top goes straight back to
|
||||
an empty form.
|
||||
- **Effects:** under "While equipped" in the weapon's pop-out, saved with
|
||||
"Save Effects". A defending blade can give +1 AC, a heavy maul −5 speed.
|
||||
They count only while the weapon is equipped, and do not change its own
|
||||
attack or damage.
|
||||
- **Changing:** starting level, growth and the starting-option tick box are
|
||||
changed in the pop-out, and saved as they are changed. Name, damage, type
|
||||
and ability cannot be changed on screen once created (the API accepts it);
|
||||
remove and re-add instead.
|
||||
- **Removing:** "Remove from campaign" at the foot of the pop-out, after a
|
||||
confirmation. 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.
|
||||
@@ -86,6 +96,10 @@ 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).
|
||||
|
||||
Each library weapon can be added once. A weapon the pool already has by that
|
||||
name is left out of the library list, and comes back if the pool's weapon is
|
||||
renamed or deleted.
|
||||
|
||||
## 4. Giving weapons to characters
|
||||
|
||||
On a character's sheet, the DM picks a weapon from the pool and clicks Give.
|
||||
@@ -95,7 +109,10 @@ On a character's sheet, the DM picks a weapon from the pool and clicks Give.
|
||||
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, or the DM, ticks **Equipped**.
|
||||
- The owning player, or the DM, ticks **Equipped**. While the character is in
|
||||
a battle in progress, a player can only change it as the battle begins or on
|
||||
their own turn after their attack has landed
|
||||
([ENCOUNTERS.md](ENCOUNTERS.md), section 5); the DM always can.
|
||||
- **Only what is equipped counts.** A weapon has to be equipped to be used
|
||||
in an encounter, and gear only gives its effects while equipped. What is
|
||||
not equipped stays in the pack: still the character's, still listed on the
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "1.11.1",
|
||||
"version": "1.31.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -18,12 +18,14 @@
|
||||
"socket.io-client": "^4.8.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/compression": "^1.8.1",
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.18",
|
||||
"@types/react-dom": "^19.2.7",
|
||||
"@vitejs/plugin-react": "^6.1.1",
|
||||
"compression": "^1.8.2",
|
||||
"oxlint": "^1.81.0",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript": "~7.0.2",
|
||||
"vite": "^8.3.0"
|
||||
}
|
||||
}
|
||||
|
||||
+30
-24
@@ -1,35 +1,41 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { Navigate, Route, Routes } from 'react-router-dom';
|
||||
import { Layout } from './components/Layout';
|
||||
import { ProtectedRoute } from './components/ProtectedRoute';
|
||||
import { LoginPage } from './pages/LoginPage';
|
||||
import { RegisterPage } from './pages/RegisterPage';
|
||||
import { CampaignListPage } from './pages/CampaignListPage';
|
||||
import { CampaignHomePage } from './pages/CampaignHomePage';
|
||||
import { PartyOverviewPage } from './pages/PartyOverviewPage';
|
||||
import { CharacterSheetPage } from './pages/CharacterSheetPage';
|
||||
import { CharacterBuilderPage } from './pages/CharacterBuilderPage';
|
||||
import { EncounterPage } from './pages/EncounterPage';
|
||||
import { AccountPage } from './pages/AccountPage';
|
||||
|
||||
// Each page is its own file to download, fetched the first time it is opened,
|
||||
// so signing in does not wait on the encounter tracker or the character builder.
|
||||
const RegisterPage = lazy(() => import('./pages/RegisterPage').then((m) => ({ default: m.RegisterPage })));
|
||||
const CampaignListPage = lazy(() => import('./pages/CampaignListPage').then((m) => ({ default: m.CampaignListPage })));
|
||||
const CampaignHomePage = lazy(() => import('./pages/CampaignHomePage').then((m) => ({ default: m.CampaignHomePage })));
|
||||
const PartyOverviewPage = lazy(() => import('./pages/PartyOverviewPage').then((m) => ({ default: m.PartyOverviewPage })));
|
||||
const CharacterSheetPage = lazy(() => import('./pages/CharacterSheetPage').then((m) => ({ default: m.CharacterSheetPage })));
|
||||
const CharacterBuilderPage = lazy(() => import('./pages/CharacterBuilderPage').then((m) => ({ default: m.CharacterBuilderPage })));
|
||||
const EncounterPage = lazy(() => import('./pages/EncounterPage').then((m) => ({ default: m.EncounterPage })));
|
||||
const AccountPage = lazy(() => import('./pages/AccountPage').then((m) => ({ default: m.AccountPage })));
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/register" element={<RegisterPage />} />
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route element={<Layout />}>
|
||||
<Route path="/" element={<Navigate to="/campaigns" replace />} />
|
||||
<Route path="/campaigns" element={<CampaignListPage />} />
|
||||
<Route path="/campaigns/:campaignId" element={<CampaignHomePage />} />
|
||||
<Route path="/campaigns/:campaignId/party" element={<PartyOverviewPage />} />
|
||||
<Route path="/characters/:characterId" element={<CharacterSheetPage />} />
|
||||
<Route path="/characters/:characterId/build" element={<CharacterBuilderPage />} />
|
||||
<Route path="/encounters/:encounterId" element={<EncounterPage />} />
|
||||
<Route path="/account" element={<AccountPage />} />
|
||||
<Suspense fallback={null}>
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/register" element={<RegisterPage />} />
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route element={<Layout />}>
|
||||
<Route path="/" element={<Navigate to="/campaigns" replace />} />
|
||||
<Route path="/campaigns" element={<CampaignListPage />} />
|
||||
<Route path="/campaigns/:campaignId" element={<CampaignHomePage />} />
|
||||
<Route path="/campaigns/:campaignId/party" element={<PartyOverviewPage />} />
|
||||
<Route path="/characters/:characterId" element={<CharacterSheetPage />} />
|
||||
<Route path="/characters/:characterId/build" element={<CharacterBuilderPage />} />
|
||||
<Route path="/encounters/:encounterId" element={<EncounterPage />} />
|
||||
<Route path="/account" element={<AccountPage />} />
|
||||
</Route>
|
||||
</Route>
|
||||
</Route>
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+294
-24
@@ -1,13 +1,19 @@
|
||||
import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query';
|
||||
import { apiClient } from './client';
|
||||
import type {
|
||||
Ability,
|
||||
ArmorType,
|
||||
ActionPatch,
|
||||
ActionSource,
|
||||
BuildOptions,
|
||||
Campaign,
|
||||
CharacterClass,
|
||||
CampaignLibrary,
|
||||
CampaignMemberSummary,
|
||||
CharacterDetail,
|
||||
CharacterSummary,
|
||||
Currency,
|
||||
DiceRollRecord,
|
||||
DiceMode,
|
||||
Encounter,
|
||||
EncounterMode,
|
||||
@@ -15,12 +21,19 @@ import type {
|
||||
GearEffect,
|
||||
GoldTransaction,
|
||||
Item,
|
||||
LevelUpApproval,
|
||||
LevelUpPlan,
|
||||
Location,
|
||||
MulticlassReference,
|
||||
Monster,
|
||||
Note,
|
||||
Npc,
|
||||
ProgressionLevel,
|
||||
SaleOffer,
|
||||
QuickStats,
|
||||
RestResult,
|
||||
RestType,
|
||||
RollSpec,
|
||||
Spell,
|
||||
Weapon,
|
||||
} from './types';
|
||||
@@ -62,6 +75,16 @@ export function useCreateCampaign() {
|
||||
});
|
||||
}
|
||||
|
||||
// A ready-made world (a seed file on the server) as a new campaign, by its code.
|
||||
export function useCreateCampaignFromSeed() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (code: string) =>
|
||||
(await apiClient.post<{ campaign: Campaign }>('/campaigns/from-seed', { code })).data.campaign,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaigns'] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateCampaign(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
@@ -156,7 +179,7 @@ export function useCharacter(characterId: string | undefined) {
|
||||
export function usePatchCharacter(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: Partial<Omit<CharacterDetail, 'gold'>>) =>
|
||||
mutationFn: async (data: Partial<Omit<CharacterDetail, 'gold'>> & { hitDiceUsed?: number }) =>
|
||||
(await apiClient.patch<{ character: CharacterDetail }>(`/characters/${characterId}`, data)).data.character,
|
||||
onSuccess: (character) => {
|
||||
qc.setQueryData(['character', characterId], character);
|
||||
@@ -187,6 +210,111 @@ export function useDeathSave(characterId: string) {
|
||||
});
|
||||
}
|
||||
|
||||
// The slot tracker. Spending a slot is the player's (or the DM's); setting how
|
||||
// many are spent, and giving them all back, are the DM's alone.
|
||||
export type SpellSlotAction = { action: 'use'; level: number } | { action: 'set'; level: number; used: number } | { action: 'restore' };
|
||||
|
||||
export function useSpellSlots(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: SpellSlotAction) =>
|
||||
(await apiClient.post<{ character: CharacterDetail }>(`/characters/${characterId}/spell-slots`, data)).data.character,
|
||||
onSuccess: (character) => {
|
||||
invalidateCharacter(qc, characterId); // the sheet and its quick stats
|
||||
qc.invalidateQueries({ queryKey: ['campaign', character.campaignId, 'characters'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// The class counters. Spending is for the character's own player and the DM,
|
||||
// one use at a time or `amount` from a pool; setting how many are spent, and
|
||||
// giving them all back, are the DM's alone.
|
||||
export type ResourceAction = { action: 'use'; key: string; amount?: number } | { action: 'set'; key: string; used: number } | { action: 'restore' };
|
||||
|
||||
export function useResources(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: ResourceAction) =>
|
||||
(await apiClient.post<{ character: CharacterDetail }>(`/characters/${characterId}/resources`, data)).data.character,
|
||||
onSuccess: (character) => {
|
||||
invalidateCharacter(qc, characterId);
|
||||
qc.invalidateQueries({ queryKey: ['encounter'] }); // a character combatant shows its counters
|
||||
qc.invalidateQueries({ queryKey: ['campaign', character.campaignId, 'characters'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Inspiration, exhaustion and conditions. The DM sets all three; the
|
||||
// character's own player may spend inspiration (set it to false).
|
||||
export function useCharacterState(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: { inspiration?: boolean; exhaustion?: number; conditions?: string[] }) =>
|
||||
(await apiClient.patch<{ character: CharacterDetail }>(`/characters/${characterId}`, data)).data.character,
|
||||
onSuccess: (character) => {
|
||||
invalidateCharacter(qc, characterId);
|
||||
qc.invalidateQueries({ queryKey: ['encounter'] }); // a character combatant shows all of it
|
||||
qc.invalidateQueries({ queryKey: ['campaign', character.campaignId, 'characters'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// What a character's next level brings. DM only.
|
||||
// `toClass`: the plan for a level in that class (multiclassing); the first class when null.
|
||||
export function useLevelUpPlan(characterId: string, enabled: boolean, toClass: CharacterClass | null = null) {
|
||||
return useQuery({
|
||||
queryKey: ['character', characterId, 'level-up', toClass],
|
||||
enabled,
|
||||
gcTime: 0, // never open on the plan for a level the character has already reached
|
||||
queryFn: async () =>
|
||||
(await apiClient.get<{ plan: LevelUpPlan }>(`/characters/${characterId}/level-up`, { params: toClass ? { class: toClass } : {} })).data.plan,
|
||||
});
|
||||
}
|
||||
|
||||
// Takes the character up one level, with the choices that go with it.
|
||||
export function useLevelUp(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: { characterClass?: CharacterClass; subclass?: string; boon?: string; weaponId?: string | null; spellIds?: string[]; hpRoll?: number }) =>
|
||||
(await apiClient.post<{ character: CharacterDetail; hpRolled: number | null }>(`/characters/${characterId}/level-up`, data)).data,
|
||||
onSuccess: ({ character }) => {
|
||||
invalidateCharacter(qc, characterId);
|
||||
qc.invalidateQueries({ queryKey: ['encounter'] }); // a character combatant shows the sheet's HP
|
||||
qc.invalidateQueries({ queryKey: ['campaign', character.campaignId, 'characters'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// A short or long rest for any of the party at once. On a short rest each
|
||||
// character spends `hitDice` Hit Dice; `rolled` is what they added up to at
|
||||
// the table, and left out the site rolls them.
|
||||
export function useRest(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: { type: RestType; characters: { characterId: string; hitDice?: number; rolled?: number | null }[] }) =>
|
||||
(await apiClient.post<{ type: RestType; results: RestResult[] }>(`/campaigns/${campaignId}/rest`, data)).data,
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['character'] });
|
||||
qc.invalidateQueries({ queryKey: ['encounter'] });
|
||||
qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'characters'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// The DM approves a level for any of the party at once (or takes an approval
|
||||
// back); each character's player then takes theirs.
|
||||
export function useApproveLevelUps(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: { characterIds: string[]; revoke?: boolean }) =>
|
||||
(await apiClient.post<{ revoke: boolean; results: LevelUpApproval[] }>(`/campaigns/${campaignId}/level-up`, data)).data,
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['character'] });
|
||||
qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'characters'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteCharacter(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
@@ -258,6 +386,53 @@ export function useBuildOptions() {
|
||||
});
|
||||
}
|
||||
|
||||
// The latest rolls at the table that this member may see, newest first.
|
||||
export function useRolls(campaignId: string | null | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['campaign', campaignId, 'rolls'],
|
||||
enabled: Boolean(campaignId),
|
||||
queryFn: async () => (await apiClient.get<{ rolls: DiceRollRecord[] }>(`/campaigns/${campaignId}/rolls`, { params: { limit: 40 } })).data.rolls,
|
||||
});
|
||||
}
|
||||
|
||||
// Makes a roll at the table: the server rolls it (or checks dice typed in),
|
||||
// keeps it and tells the table.
|
||||
export function useRoll(campaignId: string | null | undefined) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (spec: RollSpec) => (await apiClient.post<{ roll: DiceRollRecord }>(`/campaigns/${campaignId}/rolls`, spec)).data.roll,
|
||||
onSuccess: (roll) => {
|
||||
// Shown at once in the feed, without waiting for the server to say so.
|
||||
qc.setQueryData<DiceRollRecord[]>(['campaign', campaignId, 'rolls'], (rolls) => (rolls && !rolls.some((r) => r.id === roll.id) ? [roll, ...rolls] : rolls));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Multiclassing requirements and the suggested routes.
|
||||
export function useMulticlassReference(enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: ['multiclass-reference'],
|
||||
enabled,
|
||||
staleTime: Infinity,
|
||||
queryFn: async () => (await apiClient.get<MulticlassReference>('/reference/multiclass')).data,
|
||||
});
|
||||
}
|
||||
|
||||
// What each level from 1 to 20 gives a class, with a subclass's lines when one is given.
|
||||
export function useProgression(characterClass: CharacterClass | null | undefined, subclass?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['progression', characterClass, subclass ?? null],
|
||||
enabled: Boolean(characterClass),
|
||||
staleTime: Infinity, // rules: they never change while the app is open
|
||||
queryFn: async () =>
|
||||
(
|
||||
await apiClient.get<{ levels: ProgressionLevel[] }>('/reference/progression', {
|
||||
params: { class: characterClass, ...(subclass ? { subclass } : {}) },
|
||||
})
|
||||
).data.levels,
|
||||
});
|
||||
}
|
||||
|
||||
function invalidateCharacter(qc: ReturnType<typeof useQueryClient>, characterId: string) {
|
||||
qc.invalidateQueries({ queryKey: ['character', characterId] });
|
||||
}
|
||||
@@ -473,6 +648,12 @@ export function usePatchPoolEntry(campaignId: string, pool: Pool) {
|
||||
exchangeCash?: number | null;
|
||||
effects?: GearEffect[];
|
||||
effectNote?: string | null;
|
||||
// A spell: how it lands in a battle. An NPC: where they are found.
|
||||
attackRoll?: boolean;
|
||||
saveAbility?: Ability | null;
|
||||
halfOnSave?: boolean;
|
||||
locationId?: string | null;
|
||||
armorType?: ArmorType | null; // an item: what kind of armor it is, if any
|
||||
}) =>
|
||||
(await apiClient.patch(`/campaigns/${campaignId}/${pool}/${id}`, data)).data,
|
||||
onSuccess: () => {
|
||||
@@ -666,7 +847,8 @@ export function useCampaignEncounters(campaignId: string | undefined) {
|
||||
export function useCreateEncounter(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: { name: string; mode?: EncounterMode }) =>
|
||||
// Where it goes in the campaign's order: the top, the bottom (the default), or straight after another.
|
||||
mutationFn: async (data: { name: string; mode?: EncounterMode; position?: 'TOP' | 'BOTTOM'; afterEncounterId?: string; placeIds?: string[] }) =>
|
||||
(await apiClient.post<{ encounter: Encounter }>(`/campaigns/${campaignId}/encounters`, data)).data.encounter,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'encounters'] }),
|
||||
});
|
||||
@@ -725,12 +907,21 @@ export function useEncounter(encounterId: string | undefined) {
|
||||
});
|
||||
}
|
||||
|
||||
// Every change to an encounter is answered with the encounter as this viewer
|
||||
// sees it, so the cache takes that as it is: no second request for what just
|
||||
// came back.
|
||||
function keepEncounter(qc: QueryClient, encounterId: string, data: unknown) {
|
||||
const encounter = (data as { encounter?: Encounter } | undefined)?.encounter;
|
||||
if (encounter) qc.setQueryData(['encounter', encounterId], encounter);
|
||||
else qc.invalidateQueries({ queryKey: ['encounter', encounterId] });
|
||||
}
|
||||
|
||||
export function useAddParticipant(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: { characterId?: string; monsterId?: string; npcId?: string; displayName?: string; initiativeRoll?: number }) =>
|
||||
mutationFn: async (data: { characterId?: string; monsterId?: string; npcId?: string; displayName?: string; initiativeRoll?: number; count?: number }) =>
|
||||
(await apiClient.post(`/encounters/${encounterId}/participants`, data)).data,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
|
||||
onSuccess: (data) => keepEncounter(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -739,7 +930,7 @@ export function usePatchParticipant(encounterId: string) {
|
||||
return useMutation({
|
||||
mutationFn: async ({ participantId, ...data }: Partial<EncounterParticipant> & { participantId: string }) =>
|
||||
(await apiClient.patch(`/encounters/${encounterId}/participants/${participantId}`, data)).data,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
|
||||
onSuccess: (data) => keepEncounter(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -747,8 +938,17 @@ export function useRemoveParticipant(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (participantId: string) =>
|
||||
apiClient.delete(`/encounters/${encounterId}/participants/${participantId}`),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
|
||||
(await apiClient.delete(`/encounters/${encounterId}/participants/${participantId}`)).data,
|
||||
onSuccess: (data) => keepEncounter(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
// Rolls a d20 for every monster and NPC that has no initiative roll yet. DM only.
|
||||
export function useRollInitiative(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async () => (await apiClient.post<{ rolled: number }>(`/encounters/${encounterId}/roll-initiative`)).data,
|
||||
onSuccess: (data) => keepEncounter(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -756,7 +956,7 @@ export function useAdvanceRound(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async () => (await apiClient.post(`/encounters/${encounterId}/advance-round`)).data,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
|
||||
onSuccess: (data) => keepEncounter(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -771,8 +971,8 @@ export function usePatchEncounter(encounterId: string) {
|
||||
dmNotes?: string | null;
|
||||
locationId?: string | null;
|
||||
}) => (await apiClient.patch(`/encounters/${encounterId}`, data)).data,
|
||||
onSuccess: (_data, variables) => {
|
||||
qc.invalidateQueries({ queryKey: ['encounter', encounterId] });
|
||||
onSuccess: (data, variables) => {
|
||||
keepEncounter(qc, encounterId, data);
|
||||
// The campaign page lists encounters by name, mode and status, and an
|
||||
// encounter in progress carries its characters to its location.
|
||||
if (variables.status || variables.mode || variables.name || variables.locationId !== undefined) {
|
||||
@@ -790,7 +990,62 @@ export function useSetTargets(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (participantIds: string[]) => (await apiClient.put(`/encounters/${encounterId}/targets`, { participantIds })).data,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
|
||||
onSuccess: (data) => keepEncounter(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
// Free roam: the DM sets the places the party can go to in the scene.
|
||||
export function useSetPlaces(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (locationIds: string[]) => (await apiClient.put(`/encounters/${encounterId}/places`, { locationIds })).data,
|
||||
onSuccess: (data) => keepEncounter(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
// Free roam: a character goes to one of the scene's places.
|
||||
export function useVisitPlace(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: { characterId: string; locationId: string }) => (await apiClient.post(`/encounters/${encounterId}/visit`, data)).data,
|
||||
onSuccess: (data, { characterId }) => {
|
||||
keepEncounter(qc, encounterId, data);
|
||||
qc.invalidateQueries({ queryKey: ['character', characterId] });
|
||||
qc.invalidateQueries({ queryKey: ['campaign'] }); // the places a player knows, and where the party is
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Declares an attack or a spell: by whoever is on turn unless an actor is
|
||||
// named, at the targets marked unless some are given.
|
||||
export function useDeclareAction(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: { source: ActionSource; actorParticipantId?: string; targetIds?: string[]; hidden?: boolean }) =>
|
||||
(await apiClient.post(`/encounters/${encounterId}/actions`, data)).data,
|
||||
onSuccess: (data) => keepEncounter(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
// Puts a roll, a ruling or the damage into an action still being resolved.
|
||||
export function usePatchAction(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async ({ actionId, ...data }: ActionPatch & { actionId: string }) => (await apiClient.patch(`/encounters/${encounterId}/actions/${actionId}`, data)).data,
|
||||
onSuccess: (data) => keepEncounter(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
// The DM lets an action land. Answers with a save to call for anyone hurt while concentrating.
|
||||
export function useApplyAction(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (actionId: string) =>
|
||||
(await apiClient.post<{ concentration: { name: string; damage: number; dc: number }[]; slotNote: string | null }>(`/encounters/${encounterId}/actions/${actionId}/apply`)).data,
|
||||
onSuccess: (data) => {
|
||||
keepEncounter(qc, encounterId, data);
|
||||
qc.invalidateQueries({ queryKey: ['character'] }); // HP, and a spell slot spent
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -800,8 +1055,8 @@ export function useReviveParticipant(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (participantId: string) => (await apiClient.post(`/encounters/${encounterId}/participants/${participantId}/revive`)).data,
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['encounter', encounterId] });
|
||||
onSuccess: (data) => {
|
||||
keepEncounter(qc, encounterId, data);
|
||||
qc.invalidateQueries({ queryKey: ['character'] }); // the revived character's sheet
|
||||
},
|
||||
});
|
||||
@@ -811,7 +1066,7 @@ 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] }),
|
||||
onSuccess: (data) => keepEncounter(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -828,27 +1083,42 @@ 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] }),
|
||||
onSuccess: (data) => keepEncounter(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
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] }),
|
||||
mutationFn: async (rewardId: string) => (await apiClient.delete(`/encounters/${encounterId}/rewards/${rewardId}`)).data,
|
||||
onSuccess: (data) => keepEncounter(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
// Awarding is what actually changes the character: a gold ledger entry, or
|
||||
// the weapon/item added to what they hold.
|
||||
// Hands out the encounter's XP, shared evenly between the characters in it:
|
||||
// what its monsters are worth, or the amount given. Once only. DM only.
|
||||
export function useAwardXp(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (xp?: number) =>
|
||||
(await apiClient.post<{ xp: number; share: number; awardedTo: string[] }>(`/encounters/${encounterId}/award-xp`, xp ? { xp } : {})).data,
|
||||
onSuccess: (data) => {
|
||||
keepEncounter(qc, encounterId, data);
|
||||
qc.invalidateQueries({ queryKey: ['character'] });
|
||||
qc.invalidateQueries({ queryKey: ['campaign'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
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] });
|
||||
onSuccess: (data) => {
|
||||
keepEncounter(qc, encounterId, data);
|
||||
qc.invalidateQueries({ queryKey: ['character'] });
|
||||
qc.invalidateQueries({ queryKey: ['campaign'] });
|
||||
},
|
||||
@@ -881,7 +1151,7 @@ export function useCreateNpc(campaignId: string) {
|
||||
// in progress, characters in the scene change money and buy
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
export type NewWare = ({ npcId: string } | { encounterId: string }) &
|
||||
export type NewWare = ({ npcId: string } | { encounterId: string } | { locationId: string }) &
|
||||
({ weaponId: string } | { itemId: string }) & { price: number; currency: Currency; level?: number; stock: number | null };
|
||||
|
||||
// Wares reach the screen inside the NPC list and inside each encounter.
|
||||
@@ -917,8 +1187,8 @@ export function useDeleteWare(campaignId: string) {
|
||||
}
|
||||
|
||||
// Both change what a character holds, so the sheet and the party list refresh too.
|
||||
function invalidateAfterTrade(qc: QueryClient, encounterId: string) {
|
||||
qc.invalidateQueries({ queryKey: ['encounter', encounterId] });
|
||||
function invalidateAfterTrade(qc: QueryClient, encounterId: string, data: unknown) {
|
||||
keepEncounter(qc, encounterId, data);
|
||||
qc.invalidateQueries({ queryKey: ['character'] });
|
||||
qc.invalidateQueries({ queryKey: ['campaign'] });
|
||||
}
|
||||
@@ -929,7 +1199,7 @@ export function useExchangeWithNpc(encounterId: string) {
|
||||
return useMutation({
|
||||
mutationFn: async (data: { characterId: string; npcId: string; from: 'GOLD' | 'CASH'; amount: number }) =>
|
||||
(await apiClient.post<{ received: number; currency: Currency }>(`/encounters/${encounterId}/exchange`, data)).data,
|
||||
onSuccess: () => invalidateAfterTrade(qc, encounterId),
|
||||
onSuccess: (data) => invalidateAfterTrade(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -938,7 +1208,7 @@ export function useBuyWare(encounterId: string) {
|
||||
return useMutation({
|
||||
mutationFn: async ({ wareId, ...data }: { wareId: string; characterId: string; quantity?: number }) =>
|
||||
(await apiClient.post(`/encounters/${encounterId}/wares/${wareId}/buy`, data)).data,
|
||||
onSuccess: () => invalidateAfterTrade(qc, encounterId),
|
||||
onSuccess: (data) => invalidateAfterTrade(qc, encounterId, data),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user