Compare commits
3 Commits
bcd720cae8
...
0182e9eb79
| Author | SHA1 | Date | |
|---|---|---|---|
| 0182e9eb79 | |||
| 9f494461de | |||
| 37e2b27870 |
@@ -4,3 +4,4 @@ dist/
|
||||
vite.config.js
|
||||
vite.config.d.ts
|
||||
Notes/rendered-pages/
|
||||
Notes/_codex_tables/
|
||||
|
||||
+393
-59
@@ -3,26 +3,41 @@ import React from "react";
|
||||
import { sampleContentPack } from "@/data/sampleContentPack";
|
||||
import { createStartingAdventurer } from "@/rules/character";
|
||||
import {
|
||||
deleteSavedRun,
|
||||
buildCampaignSaveLabel,
|
||||
deleteSavedCampaignSession,
|
||||
exportCampaignSession,
|
||||
getBrowserStorage,
|
||||
listSavedRuns,
|
||||
loadSavedRun,
|
||||
saveRun,
|
||||
type SavedRunSummary,
|
||||
importCampaignSession,
|
||||
listSavedCampaigns,
|
||||
loadSavedCampaignSession,
|
||||
saveCampaignSession,
|
||||
type SavedCampaignSummary,
|
||||
} from "@/rules/persistence";
|
||||
import { createCampaignSession, updateSessionRun, type CampaignSession } from "@/rules/campaign";
|
||||
import {
|
||||
createRunState,
|
||||
canCompleteCurrentLevel,
|
||||
completeCurrentLevel,
|
||||
enterCurrentRoom,
|
||||
getAvailableMoves,
|
||||
isCurrentRoomCombatReady,
|
||||
resolveCurrentRoomObject,
|
||||
resolveRunEnemyTurn,
|
||||
resolveRunPlayerTurn,
|
||||
resumeDungeon,
|
||||
returnToTown,
|
||||
searchCurrentRoom,
|
||||
startCombatInCurrentRoom,
|
||||
travelCurrentExit,
|
||||
useRunMagicItem,
|
||||
} from "@/rules/runState";
|
||||
import { getNextLevelXpThreshold, MAX_ADVENTURER_LEVEL } from "@/rules/progression";
|
||||
import {
|
||||
AMULET_FIRE_RESISTANCE_STATUS_ID,
|
||||
AMULET_RESISTANCE_STATUS_ID,
|
||||
INSIGHTFUL_COMBAT_STATUS_ID,
|
||||
getCarriedItemCount,
|
||||
hasStatus,
|
||||
} from "@/rules/magicItems";
|
||||
import {
|
||||
getConsumableCounts,
|
||||
restWithRation,
|
||||
@@ -39,7 +54,7 @@ import {
|
||||
import { useTownService } from "@/rules/townServices";
|
||||
import type { RunState } from "@/types/state";
|
||||
|
||||
function createDemoRun() {
|
||||
function createDemoSession() {
|
||||
const adventurer = createStartingAdventurer(sampleContentPack, {
|
||||
name: "Aster",
|
||||
weaponId: "weapon.short-sword",
|
||||
@@ -47,9 +62,8 @@ function createDemoRun() {
|
||||
scrollId: "scroll.lesser-heal",
|
||||
});
|
||||
|
||||
return createRunState({
|
||||
return createCampaignSession({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.demo",
|
||||
adventurer,
|
||||
});
|
||||
}
|
||||
@@ -87,11 +101,24 @@ function getTownServiceDescription(serviceId: string) {
|
||||
}
|
||||
|
||||
function getItemName(definitionId: string) {
|
||||
return sampleContentPack.items.find((item) => item.id === definitionId)?.name ?? definitionId;
|
||||
return (
|
||||
sampleContentPack.items.find((item) => item.id === definitionId)?.name ??
|
||||
sampleContentPack.potions.find((potion) => potion.id === definitionId)?.name ??
|
||||
sampleContentPack.scrolls.find((scroll) => scroll.id === definitionId)?.name ??
|
||||
sampleContentPack.armour.find((armour) => armour.id === definitionId)?.name ??
|
||||
sampleContentPack.weapons.find((weapon) => weapon.id === definitionId)?.name ??
|
||||
definitionId
|
||||
);
|
||||
}
|
||||
|
||||
function getItemValue(definitionId: string) {
|
||||
return sampleContentPack.items.find((item) => item.id === definitionId)?.valueGp ?? 0;
|
||||
return (
|
||||
sampleContentPack.items.find((item) => item.id === definitionId)?.valueGp ??
|
||||
sampleContentPack.potions.find((potion) => potion.id === definitionId)?.valueGp ??
|
||||
sampleContentPack.scrolls.find((scroll) => scroll.id === definitionId)?.valueGp ??
|
||||
sampleContentPack.armour.find((armour) => armour.id === definitionId)?.valueGp ??
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
function getManoeuvreName(manoeuvreId: string) {
|
||||
@@ -103,12 +130,15 @@ function getCombatTargetNumber(enemyArmourValue = 0) {
|
||||
}
|
||||
|
||||
function App() {
|
||||
const [run, setRun] = React.useState<RunState>(() => createDemoRun());
|
||||
const [savedRuns, setSavedRuns] = React.useState<SavedRunSummary[]>([]);
|
||||
const [session, setSession] = React.useState<CampaignSession>(() => createDemoSession());
|
||||
const [savedCampaigns, setSavedCampaigns] = React.useState<SavedCampaignSummary[]>([]);
|
||||
const run = session.run;
|
||||
const campaign = session.campaign;
|
||||
const currentLevel = run.dungeon.levels[run.currentLevel];
|
||||
const currentRoom = run.currentRoomId ? currentLevel?.rooms[run.currentRoomId] : undefined;
|
||||
const availableMoves = getAvailableMoves(run);
|
||||
const combatReadyEncounter = isCurrentRoomCombatReady(run);
|
||||
const levelCompletionReady = canCompleteCurrentLevel(run);
|
||||
const inTown = run.phase === "town";
|
||||
const knownServices = sampleContentPack.townServices.filter((service) =>
|
||||
run.townState.knownServices.includes(service.id),
|
||||
@@ -123,6 +153,23 @@ function App() {
|
||||
0,
|
||||
);
|
||||
const consumableCounts = getConsumableCounts(run);
|
||||
const magicItemCounts = {
|
||||
ringOfLeaving: getCarriedItemCount(run, "item.ring-of-leaving"),
|
||||
ringOfSpells: getCarriedItemCount(run, "item.ring-of-spells"),
|
||||
amuletOfResistance: getCarriedItemCount(run, "item.amulet-of-resistance"),
|
||||
amuletOfFireResistance: getCarriedItemCount(run, "item.amulet-of-fire-resistance"),
|
||||
wandOfFire: getCarriedItemCount(run, "item.wand-of-fire"),
|
||||
wandOfSleep: getCarriedItemCount(run, "item.wand-of-sleep"),
|
||||
potionOfAura: getCarriedItemCount(run, "item.potion-of-aura"),
|
||||
insightfulCombat: getCarriedItemCount(run, "item.potion-of-insightful-combat"),
|
||||
};
|
||||
const magicStatuses = {
|
||||
resistance: hasStatus(run.adventurerSnapshot.statuses, AMULET_RESISTANCE_STATUS_ID),
|
||||
fireResistance: hasStatus(run.adventurerSnapshot.statuses, AMULET_FIRE_RESISTANCE_STATUS_ID),
|
||||
insight:
|
||||
hasStatus(run.adventurerSnapshot.statuses, INSIGHTFUL_COMBAT_STATUS_ID) ||
|
||||
hasStatus(run.activeCombat?.player.statuses ?? [], INSIGHTFUL_COMBAT_STATUS_ID),
|
||||
};
|
||||
const latestCombatLogs = run.activeCombat?.combatLog.slice(-3).reverse() ?? [];
|
||||
const nextLevelXpThreshold =
|
||||
run.adventurerSnapshot.level >= MAX_ADVENTURER_LEVEL
|
||||
@@ -140,35 +187,56 @@ function App() {
|
||||
return;
|
||||
}
|
||||
|
||||
setSavedRuns(listSavedRuns(storage));
|
||||
setSavedCampaigns(listSavedCampaigns(storage));
|
||||
}, []);
|
||||
|
||||
const handleReset = () => {
|
||||
setRun(createDemoRun());
|
||||
setSession(createDemoSession());
|
||||
};
|
||||
|
||||
const refreshSavedRuns = React.useCallback(() => {
|
||||
const refreshSavedCampaigns = React.useCallback(() => {
|
||||
const storage = getBrowserStorage();
|
||||
|
||||
if (!storage) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSavedRuns(listSavedRuns(storage));
|
||||
setSavedCampaigns(listSavedCampaigns(storage));
|
||||
}, []);
|
||||
|
||||
const updateRun = React.useCallback(
|
||||
(transform: (currentRun: RunState) => RunState) => {
|
||||
setSession((previous) => updateSessionRun(sampleContentPack, previous, transform(previous.run)));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
const storage = getBrowserStorage();
|
||||
|
||||
if (!storage) {
|
||||
return;
|
||||
}
|
||||
|
||||
saveCampaignSession(storage, session, {
|
||||
saveId: `campaign.${campaign.id}.autosave`,
|
||||
label: `${buildCampaignSaveLabel(session)} · autosave`,
|
||||
});
|
||||
setSavedCampaigns(listSavedCampaigns(storage));
|
||||
}, [campaign.id, session]);
|
||||
|
||||
const handleEnterRoom = () => {
|
||||
setRun((previous) => enterCurrentRoom({ content: sampleContentPack, run: previous }).run);
|
||||
updateRun((previous) => enterCurrentRoom({ content: sampleContentPack, run: previous }).run);
|
||||
};
|
||||
|
||||
const handleStartCombat = () => {
|
||||
setRun((previous) =>
|
||||
updateRun((previous) =>
|
||||
startCombatInCurrentRoom({ content: sampleContentPack, run: previous }).run,
|
||||
);
|
||||
};
|
||||
|
||||
const handleTravel = (direction: "north" | "east" | "south" | "west") => {
|
||||
setRun((previous) =>
|
||||
updateRun((previous) =>
|
||||
travelCurrentExit({
|
||||
content: sampleContentPack,
|
||||
run: previous,
|
||||
@@ -178,7 +246,7 @@ function App() {
|
||||
};
|
||||
|
||||
const handlePlayerTurn = (manoeuvreId: string, targetEnemyId: string) => {
|
||||
setRun((previous) =>
|
||||
updateRun((previous) =>
|
||||
resolveRunPlayerTurn({
|
||||
content: sampleContentPack,
|
||||
run: previous,
|
||||
@@ -189,21 +257,39 @@ function App() {
|
||||
};
|
||||
|
||||
const handleEnemyTurn = () => {
|
||||
setRun((previous) =>
|
||||
updateRun((previous) =>
|
||||
resolveRunEnemyTurn({ content: sampleContentPack, run: previous }).run,
|
||||
);
|
||||
};
|
||||
|
||||
const handleReturnToTown = () => {
|
||||
setRun((previous) => returnToTown(previous).run);
|
||||
updateRun((previous) => returnToTown(previous).run);
|
||||
};
|
||||
|
||||
const handleSearchRoom = () => {
|
||||
updateRun((previous) => searchCurrentRoom(previous).run);
|
||||
};
|
||||
|
||||
const handleResolveRoomObject = (objectId: string) => {
|
||||
updateRun((previous) =>
|
||||
resolveCurrentRoomObject({
|
||||
content: sampleContentPack,
|
||||
run: previous,
|
||||
objectId,
|
||||
}).run,
|
||||
);
|
||||
};
|
||||
|
||||
const handleCompleteLevel = () => {
|
||||
updateRun((previous) => completeCurrentLevel(previous).run);
|
||||
};
|
||||
|
||||
const handleResumeDungeon = () => {
|
||||
setRun((previous) => resumeDungeon(previous).run);
|
||||
updateRun((previous) => resumeDungeon(previous).run);
|
||||
};
|
||||
|
||||
const handleUseTownService = (serviceId: string) => {
|
||||
setRun((previous) =>
|
||||
updateRun((previous) =>
|
||||
useTownService({
|
||||
content: sampleContentPack,
|
||||
run: previous,
|
||||
@@ -213,7 +299,7 @@ function App() {
|
||||
};
|
||||
|
||||
const handleGrantTreasure = (definitionId: string) => {
|
||||
setRun((previous) =>
|
||||
updateRun((previous) =>
|
||||
grantDebugTreasure({
|
||||
content: sampleContentPack,
|
||||
run: previous,
|
||||
@@ -223,7 +309,7 @@ function App() {
|
||||
};
|
||||
|
||||
const handleStashTreasure = (definitionId: string) => {
|
||||
setRun((previous) =>
|
||||
updateRun((previous) =>
|
||||
stashCarriedTreasure({
|
||||
content: sampleContentPack,
|
||||
run: previous,
|
||||
@@ -233,7 +319,7 @@ function App() {
|
||||
};
|
||||
|
||||
const handleWithdrawTreasure = (definitionId: string) => {
|
||||
setRun((previous) =>
|
||||
updateRun((previous) =>
|
||||
withdrawStashedTreasure({
|
||||
content: sampleContentPack,
|
||||
run: previous,
|
||||
@@ -243,7 +329,7 @@ function App() {
|
||||
};
|
||||
|
||||
const handleQueueTreasure = (definitionId: string, source: "carried" | "stash") => {
|
||||
setRun((previous) =>
|
||||
updateRun((previous) =>
|
||||
queueTreasureForSale({
|
||||
content: sampleContentPack,
|
||||
run: previous,
|
||||
@@ -254,7 +340,7 @@ function App() {
|
||||
};
|
||||
|
||||
const handleSellPending = () => {
|
||||
setRun((previous) =>
|
||||
updateRun((previous) =>
|
||||
sellPendingTreasure({
|
||||
content: sampleContentPack,
|
||||
run: previous,
|
||||
@@ -263,7 +349,7 @@ function App() {
|
||||
};
|
||||
|
||||
const handleUsePotion = () => {
|
||||
setRun((previous) =>
|
||||
updateRun((previous) =>
|
||||
usePotion({
|
||||
content: sampleContentPack,
|
||||
run: previous,
|
||||
@@ -273,7 +359,7 @@ function App() {
|
||||
};
|
||||
|
||||
const handleUseScroll = () => {
|
||||
setRun((previous) =>
|
||||
updateRun((previous) =>
|
||||
useScroll({
|
||||
content: sampleContentPack,
|
||||
run: previous,
|
||||
@@ -284,7 +370,7 @@ function App() {
|
||||
};
|
||||
|
||||
const handleRationRest = () => {
|
||||
setRun((previous) =>
|
||||
updateRun((previous) =>
|
||||
restWithRation({
|
||||
content: sampleContentPack,
|
||||
run: previous,
|
||||
@@ -293,26 +379,37 @@ function App() {
|
||||
);
|
||||
};
|
||||
|
||||
const handleSaveRun = () => {
|
||||
const storage = getBrowserStorage();
|
||||
|
||||
if (!storage) {
|
||||
return;
|
||||
}
|
||||
|
||||
saveRun(storage, run);
|
||||
refreshSavedRuns();
|
||||
const handleUseMagicItem = (definitionId: string) => {
|
||||
updateRun((previous) =>
|
||||
useRunMagicItem({
|
||||
content: sampleContentPack,
|
||||
run: previous,
|
||||
definitionId,
|
||||
targetEnemyId: previous.activeCombat?.enemies.find((enemy) => enemy.hpCurrent > 0)?.id,
|
||||
}).run,
|
||||
);
|
||||
};
|
||||
|
||||
const handleLoadRun = (saveId: string) => {
|
||||
const handleSaveCampaign = () => {
|
||||
const storage = getBrowserStorage();
|
||||
|
||||
if (!storage) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRun(loadSavedRun(storage, saveId));
|
||||
refreshSavedRuns();
|
||||
saveCampaignSession(storage, session);
|
||||
refreshSavedCampaigns();
|
||||
};
|
||||
|
||||
const handleLoadCampaign = (saveId: string) => {
|
||||
const storage = getBrowserStorage();
|
||||
|
||||
if (!storage) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSession(loadSavedCampaignSession(storage, saveId));
|
||||
refreshSavedCampaigns();
|
||||
};
|
||||
|
||||
const handleDeleteSave = (saveId: string) => {
|
||||
@@ -322,7 +419,31 @@ function App() {
|
||||
return;
|
||||
}
|
||||
|
||||
setSavedRuns(deleteSavedRun(storage, saveId));
|
||||
setSavedCampaigns(deleteSavedCampaignSession(storage, saveId));
|
||||
};
|
||||
|
||||
const handleExportCampaign = () => {
|
||||
const blob = new Blob([exportCampaignSession(session)], { type: "application/json" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
|
||||
link.href = url;
|
||||
link.download = `${campaign.id}.json`;
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const handleImportCampaign = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
|
||||
const imported = importCampaignSession(await file.text());
|
||||
setSession(imported);
|
||||
refreshSavedCampaigns();
|
||||
event.target.value = "";
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -330,20 +451,27 @@ function App() {
|
||||
<section className="hero">
|
||||
<div>
|
||||
<p className="eyebrow">2D6 Dungeon Web</p>
|
||||
<h1>Dungeon Loop Shell</h1>
|
||||
<h1>Campaign Command Table</h1>
|
||||
<p className="lede">
|
||||
Traverse generated rooms, auto-resolve room entry, and engage combat
|
||||
when a room reveals a real encounter.
|
||||
Keep the active delve, town ledger, and campaign record in one place while you
|
||||
explore Level 1 and carry progress forward between sessions.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="hero-actions">
|
||||
<button className="button button-primary" onClick={handleReset}>
|
||||
Reset Demo Run
|
||||
Reset Demo Campaign
|
||||
</button>
|
||||
<button className="button" onClick={handleSaveRun}>
|
||||
Save Run
|
||||
<button className="button" onClick={handleSaveCampaign}>
|
||||
Save Campaign
|
||||
</button>
|
||||
<button className="button" onClick={handleExportCampaign}>
|
||||
Export JSON
|
||||
</button>
|
||||
<label className="button button-file">
|
||||
Import JSON
|
||||
<input type="file" accept="application/json" onChange={handleImportCampaign} />
|
||||
</label>
|
||||
<button
|
||||
className="button"
|
||||
onClick={inTown ? handleResumeDungeon : handleReturnToTown}
|
||||
@@ -352,7 +480,7 @@ function App() {
|
||||
{inTown ? "Resume Dungeon" : "Return To Town"}
|
||||
</button>
|
||||
<div className="status-chip">
|
||||
<span>Run Phase</span>
|
||||
<span>Campaign Phase</span>
|
||||
<strong>{run.phase}</strong>
|
||||
</div>
|
||||
</div>
|
||||
@@ -407,6 +535,39 @@ function App() {
|
||||
) : null}
|
||||
|
||||
<section className="dashboard-grid">
|
||||
<article className="panel">
|
||||
<div className="panel-header">
|
||||
<h2>Campaign Ledger</h2>
|
||||
<span>{campaign.id}</span>
|
||||
</div>
|
||||
<div className="town-summary-grid">
|
||||
<div className="encounter-box">
|
||||
<span className="encounter-label">Adventurer</span>
|
||||
<strong>{campaign.adventurer.name}</strong>
|
||||
</div>
|
||||
<div className="encounter-box">
|
||||
<span className="encounter-label">Run History</span>
|
||||
<strong>{campaign.runHistory.length}</strong>
|
||||
</div>
|
||||
<div className="encounter-box">
|
||||
<span className="encounter-label">Town Visits</span>
|
||||
<strong>{campaign.townState.visits}</strong>
|
||||
</div>
|
||||
<div className="encounter-box">
|
||||
<span className="encounter-label">Updated</span>
|
||||
<strong>{new Date(campaign.updatedAt).toLocaleTimeString()}</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div className="room-meta">
|
||||
<span>Completed Levels: {campaign.completedLevels.join(", ") || "None"}</span>
|
||||
<span>Unlocked Levels: {campaign.unlockedLevels.join(", ")}</span>
|
||||
</div>
|
||||
<p className="supporting-text">
|
||||
Campaign saves include the adventurer sheet, town state, run history snapshot, and
|
||||
the active dungeon delve.
|
||||
</p>
|
||||
</article>
|
||||
|
||||
<article className="panel panel-highlight">
|
||||
<div className="panel-header">
|
||||
<h2>Adventurer</h2>
|
||||
@@ -512,30 +673,147 @@ function App() {
|
||||
Eat And Rest
|
||||
</button>
|
||||
</article>
|
||||
<article className="recovery-card">
|
||||
<span className="encounter-label">Relic</span>
|
||||
<strong>Ring of Leaving</strong>
|
||||
<p className="supporting-text">
|
||||
Escape straight back to town from the dungeon. Carried: {magicItemCounts.ringOfLeaving}
|
||||
</p>
|
||||
<button
|
||||
className="button"
|
||||
onClick={() => handleUseMagicItem("item.ring-of-leaving")}
|
||||
disabled={inTown || Boolean(run.activeCombat) || magicItemCounts.ringOfLeaving === 0}
|
||||
>
|
||||
Invoke Ring
|
||||
</button>
|
||||
</article>
|
||||
<article className="recovery-card">
|
||||
<span className="encounter-label">Relic</span>
|
||||
<strong>Ring of Spells</strong>
|
||||
<p className="supporting-text">
|
||||
Release a stored charm to restore 2 HP. Carried: {magicItemCounts.ringOfSpells}
|
||||
</p>
|
||||
<button
|
||||
className="button"
|
||||
onClick={() => handleUseMagicItem("item.ring-of-spells")}
|
||||
disabled={magicItemCounts.ringOfSpells === 0}
|
||||
>
|
||||
Invoke Ring
|
||||
</button>
|
||||
</article>
|
||||
<article className="recovery-card">
|
||||
<span className="encounter-label">Relic</span>
|
||||
<strong>Amulet of Resistance</strong>
|
||||
<p className="supporting-text">
|
||||
Reduce the next damage taken by 1. Carried: {magicItemCounts.amuletOfResistance}
|
||||
</p>
|
||||
<button
|
||||
className="button"
|
||||
onClick={() => handleUseMagicItem("item.amulet-of-resistance")}
|
||||
disabled={inTown || magicItemCounts.amuletOfResistance === 0 || magicStatuses.resistance}
|
||||
>
|
||||
Raise Ward
|
||||
</button>
|
||||
</article>
|
||||
<article className="recovery-card">
|
||||
<span className="encounter-label">Relic</span>
|
||||
<strong>Amulet of Fire Resistance</strong>
|
||||
<p className="supporting-text">
|
||||
Reduce the next damage taken by 2. Carried: {magicItemCounts.amuletOfFireResistance}
|
||||
</p>
|
||||
<button
|
||||
className="button"
|
||||
onClick={() => handleUseMagicItem("item.amulet-of-fire-resistance")}
|
||||
disabled={inTown || magicItemCounts.amuletOfFireResistance === 0 || magicStatuses.fireResistance}
|
||||
>
|
||||
Raise Fire Ward
|
||||
</button>
|
||||
</article>
|
||||
<article className="recovery-card">
|
||||
<span className="encounter-label">Wand</span>
|
||||
<strong>Wand of Fire</strong>
|
||||
<p className="supporting-text">
|
||||
Scorch the first living enemy for 2 damage. Carried: {magicItemCounts.wandOfFire}
|
||||
</p>
|
||||
<button
|
||||
className="button"
|
||||
onClick={() => handleUseMagicItem("item.wand-of-fire")}
|
||||
disabled={!run.activeCombat || run.activeCombat.actingSide !== "player" || magicItemCounts.wandOfFire === 0}
|
||||
>
|
||||
Cast Fire
|
||||
</button>
|
||||
</article>
|
||||
<article className="recovery-card">
|
||||
<span className="encounter-label">Wand</span>
|
||||
<strong>Wand of Sleep</strong>
|
||||
<p className="supporting-text">
|
||||
Put the first living enemy to sleep for its next turn. Carried: {magicItemCounts.wandOfSleep}
|
||||
</p>
|
||||
<button
|
||||
className="button"
|
||||
onClick={() => handleUseMagicItem("item.wand-of-sleep")}
|
||||
disabled={!run.activeCombat || run.activeCombat.actingSide !== "player" || magicItemCounts.wandOfSleep === 0}
|
||||
>
|
||||
Cast Sleep
|
||||
</button>
|
||||
</article>
|
||||
<article className="recovery-card">
|
||||
<span className="encounter-label">Potion</span>
|
||||
<strong>Potion of Aura</strong>
|
||||
<p className="supporting-text">
|
||||
Reveal hidden room objects while exploring. Carried: {magicItemCounts.potionOfAura}
|
||||
</p>
|
||||
<button
|
||||
className="button"
|
||||
onClick={() => handleUseMagicItem("item.potion-of-aura")}
|
||||
disabled={inTown || Boolean(run.activeCombat) || magicItemCounts.potionOfAura === 0}
|
||||
>
|
||||
Drink Aura
|
||||
</button>
|
||||
</article>
|
||||
<article className="recovery-card">
|
||||
<span className="encounter-label">Potion</span>
|
||||
<strong>Insightful Combat</strong>
|
||||
<p className="supporting-text">
|
||||
Gain +1 precision on the next attack. Carried: {magicItemCounts.insightfulCombat}
|
||||
</p>
|
||||
<button
|
||||
className="button"
|
||||
onClick={() => handleUseMagicItem("item.potion-of-insightful-combat")}
|
||||
disabled={!run.activeCombat || run.activeCombat.actingSide !== "player" || magicItemCounts.insightfulCombat === 0 || magicStatuses.insight}
|
||||
>
|
||||
Drink Combat Draft
|
||||
</button>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<article className="panel panel-saves">
|
||||
<div className="panel-header">
|
||||
<h2>Save Archive</h2>
|
||||
<span>{savedRuns.length} saves</span>
|
||||
<h2>Campaign Archive</h2>
|
||||
<span>{savedCampaigns.length} saves</span>
|
||||
</div>
|
||||
{savedRuns.length === 0 ? (
|
||||
<p className="supporting-text">No saved runs yet. Save the current run to persist progress.</p>
|
||||
{savedCampaigns.length === 0 ? (
|
||||
<p className="supporting-text">
|
||||
No saved campaigns yet. The current campaign autosaves as you play, and you can
|
||||
archive manual snapshots here.
|
||||
</p>
|
||||
) : (
|
||||
<div className="save-list">
|
||||
{savedRuns.map((save) => (
|
||||
{savedCampaigns.map((save) => (
|
||||
<article key={save.id} className="save-card">
|
||||
<div>
|
||||
<span className="encounter-label">{save.phase}</span>
|
||||
<strong>{save.label}</strong>
|
||||
<p className="supporting-text">
|
||||
Saved {new Date(save.savedAt).toLocaleString()} · Level {save.currentLevel}
|
||||
{" · "}
|
||||
Town visits {save.visits}
|
||||
</p>
|
||||
</div>
|
||||
<div className="save-actions">
|
||||
<button className="button" onClick={() => handleLoadRun(save.id)}>
|
||||
<button className="button" onClick={() => handleLoadCampaign(save.id)}>
|
||||
Load
|
||||
</button>
|
||||
<button className="button" onClick={() => handleDeleteSave(save.id)}>
|
||||
@@ -564,6 +842,10 @@ function App() {
|
||||
<span className="encounter-label">Current Gold</span>
|
||||
<strong>{run.adventurerSnapshot.inventory.currency.gold}</strong>
|
||||
</div>
|
||||
<div className="encounter-box">
|
||||
<span className="encounter-label">Current Silver</span>
|
||||
<strong>{run.adventurerSnapshot.inventory.currency.silver}</strong>
|
||||
</div>
|
||||
<div className="encounter-box">
|
||||
<span className="encounter-label">Rooms Found</span>
|
||||
<strong>{currentLevel?.discoveredRoomOrder.length ?? 0}</strong>
|
||||
@@ -720,12 +1002,20 @@ function App() {
|
||||
<div className="room-meta">
|
||||
<span>Entered: {currentRoom?.discovery.entered ? "Yes" : "No"}</span>
|
||||
<span>Cleared: {currentRoom?.discovery.cleared ? "Yes" : "No"}</span>
|
||||
<span>Searched: {currentRoom?.discovery.searched ? "Yes" : "No"}</span>
|
||||
<span>Exits: {currentRoom?.exits.length ?? 0}</span>
|
||||
</div>
|
||||
<div className="button-row">
|
||||
<button className="button" onClick={handleEnterRoom}>
|
||||
Enter Room
|
||||
</button>
|
||||
<button
|
||||
className="button"
|
||||
onClick={handleSearchRoom}
|
||||
disabled={!currentRoom || Boolean(run.activeCombat)}
|
||||
>
|
||||
Search Room
|
||||
</button>
|
||||
<button
|
||||
className="button button-primary"
|
||||
onClick={handleStartCombat}
|
||||
@@ -733,11 +1023,55 @@ function App() {
|
||||
>
|
||||
Start Combat
|
||||
</button>
|
||||
<button
|
||||
className="button"
|
||||
onClick={handleCompleteLevel}
|
||||
disabled={!levelCompletionReady}
|
||||
>
|
||||
Complete Level
|
||||
</button>
|
||||
</div>
|
||||
<div className="encounter-box">
|
||||
<span className="encounter-label">Encounter</span>
|
||||
<strong>{currentRoom?.encounter?.resultLabel ?? "None"}</strong>
|
||||
</div>
|
||||
<div className="combat-feed">
|
||||
<div className="panel-header">
|
||||
<h2>Room Objects</h2>
|
||||
<span>{currentRoom?.objects.filter((object) => !object.hidden).length ?? 0} visible</span>
|
||||
</div>
|
||||
{!currentRoom || currentRoom.objects.filter((object) => !object.hidden).length === 0 ? (
|
||||
<p className="supporting-text">No discovered objects in this room yet.</p>
|
||||
) : (
|
||||
currentRoom.objects
|
||||
.filter((object) => !object.hidden)
|
||||
.map((object) => (
|
||||
<article key={object.id} className="enemy-card">
|
||||
<span>{object.objectType}</span>
|
||||
<strong>{object.title}</strong>
|
||||
{object.sourceTableCode ? <em>{object.sourceTableCode}</em> : null}
|
||||
<p className="supporting-text">
|
||||
{object.resolutionLabel
|
||||
? `${object.notes ?? "Interact with this object to resolve its effect."} Last result: ${object.resolutionLabel}.`
|
||||
: object.notes ?? "Interact with this object to resolve its effect."}
|
||||
</p>
|
||||
<button
|
||||
className="button"
|
||||
onClick={() => handleResolveRoomObject(object.id)}
|
||||
disabled={object.interacted || Boolean(run.activeCombat)}
|
||||
>
|
||||
{object.interacted ? "Resolved" : "Resolve Object"}
|
||||
</button>
|
||||
</article>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
{levelCompletionReady ? (
|
||||
<p className="supporting-text">
|
||||
This room qualifies as the final cleared chamber. Completing the level will reveal
|
||||
stairs down, record the victory, and return you to town.
|
||||
</p>
|
||||
) : null}
|
||||
</article>
|
||||
|
||||
<article className="panel">
|
||||
|
||||
@@ -30,6 +30,20 @@ describe("level 1 content helpers", () => {
|
||||
expect(table.entries).toHaveLength(6);
|
||||
});
|
||||
|
||||
it("finds encoded level 1 room interaction tables by code", () => {
|
||||
const table = findTableByCode(sampleContentPack, "CT1");
|
||||
|
||||
expect(table.name).toBe("Chest Table 1");
|
||||
expect(table.diceKind).toBe("2d6");
|
||||
expect(table.entries).toHaveLength(11);
|
||||
});
|
||||
|
||||
it("finds newly encoded codex follow-up tables by code", () => {
|
||||
expect(findTableByCode(sampleContentPack, "PT2GEM1").diceKind).toBe("d3");
|
||||
expect(findTableByCode(sampleContentPack, "MR1").entries).toHaveLength(6);
|
||||
expect(findTableByCode(sampleContentPack, "POT4").entries).toHaveLength(6);
|
||||
});
|
||||
|
||||
it("resolves a small room template from a table lookup", () => {
|
||||
const lookup = lookupTable(findTableByCode(sampleContentPack, "L1SR"), {
|
||||
roller: createSequenceRoller([3, 4]),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,6 +2,10 @@ import type { ContentPack } from "@/types/content";
|
||||
|
||||
import { contentPackSchema } from "@/schemas/content";
|
||||
import { level1RoomTemplates } from "./level1Rooms";
|
||||
import {
|
||||
getLevel1RoomObjects,
|
||||
level1RoomInteractionTables,
|
||||
} from "./level1RoomObjects";
|
||||
import { level1EncounterTables } from "./level1Tables";
|
||||
|
||||
const samplePack = {
|
||||
@@ -13,6 +17,7 @@ const samplePack = {
|
||||
],
|
||||
tables: [
|
||||
...level1EncounterTables,
|
||||
...level1RoomInteractionTables,
|
||||
{
|
||||
id: "table.level1.humanoid-loot",
|
||||
code: "L1HL",
|
||||
@@ -264,6 +269,492 @@ const samplePack = {
|
||||
valueGp: 12,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.malako-leaves",
|
||||
name: "Malako Leaves",
|
||||
itemType: "herb",
|
||||
stackable: true,
|
||||
consumable: false,
|
||||
valueGp: 2,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.dankoma-stems",
|
||||
name: "Dankoma Stems",
|
||||
itemType: "herb",
|
||||
stackable: true,
|
||||
consumable: false,
|
||||
valueGp: 2,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.redroot-spines",
|
||||
name: "Redroot Spines",
|
||||
itemType: "herb",
|
||||
stackable: true,
|
||||
consumable: false,
|
||||
valueGp: 2,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.wolf-worm-eggs",
|
||||
name: "Wolf Worm Eggs",
|
||||
itemType: "herb",
|
||||
stackable: true,
|
||||
consumable: false,
|
||||
valueGp: 2,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.scarlet-ore-leaves",
|
||||
name: "Scarlet Ore Leaves",
|
||||
itemType: "herb",
|
||||
stackable: true,
|
||||
consumable: false,
|
||||
valueGp: 2,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.oretauts-leaves",
|
||||
name: "Oretauts Leaves",
|
||||
itemType: "herb",
|
||||
stackable: true,
|
||||
consumable: false,
|
||||
valueGp: 2,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.pearl",
|
||||
name: "Pearl",
|
||||
itemType: "treasure",
|
||||
stackable: true,
|
||||
consumable: false,
|
||||
valueGp: 5,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.sapphire",
|
||||
name: "Sapphire",
|
||||
itemType: "treasure",
|
||||
stackable: true,
|
||||
consumable: false,
|
||||
valueGp: 10,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.garnet",
|
||||
name: "Garnet",
|
||||
itemType: "treasure",
|
||||
stackable: true,
|
||||
consumable: false,
|
||||
valueGp: 8,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.ruby",
|
||||
name: "Ruby",
|
||||
itemType: "treasure",
|
||||
stackable: true,
|
||||
consumable: false,
|
||||
valueGp: 12,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.emerald",
|
||||
name: "Emerald",
|
||||
itemType: "treasure",
|
||||
stackable: true,
|
||||
consumable: false,
|
||||
valueGp: 12,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.diamond",
|
||||
name: "Diamond",
|
||||
itemType: "treasure",
|
||||
stackable: true,
|
||||
consumable: false,
|
||||
valueGp: 20,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.half-copper-pendant",
|
||||
name: "Half a Copper Pendant",
|
||||
itemType: "treasure",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 5,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.half-gold-pendant",
|
||||
name: "Half a Gold Pendant",
|
||||
itemType: "treasure",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 5,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.half-gold-cross",
|
||||
name: "Half a Gold Cross",
|
||||
itemType: "treasure",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 20,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.half-silver-cross",
|
||||
name: "Half a Silver Cross",
|
||||
itemType: "treasure",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 3,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.half-gold-symbol",
|
||||
name: "Half a Gold Symbol",
|
||||
itemType: "treasure",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 15,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.half-gold-symbol-high",
|
||||
name: "Half a Gold Symbol",
|
||||
itemType: "treasure",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 40,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.god-ornate-goada",
|
||||
name: "Goada the Helm",
|
||||
itemType: "treasure",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 18,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.god-ornate-intuneric",
|
||||
name: "Intuneric the Murk",
|
||||
itemType: "treasure",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 18,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.god-ornate-murtayne",
|
||||
name: "Murtayne the Pup",
|
||||
itemType: "treasure",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 18,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.god-ornate-nevzator",
|
||||
name: "Nevzator the Blind",
|
||||
itemType: "treasure",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 18,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.god-ornate-radacina",
|
||||
name: "Radacina the X",
|
||||
itemType: "treasure",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 18,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.god-ornate-madi",
|
||||
name: "Madi the Sphere",
|
||||
itemType: "treasure",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 18,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.ring-encountered",
|
||||
name: "Encountered Ring",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 20,
|
||||
rulesText: "Magic ring from MR1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.ring-of-baseness",
|
||||
name: "Ring of Baseness",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 20,
|
||||
rulesText: "Magic ring from MR1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.ring-of-spells",
|
||||
name: "Ring of Spells",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 25,
|
||||
rulesText: "Magic ring from MR1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.ring-of-steadiness",
|
||||
name: "Ring of Steadiness",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 25,
|
||||
rulesText: "Magic ring from MR1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.ring-of-transformation",
|
||||
name: "Ring of Transformation",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 30,
|
||||
rulesText: "Magic ring from MR1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.ring-of-leaving",
|
||||
name: "Ring of Leaving",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 30,
|
||||
rulesText: "Magic ring from MR1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.amulet-of-resistance",
|
||||
name: "Amulet of Resistance",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 30,
|
||||
rulesText: "Magic amulet from MA1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.amulet-of-fire-resistance",
|
||||
name: "Amulet of Fire Resistance",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 35,
|
||||
rulesText: "Magic amulet from MA1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.amulet-of-ice-resistance",
|
||||
name: "Amulet of Ice Resistance",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 35,
|
||||
rulesText: "Magic amulet from MA1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.amulet-of-poison-resistance",
|
||||
name: "Amulet of Poison Resistance",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 35,
|
||||
rulesText: "Magic amulet from MA1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.wand-of-fireballs",
|
||||
name: "Wand of Fireballs",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 50,
|
||||
rulesText: "Magic wand from MW1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.wand-of-fire",
|
||||
name: "Wand of Fire",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 40,
|
||||
rulesText: "Magic wand from MW1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.wand-of-sunder",
|
||||
name: "Wand of Sunder",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 45,
|
||||
rulesText: "Magic wand from MW1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.wand-of-sleep",
|
||||
name: "Wand of Sleep",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 40,
|
||||
rulesText: "Magic wand from MW1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.wand-of-paralysis",
|
||||
name: "Wand of Paralysis",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 45,
|
||||
rulesText: "Magic wand from MW1; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.potion-of-swamp-lung",
|
||||
name: "Potion of Swamp Lung",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: true,
|
||||
valueGp: 10,
|
||||
rulesText: "Codex potion result; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.potion-of-aura",
|
||||
name: "Potion of Aura",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: true,
|
||||
valueGp: 15,
|
||||
rulesText: "Codex potion result; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.potion-of-insightful-combat",
|
||||
name: "Potion of Insightful Combat",
|
||||
itemType: "misc",
|
||||
stackable: false,
|
||||
consumable: true,
|
||||
valueGp: 40,
|
||||
rulesText: "Codex potion result; effect automation pending.",
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.padded-tunic",
|
||||
name: "Padded Tunic",
|
||||
itemType: "gear",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 5,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.scale-jacket",
|
||||
name: "Scale Jacket",
|
||||
itemType: "gear",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 12,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.hide-doublet",
|
||||
name: "Hide Doublet",
|
||||
itemType: "gear",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 9,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.bishops-mail",
|
||||
name: "Bishops Mail",
|
||||
itemType: "gear",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 16,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.morning-jacket",
|
||||
name: "Morning Jacket",
|
||||
itemType: "gear",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 7,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.leather-breastplate",
|
||||
name: "Leather Breastplate",
|
||||
itemType: "gear",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 11,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.leather-bracers",
|
||||
name: "Leather Bracers",
|
||||
itemType: "gear",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 8,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.brigandine-coat",
|
||||
name: "Brigandine Coat",
|
||||
itemType: "gear",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 14,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.hide-doublet-alt",
|
||||
name: "Hide Doublet",
|
||||
itemType: "gear",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 9,
|
||||
mvp: true,
|
||||
},
|
||||
{
|
||||
id: "item.woden-shield",
|
||||
name: "Woden Shield",
|
||||
itemType: "gear",
|
||||
stackable: false,
|
||||
consumable: false,
|
||||
valueGp: 10,
|
||||
mvp: true,
|
||||
},
|
||||
],
|
||||
potions: [
|
||||
{
|
||||
@@ -274,6 +765,27 @@ const samplePack = {
|
||||
effects: [{ type: "heal", amount: 3, target: "self" }],
|
||||
mvp: true,
|
||||
},
|
||||
{ id: "potion.no-healing", name: "Potion of No Healing", tableSource: "POT1", useTiming: "any", effects: [], valueGp: 5, mvp: true },
|
||||
{ id: "potion.healing-alt", name: "Potion of Healing", tableSource: "POT1", useTiming: "any", effects: [{ type: "heal", amount: 3, target: "self" }], valueGp: 25, mvp: true },
|
||||
{ id: "potion.examination", name: "Potion of Examination", tableSource: "POT1", useTiming: "exploration", effects: [], valueGp: 5, mvp: true },
|
||||
{ id: "potion.strength", name: "Potion of Strength", tableSource: "POT1", useTiming: "combat", effects: [], valueGp: 15, mvp: true },
|
||||
{ id: "potion.extra-healing", name: "Potion of Extra Healing", tableSource: "POT2", useTiming: "any", effects: [{ type: "heal", amount: 5, target: "self" }], valueGp: 40, mvp: true },
|
||||
{ id: "potion.prowess", name: "Potion of Prowess", tableSource: "POT2", useTiming: "combat", effects: [], valueGp: 26, mvp: true },
|
||||
{ id: "potion.mighty-strength", name: "Potion of Mighty Strength", tableSource: "POT2", useTiming: "combat", effects: [], valueGp: 20, mvp: true },
|
||||
{ id: "potion.gain-health", name: "Potion of Gain Health", tableSource: "POT2", useTiming: "any", effects: [{ type: "heal", amount: 15, target: "self" }], valueGp: 25, mvp: true },
|
||||
{ id: "potion.finesse", name: "Potion of Finesse", tableSource: "POT2", useTiming: "combat", effects: [], valueGp: 50, mvp: true },
|
||||
{ id: "potion.finesse-alt", name: "Potion of Finesse", tableSource: "POT2", useTiming: "combat", effects: [], valueGp: 50, mvp: true },
|
||||
{ id: "potion.finesse-3", name: "Potion of Finesse", tableSource: "POT3", useTiming: "combat", effects: [], valueGp: 50, mvp: true },
|
||||
{ id: "potion.gain-health-alt", name: "Potion of Gain Health", tableSource: "POT3", useTiming: "any", effects: [{ type: "heal", amount: 15, target: "self" }], valueGp: 25, mvp: true },
|
||||
{ id: "potion.gain-health-2", name: "Potion of Gain Health", tableSource: "POT3", useTiming: "any", effects: [{ type: "heal", amount: 15, target: "self" }], valueGp: 25, mvp: true },
|
||||
{ id: "potion.divine-shield", name: "Potion of Divine Shield", tableSource: "POT3", useTiming: "combat", effects: [], valueGp: 1000, mvp: true },
|
||||
{ id: "potion.willpower", name: "Potion of Willpower", tableSource: "POT3", useTiming: "exploration", effects: [], valueGp: 30, mvp: true },
|
||||
{ id: "potion.further-healing", name: "Further Healing", tableSource: "POT4", useTiming: "any", effects: [{ type: "heal", amount: 25, target: "self" }], valueGp: 40, mvp: true },
|
||||
{ id: "potion.healing-4", name: "Potion of Healing", tableSource: "POT4", useTiming: "any", effects: [{ type: "heal", amount: 3, target: "self" }], valueGp: 25, mvp: true },
|
||||
{ id: "potion.steadiness", name: "Potion of Steadiness", tableSource: "POT4", useTiming: "combat", effects: [], valueGp: 8, mvp: true },
|
||||
{ id: "potion.domination", name: "Potion of Domination", tableSource: "POT4", useTiming: "combat", effects: [], valueGp: 200, mvp: true },
|
||||
{ id: "potion.dexterous-actions", name: "Potion of Dexterous Actions", tableSource: "POT4", useTiming: "combat", effects: [], valueGp: 100, mvp: true },
|
||||
{ id: "potion.power-of-invisibility", name: "Power of Invisibility", tableSource: "BST2", useTiming: "any", effects: [], valueGp: 80, mvp: true },
|
||||
],
|
||||
scrolls: [
|
||||
{
|
||||
@@ -289,6 +801,12 @@ const samplePack = {
|
||||
startingOption: true,
|
||||
mvp: true,
|
||||
},
|
||||
{ id: "scroll.balance", name: "Scroll of Balance", tableSource: "SCT1", onSuccess: [], startingOption: false, valueGp: 20, mvp: true },
|
||||
{ id: "scroll.reading", name: "Scroll of Reading", tableSource: "SCT1", onSuccess: [], startingOption: false, valueGp: 15, mvp: true },
|
||||
{ id: "scroll.brute-force", name: "Scroll of Brute Force", tableSource: "SCT1", onSuccess: [], startingOption: false, valueGp: 20, mvp: true },
|
||||
{ id: "scroll.ignite", name: "Scroll of Ignite", tableSource: "SCT1", onSuccess: [], startingOption: false, valueGp: 15, mvp: true },
|
||||
{ id: "scroll.mental-whip", name: "Scroll of Mental Whip", tableSource: "SCT1", onSuccess: [], startingOption: false, valueGp: 20, mvp: true },
|
||||
{ id: "scroll.paralysis", name: "Scroll of Paralysis", tableSource: "SCT1", onSuccess: [], startingOption: false, valueGp: 25, mvp: true },
|
||||
],
|
||||
creatures: [
|
||||
{
|
||||
@@ -419,7 +937,10 @@ const samplePack = {
|
||||
tags: ["starter", "entry"],
|
||||
mvp: true,
|
||||
},
|
||||
...level1RoomTemplates,
|
||||
...level1RoomTemplates.map((template) => ({
|
||||
...template,
|
||||
objects: getLevel1RoomObjects(template.id),
|
||||
})),
|
||||
],
|
||||
townServices: [
|
||||
{
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { sampleContentPack } from "@/data/sampleContentPack";
|
||||
|
||||
import { createStartingAdventurer } from "./character";
|
||||
import { createCampaignSession, summarizeRun, syncCampaignFromRun, updateSessionRun } from "./campaign";
|
||||
import { returnToTown } from "./runState";
|
||||
|
||||
function createAdventurer() {
|
||||
return createStartingAdventurer(sampleContentPack, {
|
||||
name: "Aster",
|
||||
weaponId: "weapon.short-sword",
|
||||
armourId: "armour.leather-vest",
|
||||
scrollId: "scroll.lesser-heal",
|
||||
});
|
||||
}
|
||||
|
||||
describe("campaign session", () => {
|
||||
it("creates a synced campaign and run together", () => {
|
||||
const session = createCampaignSession({
|
||||
content: sampleContentPack,
|
||||
adventurer: createAdventurer(),
|
||||
campaignId: "campaign.test",
|
||||
at: "2026-03-18T20:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(session.campaign.id).toBe("campaign.test");
|
||||
expect(session.campaign.adventurer.name).toBe("Aster");
|
||||
expect(session.campaign.runHistory[0]?.runId).toBe(session.run.id);
|
||||
});
|
||||
|
||||
it("syncs campaign state from an updated run", () => {
|
||||
const session = createCampaignSession({
|
||||
content: sampleContentPack,
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const nextRun = returnToTown(session.run, "2026-03-18T20:10:00.000Z").run;
|
||||
const synced = syncCampaignFromRun(
|
||||
sampleContentPack,
|
||||
session.campaign,
|
||||
nextRun,
|
||||
"2026-03-18T20:10:00.000Z",
|
||||
);
|
||||
|
||||
expect(synced.townState.visits).toBe(1);
|
||||
expect(synced.updatedAt).toBe("2026-03-18T20:10:00.000Z");
|
||||
expect(synced.runHistory[0]?.outcome).toBe("saved-in-progress");
|
||||
});
|
||||
|
||||
it("updates a session run and campaign together", () => {
|
||||
const session = createCampaignSession({
|
||||
content: sampleContentPack,
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const updated = updateSessionRun(
|
||||
sampleContentPack,
|
||||
session,
|
||||
returnToTown(session.run, "2026-03-18T20:10:00.000Z").run,
|
||||
"2026-03-18T20:10:00.000Z",
|
||||
);
|
||||
|
||||
expect(updated.run.phase).toBe("town");
|
||||
expect(updated.campaign.townState.visits).toBe(1);
|
||||
});
|
||||
|
||||
it("promotes completed and unlocked levels from run flags", () => {
|
||||
const session = createCampaignSession({
|
||||
content: sampleContentPack,
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const nextRun = {
|
||||
...session.run,
|
||||
dungeon: {
|
||||
...session.run.dungeon,
|
||||
globalFlags: ["level:1:completed"],
|
||||
},
|
||||
};
|
||||
const synced = syncCampaignFromRun(
|
||||
sampleContentPack,
|
||||
session.campaign,
|
||||
nextRun,
|
||||
"2026-03-18T20:15:00.000Z",
|
||||
);
|
||||
|
||||
expect(synced.completedLevels).toContain(1);
|
||||
expect(synced.unlockedLevels).toContain(2);
|
||||
});
|
||||
|
||||
it("summarizes failed runs as defeats", () => {
|
||||
const session = createCampaignSession({
|
||||
content: sampleContentPack,
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
|
||||
const summary = summarizeRun({
|
||||
...session.run,
|
||||
status: "failed",
|
||||
});
|
||||
|
||||
expect(summary.outcome).toBe("defeated");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
import type { ContentPack } from "@/types/content";
|
||||
import type { CampaignState, RunState, RunSummary } from "@/types/state";
|
||||
|
||||
import { createRunState } from "./runState";
|
||||
|
||||
export const RULES_VERSION = "0.1.0";
|
||||
|
||||
export type CampaignSession = {
|
||||
campaign: CampaignState;
|
||||
run: RunState;
|
||||
};
|
||||
|
||||
export type CreateCampaignSessionOptions = {
|
||||
content: ContentPack;
|
||||
adventurer: CampaignState["adventurer"];
|
||||
at?: string;
|
||||
campaignId?: string;
|
||||
runId?: string;
|
||||
rulesVersion?: string;
|
||||
};
|
||||
|
||||
function dedupeNumbers(values: number[]) {
|
||||
return [...new Set(values)].sort((left, right) => left - right);
|
||||
}
|
||||
|
||||
function getCompletedLevels(run: RunState) {
|
||||
return run.dungeon.globalFlags
|
||||
.map((flag) => /^level:(\d+):completed$/.exec(flag)?.[1])
|
||||
.filter((value): value is string => Boolean(value))
|
||||
.map((value) => Number.parseInt(value, 10))
|
||||
.filter((value) => Number.isFinite(value));
|
||||
}
|
||||
|
||||
function inferRunOutcome(run: RunState): RunSummary["outcome"] {
|
||||
if (run.status === "failed") {
|
||||
return "defeated";
|
||||
}
|
||||
|
||||
if (run.status === "completed") {
|
||||
return "escaped";
|
||||
}
|
||||
|
||||
return "saved-in-progress";
|
||||
}
|
||||
|
||||
export function summarizeRun(run: RunState, endedAt?: string): RunSummary {
|
||||
const roomsVisited = Object.values(run.dungeon.levels).reduce(
|
||||
(total, level) =>
|
||||
total + Object.values(level.rooms).filter((room) => room.discovery.entered).length,
|
||||
0,
|
||||
);
|
||||
const treasureValue = run.lootedItems.reduce((total, item) => total + item.quantity, 0);
|
||||
|
||||
return {
|
||||
runId: run.id,
|
||||
startedAt: run.startedAt,
|
||||
endedAt,
|
||||
deepestLevel: run.currentLevel,
|
||||
roomsVisited,
|
||||
creaturesDefeated: [...run.defeatedCreatureIds],
|
||||
xpGained: run.xpGained,
|
||||
treasureValue,
|
||||
outcome: inferRunOutcome(run),
|
||||
};
|
||||
}
|
||||
|
||||
function upsertRunSummary(runHistory: RunSummary[], summary: RunSummary) {
|
||||
const nextHistory = runHistory.filter((entry) => entry.runId !== summary.runId);
|
||||
nextHistory.unshift(summary);
|
||||
return nextHistory;
|
||||
}
|
||||
|
||||
export function createCampaignFromRun(
|
||||
content: ContentPack,
|
||||
run: RunState,
|
||||
options?: {
|
||||
at?: string;
|
||||
rulesVersion?: string;
|
||||
},
|
||||
): CampaignState {
|
||||
const at = options?.at ?? run.startedAt;
|
||||
|
||||
return {
|
||||
id: run.campaignId,
|
||||
createdAt: at,
|
||||
updatedAt: at,
|
||||
rulesVersion: options?.rulesVersion ?? RULES_VERSION,
|
||||
contentVersion: content.version,
|
||||
adventurer: structuredClone(run.adventurerSnapshot),
|
||||
unlockedLevels: [1],
|
||||
completedLevels: [],
|
||||
townState: structuredClone(run.townState),
|
||||
questState: [],
|
||||
campaignFlags: [],
|
||||
runHistory: [summarizeRun(run)],
|
||||
};
|
||||
}
|
||||
|
||||
export function syncCampaignFromRun(
|
||||
content: ContentPack,
|
||||
campaign: CampaignState,
|
||||
run: RunState,
|
||||
at = new Date().toISOString(),
|
||||
): CampaignState {
|
||||
const completedLevels = dedupeNumbers([...campaign.completedLevels, ...getCompletedLevels(run)]);
|
||||
const unlockedLevels = dedupeNumbers([
|
||||
...campaign.unlockedLevels,
|
||||
run.currentLevel,
|
||||
...completedLevels,
|
||||
...completedLevels.map((level) => level + 1),
|
||||
]);
|
||||
|
||||
return {
|
||||
...structuredClone(campaign),
|
||||
updatedAt: at,
|
||||
contentVersion: content.version,
|
||||
adventurer: structuredClone(run.adventurerSnapshot),
|
||||
townState: structuredClone(run.townState),
|
||||
unlockedLevels,
|
||||
completedLevels,
|
||||
runHistory: upsertRunSummary(campaign.runHistory, summarizeRun(run)),
|
||||
};
|
||||
}
|
||||
|
||||
export function createCampaignSession(
|
||||
options: CreateCampaignSessionOptions,
|
||||
): CampaignSession {
|
||||
const run = createRunState({
|
||||
content: options.content,
|
||||
adventurer: options.adventurer,
|
||||
campaignId: options.campaignId ?? "campaign.demo",
|
||||
runId: options.runId,
|
||||
at: options.at,
|
||||
});
|
||||
const campaign = createCampaignFromRun(options.content, run, {
|
||||
at: options.at,
|
||||
rulesVersion: options.rulesVersion,
|
||||
});
|
||||
|
||||
return {
|
||||
campaign,
|
||||
run,
|
||||
};
|
||||
}
|
||||
|
||||
export function updateSessionRun(
|
||||
content: ContentPack,
|
||||
session: CampaignSession,
|
||||
nextRun: RunState,
|
||||
at = new Date().toISOString(),
|
||||
): CampaignSession {
|
||||
return {
|
||||
run: nextRun,
|
||||
campaign: syncCampaignFromRun(content, session.campaign, nextRun, at),
|
||||
};
|
||||
}
|
||||
@@ -123,6 +123,7 @@ export function createStartingAdventurer(
|
||||
stored: [],
|
||||
currency: {
|
||||
gold: 0,
|
||||
silver: 0,
|
||||
},
|
||||
rationCount: 3,
|
||||
lightSources: [makeInventoryEntry("item.lantern")],
|
||||
|
||||
@@ -7,6 +7,12 @@ import type {
|
||||
import type { AdventurerState, CombatState, CombatantState } from "@/types/state";
|
||||
import type { LogEntry } from "@/types/rules";
|
||||
|
||||
import {
|
||||
INSIGHTFUL_COMBAT_STATUS_ID,
|
||||
SLEEPING_STATUS_ID,
|
||||
consumeWardReduction,
|
||||
consumeStatusValue,
|
||||
} from "./magicItems";
|
||||
import { roll2D6, type DiceRoller } from "./dice";
|
||||
|
||||
export type ResolvePlayerAttackOptions = {
|
||||
@@ -138,9 +144,11 @@ export function resolvePlayerAttack(
|
||||
}
|
||||
|
||||
const roll = roll2D6(options.roller);
|
||||
const insightfulBonus = consumeStatusValue(combat.player.statuses, INSIGHTFUL_COMBAT_STATUS_ID);
|
||||
const accuracy =
|
||||
(roll.total ?? 0) +
|
||||
combat.player.precision +
|
||||
insightfulBonus +
|
||||
(manoeuvre.precisionModifier ?? 0);
|
||||
const targetNumber = BASE_TARGET_NUMBER + (target.armourValue ?? 0);
|
||||
const hit = accuracy >= targetNumber;
|
||||
@@ -207,15 +215,42 @@ export function resolveEnemyTurn(
|
||||
throw new Error("No living enemies are available to act.");
|
||||
}
|
||||
|
||||
const sleptThroughTurn = consumeStatusValue(attacker.statuses, SLEEPING_STATUS_ID) > 0;
|
||||
|
||||
if (sleptThroughTurn) {
|
||||
combat.actingSide = "player";
|
||||
combat.round += 1;
|
||||
|
||||
const logEntries: LogEntry[] = [
|
||||
createLogEntry(
|
||||
`${combat.id}.enemy.${combat.combatLog.length + 1}`,
|
||||
at,
|
||||
`${attacker.name} sleeps through the turn.`,
|
||||
[attacker.id, combat.player.id],
|
||||
),
|
||||
];
|
||||
|
||||
combat.combatLog.push(...logEntries);
|
||||
|
||||
return {
|
||||
combat,
|
||||
logEntries,
|
||||
defeatedEnemyIds: [],
|
||||
combatEnded: false,
|
||||
};
|
||||
}
|
||||
|
||||
const roll = roll2D6(options.roller);
|
||||
const armourValue = getPlayerArmourValue(options.content, options.adventurer);
|
||||
const accuracy = (roll.total ?? 0) + attacker.precision;
|
||||
const targetNumber = BASE_TARGET_NUMBER + armourValue;
|
||||
const hit = accuracy >= targetNumber;
|
||||
const rawDamage = hit ? Math.max(1, 1 + attacker.discipline) : 0;
|
||||
const damageReduction = hit ? consumeWardReduction(combat.player.statuses) : 0;
|
||||
const damage = hit ? Math.max(0, rawDamage - damageReduction) : 0;
|
||||
|
||||
if (hit) {
|
||||
combat.player.hpCurrent = Math.max(0, combat.player.hpCurrent - rawDamage);
|
||||
combat.player.hpCurrent = Math.max(0, combat.player.hpCurrent - damage);
|
||||
}
|
||||
|
||||
combat.lastRoll = roll;
|
||||
@@ -227,7 +262,7 @@ export function resolveEnemyTurn(
|
||||
`${combat.id}.enemy.${combat.combatLog.length + 1}`,
|
||||
at,
|
||||
hit
|
||||
? `${attacker.name} attacks ${combat.player.name}, rolls ${roll.total}, and deals ${rawDamage} damage.`
|
||||
? `${attacker.name} attacks ${combat.player.name}, rolls ${roll.total}, and deals ${damage} damage${damageReduction > 0 ? ` after resistance reduces it by ${damageReduction}` : ""}.`
|
||||
: `${attacker.name} attacks ${combat.player.name}, rolls ${roll.total}, and misses.`,
|
||||
[attacker.id, combat.player.id],
|
||||
),
|
||||
|
||||
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { sampleContentPack } from "@/data/sampleContentPack";
|
||||
|
||||
import {
|
||||
addSecretDoorFallback,
|
||||
expandLevelFromExit,
|
||||
getUnresolvedExits,
|
||||
initializeDungeonLevel,
|
||||
@@ -84,4 +85,17 @@ describe("dungeon state", () => {
|
||||
}),
|
||||
).toThrow("already connected");
|
||||
});
|
||||
|
||||
it("adds a fallback secret exit when progression stalls", () => {
|
||||
const levelState = initializeDungeonLevel({ content: sampleContentPack });
|
||||
const room = levelState.rooms["room.level1.start"]!;
|
||||
|
||||
room.exits = [];
|
||||
|
||||
const fallback = addSecretDoorFallback(levelState);
|
||||
|
||||
expect(fallback.levelState.secretDoorUsed).toBe(true);
|
||||
expect(fallback.room.id).toBe("room.level1.start");
|
||||
expect(fallback.exit.exitType).toBe("secret");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -28,6 +28,17 @@ export type ExpansionResult = {
|
||||
fromRoom: RoomState;
|
||||
};
|
||||
|
||||
export type PlaceStairsDownResult = {
|
||||
levelState: DungeonLevelState;
|
||||
room: RoomState;
|
||||
};
|
||||
|
||||
export type SecretDoorFallbackResult = {
|
||||
levelState: DungeonLevelState;
|
||||
room: RoomState;
|
||||
exit: RoomExitState;
|
||||
};
|
||||
|
||||
const DIRECTION_VECTORS: Record<CardinalDirection, { x: number; y: number }> = {
|
||||
north: { x: 0, y: -1 },
|
||||
east: { x: 1, y: 0 },
|
||||
@@ -77,6 +88,16 @@ function cloneLevel(levelState: DungeonLevelState): DungeonLevelState {
|
||||
};
|
||||
}
|
||||
|
||||
function getAvailableStairsDirection(room: RoomState): CardinalDirection {
|
||||
const usedDirections = new Set(room.exits.map((exit) => exit.direction));
|
||||
|
||||
return (
|
||||
(["north", "east", "south", "west"] as const).find(
|
||||
(direction) => !usedDirections.has(direction),
|
||||
) ?? "north"
|
||||
);
|
||||
}
|
||||
|
||||
function findExit(room: RoomState, direction: CardinalDirection): RoomExitState {
|
||||
const exit = room.exits.find((candidate) => candidate.direction === direction);
|
||||
|
||||
@@ -96,6 +117,12 @@ function computeNextPosition(room: RoomState, direction: CardinalDirection) {
|
||||
};
|
||||
}
|
||||
|
||||
function isCoordinateOccupied(levelState: DungeonLevelState, position: { x: number; y: number }) {
|
||||
return Object.values(levelState.rooms).some(
|
||||
(room) => room.position.x === position.x && room.position.y === position.y,
|
||||
);
|
||||
}
|
||||
|
||||
function connectRooms(
|
||||
fromRoom: RoomState,
|
||||
toRoom: RoomState,
|
||||
@@ -135,6 +162,18 @@ function assertCoordinateAvailable(levelState: DungeonLevelState, position: { x:
|
||||
}
|
||||
}
|
||||
|
||||
function getLegalNewExitDirections(levelState: DungeonLevelState, room: RoomState) {
|
||||
const usedDirections = new Set(room.exits.map((exit) => exit.direction));
|
||||
|
||||
return (["north", "east", "south", "west"] as const).filter((direction) => {
|
||||
if (usedDirections.has(direction)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !isCoordinateOccupied(levelState, computeNextPosition(room, direction));
|
||||
});
|
||||
}
|
||||
|
||||
export function initializeDungeonLevel(
|
||||
options: InitializeLevelOptions,
|
||||
): DungeonLevelState {
|
||||
@@ -217,3 +256,126 @@ export function expandLevelFromExit(
|
||||
fromRoom,
|
||||
};
|
||||
}
|
||||
|
||||
export function canPlaceStairsDown(
|
||||
levelState: DungeonLevelState,
|
||||
roomId: string,
|
||||
) {
|
||||
const room = levelState.rooms[roomId];
|
||||
|
||||
if (!room) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (levelState.stairsDownRoomId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!room.discovery.cleared) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (getUnresolvedExits(levelState).length > 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !Object.values(levelState.rooms).some(
|
||||
(candidate) =>
|
||||
candidate.id !== roomId &&
|
||||
candidate.roomClass !== "start" &&
|
||||
candidate.roomClass !== "stairs" &&
|
||||
!candidate.discovery.cleared,
|
||||
);
|
||||
}
|
||||
|
||||
export function placeStairsDown(
|
||||
levelState: DungeonLevelState,
|
||||
roomId: string,
|
||||
): PlaceStairsDownResult {
|
||||
if (!canPlaceStairsDown(levelState, roomId)) {
|
||||
throw new Error(`Cannot place stairs down in room ${roomId}.`);
|
||||
}
|
||||
|
||||
const nextLevelState = cloneLevel(levelState);
|
||||
const room = nextLevelState.rooms[roomId];
|
||||
|
||||
if (!room) {
|
||||
throw new Error(`Unknown room id: ${roomId}`);
|
||||
}
|
||||
|
||||
if (!room.exits.some((exit) => exit.exitType === "stairs")) {
|
||||
room.exits.push({
|
||||
id: `${room.id}.exit.${room.exits.length + 1}`,
|
||||
direction: getAvailableStairsDirection(room),
|
||||
exitType: "stairs",
|
||||
discovered: true,
|
||||
traversable: true,
|
||||
destinationLevel: levelState.level + 1,
|
||||
});
|
||||
}
|
||||
|
||||
if (!room.flags.includes("stairs-down")) {
|
||||
room.flags.push("stairs-down");
|
||||
}
|
||||
|
||||
if (!room.notes.some((note) => note.includes("stairs"))) {
|
||||
room.notes.push(`A stairway descends toward level ${levelState.level + 1}.`);
|
||||
}
|
||||
|
||||
nextLevelState.rooms[roomId] = room;
|
||||
nextLevelState.stairsDownRoomId = roomId;
|
||||
|
||||
return {
|
||||
levelState: nextLevelState,
|
||||
room,
|
||||
};
|
||||
}
|
||||
|
||||
export function addSecretDoorFallback(
|
||||
levelState: DungeonLevelState,
|
||||
): SecretDoorFallbackResult {
|
||||
if (levelState.secretDoorUsed) {
|
||||
throw new Error("Secret door fallback has already been used on this level.");
|
||||
}
|
||||
|
||||
const nextLevelState = cloneLevel(levelState);
|
||||
|
||||
for (const roomId of [...nextLevelState.discoveredRoomOrder].reverse()) {
|
||||
const room = nextLevelState.rooms[roomId];
|
||||
|
||||
if (!room) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const direction = getLegalNewExitDirections(nextLevelState, room)[0];
|
||||
|
||||
if (!direction) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const exit: RoomExitState = {
|
||||
id: `${room.id}.exit.${room.exits.length + 1}`,
|
||||
direction,
|
||||
exitType: "secret",
|
||||
discovered: true,
|
||||
traversable: true,
|
||||
};
|
||||
|
||||
room.exits.push(exit);
|
||||
|
||||
if (!room.flags.includes("fallback-secret-exit")) {
|
||||
room.flags.push("fallback-secret-exit");
|
||||
}
|
||||
|
||||
nextLevelState.rooms[roomId] = room;
|
||||
nextLevelState.secretDoorUsed = true;
|
||||
|
||||
return {
|
||||
levelState: nextLevelState,
|
||||
room,
|
||||
exit,
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error("No eligible room could host a fallback secret door.");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { RoomState, RunState, StatusInstance } from "@/types/state";
|
||||
|
||||
export const AMULET_RESISTANCE_STATUS_ID = "status.amulet-of-resistance";
|
||||
export const AMULET_FIRE_RESISTANCE_STATUS_ID = "status.amulet-of-fire-resistance";
|
||||
export const INSIGHTFUL_COMBAT_STATUS_ID = "status.insightful-combat";
|
||||
export const SLEEPING_STATUS_ID = "status.sleeping";
|
||||
|
||||
function findCarriedEntry(run: RunState, definitionId: string) {
|
||||
return run.adventurerSnapshot.inventory.carried.find((entry) => entry.definitionId === definitionId);
|
||||
}
|
||||
|
||||
export function getCarriedItemCount(run: RunState, definitionId: string) {
|
||||
return findCarriedEntry(run, definitionId)?.quantity ?? 0;
|
||||
}
|
||||
|
||||
export function consumeCarriedItem(run: RunState, definitionId: string, quantity = 1) {
|
||||
const existing = findCarriedEntry(run, definitionId);
|
||||
|
||||
if (!existing || existing.quantity < quantity) {
|
||||
throw new Error(`No carried ${definitionId} is available to consume.`);
|
||||
}
|
||||
|
||||
existing.quantity -= quantity;
|
||||
|
||||
if (existing.quantity === 0) {
|
||||
const index = run.adventurerSnapshot.inventory.carried.indexOf(existing);
|
||||
run.adventurerSnapshot.inventory.carried.splice(index, 1);
|
||||
}
|
||||
}
|
||||
|
||||
export function hasStatus(statuses: StatusInstance[], statusId: string) {
|
||||
return statuses.some((status) => status.id === statusId);
|
||||
}
|
||||
|
||||
export function addStatus(statuses: StatusInstance[], status: StatusInstance) {
|
||||
if (!hasStatus(statuses, status.id)) {
|
||||
statuses.push(status);
|
||||
}
|
||||
}
|
||||
|
||||
export function consumeStatusValue(statuses: StatusInstance[], statusId: string) {
|
||||
const index = statuses.findIndex((status) => status.id === statusId);
|
||||
|
||||
if (index === -1) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const [removed] = statuses.splice(index, 1);
|
||||
return removed?.value ?? 0;
|
||||
}
|
||||
|
||||
export function consumeWardReduction(statuses: StatusInstance[]) {
|
||||
return (
|
||||
consumeStatusValue(statuses, AMULET_RESISTANCE_STATUS_ID) +
|
||||
consumeStatusValue(statuses, AMULET_FIRE_RESISTANCE_STATUS_ID)
|
||||
);
|
||||
}
|
||||
|
||||
export function revealHiddenObjects(room: RoomState) {
|
||||
const hiddenObjects = room.objects.filter((object) => object.hidden);
|
||||
|
||||
hiddenObjects.forEach((object) => {
|
||||
object.hidden = false;
|
||||
});
|
||||
|
||||
if (hiddenObjects.length > 0) {
|
||||
room.discovery.searched = true;
|
||||
}
|
||||
|
||||
return hiddenObjects;
|
||||
}
|
||||
@@ -3,11 +3,18 @@ import { describe, expect, it } from "vitest";
|
||||
import { sampleContentPack } from "@/data/sampleContentPack";
|
||||
|
||||
import { createStartingAdventurer } from "./character";
|
||||
import { createCampaignSession } from "./campaign";
|
||||
import {
|
||||
deleteSavedCampaignSession,
|
||||
deleteSavedRun,
|
||||
exportCampaignSession,
|
||||
importCampaignSession,
|
||||
listSavedCampaigns,
|
||||
loadSavedRun,
|
||||
loadSavedCampaignSession,
|
||||
saveRun,
|
||||
listSavedRuns,
|
||||
saveCampaignSession,
|
||||
type StorageLike,
|
||||
} from "./persistence";
|
||||
import { createRunState, returnToTown } from "./runState";
|
||||
@@ -100,3 +107,54 @@ describe("run persistence", () => {
|
||||
expect(listSavedRuns(storage)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("campaign persistence", () => {
|
||||
it("saves and loads a campaign session", () => {
|
||||
const storage = createMemoryStorage();
|
||||
const session = createCampaignSession({
|
||||
content: sampleContentPack,
|
||||
adventurer: createAdventurer(),
|
||||
campaignId: "campaign.1",
|
||||
at: "2026-03-18T23:00:00.000Z",
|
||||
});
|
||||
|
||||
saveCampaignSession(storage, session, {
|
||||
saveId: "campaign.one",
|
||||
savedAt: "2026-03-18T23:00:00.000Z",
|
||||
});
|
||||
|
||||
const loaded = loadSavedCampaignSession(storage, "campaign.one");
|
||||
|
||||
expect(loaded.campaign.id).toBe("campaign.1");
|
||||
expect(loaded.run.adventurerSnapshot.name).toBe("Aster");
|
||||
});
|
||||
|
||||
it("lists and deletes campaign saves", () => {
|
||||
const storage = createMemoryStorage();
|
||||
const session = createCampaignSession({
|
||||
content: sampleContentPack,
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
|
||||
saveCampaignSession(storage, session, {
|
||||
saveId: "campaign.one",
|
||||
savedAt: "2026-03-18T23:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(listSavedCampaigns(storage)).toHaveLength(1);
|
||||
expect(deleteSavedCampaignSession(storage, "campaign.one")).toEqual([]);
|
||||
});
|
||||
|
||||
it("exports and imports campaign json", () => {
|
||||
const session = createCampaignSession({
|
||||
content: sampleContentPack,
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
|
||||
const exported = exportCampaignSession(session);
|
||||
const imported = importCampaignSession(exported);
|
||||
|
||||
expect(imported.campaign.id).toBe(session.campaign.id);
|
||||
expect(imported.run.id).toBe(session.run.id);
|
||||
});
|
||||
});
|
||||
|
||||
+142
-1
@@ -1,7 +1,8 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { runStateSchema } from "@/schemas/state";
|
||||
import { campaignStateSchema, runStateSchema } from "@/schemas/state";
|
||||
import type { RunState } from "@/types/state";
|
||||
import type { CampaignSession } from "./campaign";
|
||||
|
||||
export type StorageLike = {
|
||||
getItem(key: string): string | null;
|
||||
@@ -26,7 +27,26 @@ export type SavedRunSummary = {
|
||||
adventurerName: string;
|
||||
};
|
||||
|
||||
export type SavedCampaignRecord = {
|
||||
id: string;
|
||||
label: string;
|
||||
savedAt: string;
|
||||
session: CampaignSession;
|
||||
};
|
||||
|
||||
export type SavedCampaignSummary = {
|
||||
id: string;
|
||||
label: string;
|
||||
savedAt: string;
|
||||
campaignId: string;
|
||||
adventurerName: string;
|
||||
currentLevel: number;
|
||||
phase: RunState["phase"];
|
||||
visits: number;
|
||||
};
|
||||
|
||||
const STORAGE_KEY = "d2d6-dungeon.run-saves.v1";
|
||||
const CAMPAIGN_STORAGE_KEY = "d2d6-dungeon.campaign-saves.v1";
|
||||
|
||||
const savedRunRecordSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
@@ -36,6 +56,16 @@ const savedRunRecordSchema = z.object({
|
||||
});
|
||||
|
||||
const savedRunRecordListSchema = z.array(savedRunRecordSchema);
|
||||
const savedCampaignRecordSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
savedAt: z.string().min(1),
|
||||
session: z.object({
|
||||
campaign: campaignStateSchema,
|
||||
run: runStateSchema,
|
||||
}),
|
||||
});
|
||||
const savedCampaignRecordListSchema = z.array(savedCampaignRecordSchema);
|
||||
|
||||
function readSaveRecords(storage: StorageLike): SavedRunRecord[] {
|
||||
const raw = storage.getItem(STORAGE_KEY);
|
||||
@@ -52,6 +82,21 @@ function writeSaveRecords(storage: StorageLike, records: SavedRunRecord[]) {
|
||||
storage.setItem(STORAGE_KEY, JSON.stringify(records));
|
||||
}
|
||||
|
||||
function readCampaignRecords(storage: StorageLike): SavedCampaignRecord[] {
|
||||
const raw = storage.getItem(CAMPAIGN_STORAGE_KEY);
|
||||
|
||||
if (!raw) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
return savedCampaignRecordListSchema.parse(parsed);
|
||||
}
|
||||
|
||||
function writeCampaignRecords(storage: StorageLike, records: SavedCampaignRecord[]) {
|
||||
storage.setItem(CAMPAIGN_STORAGE_KEY, JSON.stringify(records));
|
||||
}
|
||||
|
||||
function toSummary(record: SavedRunRecord): SavedRunSummary {
|
||||
return {
|
||||
id: record.id,
|
||||
@@ -64,11 +109,28 @@ function toSummary(record: SavedRunRecord): SavedRunSummary {
|
||||
};
|
||||
}
|
||||
|
||||
function toCampaignSummary(record: SavedCampaignRecord): SavedCampaignSummary {
|
||||
return {
|
||||
id: record.id,
|
||||
label: record.label,
|
||||
savedAt: record.savedAt,
|
||||
campaignId: record.session.campaign.id,
|
||||
adventurerName: record.session.campaign.adventurer.name,
|
||||
currentLevel: record.session.run.currentLevel,
|
||||
phase: record.session.run.phase,
|
||||
visits: record.session.campaign.townState.visits,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildSaveLabel(run: RunState) {
|
||||
const roomLabel = run.currentRoomId ?? "unknown-room";
|
||||
return `${run.adventurerSnapshot.name} · L${run.currentLevel} · ${run.phase} · ${roomLabel}`;
|
||||
}
|
||||
|
||||
export function buildCampaignSaveLabel(session: CampaignSession) {
|
||||
return `${session.campaign.adventurer.name} · L${session.run.currentLevel} · ${session.run.phase} · ${session.campaign.runHistory.length} log`;
|
||||
}
|
||||
|
||||
export function listSavedRuns(storage: StorageLike): SavedRunSummary[] {
|
||||
return readSaveRecords(storage)
|
||||
.sort((left, right) => right.savedAt.localeCompare(left.savedAt))
|
||||
@@ -128,3 +190,82 @@ export function getBrowserStorage(): StorageLike | null {
|
||||
|
||||
return window.localStorage;
|
||||
}
|
||||
|
||||
export function listSavedCampaigns(storage: StorageLike): SavedCampaignSummary[] {
|
||||
return readCampaignRecords(storage)
|
||||
.sort((left, right) => right.savedAt.localeCompare(left.savedAt))
|
||||
.map(toCampaignSummary);
|
||||
}
|
||||
|
||||
export function saveCampaignSession(
|
||||
storage: StorageLike,
|
||||
session: CampaignSession,
|
||||
options?: {
|
||||
saveId?: string;
|
||||
label?: string;
|
||||
savedAt?: string;
|
||||
},
|
||||
): SavedCampaignSummary {
|
||||
const savedAt = options?.savedAt ?? new Date().toISOString();
|
||||
const id = options?.saveId ?? `campaign-save.${savedAt}`;
|
||||
const label = options?.label ?? buildCampaignSaveLabel(session);
|
||||
const record = savedCampaignRecordSchema.parse({
|
||||
id,
|
||||
label,
|
||||
savedAt,
|
||||
session,
|
||||
});
|
||||
const existing = readCampaignRecords(storage).filter((entry) => entry.id !== id);
|
||||
|
||||
existing.unshift(record);
|
||||
writeCampaignRecords(storage, existing);
|
||||
|
||||
return toCampaignSummary(record);
|
||||
}
|
||||
|
||||
export function loadSavedCampaignSession(storage: StorageLike, saveId: string): CampaignSession {
|
||||
const record = readCampaignRecords(storage).find((entry) => entry.id === saveId);
|
||||
|
||||
if (!record) {
|
||||
throw new Error(`Unknown campaign save id: ${saveId}`);
|
||||
}
|
||||
|
||||
return record.session;
|
||||
}
|
||||
|
||||
export function deleteSavedCampaignSession(
|
||||
storage: StorageLike,
|
||||
saveId: string,
|
||||
): SavedCampaignSummary[] {
|
||||
const records = readCampaignRecords(storage).filter((entry) => entry.id !== saveId);
|
||||
|
||||
writeCampaignRecords(storage, records);
|
||||
|
||||
return records
|
||||
.sort((left, right) => right.savedAt.localeCompare(left.savedAt))
|
||||
.map(toCampaignSummary);
|
||||
}
|
||||
|
||||
export function exportCampaignSession(session: CampaignSession) {
|
||||
return JSON.stringify(
|
||||
{
|
||||
exportedAt: new Date().toISOString(),
|
||||
session,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
}
|
||||
|
||||
export function importCampaignSession(serialized: string): CampaignSession {
|
||||
const parsed = JSON.parse(serialized) as unknown;
|
||||
const importSchema = z.object({
|
||||
exportedAt: z.string().min(1),
|
||||
session: z.object({
|
||||
campaign: campaignStateSchema,
|
||||
run: runStateSchema,
|
||||
}),
|
||||
});
|
||||
|
||||
return importSchema.parse(parsed).session;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { sampleContentPack } from "@/data/sampleContentPack";
|
||||
|
||||
import { createStartingAdventurer } from "./character";
|
||||
import { createRoomStateFromTemplate } from "./rooms";
|
||||
import { resolveRoomObject, searchRoom } from "./roomObjects";
|
||||
import { createRunState } from "./runState";
|
||||
|
||||
function createAdventurer() {
|
||||
return createStartingAdventurer(sampleContentPack, {
|
||||
name: "Aster",
|
||||
weaponId: "weapon.short-sword",
|
||||
armourId: "armour.leather-vest",
|
||||
scrollId: "scroll.lesser-heal",
|
||||
});
|
||||
}
|
||||
|
||||
function createSequenceRoller(values: number[]) {
|
||||
let index = 0;
|
||||
|
||||
return () => {
|
||||
const next = values[index] ?? values.at(-1) ?? 1;
|
||||
index += 1;
|
||||
return next;
|
||||
};
|
||||
}
|
||||
|
||||
describe("room objects", () => {
|
||||
it("seeds room objects from searchable room templates", () => {
|
||||
const room = createRoomStateFromTemplate(
|
||||
sampleContentPack,
|
||||
"room.level1.test",
|
||||
1,
|
||||
"room.level1.normal.abandoned-guard-post",
|
||||
);
|
||||
|
||||
expect(room.objects.length).toBeGreaterThan(0);
|
||||
expect(room.objects.some((object) => object.objectType === "container")).toBe(true);
|
||||
expect(room.objects[0]?.sourceTableCode).toBe("PT1");
|
||||
});
|
||||
|
||||
it("reveals hidden objects when the room is searched", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const room = createRoomStateFromTemplate(
|
||||
sampleContentPack,
|
||||
"room.level1.test",
|
||||
1,
|
||||
"room.level1.large.dormitory",
|
||||
);
|
||||
|
||||
const hiddenObject = room.objects.find((object) => object.hidden);
|
||||
expect(hiddenObject).toBeDefined();
|
||||
|
||||
const result = searchRoom(run, room, "2026-03-18T21:00:00.000Z");
|
||||
|
||||
expect(result.room.discovery.searched).toBe(true);
|
||||
expect(result.room.objects.every((object) => object.hidden !== true)).toBe(true);
|
||||
expect(result.logEntries[0]?.text).toContain("reveals");
|
||||
});
|
||||
|
||||
it("supports multiple codex-aligned objects in a single room", () => {
|
||||
const room = createRoomStateFromTemplate(
|
||||
sampleContentPack,
|
||||
"room.level1.test",
|
||||
1,
|
||||
"room.level1.large.crate-store",
|
||||
);
|
||||
|
||||
expect(room.objects).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ sourceTableCode: "TCT1" }),
|
||||
expect.objectContaining({ sourceTableCode: "SECT1", hidden: true }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("assigns codex magical interaction tables to more Level 1 rooms", () => {
|
||||
const temple = createRoomStateFromTemplate(
|
||||
sampleContentPack,
|
||||
"room.level1.test",
|
||||
1,
|
||||
"room.level1.large.temple",
|
||||
);
|
||||
const library = createRoomStateFromTemplate(
|
||||
sampleContentPack,
|
||||
"room.level1.test.library",
|
||||
1,
|
||||
"room.level1.large.library",
|
||||
);
|
||||
|
||||
expect(temple.objects).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ sourceTableCode: "MA1" })]),
|
||||
);
|
||||
expect(library.objects).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ sourceTableCode: "SCT1" })]),
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves chained codex follow-up tables into actual carried loot", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const room = createRoomStateFromTemplate(
|
||||
sampleContentPack,
|
||||
"room.level1.test",
|
||||
1,
|
||||
"room.level1.normal.guard-post",
|
||||
);
|
||||
|
||||
room.objects.forEach((object) => {
|
||||
object.hidden = false;
|
||||
});
|
||||
|
||||
const chest = room.objects.find((object) => object.sourceTableCode === "CT1");
|
||||
expect(chest).toBeDefined();
|
||||
|
||||
const result = resolveRoomObject({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
room,
|
||||
objectId: chest!.id,
|
||||
at: "2026-03-18T21:02:00.000Z",
|
||||
roller: createSequenceRoller([4, 6, 1, 1]),
|
||||
});
|
||||
|
||||
expect(result.logEntries.some((entry) => entry.text.includes("Follow-up roll"))).toBe(true);
|
||||
expect(run.adventurerSnapshot.inventory.carried).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ definitionId: "scroll.balance" }),
|
||||
expect.objectContaining({ definitionId: "item.half-copper-pendant" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("repeats follow-up table rolls when the codex entry calls for multiples", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const room = createRoomStateFromTemplate(
|
||||
sampleContentPack,
|
||||
"room.level1.test",
|
||||
1,
|
||||
"room.level1.normal.mourning-quarters",
|
||||
);
|
||||
|
||||
room.objects.forEach((object) => {
|
||||
object.hidden = false;
|
||||
});
|
||||
|
||||
const corpse = room.objects.find((object) => object.sourceTableCode === "BST2");
|
||||
expect(corpse).toBeDefined();
|
||||
|
||||
const result = resolveRoomObject({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
room,
|
||||
objectId: corpse!.id,
|
||||
at: "2026-03-19T18:05:00.000Z",
|
||||
roller: createSequenceRoller([4, 6, 1, 2, 3]),
|
||||
});
|
||||
|
||||
expect(result.logEntries.filter((entry) => entry.text.includes("Follow-up roll")).length).toBe(3);
|
||||
expect(run.adventurerSnapshot.inventory.carried).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ definitionId: "item.pearl" }),
|
||||
expect.objectContaining({ definitionId: "item.sapphire" }),
|
||||
expect.objectContaining({ definitionId: "item.garnet" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("awards fixed silver outcomes from codex entries", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const room = createRoomStateFromTemplate(
|
||||
sampleContentPack,
|
||||
"room.level1.test",
|
||||
1,
|
||||
"room.level1.large.dormitory",
|
||||
);
|
||||
|
||||
room.objects.forEach((object) => {
|
||||
object.hidden = false;
|
||||
});
|
||||
|
||||
const pouch = room.objects.find((object) => object.sourceTableCode === "PT2");
|
||||
expect(pouch).toBeDefined();
|
||||
|
||||
resolveRoomObject({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
room,
|
||||
objectId: pouch!.id,
|
||||
at: "2026-03-19T18:07:00.000Z",
|
||||
roller: createSequenceRoller([2, 3]),
|
||||
});
|
||||
|
||||
expect(run.adventurerSnapshot.inventory.currency.silver).toBe(25);
|
||||
expect(run.silverGained).toBe(25);
|
||||
});
|
||||
|
||||
it("resolves dice-based silver and gold rewards from codex entries", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const room = createRoomStateFromTemplate(
|
||||
sampleContentPack,
|
||||
"room.level1.test",
|
||||
1,
|
||||
"room.level1.normal.abandoned-guard-post",
|
||||
);
|
||||
|
||||
room.objects.forEach((object) => {
|
||||
object.hidden = false;
|
||||
});
|
||||
|
||||
const pouch = room.objects.find((object) => object.sourceTableCode === "PT1");
|
||||
expect(pouch).toBeDefined();
|
||||
|
||||
resolveRoomObject({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
room,
|
||||
objectId: pouch!.id,
|
||||
at: "2026-03-19T18:09:00.000Z",
|
||||
roller: createSequenceRoller([4, 5, 6, 2]),
|
||||
});
|
||||
|
||||
expect(run.adventurerSnapshot.inventory.currency.silver).toBe(31);
|
||||
expect(run.adventurerSnapshot.inventory.currency.gold).toBe(2);
|
||||
});
|
||||
|
||||
it("resolves PT2 random gem results through an explicit d3 follow-up table", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const room = createRoomStateFromTemplate(
|
||||
sampleContentPack,
|
||||
"room.level1.test",
|
||||
1,
|
||||
"room.level1.large.dormitory",
|
||||
);
|
||||
|
||||
room.objects.forEach((object) => {
|
||||
object.hidden = false;
|
||||
});
|
||||
|
||||
const pouch = room.objects.find((object) => object.sourceTableCode === "PT2");
|
||||
expect(pouch).toBeDefined();
|
||||
|
||||
resolveRoomObject({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
room,
|
||||
objectId: pouch!.id,
|
||||
at: "2026-03-19T18:12:00.000Z",
|
||||
roller: createSequenceRoller([4, 6, 3]),
|
||||
});
|
||||
|
||||
expect(run.adventurerSnapshot.inventory.currency.gold).toBe(20);
|
||||
expect(run.adventurerSnapshot.inventory.carried).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ definitionId: "item.garnet" })]),
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves a room object into loot or damage", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const room = createRoomStateFromTemplate(
|
||||
sampleContentPack,
|
||||
"room.level1.test",
|
||||
1,
|
||||
"room.level1.large.crate-store",
|
||||
);
|
||||
|
||||
room.objects.forEach((object) => {
|
||||
object.hidden = false;
|
||||
});
|
||||
|
||||
const container = room.objects.find((object) => object.objectType === "container");
|
||||
expect(container).toBeDefined();
|
||||
|
||||
const result = resolveRoomObject({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
room,
|
||||
objectId: container!.id,
|
||||
at: "2026-03-18T21:01:00.000Z",
|
||||
roller: () => 6,
|
||||
});
|
||||
|
||||
expect(result.object.interacted).toBe(true);
|
||||
expect(result.object.resolutionLabel).toBe("Garnet Ring and coins");
|
||||
expect(run.adventurerSnapshot.inventory.carried).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ definitionId: "item.garnet-ring" })]),
|
||||
);
|
||||
expect(result.logEntries[0]?.text).toContain("Rolled");
|
||||
expect(result.logEntries[1]?.text).toContain("Garnet Ring and coins");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,535 @@
|
||||
import { findTableByCode } from "@/data/contentHelpers";
|
||||
import type { ContentPack, RoomObjectTemplate, RoomTemplate } from "@/types/content";
|
||||
import type { InventoryEntry, RoomObjectState, RoomState, RunState } from "@/types/state";
|
||||
import type { ContentReference, LogEntry, RuleEffect } from "@/types/rules";
|
||||
|
||||
import type { DiceRoller } from "./dice";
|
||||
import { rollDice } from "./dice";
|
||||
import { consumeWardReduction } from "./magicItems";
|
||||
import { lookupTable } from "./tables";
|
||||
|
||||
export type SearchRoomResult = {
|
||||
run: RunState;
|
||||
room: RoomState;
|
||||
logEntries: LogEntry[];
|
||||
};
|
||||
|
||||
export type ResolveRoomObjectOptions = {
|
||||
content: ContentPack;
|
||||
run: RunState;
|
||||
room: RoomState;
|
||||
objectId: string;
|
||||
at?: string;
|
||||
roller?: DiceRoller;
|
||||
};
|
||||
|
||||
export type ResolveRoomObjectResult = {
|
||||
run: RunState;
|
||||
room: RoomState;
|
||||
object: RoomObjectState;
|
||||
logEntries: LogEntry[];
|
||||
};
|
||||
|
||||
function createLogEntry(
|
||||
id: string,
|
||||
at: string,
|
||||
type: LogEntry["type"],
|
||||
text: string,
|
||||
relatedIds?: string[],
|
||||
): LogEntry {
|
||||
return {
|
||||
id,
|
||||
at,
|
||||
type,
|
||||
text,
|
||||
relatedIds,
|
||||
};
|
||||
}
|
||||
|
||||
function getTemplateText(template: RoomTemplate) {
|
||||
return `${template.title} ${template.text ?? ""} ${template.encounterText ?? ""}`.toLowerCase();
|
||||
}
|
||||
|
||||
function createObjectState(
|
||||
templateId: string,
|
||||
index: number,
|
||||
object: RoomObjectTemplate,
|
||||
): RoomObjectState {
|
||||
return {
|
||||
id: `${templateId}.object.${index + 1}`,
|
||||
objectType: object.objectType,
|
||||
title: object.title,
|
||||
sourceTableCode: object.sourceTableCode,
|
||||
interacted: false,
|
||||
resolved: false,
|
||||
hidden: object.hidden ?? false,
|
||||
searchable:
|
||||
object.searchable ?? (object.objectType === "container" || object.objectType === "corpse"),
|
||||
notes: object.notes,
|
||||
};
|
||||
}
|
||||
|
||||
function createHeuristicObjects(template: RoomTemplate): RoomObjectState[] {
|
||||
const text = getTemplateText(template);
|
||||
const objects: RoomObjectState[] = [];
|
||||
|
||||
const pushObject = (
|
||||
objectType: RoomObjectState["objectType"],
|
||||
title: string,
|
||||
options?: Partial<RoomObjectState>,
|
||||
) => {
|
||||
objects.push({
|
||||
id: `${template.id}.object.${objects.length + 1}`,
|
||||
objectType,
|
||||
title,
|
||||
interacted: false,
|
||||
searchable: objectType === "container" || objectType === "corpse",
|
||||
hidden: objectType === "container" && template.tags.includes("search"),
|
||||
resolved: false,
|
||||
...options,
|
||||
});
|
||||
};
|
||||
|
||||
if (text.includes("chest") || text.includes("crate") || text.includes("search")) {
|
||||
pushObject("container", "Searchable Cache", {
|
||||
sourceTableCode: "CT1",
|
||||
});
|
||||
}
|
||||
|
||||
if (text.includes("corpse") || text.includes("body")) {
|
||||
pushObject("corpse", "Fallen Body", {
|
||||
sourceTableCode: "BST1",
|
||||
});
|
||||
}
|
||||
|
||||
if (template.tags.includes("hazard")) {
|
||||
pushObject("hazard", "Room Hazard", {
|
||||
hidden: false,
|
||||
searchable: false,
|
||||
sourceTableCode: "L1TR",
|
||||
notes: "This danger triggers when you meddle with the room.",
|
||||
});
|
||||
}
|
||||
|
||||
if (text.includes("altar")) {
|
||||
pushObject("altar", "Strange Altar", {
|
||||
hidden: false,
|
||||
searchable: false,
|
||||
sourceTableCode: "URL1",
|
||||
notes: "The altar seems important and can be inspected.",
|
||||
});
|
||||
}
|
||||
|
||||
if (text.includes("prisoner")) {
|
||||
pushObject("quest", "Possible Prisoner", {
|
||||
hidden: true,
|
||||
searchable: true,
|
||||
sourceTableCode: "ENP1",
|
||||
notes: "Searching may uncover a captive or hidden stash.",
|
||||
});
|
||||
}
|
||||
|
||||
return objects;
|
||||
}
|
||||
|
||||
export function createRoomObjectsFromTemplate(template: RoomTemplate): RoomObjectState[] {
|
||||
if (template.objects?.length) {
|
||||
return template.objects.map((object, index) => createObjectState(template.id, index, object));
|
||||
}
|
||||
|
||||
return createHeuristicObjects(template);
|
||||
}
|
||||
|
||||
function awardEntry(run: RunState, definitionId: string, quantity = 1) {
|
||||
const existing = run.adventurerSnapshot.inventory.carried.find(
|
||||
(entry) => entry.definitionId === definitionId,
|
||||
);
|
||||
|
||||
if (existing) {
|
||||
existing.quantity += quantity;
|
||||
return;
|
||||
}
|
||||
|
||||
run.adventurerSnapshot.inventory.carried.push({
|
||||
definitionId,
|
||||
quantity,
|
||||
} satisfies InventoryEntry);
|
||||
}
|
||||
|
||||
function isAwardableReferenceType(referenceType: ContentReference["type"]) {
|
||||
return ["item", "potion", "scroll", "armour", "weapon"].includes(referenceType);
|
||||
}
|
||||
|
||||
function applyRuleEffect(
|
||||
run: RunState,
|
||||
effect: RuleEffect,
|
||||
roller?: DiceRoller,
|
||||
): { gold: number; silver: number; items: number; damage: number; healing: number } {
|
||||
const rolledAmount =
|
||||
effect.diceKind
|
||||
? Array.from({ length: effect.rollCount ?? 1 }, () => {
|
||||
const roll = rollDice(effect.diceKind!, roller);
|
||||
return roll.modifiedTotal ?? roll.total ?? 0;
|
||||
}).reduce((total, value) => total + value, 0)
|
||||
: 0;
|
||||
const amount = (effect.amount ?? 0) + rolledAmount;
|
||||
|
||||
switch (effect.type) {
|
||||
case "gain-gold": {
|
||||
run.adventurerSnapshot.inventory.currency.gold += amount;
|
||||
run.goldGained += amount;
|
||||
return { gold: amount, silver: 0, items: 0, damage: 0, healing: 0 };
|
||||
}
|
||||
case "gain-silver": {
|
||||
run.adventurerSnapshot.inventory.currency.silver += amount;
|
||||
run.silverGained += amount;
|
||||
return { gold: 0, silver: amount, items: 0, damage: 0, healing: 0 };
|
||||
}
|
||||
case "take-damage": {
|
||||
const prevented = consumeWardReduction(run.adventurerSnapshot.statuses);
|
||||
run.adventurerSnapshot.hp.current = Math.max(0, run.adventurerSnapshot.hp.current - amount);
|
||||
if (prevented > 0) {
|
||||
run.adventurerSnapshot.hp.current = Math.min(
|
||||
run.adventurerSnapshot.hp.max,
|
||||
run.adventurerSnapshot.hp.current + Math.min(prevented, amount),
|
||||
);
|
||||
}
|
||||
if (run.activeCombat) {
|
||||
run.activeCombat.player.hpCurrent = run.adventurerSnapshot.hp.current;
|
||||
consumeWardReduction(run.activeCombat.player.statuses);
|
||||
}
|
||||
return {
|
||||
gold: 0,
|
||||
silver: 0,
|
||||
items: 0,
|
||||
damage: Math.max(0, amount - prevented),
|
||||
healing: 0,
|
||||
};
|
||||
}
|
||||
case "heal": {
|
||||
const current = run.adventurerSnapshot.hp.current;
|
||||
const max = run.adventurerSnapshot.hp.max;
|
||||
const healed = Math.max(0, Math.min(amount, max - current));
|
||||
run.adventurerSnapshot.hp.current += healed;
|
||||
if (run.activeCombat) {
|
||||
run.activeCombat.player.hpCurrent = run.adventurerSnapshot.hp.current;
|
||||
}
|
||||
return { gold: 0, silver: 0, items: 0, damage: 0, healing: healed };
|
||||
}
|
||||
case "add-item": {
|
||||
if (!effect.referenceId) {
|
||||
return { gold: 0, silver: 0, items: 0, damage: 0, healing: 0 };
|
||||
}
|
||||
|
||||
const quantity = effect.amount ?? 1;
|
||||
awardEntry(run, effect.referenceId, quantity);
|
||||
run.lootedItems.push({
|
||||
definitionId: effect.referenceId,
|
||||
quantity,
|
||||
});
|
||||
return { gold: 0, silver: 0, items: quantity, damage: 0, healing: 0 };
|
||||
}
|
||||
default:
|
||||
return { gold: 0, silver: 0, items: 0, damage: 0, healing: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
function summarizeOutcome(summary: {
|
||||
gold: number;
|
||||
silver: number;
|
||||
items: number;
|
||||
damage: number;
|
||||
healing: number;
|
||||
}) {
|
||||
const parts: string[] = [];
|
||||
|
||||
if (summary.gold > 0) {
|
||||
parts.push(`${summary.gold} gold`);
|
||||
}
|
||||
|
||||
if (summary.silver > 0) {
|
||||
parts.push(`${summary.silver} silver`);
|
||||
}
|
||||
|
||||
if (summary.items > 0) {
|
||||
parts.push(summary.items === 1 ? "1 item" : `${summary.items} items`);
|
||||
}
|
||||
|
||||
if (summary.damage > 0) {
|
||||
parts.push(`${summary.damage} damage`);
|
||||
}
|
||||
|
||||
if (summary.healing > 0) {
|
||||
parts.push(`${summary.healing} HP`);
|
||||
}
|
||||
|
||||
return parts.join(", ");
|
||||
}
|
||||
|
||||
function findTableByReference(content: ContentPack, referenceId: string) {
|
||||
const directMatch = content.tables.find(
|
||||
(table) => table.id === referenceId || table.code === referenceId,
|
||||
);
|
||||
|
||||
return directMatch ?? findTableByCode(content, referenceId);
|
||||
}
|
||||
|
||||
function resolveReferences(options: {
|
||||
content: ContentPack;
|
||||
run: RunState;
|
||||
room: RoomState;
|
||||
object: RoomObjectState;
|
||||
references: ContentReference[];
|
||||
at: string;
|
||||
roller?: DiceRoller;
|
||||
depth: number;
|
||||
}) {
|
||||
const logEntries: LogEntry[] = [];
|
||||
const summary = { gold: 0, silver: 0, items: 0, damage: 0, healing: 0 };
|
||||
|
||||
if (options.depth > 1) {
|
||||
return { logEntries, summary };
|
||||
}
|
||||
|
||||
for (const reference of options.references) {
|
||||
const quantity = reference.quantity ?? 1;
|
||||
|
||||
if (isAwardableReferenceType(reference.type)) {
|
||||
awardEntry(options.run, reference.id, quantity);
|
||||
options.run.lootedItems.push({
|
||||
definitionId: reference.id,
|
||||
quantity,
|
||||
});
|
||||
summary.items += quantity;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (reference.type !== "table") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const table = findTableByReference(options.content, reference.id);
|
||||
|
||||
for (let iteration = 0; iteration < quantity; iteration += 1) {
|
||||
const lookup = lookupTable(table, { roller: options.roller });
|
||||
const total = lookup.roll.modifiedTotal ?? lookup.roll.total;
|
||||
const suffix = quantity > 1 ? ` (${iteration + 1}/${quantity})` : "";
|
||||
|
||||
logEntries.push(
|
||||
createLogEntry(
|
||||
`${options.room.id}.object.${options.object.id}.subroll.${table.code}.${options.depth}.${iteration + 1}`,
|
||||
options.at,
|
||||
"roll",
|
||||
`Follow-up roll${suffix} ${lookup.roll.diceKind} [${lookup.roll.rolls.join(", ")}] on ${table.code} for ${total}: ${lookup.entry.label}.`,
|
||||
[options.room.id, options.object.id, table.code],
|
||||
),
|
||||
);
|
||||
|
||||
for (const effect of lookup.entry.effects ?? []) {
|
||||
const applied = applyRuleEffect(options.run, effect, options.roller);
|
||||
summary.gold += applied.gold;
|
||||
summary.silver += applied.silver;
|
||||
summary.items += applied.items;
|
||||
summary.damage += applied.damage;
|
||||
summary.healing += applied.healing;
|
||||
}
|
||||
|
||||
const nested = resolveReferences({
|
||||
...options,
|
||||
references: lookup.entry.references ?? [],
|
||||
depth: options.depth + 1,
|
||||
});
|
||||
|
||||
summary.gold += nested.summary.gold;
|
||||
summary.silver += nested.summary.silver;
|
||||
summary.items += nested.summary.items;
|
||||
summary.damage += nested.summary.damage;
|
||||
summary.healing += nested.summary.healing;
|
||||
logEntries.push(...nested.logEntries);
|
||||
|
||||
logEntries.push(
|
||||
createLogEntry(
|
||||
`${options.room.id}.object.${options.object.id}.subresult.${table.code}.${options.depth}.${iteration + 1}`,
|
||||
options.at,
|
||||
"room",
|
||||
`Follow-up result${suffix}: ${lookup.entry.text ?? lookup.entry.label}.`,
|
||||
[options.room.id, options.object.id, table.code],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { logEntries, summary };
|
||||
}
|
||||
|
||||
export function searchRoom(
|
||||
run: RunState,
|
||||
room: RoomState,
|
||||
at = new Date().toISOString(),
|
||||
): SearchRoomResult {
|
||||
room.discovery.searched = true;
|
||||
|
||||
const hiddenObjects = room.objects.filter((object) => object.hidden);
|
||||
|
||||
hiddenObjects.forEach((object) => {
|
||||
object.hidden = false;
|
||||
});
|
||||
|
||||
const logEntries =
|
||||
hiddenObjects.length > 0
|
||||
? hiddenObjects.map((object, index) =>
|
||||
createLogEntry(
|
||||
`${room.id}.search.${index + 1}`,
|
||||
at,
|
||||
"room",
|
||||
`Searching ${room.id} reveals ${object.title}.`,
|
||||
[room.id, object.id],
|
||||
),
|
||||
)
|
||||
: [
|
||||
createLogEntry(
|
||||
`${room.id}.search.empty`,
|
||||
at,
|
||||
"room",
|
||||
`Searched ${room.id} but found nothing new.`,
|
||||
[room.id],
|
||||
),
|
||||
];
|
||||
|
||||
return {
|
||||
run,
|
||||
room,
|
||||
logEntries,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveRoomObject(
|
||||
options: ResolveRoomObjectOptions,
|
||||
): ResolveRoomObjectResult {
|
||||
const room = options.room;
|
||||
const object = room.objects.find((entry) => entry.id === options.objectId);
|
||||
|
||||
if (!object) {
|
||||
throw new Error(`Unknown room object id: ${options.objectId}`);
|
||||
}
|
||||
|
||||
if (object.hidden) {
|
||||
throw new Error(`Room object ${options.objectId} is still hidden.`);
|
||||
}
|
||||
|
||||
if (object.interacted) {
|
||||
throw new Error(`Room object ${options.objectId} has already been resolved.`);
|
||||
}
|
||||
|
||||
const at = options.at ?? new Date().toISOString();
|
||||
const logEntries: LogEntry[] = [];
|
||||
|
||||
object.interacted = true;
|
||||
object.resolved = true;
|
||||
|
||||
if (object.sourceTableCode) {
|
||||
const table = findTableByCode(options.content, object.sourceTableCode);
|
||||
const lookup = lookupTable(table, { roller: options.roller });
|
||||
const total = lookup.roll.modifiedTotal ?? lookup.roll.total;
|
||||
const summary = { gold: 0, silver: 0, items: 0, damage: 0, healing: 0 };
|
||||
|
||||
object.resolutionLabel = lookup.entry.label;
|
||||
object.resolutionEntryKey = lookup.entry.key;
|
||||
|
||||
logEntries.push(
|
||||
createLogEntry(
|
||||
`${room.id}.object.${object.id}.roll`,
|
||||
at,
|
||||
"roll",
|
||||
`Rolled ${lookup.roll.diceKind} [${lookup.roll.rolls.join(", ")}] on ${object.sourceTableCode} for ${total}: ${lookup.entry.label}.`,
|
||||
[room.id, object.id, object.sourceTableCode],
|
||||
),
|
||||
);
|
||||
|
||||
for (const effect of lookup.entry.effects ?? []) {
|
||||
const applied = applyRuleEffect(options.run, effect, options.roller);
|
||||
summary.gold += applied.gold;
|
||||
summary.silver += applied.silver;
|
||||
summary.items += applied.items;
|
||||
summary.damage += applied.damage;
|
||||
summary.healing += applied.healing;
|
||||
}
|
||||
|
||||
const referenceResolution = resolveReferences({
|
||||
content: options.content,
|
||||
run: options.run,
|
||||
room,
|
||||
object,
|
||||
references: lookup.entry.references ?? [],
|
||||
at,
|
||||
roller: options.roller,
|
||||
depth: 0,
|
||||
});
|
||||
|
||||
summary.gold += referenceResolution.summary.gold;
|
||||
summary.items += referenceResolution.summary.items;
|
||||
summary.damage += referenceResolution.summary.damage;
|
||||
summary.healing += referenceResolution.summary.healing;
|
||||
logEntries.push(...referenceResolution.logEntries);
|
||||
|
||||
logEntries.push(
|
||||
createLogEntry(
|
||||
`${room.id}.object.${object.id}.result`,
|
||||
at,
|
||||
"room",
|
||||
`${object.title}: ${lookup.entry.text ?? lookup.entry.label}${summarizeOutcome(summary) ? ` (${summarizeOutcome(summary)})` : ""}.`,
|
||||
[room.id, object.id, object.sourceTableCode],
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
run: options.run,
|
||||
room,
|
||||
object,
|
||||
logEntries,
|
||||
};
|
||||
}
|
||||
|
||||
const fallbackSummary = [
|
||||
object.rewardGold ? `${object.rewardGold} gold` : undefined,
|
||||
object.rewardItemId ? "1 item" : undefined,
|
||||
object.damage ? `${object.damage} damage` : undefined,
|
||||
].filter((entry): entry is string => Boolean(entry));
|
||||
|
||||
if (object.rewardGold) {
|
||||
options.run.adventurerSnapshot.inventory.currency.gold += object.rewardGold;
|
||||
options.run.goldGained += object.rewardGold;
|
||||
}
|
||||
|
||||
if (object.rewardItemId) {
|
||||
awardEntry(options.run, object.rewardItemId);
|
||||
options.run.lootedItems.push({
|
||||
definitionId: object.rewardItemId,
|
||||
quantity: 1,
|
||||
});
|
||||
}
|
||||
|
||||
if (object.damage) {
|
||||
options.run.adventurerSnapshot.hp.current = Math.max(
|
||||
0,
|
||||
options.run.adventurerSnapshot.hp.current - object.damage,
|
||||
);
|
||||
}
|
||||
|
||||
logEntries.push(
|
||||
createLogEntry(
|
||||
`${room.id}.object.${object.id}.result`,
|
||||
at,
|
||||
"room",
|
||||
`${object.title} resolved${fallbackSummary.length > 0 ? `: ${fallbackSummary.join(", ")}.` : "."}`,
|
||||
[room.id, object.id],
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
run: options.run,
|
||||
room,
|
||||
object,
|
||||
logEntries,
|
||||
};
|
||||
}
|
||||
+16
-2
@@ -8,6 +8,7 @@ import type { DungeonLevelState, RoomExitState, RoomState } from "@/types/state"
|
||||
|
||||
import { lookupTable, type TableLookupResult } from "./tables";
|
||||
import type { DiceRoller } from "./dice";
|
||||
import { createRoomObjectsFromTemplate } from "./roomObjects";
|
||||
|
||||
export type RoomGenerationOptions = {
|
||||
content: ContentPack;
|
||||
@@ -40,6 +41,18 @@ const DEFAULT_ROOM_DIMENSIONS: Record<RoomClass, { width: number; height: number
|
||||
|
||||
const DEFAULT_DIRECTIONS = ["north", "east", "south", "west"] as const;
|
||||
|
||||
function getDirectionSeed(roomId: string) {
|
||||
return Array.from(roomId).reduce((total, char) => total + char.charCodeAt(0), 0);
|
||||
}
|
||||
|
||||
function getDirectionOrder(roomId: string) {
|
||||
const rotation = getDirectionSeed(roomId) % DEFAULT_DIRECTIONS.length;
|
||||
return [
|
||||
...DEFAULT_DIRECTIONS.slice(rotation),
|
||||
...DEFAULT_DIRECTIONS.slice(0, rotation),
|
||||
];
|
||||
}
|
||||
|
||||
function inferExitType(exitHint?: string): ExitType {
|
||||
const normalized = exitHint?.toLowerCase() ?? "";
|
||||
|
||||
@@ -91,8 +104,9 @@ function createExits(
|
||||
): RoomExitState[] {
|
||||
const exitCount = inferExitCount(roomClass, exitHint);
|
||||
const exitType = inferExitType(exitHint);
|
||||
const directionOrder = getDirectionOrder(roomId);
|
||||
|
||||
return DEFAULT_DIRECTIONS.slice(0, exitCount).map((direction, index) => ({
|
||||
return directionOrder.slice(0, exitCount).map((direction, index) => ({
|
||||
id: `${roomId}.exit.${index + 1}`,
|
||||
direction,
|
||||
exitType,
|
||||
@@ -135,7 +149,7 @@ export function createRoomStateFromTemplate(
|
||||
searched: false,
|
||||
},
|
||||
encounter: undefined,
|
||||
objects: [],
|
||||
objects: createRoomObjectsFromTemplate(template),
|
||||
notes: [template.text ?? template.title, template.encounterText].filter(
|
||||
(note): note is string => Boolean(note),
|
||||
),
|
||||
|
||||
@@ -3,17 +3,23 @@ import { describe, expect, it } from "vitest";
|
||||
import { sampleContentPack } from "@/data/sampleContentPack";
|
||||
|
||||
import { createStartingAdventurer } from "./character";
|
||||
import { createRoomStateFromTemplate } from "./rooms";
|
||||
import {
|
||||
canCompleteCurrentLevel,
|
||||
completeCurrentLevel,
|
||||
createRunState,
|
||||
enterCurrentRoom,
|
||||
getAvailableMoves,
|
||||
isCurrentRoomCombatReady,
|
||||
resolveCurrentRoomObject,
|
||||
resolveRunEnemyTurn,
|
||||
resolveRunPlayerTurn,
|
||||
resumeDungeon,
|
||||
returnToTown,
|
||||
searchCurrentRoom,
|
||||
startCombatInCurrentRoom,
|
||||
travelCurrentExit,
|
||||
useRunMagicItem,
|
||||
} from "./runState";
|
||||
|
||||
function createSequenceRoller(values: number[]) {
|
||||
@@ -68,6 +74,29 @@ describe("run state flow", () => {
|
||||
expect(result.run.log[0]?.text).toContain("Re-entered Entry Chamber");
|
||||
});
|
||||
|
||||
it("reveals a fallback secret exit when room entry would otherwise stall progression", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
at: "2026-03-15T14:00:00.000Z",
|
||||
});
|
||||
|
||||
run.dungeon.levels["1"]!.rooms["room.level1.start"]!.exits = [];
|
||||
|
||||
const result = enterCurrentRoom({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
at: "2026-03-15T14:01:00.000Z",
|
||||
});
|
||||
|
||||
expect(result.run.dungeon.levels["1"]!.secretDoorUsed).toBe(true);
|
||||
expect(result.run.dungeon.levels["1"]!.rooms["room.level1.start"]!.exits).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ exitType: "secret" })]),
|
||||
);
|
||||
expect(result.run.log.at(-1)?.text).toContain("secret exit");
|
||||
});
|
||||
|
||||
it("starts combat from the current room and stores the active combat state", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
@@ -347,6 +376,362 @@ describe("run state flow", () => {
|
||||
expect(isCurrentRoomCombatReady(run)).toBe(true);
|
||||
});
|
||||
|
||||
it("invokes Ring of Leaving to escape directly back to town", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
run.adventurerSnapshot.inventory.carried.push({
|
||||
definitionId: "item.ring-of-leaving",
|
||||
quantity: 1,
|
||||
});
|
||||
|
||||
const result = useRunMagicItem({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
definitionId: "item.ring-of-leaving",
|
||||
at: "2026-03-19T22:30:00.000Z",
|
||||
});
|
||||
|
||||
expect(result.run.phase).toBe("town");
|
||||
expect(result.run.log.at(-1)?.text).toContain("Ring of Leaving");
|
||||
});
|
||||
|
||||
it("uses Potion of Aura to reveal hidden room objects", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const room = createRoomStateFromTemplate(
|
||||
sampleContentPack,
|
||||
"room.level1.aura-test",
|
||||
1,
|
||||
"room.level1.normal.abandoned-guard-post",
|
||||
);
|
||||
|
||||
run.dungeon.levels["1"]!.rooms[room.id] = room;
|
||||
run.dungeon.levels["1"]!.discoveredRoomOrder.push(room.id);
|
||||
run.currentRoomId = room.id;
|
||||
run.adventurerSnapshot.inventory.carried.push({
|
||||
definitionId: "item.potion-of-aura",
|
||||
quantity: 1,
|
||||
});
|
||||
|
||||
const result = useRunMagicItem({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
definitionId: "item.potion-of-aura",
|
||||
at: "2026-03-19T22:31:00.000Z",
|
||||
});
|
||||
|
||||
expect(result.run.dungeon.levels["1"]!.rooms[room.id]!.objects.every((object) => !object.hidden)).toBe(true);
|
||||
expect(
|
||||
result.run.adventurerSnapshot.inventory.carried.some((entry) => entry.definitionId === "item.potion-of-aura"),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("uses Potion of Insightful Combat to improve the next attack", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const room = run.dungeon.levels["1"]!.rooms["room.level1.start"]!;
|
||||
|
||||
room.encounter = {
|
||||
id: `${room.id}.encounter`,
|
||||
sourceTableCode: "L1CE",
|
||||
creatureIds: ["a"],
|
||||
creatureNames: ["Giant Rat"],
|
||||
resultLabel: "Giant Rat",
|
||||
resolved: true,
|
||||
};
|
||||
|
||||
const withCombat = startCombatInCurrentRoom({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
at: "2026-03-19T22:32:00.000Z",
|
||||
}).run;
|
||||
|
||||
withCombat.adventurerSnapshot.inventory.carried.push({
|
||||
definitionId: "item.potion-of-insightful-combat",
|
||||
quantity: 1,
|
||||
});
|
||||
|
||||
const buffed = useRunMagicItem({
|
||||
content: sampleContentPack,
|
||||
run: withCombat,
|
||||
definitionId: "item.potion-of-insightful-combat",
|
||||
at: "2026-03-19T22:33:00.000Z",
|
||||
}).run;
|
||||
|
||||
const attacked = resolveRunPlayerTurn({
|
||||
content: sampleContentPack,
|
||||
run: buffed,
|
||||
manoeuvreId: "manoeuvre.exact-strike",
|
||||
targetEnemyId: buffed.activeCombat!.enemies[0]!.id,
|
||||
roller: createSequenceRoller([2, 3, 1]),
|
||||
at: "2026-03-19T22:34:00.000Z",
|
||||
}).run;
|
||||
|
||||
expect(attacked.activeCombat).toBeUndefined();
|
||||
expect(attacked.lastCombatOutcome?.result).toBe("victory");
|
||||
expect(attacked.adventurerSnapshot.statuses.some((status) => status.id === "status.insightful-combat")).toBe(false);
|
||||
});
|
||||
|
||||
it("uses Amulet of Resistance to reduce the next incoming hit", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const room = run.dungeon.levels["1"]!.rooms["room.level1.start"]!;
|
||||
|
||||
room.encounter = {
|
||||
id: `${room.id}.encounter`,
|
||||
sourceTableCode: "L1G",
|
||||
creatureIds: ["a"],
|
||||
creatureNames: ["Guard"],
|
||||
resultLabel: "Guard",
|
||||
resolved: true,
|
||||
};
|
||||
|
||||
const withCombat = startCombatInCurrentRoom({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
at: "2026-03-19T22:35:00.000Z",
|
||||
}).run;
|
||||
|
||||
withCombat.adventurerSnapshot.inventory.carried.push({
|
||||
definitionId: "item.amulet-of-resistance",
|
||||
quantity: 1,
|
||||
});
|
||||
|
||||
const warded = useRunMagicItem({
|
||||
content: sampleContentPack,
|
||||
run: withCombat,
|
||||
definitionId: "item.amulet-of-resistance",
|
||||
at: "2026-03-19T22:36:00.000Z",
|
||||
}).run;
|
||||
warded.activeCombat!.actingSide = "enemy";
|
||||
|
||||
const afterEnemy = resolveRunEnemyTurn({
|
||||
content: sampleContentPack,
|
||||
run: warded,
|
||||
roller: createSequenceRoller([6, 6]),
|
||||
at: "2026-03-19T22:37:00.000Z",
|
||||
}).run;
|
||||
|
||||
expect(afterEnemy.adventurerSnapshot.hp.current).toBe(withCombat.adventurerSnapshot.hp.current - 1);
|
||||
});
|
||||
|
||||
it("uses Wand of Fire as a combat action and can finish the fight", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const room = run.dungeon.levels["1"]!.rooms["room.level1.start"]!;
|
||||
|
||||
room.encounter = {
|
||||
id: `${room.id}.encounter`,
|
||||
sourceTableCode: "L1G",
|
||||
creatureIds: ["a"],
|
||||
creatureNames: ["Guard"],
|
||||
resultLabel: "Guard",
|
||||
resolved: true,
|
||||
};
|
||||
|
||||
const withCombat = startCombatInCurrentRoom({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
at: "2026-03-19T22:38:00.000Z",
|
||||
}).run;
|
||||
|
||||
withCombat.activeCombat!.enemies[0]!.hpCurrent = 2;
|
||||
withCombat.adventurerSnapshot.inventory.carried.push({
|
||||
definitionId: "item.wand-of-fire",
|
||||
quantity: 1,
|
||||
});
|
||||
|
||||
const result = useRunMagicItem({
|
||||
content: sampleContentPack,
|
||||
run: withCombat,
|
||||
definitionId: "item.wand-of-fire",
|
||||
at: "2026-03-19T22:39:00.000Z",
|
||||
});
|
||||
|
||||
expect(result.run.activeCombat).toBeUndefined();
|
||||
expect(result.run.dungeon.levels["1"]!.rooms["room.level1.start"]!.discovery.cleared).toBe(true);
|
||||
expect(result.run.lastCombatOutcome?.result).toBe("victory");
|
||||
});
|
||||
|
||||
it("uses Ring of Spells to restore HP without consuming the ring", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
run.adventurerSnapshot.hp.current = 6;
|
||||
run.adventurerSnapshot.inventory.carried.push({
|
||||
definitionId: "item.ring-of-spells",
|
||||
quantity: 1,
|
||||
});
|
||||
|
||||
const result = useRunMagicItem({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
definitionId: "item.ring-of-spells",
|
||||
at: "2026-03-19T22:40:00.000Z",
|
||||
});
|
||||
|
||||
expect(result.run.adventurerSnapshot.hp.current).toBe(8);
|
||||
expect(
|
||||
result.run.adventurerSnapshot.inventory.carried.some((entry) => entry.definitionId === "item.ring-of-spells"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("uses Amulet of Fire Resistance to absorb a stronger hit", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const room = run.dungeon.levels["1"]!.rooms["room.level1.start"]!;
|
||||
|
||||
room.encounter = {
|
||||
id: `${room.id}.encounter`,
|
||||
sourceTableCode: "L1G",
|
||||
creatureIds: ["a"],
|
||||
creatureNames: ["Guard"],
|
||||
resultLabel: "Guard",
|
||||
resolved: true,
|
||||
};
|
||||
|
||||
const withCombat = startCombatInCurrentRoom({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
at: "2026-03-19T22:41:00.000Z",
|
||||
}).run;
|
||||
|
||||
withCombat.adventurerSnapshot.inventory.carried.push({
|
||||
definitionId: "item.amulet-of-fire-resistance",
|
||||
quantity: 1,
|
||||
});
|
||||
|
||||
const warded = useRunMagicItem({
|
||||
content: sampleContentPack,
|
||||
run: withCombat,
|
||||
definitionId: "item.amulet-of-fire-resistance",
|
||||
at: "2026-03-19T22:42:00.000Z",
|
||||
}).run;
|
||||
warded.activeCombat!.actingSide = "enemy";
|
||||
|
||||
const afterEnemy = resolveRunEnemyTurn({
|
||||
content: sampleContentPack,
|
||||
run: warded,
|
||||
roller: createSequenceRoller([6, 6]),
|
||||
at: "2026-03-19T22:43:00.000Z",
|
||||
}).run;
|
||||
|
||||
expect(afterEnemy.adventurerSnapshot.hp.current).toBe(withCombat.adventurerSnapshot.hp.current);
|
||||
});
|
||||
|
||||
it("uses Wand of Sleep to skip the next enemy turn", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
});
|
||||
const room = run.dungeon.levels["1"]!.rooms["room.level1.start"]!;
|
||||
|
||||
room.encounter = {
|
||||
id: `${room.id}.encounter`,
|
||||
sourceTableCode: "L1G",
|
||||
creatureIds: ["a"],
|
||||
creatureNames: ["Guard"],
|
||||
resultLabel: "Guard",
|
||||
resolved: true,
|
||||
};
|
||||
|
||||
const withCombat = startCombatInCurrentRoom({
|
||||
content: sampleContentPack,
|
||||
run,
|
||||
at: "2026-03-19T22:44:00.000Z",
|
||||
}).run;
|
||||
|
||||
withCombat.adventurerSnapshot.inventory.carried.push({
|
||||
definitionId: "item.wand-of-sleep",
|
||||
quantity: 1,
|
||||
});
|
||||
|
||||
const slept = useRunMagicItem({
|
||||
content: sampleContentPack,
|
||||
run: withCombat,
|
||||
definitionId: "item.wand-of-sleep",
|
||||
at: "2026-03-19T22:45:00.000Z",
|
||||
}).run;
|
||||
|
||||
const afterEnemy = resolveRunEnemyTurn({
|
||||
content: sampleContentPack,
|
||||
run: slept,
|
||||
roller: createSequenceRoller([6, 6]),
|
||||
at: "2026-03-19T22:46:00.000Z",
|
||||
}).run;
|
||||
|
||||
expect(afterEnemy.adventurerSnapshot.hp.current).toBe(withCombat.adventurerSnapshot.hp.current);
|
||||
expect(afterEnemy.activeCombat?.actingSide).toBe("player");
|
||||
expect(afterEnemy.log.at(-1)?.text).toContain("sleeps through the turn");
|
||||
});
|
||||
|
||||
it("supports searching and resolving room objects through run state", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
at: "2026-03-15T14:00:00.000Z",
|
||||
});
|
||||
const room = run.dungeon.levels["1"]!.rooms["room.level1.start"]!;
|
||||
|
||||
room.objects = [
|
||||
{
|
||||
id: "room.level1.start.object.1",
|
||||
objectType: "container",
|
||||
title: "Hidden Cache",
|
||||
sourceTableCode: "TCT1",
|
||||
interacted: false,
|
||||
resolved: false,
|
||||
hidden: true,
|
||||
searchable: true,
|
||||
},
|
||||
];
|
||||
|
||||
const searched = searchCurrentRoom(run, "2026-03-15T14:06:00.000Z").run;
|
||||
|
||||
expect(searched.dungeon.levels["1"]!.rooms["room.level1.start"]!.discovery.searched).toBe(true);
|
||||
expect(searched.dungeon.levels["1"]!.rooms["room.level1.start"]!.objects[0]!.hidden).toBe(false);
|
||||
|
||||
const resolved = resolveCurrentRoomObject({
|
||||
content: sampleContentPack,
|
||||
run: searched,
|
||||
objectId: "room.level1.start.object.1",
|
||||
roller: () => 6,
|
||||
at: "2026-03-15T14:07:00.000Z",
|
||||
}).run;
|
||||
|
||||
expect(resolved.adventurerSnapshot.inventory.currency.gold).toBeGreaterThan(
|
||||
searched.adventurerSnapshot.inventory.currency.gold,
|
||||
);
|
||||
expect(resolved.adventurerSnapshot.inventory.carried).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ definitionId: "item.garnet-ring" })]),
|
||||
);
|
||||
expect(
|
||||
resolved.dungeon.levels["1"]!.rooms["room.level1.start"]!.objects[0]!.resolutionLabel,
|
||||
).toBe("Garnet Ring and coins");
|
||||
});
|
||||
|
||||
it("returns to town and later resumes the dungeon", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
@@ -364,4 +749,26 @@ describe("run state flow", () => {
|
||||
expect(resumed.phase).toBe("dungeon");
|
||||
expect(resumed.log.at(-1)?.text).toContain("resumed the dungeon delve");
|
||||
});
|
||||
|
||||
it("places stairs and completes the current level when the map is exhausted", () => {
|
||||
const run = createRunState({
|
||||
content: sampleContentPack,
|
||||
campaignId: "campaign.1",
|
||||
adventurer: createAdventurer(),
|
||||
at: "2026-03-15T14:00:00.000Z",
|
||||
});
|
||||
const room = run.dungeon.levels["1"]!.rooms["room.level1.start"]!;
|
||||
|
||||
room.discovery.cleared = true;
|
||||
room.exits = [];
|
||||
|
||||
expect(canCompleteCurrentLevel(run)).toBe(true);
|
||||
|
||||
const result = completeCurrentLevel(run, "2026-03-15T15:30:00.000Z");
|
||||
|
||||
expect(result.run.phase).toBe("town");
|
||||
expect(result.run.dungeon.levels["1"]!.stairsDownRoomId).toBe("room.level1.start");
|
||||
expect(result.run.dungeon.globalFlags).toContain("level:1:completed");
|
||||
expect(result.run.log.at(-1)?.text).toContain("Returned to town");
|
||||
});
|
||||
});
|
||||
|
||||
+500
-11
@@ -12,6 +12,17 @@ import { startCombatFromRoom } from "./combat";
|
||||
import { createInitialTownState } from "./townServices";
|
||||
import { resolveCombatLoot } from "./loot";
|
||||
import { applyLevelProgression } from "./progression";
|
||||
import {
|
||||
AMULET_FIRE_RESISTANCE_STATUS_ID,
|
||||
AMULET_RESISTANCE_STATUS_ID,
|
||||
INSIGHTFUL_COMBAT_STATUS_ID,
|
||||
SLEEPING_STATUS_ID,
|
||||
addStatus,
|
||||
consumeCarriedItem,
|
||||
getCarriedItemCount,
|
||||
hasStatus,
|
||||
revealHiddenObjects,
|
||||
} from "./magicItems";
|
||||
import {
|
||||
resolveEnemyTurn,
|
||||
resolvePlayerAttack,
|
||||
@@ -19,12 +30,16 @@ import {
|
||||
type ResolvePlayerAttackOptions,
|
||||
} from "./combatTurns";
|
||||
import {
|
||||
addSecretDoorFallback,
|
||||
canPlaceStairsDown,
|
||||
expandLevelFromExit,
|
||||
getUnresolvedExits,
|
||||
initializeDungeonLevel,
|
||||
placeStairsDown,
|
||||
} from "./dungeon";
|
||||
import type { DiceRoller } from "./dice";
|
||||
import { enterRoom } from "./roomEntry";
|
||||
import { resolveRoomObject, searchRoom } from "./roomObjects";
|
||||
|
||||
export type CreateRunOptions = {
|
||||
content: ContentPack;
|
||||
@@ -85,6 +100,28 @@ export type RunTransitionResult = {
|
||||
logEntries: LogEntry[];
|
||||
};
|
||||
|
||||
export type ResolveRoomObjectOptions = {
|
||||
content: ContentPack;
|
||||
run: RunState;
|
||||
objectId: string;
|
||||
roller?: DiceRoller;
|
||||
at?: string;
|
||||
};
|
||||
|
||||
export type UseRunMagicItemOptions = {
|
||||
content: ContentPack;
|
||||
run: RunState;
|
||||
definitionId: string;
|
||||
targetEnemyId?: string;
|
||||
at?: string;
|
||||
};
|
||||
|
||||
function appendDungeonFlag(run: RunState, flag: string) {
|
||||
if (!run.dungeon.globalFlags.includes(flag)) {
|
||||
run.dungeon.globalFlags.push(flag);
|
||||
}
|
||||
}
|
||||
|
||||
function createLogEntry(
|
||||
id: string,
|
||||
at: string,
|
||||
@@ -275,6 +312,34 @@ function appendLogs(run: RunState, logEntries: LogEntry[]) {
|
||||
run.log.push(...logEntries);
|
||||
}
|
||||
|
||||
function ensureStalledProgressionRecovery(
|
||||
run: RunState,
|
||||
at: string,
|
||||
): LogEntry[] {
|
||||
const levelState = run.dungeon.levels[run.currentLevel];
|
||||
|
||||
if (!levelState || levelState.secretDoorUsed || levelState.stairsDownRoomId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (getUnresolvedExits(levelState).length > 0 || canCompleteCurrentLevel(run)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const fallback = addSecretDoorFallback(levelState);
|
||||
run.dungeon.levels[run.currentLevel] = fallback.levelState;
|
||||
|
||||
return [
|
||||
createLogEntry(
|
||||
`level.${run.currentLevel}.fallback-secret-door.${run.log.length + 1}`,
|
||||
at,
|
||||
"room",
|
||||
`Progress stalled, so a secret exit was revealed in ${fallback.room.id}.`,
|
||||
[fallback.room.id, fallback.exit.id],
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
function createRewardLog(
|
||||
id: string,
|
||||
at: string,
|
||||
@@ -411,6 +476,7 @@ export function createRunState(options: CreateRunOptions): RunState {
|
||||
defeatedCreatureIds: [],
|
||||
xpGained: 0,
|
||||
goldGained: 0,
|
||||
silverGained: 0,
|
||||
lootedItems: [],
|
||||
log: [],
|
||||
pendingEffects: [],
|
||||
@@ -492,10 +558,12 @@ export function enterCurrentRoom(
|
||||
|
||||
run.dungeon.levels[run.currentLevel] = entry.levelState;
|
||||
appendLogs(run, entry.logEntries);
|
||||
const recoveryLogs = ensureStalledProgressionRecovery(run, options.at ?? new Date().toISOString());
|
||||
appendLogs(run, recoveryLogs);
|
||||
|
||||
return {
|
||||
run,
|
||||
logEntries: entry.logEntries,
|
||||
logEntries: [...entry.logEntries, ...recoveryLogs],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -531,6 +599,126 @@ export function isCurrentRoomCombatReady(run: RunState) {
|
||||
);
|
||||
}
|
||||
|
||||
export function canCompleteCurrentLevel(run: RunState) {
|
||||
if (run.phase !== "dungeon" || run.activeCombat || !run.currentRoomId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const levelState = run.dungeon.levels[run.currentLevel];
|
||||
|
||||
if (!levelState) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return canPlaceStairsDown(levelState, run.currentRoomId);
|
||||
}
|
||||
|
||||
export function completeCurrentLevel(
|
||||
run: RunState,
|
||||
at = new Date().toISOString(),
|
||||
): RunTransitionResult {
|
||||
const nextRun = cloneRun(run);
|
||||
|
||||
if (nextRun.phase !== "dungeon") {
|
||||
throw new Error("Cannot complete a level while the run is in town.");
|
||||
}
|
||||
|
||||
if (nextRun.activeCombat) {
|
||||
throw new Error("Cannot complete a level during active combat.");
|
||||
}
|
||||
|
||||
const levelState = requireCurrentLevel(nextRun);
|
||||
const roomId = requireCurrentRoomId(nextRun);
|
||||
const placement = placeStairsDown(levelState, roomId);
|
||||
|
||||
nextRun.dungeon.levels[nextRun.currentLevel] = placement.levelState;
|
||||
nextRun.dungeon.revealedPercentByLevel[nextRun.currentLevel] = 100;
|
||||
appendDungeonFlag(nextRun, `level:${nextRun.currentLevel}:completed`);
|
||||
appendDungeonFlag(nextRun, `level:${nextRun.currentLevel + 1}:unlocked`);
|
||||
|
||||
const completionLogs = [
|
||||
createLogEntry(
|
||||
`level.${nextRun.currentLevel}.stairs.${nextRun.log.length + 1}`,
|
||||
at,
|
||||
"room",
|
||||
`A stairway down was revealed in ${roomId}.`,
|
||||
[roomId],
|
||||
),
|
||||
createLogEntry(
|
||||
`level.${nextRun.currentLevel}.complete.${nextRun.log.length + 2}`,
|
||||
at,
|
||||
"progression",
|
||||
`Completed level ${nextRun.currentLevel} and unlocked level ${nextRun.currentLevel + 1}.`,
|
||||
[roomId],
|
||||
),
|
||||
];
|
||||
|
||||
appendLogs(nextRun, completionLogs);
|
||||
|
||||
const returned = returnToTown(nextRun, at);
|
||||
|
||||
return {
|
||||
run: returned.run,
|
||||
logEntries: [...completionLogs, ...returned.logEntries],
|
||||
};
|
||||
}
|
||||
|
||||
export function searchCurrentRoom(
|
||||
run: RunState,
|
||||
at = new Date().toISOString(),
|
||||
): RunTransitionResult {
|
||||
const nextRun = cloneRun(run);
|
||||
|
||||
if (nextRun.phase !== "dungeon") {
|
||||
throw new Error("Cannot search rooms while in town.");
|
||||
}
|
||||
|
||||
if (nextRun.activeCombat) {
|
||||
throw new Error("Cannot search rooms during active combat.");
|
||||
}
|
||||
|
||||
const room = requireCurrentRoom(nextRun);
|
||||
const result = searchRoom(nextRun, room, at);
|
||||
|
||||
appendLogs(nextRun, result.logEntries);
|
||||
|
||||
return {
|
||||
run: nextRun,
|
||||
logEntries: result.logEntries,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveCurrentRoomObject(
|
||||
options: ResolveRoomObjectOptions,
|
||||
): RunTransitionResult {
|
||||
const nextRun = cloneRun(options.run);
|
||||
|
||||
if (nextRun.phase !== "dungeon") {
|
||||
throw new Error("Cannot resolve room objects while in town.");
|
||||
}
|
||||
|
||||
if (nextRun.activeCombat) {
|
||||
throw new Error("Cannot resolve room objects during active combat.");
|
||||
}
|
||||
|
||||
const room = requireCurrentRoom(nextRun);
|
||||
const result = resolveRoomObject({
|
||||
content: options.content,
|
||||
run: nextRun,
|
||||
room,
|
||||
objectId: options.objectId,
|
||||
roller: options.roller,
|
||||
at: options.at,
|
||||
});
|
||||
|
||||
appendLogs(nextRun, result.logEntries);
|
||||
|
||||
return {
|
||||
run: nextRun,
|
||||
logEntries: result.logEntries,
|
||||
};
|
||||
}
|
||||
|
||||
export function travelCurrentExit(
|
||||
options: TravelCurrentExitOptions,
|
||||
): RunTransitionResult {
|
||||
@@ -572,17 +760,39 @@ export function travelCurrentExit(
|
||||
throw new Error(`Exit ${exit.id} is no longer available for generation.`);
|
||||
}
|
||||
|
||||
const expansion = expandLevelFromExit({
|
||||
content: options.content,
|
||||
levelState,
|
||||
fromRoomId: roomId,
|
||||
exitDirection: options.exitDirection,
|
||||
roomTableCode: options.roomTableCode ?? inferNextRoomTableCode(run),
|
||||
roller: options.roller,
|
||||
});
|
||||
try {
|
||||
const expansion = expandLevelFromExit({
|
||||
content: options.content,
|
||||
levelState,
|
||||
fromRoomId: roomId,
|
||||
exitDirection: options.exitDirection,
|
||||
roomTableCode: options.roomTableCode ?? inferNextRoomTableCode(run),
|
||||
roller: options.roller,
|
||||
});
|
||||
|
||||
nextLevelState = expansion.levelState;
|
||||
destinationRoomId = expansion.createdRoom.id;
|
||||
nextLevelState = expansion.levelState;
|
||||
destinationRoomId = expansion.createdRoom.id;
|
||||
} catch (error) {
|
||||
exit.traversable = false;
|
||||
exit.discovered = true;
|
||||
run.dungeon.levels[run.currentLevel] = levelState;
|
||||
|
||||
const blockedLog = createLogEntry(
|
||||
`${roomId}.blocked.${options.exitDirection}.${run.log.length + 1}`,
|
||||
at,
|
||||
"room",
|
||||
`The ${options.exitDirection} passage from ${room.id} could not be extended and is now marked blocked.`,
|
||||
[room.id, exit.id],
|
||||
);
|
||||
const recoveryLogs = ensureStalledProgressionRecovery(run, at);
|
||||
|
||||
appendLogs(run, [blockedLog, ...recoveryLogs]);
|
||||
|
||||
return {
|
||||
run,
|
||||
logEntries: [blockedLog, ...recoveryLogs],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
run.dungeon.levels[run.currentLevel] = nextLevelState;
|
||||
@@ -754,3 +964,282 @@ export function resolveRunEnemyTurn(
|
||||
logEntries: result.logEntries,
|
||||
};
|
||||
}
|
||||
|
||||
export function useRunMagicItem(
|
||||
options: UseRunMagicItemOptions,
|
||||
): RunTransitionResult {
|
||||
const run = cloneRun(options.run);
|
||||
const at = options.at ?? new Date().toISOString();
|
||||
|
||||
if (getCarriedItemCount(run, options.definitionId) === 0) {
|
||||
throw new Error(`No carried ${options.definitionId} is available to use.`);
|
||||
}
|
||||
|
||||
switch (options.definitionId) {
|
||||
case "item.ring-of-leaving": {
|
||||
if (run.phase !== "dungeon" || run.activeCombat) {
|
||||
throw new Error("Ring of Leaving can only be invoked while exploring the dungeon.");
|
||||
}
|
||||
|
||||
run.phase = "town";
|
||||
run.lastTownAt = at;
|
||||
run.townState.visits += 1;
|
||||
|
||||
const logEntry = createLogEntry(
|
||||
`magic.ring-of-leaving.${run.log.length + 1}`,
|
||||
at,
|
||||
"town",
|
||||
`Invoked Ring of Leaving and returned safely to town from level ${run.currentLevel}.`,
|
||||
run.currentRoomId ? [run.currentRoomId, options.definitionId] : [options.definitionId],
|
||||
);
|
||||
|
||||
appendLogs(run, [logEntry]);
|
||||
return { run, logEntries: [logEntry] };
|
||||
}
|
||||
case "item.amulet-of-resistance": {
|
||||
if (run.phase !== "dungeon") {
|
||||
throw new Error("Amulet of Resistance can only be invoked in the dungeon.");
|
||||
}
|
||||
|
||||
if (hasStatus(run.adventurerSnapshot.statuses, AMULET_RESISTANCE_STATUS_ID)) {
|
||||
throw new Error("Amulet of Resistance is already warding the adventurer.");
|
||||
}
|
||||
|
||||
const status = {
|
||||
id: AMULET_RESISTANCE_STATUS_ID,
|
||||
source: options.definitionId,
|
||||
duration: run.activeCombat ? "combat" : "room",
|
||||
value: 1,
|
||||
notes: "Reduces the next damage taken by 1.",
|
||||
} as const;
|
||||
|
||||
addStatus(run.adventurerSnapshot.statuses, { ...status });
|
||||
if (run.activeCombat) {
|
||||
addStatus(run.activeCombat.player.statuses, { ...status });
|
||||
}
|
||||
|
||||
const logEntry = createLogEntry(
|
||||
`magic.amulet-of-resistance.${run.log.length + 1}`,
|
||||
at,
|
||||
"progression",
|
||||
"Invoked Amulet of Resistance. The next incoming damage will be reduced by 1.",
|
||||
[options.definitionId],
|
||||
);
|
||||
|
||||
appendLogs(run, [logEntry]);
|
||||
return { run, logEntries: [logEntry] };
|
||||
}
|
||||
case "item.amulet-of-fire-resistance": {
|
||||
if (run.phase !== "dungeon") {
|
||||
throw new Error("Amulet of Fire Resistance can only be invoked in the dungeon.");
|
||||
}
|
||||
|
||||
if (hasStatus(run.adventurerSnapshot.statuses, AMULET_FIRE_RESISTANCE_STATUS_ID)) {
|
||||
throw new Error("Amulet of Fire Resistance is already warding the adventurer.");
|
||||
}
|
||||
|
||||
const status = {
|
||||
id: AMULET_FIRE_RESISTANCE_STATUS_ID,
|
||||
source: options.definitionId,
|
||||
duration: run.activeCombat ? "combat" : "room",
|
||||
value: 2,
|
||||
notes: "Reduces the next damage taken by 2.",
|
||||
} as const;
|
||||
|
||||
addStatus(run.adventurerSnapshot.statuses, { ...status });
|
||||
if (run.activeCombat) {
|
||||
addStatus(run.activeCombat.player.statuses, { ...status });
|
||||
}
|
||||
|
||||
const logEntry = createLogEntry(
|
||||
`magic.amulet-of-fire-resistance.${run.log.length + 1}`,
|
||||
at,
|
||||
"progression",
|
||||
"Invoked Amulet of Fire Resistance. The next incoming damage will be reduced by 2.",
|
||||
[options.definitionId],
|
||||
);
|
||||
|
||||
appendLogs(run, [logEntry]);
|
||||
return { run, logEntries: [logEntry] };
|
||||
}
|
||||
case "item.ring-of-spells": {
|
||||
const healed = Math.max(
|
||||
0,
|
||||
Math.min(2, run.adventurerSnapshot.hp.max - run.adventurerSnapshot.hp.current),
|
||||
);
|
||||
run.adventurerSnapshot.hp.current += healed;
|
||||
if (run.activeCombat) {
|
||||
run.activeCombat.player.hpCurrent = run.adventurerSnapshot.hp.current;
|
||||
}
|
||||
|
||||
const logEntry = createLogEntry(
|
||||
`magic.ring-of-spells.${run.log.length + 1}`,
|
||||
at,
|
||||
"progression",
|
||||
`Ring of Spells releases a stored charm and restores ${healed} HP.`,
|
||||
[options.definitionId],
|
||||
);
|
||||
|
||||
appendLogs(run, [logEntry]);
|
||||
return { run, logEntries: [logEntry] };
|
||||
}
|
||||
case "item.potion-of-aura": {
|
||||
if (run.phase !== "dungeon" || run.activeCombat) {
|
||||
throw new Error("Potion of Aura can only be used while exploring the dungeon.");
|
||||
}
|
||||
|
||||
consumeCarriedItem(run, options.definitionId);
|
||||
const room = requireCurrentRoom(run);
|
||||
const revealed = revealHiddenObjects(room);
|
||||
const logEntry = createLogEntry(
|
||||
`magic.potion-of-aura.${run.log.length + 1}`,
|
||||
at,
|
||||
"room",
|
||||
revealed.length > 0
|
||||
? `Potion of Aura reveals ${revealed.map((entry) => entry.title).join(", ")} in the current room.`
|
||||
: "Potion of Aura shimmers through the room, but reveals nothing new.",
|
||||
[options.definitionId, room.id],
|
||||
);
|
||||
|
||||
appendLogs(run, [logEntry]);
|
||||
return { run, logEntries: [logEntry] };
|
||||
}
|
||||
case "item.potion-of-insightful-combat": {
|
||||
if (!run.activeCombat || run.activeCombat.actingSide !== "player") {
|
||||
throw new Error("Potion of Insightful Combat can only be used on the player's combat turn.");
|
||||
}
|
||||
|
||||
if (hasStatus(run.activeCombat.player.statuses, INSIGHTFUL_COMBAT_STATUS_ID)) {
|
||||
throw new Error("Insightful Combat is already active.");
|
||||
}
|
||||
|
||||
consumeCarriedItem(run, options.definitionId);
|
||||
const status = {
|
||||
id: INSIGHTFUL_COMBAT_STATUS_ID,
|
||||
source: options.definitionId,
|
||||
duration: "combat",
|
||||
value: 1,
|
||||
notes: "Adds +1 precision to the next attack.",
|
||||
} as const;
|
||||
addStatus(run.adventurerSnapshot.statuses, { ...status });
|
||||
addStatus(run.activeCombat.player.statuses, { ...status });
|
||||
|
||||
const logEntry = createLogEntry(
|
||||
`magic.potion-of-insightful-combat.${run.log.length + 1}`,
|
||||
at,
|
||||
"combat",
|
||||
"Potion of Insightful Combat sharpens the next attack with +1 precision.",
|
||||
[options.definitionId, run.activeCombat.id],
|
||||
);
|
||||
|
||||
appendLogs(run, [logEntry]);
|
||||
return { run, logEntries: [logEntry] };
|
||||
}
|
||||
case "item.wand-of-fire": {
|
||||
if (!run.activeCombat || run.activeCombat.actingSide !== "player") {
|
||||
throw new Error("Wand of Fire can only be used on the player's combat turn.");
|
||||
}
|
||||
|
||||
const target =
|
||||
run.activeCombat.enemies.find((enemy) => enemy.id === options.targetEnemyId && enemy.hpCurrent > 0) ??
|
||||
run.activeCombat.enemies.find((enemy) => enemy.hpCurrent > 0);
|
||||
|
||||
if (!target) {
|
||||
throw new Error("No living enemy is available for Wand of Fire.");
|
||||
}
|
||||
|
||||
target.hpCurrent = Math.max(0, target.hpCurrent - 2);
|
||||
run.activeCombat.actingSide = run.activeCombat.enemies.some((enemy) => enemy.hpCurrent > 0)
|
||||
? "enemy"
|
||||
: "player";
|
||||
|
||||
const logEntries: LogEntry[] = [
|
||||
createLogEntry(
|
||||
`magic.wand-of-fire.${run.log.length + 1}`,
|
||||
at,
|
||||
"combat",
|
||||
`Wand of Fire scorches ${target.name} for 2 damage.`,
|
||||
[options.definitionId, target.id, run.activeCombat.id],
|
||||
),
|
||||
];
|
||||
|
||||
if (target.hpCurrent === 0) {
|
||||
logEntries.push(
|
||||
createLogEntry(
|
||||
`magic.wand-of-fire.defeat.${run.log.length + 2}`,
|
||||
at,
|
||||
"combat",
|
||||
`${target.name} is burned down by the wand's fire.`,
|
||||
[options.definitionId, target.id, run.activeCombat.id],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
appendLogs(run, logEntries);
|
||||
run.activeCombat.combatLog.push(...logEntries);
|
||||
syncPlayerToAdventurer(run);
|
||||
|
||||
if (run.activeCombat.enemies.every((enemy) => enemy.hpCurrent === 0)) {
|
||||
const completedCombat = run.activeCombat;
|
||||
const levelState = requireCurrentLevel(run);
|
||||
const roomId = requireCurrentRoomId(run);
|
||||
const room = levelState.rooms[roomId];
|
||||
const rewardLogs = applyCombatRewards(
|
||||
options.content,
|
||||
run,
|
||||
completedCombat,
|
||||
undefined,
|
||||
at,
|
||||
);
|
||||
|
||||
if (room?.encounter) {
|
||||
room.encounter.rewardPending = false;
|
||||
room.discovery.cleared = true;
|
||||
}
|
||||
|
||||
run.activeCombat = undefined;
|
||||
appendLogs(run, rewardLogs);
|
||||
}
|
||||
|
||||
return { run, logEntries };
|
||||
}
|
||||
case "item.wand-of-sleep": {
|
||||
if (!run.activeCombat || run.activeCombat.actingSide !== "player") {
|
||||
throw new Error("Wand of Sleep can only be used on the player's combat turn.");
|
||||
}
|
||||
|
||||
const target =
|
||||
run.activeCombat.enemies.find((enemy) => enemy.id === options.targetEnemyId && enemy.hpCurrent > 0) ??
|
||||
run.activeCombat.enemies.find((enemy) => enemy.hpCurrent > 0);
|
||||
|
||||
if (!target) {
|
||||
throw new Error("No living enemy is available for Wand of Sleep.");
|
||||
}
|
||||
|
||||
if (!hasStatus(target.statuses, SLEEPING_STATUS_ID)) {
|
||||
addStatus(target.statuses, {
|
||||
id: SLEEPING_STATUS_ID,
|
||||
source: options.definitionId,
|
||||
duration: "combat",
|
||||
value: 1,
|
||||
notes: "Skips the next enemy turn.",
|
||||
});
|
||||
}
|
||||
run.activeCombat.actingSide = "enemy";
|
||||
|
||||
const logEntry = createLogEntry(
|
||||
`magic.wand-of-sleep.${run.log.length + 1}`,
|
||||
at,
|
||||
"combat",
|
||||
`Wand of Sleep sends ${target.name} into a magical slumber.`,
|
||||
[options.definitionId, target.id, run.activeCombat.id],
|
||||
);
|
||||
|
||||
appendLogs(run, [logEntry]);
|
||||
run.activeCombat.combatLog.push(logEntry);
|
||||
return { run, logEntries: [logEntry] };
|
||||
}
|
||||
default:
|
||||
throw new Error(`No magic-item action is implemented yet for ${options.definitionId}.`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,6 +157,15 @@ export const exitTemplateSchema = z.object({
|
||||
destinationLevel: z.number().int().optional(),
|
||||
});
|
||||
|
||||
export const roomObjectTemplateSchema = z.object({
|
||||
objectType: z.enum(["container", "altar", "corpse", "hazard", "feature", "quest"]),
|
||||
title: z.string().min(1),
|
||||
sourceTableCode: z.string().min(1).optional(),
|
||||
hidden: z.boolean().optional(),
|
||||
searchable: z.boolean().optional(),
|
||||
notes: z.string().optional(),
|
||||
});
|
||||
|
||||
export const roomTemplateSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
level: z.number().int().positive(),
|
||||
@@ -176,6 +185,7 @@ export const roomTemplateSchema = z.object({
|
||||
})
|
||||
.optional(),
|
||||
exits: z.array(exitTemplateSchema).optional(),
|
||||
objects: z.array(roomObjectTemplateSchema).optional(),
|
||||
encounterRefs: z.array(contentReferenceSchema).optional(),
|
||||
objectRefs: z.array(contentReferenceSchema).optional(),
|
||||
tags: z.array(z.string()),
|
||||
|
||||
@@ -17,12 +17,14 @@ export const contentReferenceTypeSchema = z.enum([
|
||||
export const contentReferenceSchema = z.object({
|
||||
type: contentReferenceTypeSchema,
|
||||
id: z.string().min(1),
|
||||
quantity: z.number().int().positive().optional(),
|
||||
});
|
||||
|
||||
export const ruleEffectSchema = z.object({
|
||||
type: z.enum([
|
||||
"gain-xp",
|
||||
"gain-gold",
|
||||
"gain-silver",
|
||||
"heal",
|
||||
"take-damage",
|
||||
"modify-shift",
|
||||
@@ -38,6 +40,8 @@ export const ruleEffectSchema = z.object({
|
||||
"log-only",
|
||||
]),
|
||||
amount: z.number().optional(),
|
||||
diceKind: diceKindSchema.optional(),
|
||||
rollCount: z.number().int().positive().optional(),
|
||||
statusId: z.string().optional(),
|
||||
target: z.enum(["self", "enemy", "room", "campaign"]).optional(),
|
||||
referenceId: z.string().optional(),
|
||||
|
||||
@@ -24,6 +24,7 @@ export const inventoryStateSchema = z.object({
|
||||
stored: z.array(inventoryEntrySchema),
|
||||
currency: z.object({
|
||||
gold: z.number().int().nonnegative(),
|
||||
silver: z.number().int().nonnegative(),
|
||||
}),
|
||||
rationCount: z.number().int().nonnegative(),
|
||||
lightSources: z.array(inventoryEntrySchema),
|
||||
@@ -120,9 +121,17 @@ export const encounterStateSchema = z.object({
|
||||
export const roomObjectStateSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
objectType: z.enum(["container", "altar", "corpse", "hazard", "feature", "quest"]),
|
||||
title: z.string().min(1),
|
||||
sourceTableCode: z.string().optional(),
|
||||
interacted: z.boolean(),
|
||||
resolved: z.boolean().optional(),
|
||||
hidden: z.boolean().optional(),
|
||||
searchable: z.boolean().optional(),
|
||||
rewardItemId: z.string().optional(),
|
||||
rewardGold: z.number().int().nonnegative().optional(),
|
||||
damage: z.number().int().nonnegative().optional(),
|
||||
resolutionLabel: z.string().optional(),
|
||||
resolutionEntryKey: z.string().optional(),
|
||||
effects: z.array(ruleEffectSchema).optional(),
|
||||
notes: z.string().optional(),
|
||||
});
|
||||
@@ -239,6 +248,7 @@ export const runStateSchema = z.object({
|
||||
defeatedCreatureIds: z.array(z.string()),
|
||||
xpGained: z.number().int().nonnegative(),
|
||||
goldGained: z.number().int().nonnegative(),
|
||||
silverGained: z.number().int().nonnegative(),
|
||||
lootedItems: z.array(inventoryEntrySchema),
|
||||
log: z.array(logEntrySchema),
|
||||
pendingEffects: z.array(ruleEffectSchema),
|
||||
|
||||
@@ -373,6 +373,10 @@ select {
|
||||
background: rgba(255, 245, 223, 0.04);
|
||||
color: #f4efe3;
|
||||
padding: 0.72rem 1rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.35rem;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
transform 140ms ease,
|
||||
@@ -401,6 +405,18 @@ select {
|
||||
background: linear-gradient(180deg, #d97833, #9f501b);
|
||||
}
|
||||
|
||||
.button-file {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.button-file input {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
opacity: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.encounter-box,
|
||||
.combat-status {
|
||||
margin-top: 1rem;
|
||||
|
||||
@@ -155,12 +155,29 @@ export type CreatureDefinition = {
|
||||
|
||||
export type ExitType = "open" | "door" | "locked" | "secret" | "shaft" | "stairs";
|
||||
|
||||
export type RoomObjectType =
|
||||
| "container"
|
||||
| "altar"
|
||||
| "corpse"
|
||||
| "hazard"
|
||||
| "feature"
|
||||
| "quest";
|
||||
|
||||
export type ExitTemplate = {
|
||||
direction?: "north" | "east" | "south" | "west";
|
||||
exitType: ExitType;
|
||||
destinationLevel?: number;
|
||||
};
|
||||
|
||||
export type RoomObjectTemplate = {
|
||||
objectType: RoomObjectType;
|
||||
title: string;
|
||||
sourceTableCode?: string;
|
||||
hidden?: boolean;
|
||||
searchable?: boolean;
|
||||
notes?: string;
|
||||
};
|
||||
|
||||
export type RoomClass = "normal" | "small" | "large" | "special" | "start" | "stairs";
|
||||
|
||||
export type RoomTemplate = {
|
||||
@@ -180,6 +197,7 @@ export type RoomTemplate = {
|
||||
height: number;
|
||||
};
|
||||
exits?: ExitTemplate[];
|
||||
objects?: RoomObjectTemplate[];
|
||||
encounterRefs?: ContentReference[];
|
||||
objectRefs?: ContentReference[];
|
||||
tags: string[];
|
||||
|
||||
@@ -15,11 +15,13 @@ export type ContentReferenceType =
|
||||
export type ContentReference = {
|
||||
type: ContentReferenceType;
|
||||
id: string;
|
||||
quantity?: number;
|
||||
};
|
||||
|
||||
export type RuleEffectType =
|
||||
| "gain-xp"
|
||||
| "gain-gold"
|
||||
| "gain-silver"
|
||||
| "heal"
|
||||
| "take-damage"
|
||||
| "modify-shift"
|
||||
@@ -39,6 +41,8 @@ export type RuleEffectTarget = "self" | "enemy" | "room" | "campaign";
|
||||
export type RuleEffect = {
|
||||
type: RuleEffectType;
|
||||
amount?: number;
|
||||
diceKind?: DiceKind;
|
||||
rollCount?: number;
|
||||
statusId?: string;
|
||||
target?: RuleEffectTarget;
|
||||
referenceId?: string;
|
||||
|
||||
@@ -25,6 +25,7 @@ export type InventoryState = {
|
||||
stored: InventoryEntry[];
|
||||
currency: {
|
||||
gold: number;
|
||||
silver: number;
|
||||
};
|
||||
rationCount: number;
|
||||
lightSources: InventoryEntry[];
|
||||
@@ -121,9 +122,17 @@ export type EncounterState = {
|
||||
export type RoomObjectState = {
|
||||
id: string;
|
||||
objectType: "container" | "altar" | "corpse" | "hazard" | "feature" | "quest";
|
||||
title: string;
|
||||
sourceTableCode?: string;
|
||||
interacted: boolean;
|
||||
resolved?: boolean;
|
||||
hidden?: boolean;
|
||||
searchable?: boolean;
|
||||
rewardItemId?: string;
|
||||
rewardGold?: number;
|
||||
damage?: number;
|
||||
resolutionLabel?: string;
|
||||
resolutionEntryKey?: string;
|
||||
effects?: RuleEffect[];
|
||||
notes?: string;
|
||||
};
|
||||
@@ -240,6 +249,7 @@ export type RunState = {
|
||||
defeatedCreatureIds: string[];
|
||||
xpGained: number;
|
||||
goldGained: number;
|
||||
silverGained: number;
|
||||
lootedItems: InventoryEntry[];
|
||||
log: LogEntry[];
|
||||
pendingEffects: RuleEffect[];
|
||||
|
||||
Reference in New Issue
Block a user