V1.27.0: battles that run themselves: track, targets, hit or miss, saves, auto-rolls

- Turn-order track: names coloured by PC, NPC or monster, this round, a flag
  where it ends, and the next round
- Target by clicking a name on the track, the card, or keys 1-9; whoever is
  on turn and every target show what they have in hand
- Attacks and spells are declared, rolled and applied: type or roll the d20
  and the app says hit, miss or critical; a save spell asks each target for
  its save against the caster's DC; the DM overrules anything and applies
- Critical damage by the campaign's rule; a spell spends its slot; a
  concentration save is called for
- Auto-rolled monster and NPC attacks: aimed (weighted), rolled, and offered
  to the DM to accept, edit or discard; hidden from players until accepted
- Monsters can have named attacks and multiattacks; spells say how they land
- A "What now" line tells the DM (and each player) what the scene waits on

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 09:14:04 +02:00
co-authored by Claude Opus 5.5
parent 8811f14732
commit 9b3637576d
29 changed files with 2693 additions and 38 deletions
+197 -5
View File
@@ -25,11 +25,14 @@ import {
useDeleteReward,
useAwardReward,
useRolls,
useApplyAction,
type NewReward,
} from '../api/queries';
import { useCampaignSocket } from '../hooks/useCampaignSocket';
import { useAuth } from '../auth/useAuth';
import { RollFeed } from '../components/RollFeed';
import { InitiativeTrack } from '../components/encounter/InitiativeTrack';
import { ActionCard, ActionComposer, RecentActions } from '../components/encounter/ActionPanel';
import { Spinner, ErrorBanner } from '../components/Spinner';
import { NumberInput } from '../components/NumberInput';
import { HpBar } from '../components/HpBar';
@@ -51,6 +54,7 @@ import type {
CharacterSummary,
Currency,
Encounter,
EncounterAction,
EncounterMode,
EncounterParticipant,
EncounterReward,
@@ -298,6 +302,50 @@ function HeadlineChips({ participant: p }: { participant: EncounterParticipant }
);
}
// What a combatant is fighting with right now, set apart so it catches the
// eye: a character's equipped weapons, or a creature's attacks. Shown on the
// card of whoever is on turn and of anyone targeted. A player is not sent a
// monster's attacks, so for them a monster shows nothing here.
function InHand({ participant: p }: { participant: EncounterParticipant }) {
const info = p.characterCombatInfo;
if (info) {
return (
<div className="in-hand" title="Equipped: what they fight with">
<span className="in-hand-label">In hand</span>
{info.weapons.length === 0 && <span className="combatant-sub">nothing equipped</span>}
{info.weapons.map((w) => (
<span key={w.characterWeaponId} className="in-hand-weapon">
⚔ {w.name}{' '}
<span className="mono">
{fmtMod(w.attackBonus)} · {w.damageDice} {fmtMod(w.damageBonus)} {w.damageType}
</span>
</span>
))}
</div>
);
}
const named = (p.monster?.attacks ?? []).filter((a) => a.name);
const stats = p.monster ?? p.npc;
const single = stats && (stats.attackBonus != null || stats.damageDice) ? [{ name: 'Attack', attackBonus: stats.attackBonus ?? 0, damageDice: stats.damageDice, count: 1 }] : [];
const attacks = named.length > 0 ? named : single;
if (attacks.length === 0) return null;
return (
<div className="in-hand" title="What it attacks with">
<span className="in-hand-label">Attacks</span>
{attacks.map((a, i) => (
<span key={i} className="in-hand-weapon">
⚔ {a.name}
{(a.count ?? 1) > 1 ? ` ×${a.count}` : ''}{' '}
<span className="mono">
{fmtMod(a.attackBonus)}
{a.damageDice ? ` · ${a.damageDice}` : ''}
</span>
</span>
))}
</div>
);
}
// "2 rd" on a condition that wears off by itself.
function roundsNote(p: EncounterParticipant, condition: string): string | undefined {
const left = p.conditionRounds?.[condition];
@@ -601,6 +649,7 @@ function CombatantCard({
</div>
<HeadlineChips participant={p} />
{(isActive || isTargeted) && <InHand participant={p} />}
{/* An NPC's description is what players are here for, so it is never tucked away. */}
{npc?.description && <p style={{ margin: '0.5rem 0 0', whiteSpace: 'pre-wrap' }}>{npc.description}</p>}
@@ -864,6 +913,68 @@ function AttackBar({
);
}
// The one thing the scene is waiting on, in a sentence: for the DM, what to
// do next; for a player, what is theirs to do. `urgent` when it is a roll or a
// ruling that holds the fight up. Null when there is nothing to say.
function whatNow({
encounter,
isDM,
active,
targets,
actions,
myTurn,
unrolled,
userId,
}: {
encounter: Encounter;
isDM: boolean;
active: EncounterParticipant | undefined;
targets: EncounterParticipant[];
actions: EncounterAction[];
myTurn: boolean;
unrolled: number;
userId: string | undefined;
}): { text: string; urgent: boolean } | null {
if (encounter.mode !== 'BATTLE') return null;
const names = (list: { name: string }[]) => list.map((t) => t.name).join(', ');
if (!isDM) {
const mine = (encounter.participants ?? []).filter((p) => p.character?.userId === userId).map((p) => p.id);
const save = actions.find((a) => a.kind === 'SAVE' && a.targets.some((t) => t.d20 == null && mine.includes(t.participantId)));
if (save) return { text: `${save.actorName}'s ${save.name}: make a ${save.detail.saveAbility} saving throw and enter your d20.`, urgent: true };
const own = actions.find((a) => a.actorParticipantId != null && mine.includes(a.actorParticipantId));
if (own?.needsRolls) return { text: `Roll your d20 for ${own.name} against ${names(own.targets.filter((t) => t.d20 == null))}.`, urgent: true };
if (own?.needsDamage) return { text: `It hits! Roll the damage for ${own.name}.`, urgent: true };
if (own?.ready) return { text: `${own.name} is ready: your DM lets it land.`, urgent: false };
if (myTurn) return targets.length === 0 ? { text: 'Your turn! Pick a target: click a name on the track above.', urgent: true } : { text: `Your turn: choose what you attack ${names(targets.map((t) => ({ name: t.displayName })))} with.`, urgent: true };
return null;
}
if (encounter.status === 'PLANNING') {
return { text: unrolled > 0 ? `Setting up: ${unrolled} still to roll initiative. Then press Begin Battle.` : 'Everyone has rolled initiative. Press Begin Battle.', urgent: false };
}
if (encounter.status !== 'ACTIVE') return null;
const pending = actions[0];
if (pending) {
const who = `${pending.actorName}'s ${pending.name}`;
const waiting = pending.targets.filter((t) => !t.outcome);
if (pending.needsRolls > 0) {
return pending.kind === 'SAVE'
? { text: `${who}: ${waiting.length} saving throw${waiting.length === 1 ? '' : 's'} to enter (${pending.detail.saveAbility}, DC ${pending.detail.saveDC}) for ${names(waiting)}.`, urgent: true }
: { text: `${who}: enter the d20 against ${names(waiting)}${waiting[0]?.ac != null ? ` (AC ${waiting[0].ac + waiting[0].penalty})` : ''}.`, urgent: true };
}
if (pending.needsDamage) return { text: `${who} hits: roll or enter the damage.`, urgent: true };
const result = pending.targets.map((t) => `${t.name}: ${t.outcome?.toLowerCase() ?? '—'}${t.finalDamage ? ` for ${t.finalDamage}` : ''}`).join('; ');
return { text: `${who} is ready (${result}). ${pending.auto ? 'Accept, change or discard it.' : 'Apply it, or overrule anything first.'}`, urgent: true };
}
if (unrolled > 0) return { text: `${unrolled} combatant${unrolled === 1 ? ' has' : 's have'} no initiative roll yet.`, urgent: false };
if (!active) return null;
if (targets.length === 0) {
return active.character
? { text: `${active.displayName}'s turn: waiting for them to pick a target (or pick one for them: click a name).`, urgent: false }
: { text: `${active.displayName}'s turn: click a name to pick its target, or press Next Turn.`, urgent: false };
}
return { text: `${active.displayName} → ${names(targets.map((t) => ({ name: t.displayName })))}: choose the attack below, or apply damage by hand.`, urgent: false };
}
const RATING_LABELS = { TRIVIAL: 'Trivial', EASY: 'Easy', MEDIUM: 'Medium', HARD: 'Hard', DEADLY: 'Deadly' } as const;
const RATING_BADGES = { TRIVIAL: '', EASY: 'badge-friendly', MEDIUM: 'badge-dm', HARD: 'badge-hostile', DEADLY: 'badge-hostile' } as const;
@@ -1202,6 +1313,7 @@ export function EncounterPage() {
const nextTurn = useNextTurn(encounterId);
const setTargets = useSetTargets(encounterId);
const revive = useReviveParticipant(encounterId);
const applyAction = useApplyAction(encounterId);
const patchEncounter = usePatchEncounter(encounterId);
const setArchived = useSetEncounterArchived(encounter?.campaignId ?? '');
const deleteEncounter = useDeleteEncounter(encounter?.campaignId ?? '');
@@ -1228,12 +1340,40 @@ export function EncounterPage() {
// The combatant whose stats are kept in view in place of whoever is on turn.
const [pinnedId, setPinnedId] = useState<string | null>(null);
// The DM's keys: N passes the turn, S opens the sheet of whoever is on turn.
// The DM's keys: N passes the turn, S opens the sheet of whoever is on turn,
// A accepts the first attack that is ready. For whoever may pick targets
// (the DM, or a player on their own turn), 1 to 9 mark the combatants in
// turn order, leaving out whoever is on turn.
const onTurn = encounter?.participants?.find((p) => p.id === encounter.activeParticipantId);
const dmRunning = isDM && encounter?.mode === 'BATTLE' && encounter.status === 'ACTIVE';
const running = encounter?.mode === 'BATTLE' && encounter.status === 'ACTIVE';
const dmRunning = isDM && running;
const marked = encounter?.targetParticipantIds ?? [];
const mayMark = isDM || (running && onTurn?.character != null && onTurn.character.userId === user?.id);
const byKey = (encounter?.participants ?? []).filter((p) => !p.hidden && !(running && p.id === encounter?.activeParticipantId)).slice(0, 9);
const readyAction = (encounter?.actions ?? []).find((a) => a.ready);
useHotkeys({
n: dmRunning && !nextTurn.isPending ? () => nextTurn.mutate(undefined, turnPassed) : undefined,
s: dmRunning && onTurn ? () => (onTurn.character ? openCharacterPanel(onTurn.character.id) : setPinnedId(onTurn.id)) : undefined,
a:
isDM && readyAction && !applyAction.isPending
? () =>
applyAction.mutate(readyAction.id, {
onError: (err: unknown) => setFormError(extractErrorMessage(err)),
onSuccess: (data) =>
notify(
...data.concentration.map((c) => `${c.name} is concentrating and took ${c.damage} damage: Constitution save, DC ${c.dc}. On a failure the spell ends: remove Concentrating.`),
...(data.slotNote ? [data.slotNote] : [])
),
})
: undefined,
...Object.fromEntries(
byKey.map((p, i) => [
String(i + 1),
mayMark
? () => setTargets.mutate(marked.includes(p.id) ? marked.filter((id) => id !== p.id) : [...marked, p.id], { onError: (err: unknown) => setFormError(extractErrorMessage(err)) })
: undefined,
])
),
});
if (isLoading) return <Spinner label="Setting the scene…" />;
@@ -1261,6 +1401,14 @@ export function EncounterPage() {
const builtCharacters = characters?.filter((c) => c.buildStage === 'COMPLETE') ?? [];
const onError = (err: unknown) => setFormError(extractErrorMessage(err));
const fail = { onError };
const toggleTarget = (participantId: string) =>
setTargets.mutate(targetIds.includes(participantId) ? targetIds.filter((id) => id !== participantId) : [...targetIds, participantId], fail);
// Attacks and spells being resolved, and whether it is this viewer's own character's turn.
const actions = encounter.actions ?? [];
const myTurn = active?.character != null && active.character.userId === user?.id;
const diceMode = campaignData?.campaign.diceMode ?? 'BOTH';
// What the DM is waiting on right now, in one line; for a player, what is theirs to do.
const cue = whatNow({ encounter, isDM, active, targets, actions, myTurn, unrolled: participants.filter((p) => p.initiativeRoll == null && !p.hidden).length, userId: user?.id });
const pickOptions: { id: string; name: string }[] =
pickType === 'character'
@@ -1318,7 +1466,7 @@ export function EncounterPage() {
onTarget={
// Nobody targets themselves: the combatant on turn has no button.
canTarget && p.id !== active?.id
? () => setTargets.mutate(targetIds.includes(p.id) ? targetIds.filter((id) => id !== p.id) : [...targetIds, p.id], fail)
? () => toggleTarget(p.id)
: undefined
}
isPinned={p.id === pinnedId}
@@ -1482,8 +1630,26 @@ export function EncounterPage() {
</div>
)}
{standing.length > 1 && (
<TurnStrip participants={standing} activeId={active?.id} targetIds={targetIds} userId={user?.id} hasActed={hasActed} />
{active ? (
<InitiativeTrack
participants={standing}
activeId={active.id}
round={encounter.currentRound}
targetIds={targetIds}
userId={user?.id}
canTarget={canTarget}
onTarget={toggleTarget}
onJump={jumpToCard}
/>
) : (
standing.length > 1 && <TurnStrip participants={standing} activeId={undefined} targetIds={targetIds} userId={user?.id} hasActed={hasActed} />
)}
{cue && (
<div className={`card cue-card${cue.urgent ? ' is-urgent' : ''}`} role="status">
<span className="cue-label">{isDM ? 'What now' : 'Your move'}</span>
<span>{cue.text}</span>
{isDM && running && <span className="combatant-sub cue-keys">Keys: 1–9 target · A accept · N next turn · S sheet</span>}
</div>
)}
{(isDM || encounter.description) && (
@@ -1514,6 +1680,22 @@ export function EncounterPage() {
<div className="encounter-layout mt-md">
<div>
{actions.map((action) => (
<ActionCard
key={action.id}
action={action}
participants={participants}
isDM={isDM}
userId={user?.id}
diceMode={diceMode}
encounterId={encounterId}
onNotice={notify}
onError={onError}
/>
))}
{encounter.status === 'ACTIVE' && isBattle && (isDM || myTurn) && (active || isDM) && (
<ActionComposer actor={active} targetCount={targets.length} isDM={isDM} encounterId={encounterId} onError={onError} />
)}
{isDM && targets.length > 0 && (
<AttackBar
attacker={active}
@@ -1658,6 +1840,16 @@ export function EncounterPage() {
</div>
)}
{isBattle && (encounter.recentActions ?? []).length > 0 && (
<details className="card" open>
<summary className="card-title" style={{ cursor: 'pointer', marginBottom: 0 }}>
⚔ What just happened
</summary>
<div className="mt-sm">
<RecentActions actions={encounter.recentActions ?? []} />
</div>
</details>
)}
{isDM && (
<details className="card" open={(rolls ?? []).length > 0}>
<summary className="card-title" style={{ cursor: 'pointer', marginBottom: 0 }}>