BlueGit

timfa questward

Add dialogue item takes with soft bag removal and path warnings.

Steps can remove items after lines (taking whatever the player has). The editor highlights takes yellow when branch/trigger conditions do not guarantee those items on every path.

timfa Tim Falken · pushed by timfa

Authored 2026-09-07 · 2 months ago

Hash
01866ad49426d6f0c99406d5f8c6fd95a6e0fc21
Parent
d39b0483
10 files changed +511 −19
client/src/editor/dialogueSimulate.js +14 −1
@@ -6,7 +6,8 @@ import { itemDefinition } from "/shared/definitions/items.js";
6 6 import { evaluateConditionSet } from "/shared/quests/conditions.js";
7 7 import {
8 8 formatDialogueRewardMessage,
9 formatDialogueQuestRewardMessage
9 formatDialogueQuestRewardMessage,
10 formatDialogueTakeMessage
10 11 } from "/shared/quests/dialogueRewards.js";
11 12
12 13 const ICON = 48;
@@ -101,6 +102,18 @@ export function initDialogueSimulate ({ getTree, getQuestTitle = null } = {})
101 102 function rewardMessagesForStep (step)
102 103 {
103 104 const messages = [];
105 const takeParts = [];
106 for (const take of step?.itemTakes ?? [])
107 {
108 const def = itemDefinition(take.itemId);
109 takeParts.push({
110 displayName: def?.displayName ?? `Item ${take.itemId}`,
111 quantity: Math.max(1, take.quantity | 0 || 1)
112 });
113 }
114 const takeMsg = formatDialogueTakeMessage(takeParts);
115 if (takeMsg)
116 { messages.push(takeMsg); }
104 117 const bagParts = [];
105 118 for (const reward of step?.itemRewards ?? [])
106 119 {
@@ -6,7 +6,8 @@ import { itemDefinition } from "/shared/definitions/items.js";
6import { evaluateConditionSet } from "/shared/quests/conditions.js";
6import { evaluateConditionSet } from "/shared/quests/conditions.js";
7import {
7import {
8 formatDialogueRewardMessage,
8 formatDialogueRewardMessage,
9 formatDialogueQuestRewardMessage
9 formatDialogueQuestRewardMessage,
10 formatDialogueTakeMessage
10} from "/shared/quests/dialogueRewards.js";
11} from "/shared/quests/dialogueRewards.js";
11
12
12const ICON = 48;
13const ICON = 48;
@@ -101,6 +102,18 @@ export function initDialogueSimulate ({ getTree, getQuestTitle = null } = {})
101 function rewardMessagesForStep (step)
102 function rewardMessagesForStep (step)
102 {
103 {
103 const messages = [];
104 const messages = [];
105 const takeParts = [];
106 for (const take of step?.itemTakes ?? [])
107 {
108 const def = itemDefinition(take.itemId);
109 takeParts.push({
110 displayName: def?.displayName ?? `Item ${take.itemId}`,
111 quantity: Math.max(1, take.quantity | 0 || 1)
112 });
113 }
114 const takeMsg = formatDialogueTakeMessage(takeParts);
115 if (takeMsg)
116 { messages.push(takeMsg); }
104 const bagParts = [];
117 const bagParts = [];
105 for (const reward of step?.itemRewards ?? [])
118 for (const reward of step?.itemRewards ?? [])
106 {
119 {
client/src/editor/dialoguesModal.js +85 −9
@@ -1,5 +1,9 @@
1 1 import { normalizeDialogueTree, normalizeQuestDef } from "/shared/quests/normalize.js";
2 2 import { emptyConditionSet } from "/shared/quests/conditions.js";
3 import {
4 dialogueTakeIsUnguaranteed,
5 unguaranteedDialogueTakes
6 } from "/shared/quests/dialoguePathTakes.js";
3 7 import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
4 8 import { renderConditionSet } from "./conditionSetEditor.js";
5 9 import { initDialogueSimulate } from "./dialogueSimulate.js";
@@ -51,7 +55,12 @@ export function initDialoguesModal ({
51 55 }
52 56 }
53 57
54 /** @type {null | { step: object, resultsEl: HTMLElement, inputEl: HTMLInputElement }} */
58 /** @type {null | {
59 * step: object,
60 * field: "itemRewards" | "itemTakes",
61 * resultsEl: HTMLElement,
62 * inputEl: HTMLInputElement
63 * }} */
55 64 let itemPickContext = null;
56 65
57 66 function closeInlineItemSearch ()
@@ -61,9 +70,9 @@ export function initDialoguesModal ({
61 70 itemPickContext = null;
62 71 }
63 72
64 function openInlineItemSearch (step, inputEl, resultsEl)
73 function openInlineItemSearch (step, field, inputEl, resultsEl)
65 74 {
66 itemPickContext = { step, inputEl, resultsEl };
75 itemPickContext = { step, field, inputEl, resultsEl };
67 76 inputEl.value = "";
68 77 renderInlineItemSearch("");
69 78 inputEl.focus();
@@ -73,10 +82,10 @@ export function initDialoguesModal ({
73 82 {
74 83 if (!itemPickContext)
75 84 { return; }
76 const { step, resultsEl } = itemPickContext;
85 const { step, field, resultsEl } = itemPickContext;
77 86 resultsEl.replaceChildren();
78 87 const q = String(query ?? "").trim().toLowerCase();
79 const taken = new Set((step.itemRewards ?? []).map((row) => row.itemId));
88 const taken = new Set((step[field] ?? []).map((row) => row.itemId));
80 89 const matches = listAllItemPickerEntries().filter((item) =>
81 90 {
82 91 if (taken.has(item.itemId))
@@ -106,9 +115,9 @@ export function initDialoguesModal ({
106 115 row.append(name, key);
107 116 row.addEventListener("click", () =>
108 117 {
109 if (!Array.isArray(step.itemRewards))
110 { step.itemRewards = []; }
111 step.itemRewards.push({ itemId: item.itemId, quantity: 1 });
118 if (!Array.isArray(step[field]))
119 { step[field] = []; }
120 step[field].push({ itemId: item.itemId, quantity: 1 });
112 121 closeInlineItemSearch();
113 122 renderEditor();
114 123 });
@@ -156,6 +165,7 @@ export function initDialoguesModal ({
156 165 stepId: `step-${draft.steps.length + 1}`,
157 166 lines: [{ speaker: "npc", text: "…", effects: [] }],
158 167 itemRewards: [],
168 itemTakes: [],
159 169 questRewards: [],
160 170 exit: { kind: "end" }
161 171 });
@@ -208,6 +218,8 @@ export function initDialoguesModal ({
208 218 stepsTitle.append(stepsStrong);
209 219 editorEl.append(stepsTitle);
210 220
221 const takeWarnings = unguaranteedDialogueTakes(draft);
222
211 223 draft.steps.forEach((step, stepIndex) =>
212 224 {
213 225 const box = document.createElement("div");
@@ -221,6 +233,7 @@ export function initDialoguesModal ({
221 233 stepId: "greeting",
222 234 lines: [{ speaker: "npc", text: "…", effects: [] }],
223 235 itemRewards: [],
236 itemTakes: [],
224 237 questRewards: [],
225 238 exit: { kind: "end" }
226 239 });
@@ -284,7 +297,7 @@ export function initDialoguesModal ({
284 297 const rewardsHead = sectionHeader("Item rewards", () =>
285 298 {
286 299 searchWrap.hidden = false;
287 openInlineItemSearch(step, searchInput, searchResults);
300 openInlineItemSearch(step, "itemRewards", searchInput, searchResults);
288 301 });
289 302 box.append(rewardsHead);
290 303 const rewardsHint = document.createElement("p");
@@ -325,6 +338,69 @@ export function initDialoguesModal ({
325 338 });
326 339 box.append(searchWrap);
327 340
341 if (!Array.isArray(step.itemTakes))
342 { step.itemTakes = []; }
343 const takeSearchWrap = document.createElement("div");
344 takeSearchWrap.className = "dialogue-reward-item-search";
345 takeSearchWrap.hidden = true;
346 const takeSearchInput = document.createElement("input");
347 takeSearchInput.type = "search";
348 takeSearchInput.placeholder = "Search items…";
349 takeSearchInput.autocomplete = "off";
350 takeSearchInput.addEventListener("input", () => renderInlineItemSearch(takeSearchInput.value));
351 const takeSearchResults = document.createElement("div");
352 takeSearchResults.className = "dialogue-reward-item-results";
353 takeSearchWrap.append(takeSearchInput, takeSearchResults);
354 const takesHead = sectionHeader("Item takes", () =>
355 {
356 takeSearchWrap.hidden = false;
357 openInlineItemSearch(step, "itemTakes", takeSearchInput, takeSearchResults);
358 });
359 box.append(takesHead);
360 const takesHint = document.createElement("p");
361 takesHint.className = "content-editor-hint";
362 takesHint.textContent = "Removed from the bag after all lines (soft: takes what the player has). Yellow = branch/trigger path does not guarantee the player has them.";
363 box.append(takesHint);
364 if (!step.itemTakes.length)
365 {
366 const empty = document.createElement("p");
367 empty.className = "content-editor-hint";
368 empty.textContent = "No item takes.";
369 box.append(empty);
370 }
371 step.itemTakes.forEach((take, takeIndex) =>
372 {
373 const def = itemDefinition(take.itemId);
374 const row = document.createElement("div");
375 row.className = "spawner-drops-row";
376 if (dialogueTakeIsUnguaranteed(takeWarnings, step.stepId, take.itemId))
377 {
378 row.classList.add("dialogue-item-take-unguaranteed");
379 row.title = "Not guaranteed by every branch/trigger path to this step.";
380 }
381 const name = document.createElement("span");
382 name.className = "spawner-sells-name";
383 name.textContent = def?.displayName ?? `Item ${take.itemId}`;
384 const qty = document.createElement("input");
385 qty.type = "number";
386 qty.min = "1";
387 qty.step = "1";
388 qty.value = String(Math.max(1, take.quantity | 0 || 1));
389 qty.title = "Quantity";
390 qty.addEventListener("input", () =>
391 {
392 step.itemTakes[takeIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
393 renderEditor();
394 });
395 row.append(name, qty, removeButton(() =>
396 {
397 step.itemTakes.splice(takeIndex, 1);
398 renderEditor();
399 }));
400 box.append(row);
401 });
402 box.append(takeSearchWrap);
403
328 404 if (!Array.isArray(step.questRewards))
329 405 { step.questRewards = []; }
330 406 const questRewardsHead = sectionHeader("Quest rewards", () =>
@@ -1,5 +1,9 @@
1import { normalizeDialogueTree, normalizeQuestDef } from "/shared/quests/normalize.js";
1import { normalizeDialogueTree, normalizeQuestDef } from "/shared/quests/normalize.js";
2import { emptyConditionSet } from "/shared/quests/conditions.js";
2import { emptyConditionSet } from "/shared/quests/conditions.js";
3import {
4 dialogueTakeIsUnguaranteed,
5 unguaranteedDialogueTakes
6} from "/shared/quests/dialoguePathTakes.js";
3import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
7import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
4import { renderConditionSet } from "./conditionSetEditor.js";
8import { renderConditionSet } from "./conditionSetEditor.js";
5import { initDialogueSimulate } from "./dialogueSimulate.js";
9import { initDialogueSimulate } from "./dialogueSimulate.js";
@@ -51,7 +55,12 @@ export function initDialoguesModal ({
51 }
55 }
52 }
56 }
53
57
54 /** @type {null | { step: object, resultsEl: HTMLElement, inputEl: HTMLInputElement }} */
58 /** @type {null | {
59 * step: object,
60 * field: "itemRewards" | "itemTakes",
61 * resultsEl: HTMLElement,
62 * inputEl: HTMLInputElement
63 * }} */
55 let itemPickContext = null;
64 let itemPickContext = null;
56
65
57 function closeInlineItemSearch ()
66 function closeInlineItemSearch ()
@@ -61,9 +70,9 @@ export function initDialoguesModal ({
61 itemPickContext = null;
70 itemPickContext = null;
62 }
71 }
63
72
64 function openInlineItemSearch (step, inputEl, resultsEl)
73 function openInlineItemSearch (step, field, inputEl, resultsEl)
65 {
74 {
66 itemPickContext = { step, inputEl, resultsEl };
75 itemPickContext = { step, field, inputEl, resultsEl };
67 inputEl.value = "";
76 inputEl.value = "";
68 renderInlineItemSearch("");
77 renderInlineItemSearch("");
69 inputEl.focus();
78 inputEl.focus();
@@ -73,10 +82,10 @@ export function initDialoguesModal ({
73 {
82 {
74 if (!itemPickContext)
83 if (!itemPickContext)
75 { return; }
84 { return; }
76 const { step, resultsEl } = itemPickContext;
85 const { step, field, resultsEl } = itemPickContext;
77 resultsEl.replaceChildren();
86 resultsEl.replaceChildren();
78 const q = String(query ?? "").trim().toLowerCase();
87 const q = String(query ?? "").trim().toLowerCase();
79 const taken = new Set((step.itemRewards ?? []).map((row) => row.itemId));
88 const taken = new Set((step[field] ?? []).map((row) => row.itemId));
80 const matches = listAllItemPickerEntries().filter((item) =>
89 const matches = listAllItemPickerEntries().filter((item) =>
81 {
90 {
82 if (taken.has(item.itemId))
91 if (taken.has(item.itemId))
@@ -106,9 +115,9 @@ export function initDialoguesModal ({
106 row.append(name, key);
115 row.append(name, key);
107 row.addEventListener("click", () =>
116 row.addEventListener("click", () =>
108 {
117 {
109 if (!Array.isArray(step.itemRewards))
118 if (!Array.isArray(step[field]))
110 { step.itemRewards = []; }
119 { step[field] = []; }
111 step.itemRewards.push({ itemId: item.itemId, quantity: 1 });
120 step[field].push({ itemId: item.itemId, quantity: 1 });
112 closeInlineItemSearch();
121 closeInlineItemSearch();
113 renderEditor();
122 renderEditor();
114 });
123 });
@@ -156,6 +165,7 @@ export function initDialoguesModal ({
156 stepId: `step-${draft.steps.length + 1}`,
165 stepId: `step-${draft.steps.length + 1}`,
157 lines: [{ speaker: "npc", text: "…", effects: [] }],
166 lines: [{ speaker: "npc", text: "…", effects: [] }],
158 itemRewards: [],
167 itemRewards: [],
168 itemTakes: [],
159 questRewards: [],
169 questRewards: [],
160 exit: { kind: "end" }
170 exit: { kind: "end" }
161 });
171 });
@@ -208,6 +218,8 @@ export function initDialoguesModal ({
208 stepsTitle.append(stepsStrong);
218 stepsTitle.append(stepsStrong);
209 editorEl.append(stepsTitle);
219 editorEl.append(stepsTitle);
210
220
221 const takeWarnings = unguaranteedDialogueTakes(draft);
222
211 draft.steps.forEach((step, stepIndex) =>
223 draft.steps.forEach((step, stepIndex) =>
212 {
224 {
213 const box = document.createElement("div");
225 const box = document.createElement("div");
@@ -221,6 +233,7 @@ export function initDialoguesModal ({
221 stepId: "greeting",
233 stepId: "greeting",
222 lines: [{ speaker: "npc", text: "…", effects: [] }],
234 lines: [{ speaker: "npc", text: "…", effects: [] }],
223 itemRewards: [],
235 itemRewards: [],
236 itemTakes: [],
224 questRewards: [],
237 questRewards: [],
225 exit: { kind: "end" }
238 exit: { kind: "end" }
226 });
239 });
@@ -284,7 +297,7 @@ export function initDialoguesModal ({
284 const rewardsHead = sectionHeader("Item rewards", () =>
297 const rewardsHead = sectionHeader("Item rewards", () =>
285 {
298 {
286 searchWrap.hidden = false;
299 searchWrap.hidden = false;
287 openInlineItemSearch(step, searchInput, searchResults);
300 openInlineItemSearch(step, "itemRewards", searchInput, searchResults);
288 });
301 });
289 box.append(rewardsHead);
302 box.append(rewardsHead);
290 const rewardsHint = document.createElement("p");
303 const rewardsHint = document.createElement("p");
@@ -325,6 +338,69 @@ export function initDialoguesModal ({
325 });
338 });
326 box.append(searchWrap);
339 box.append(searchWrap);
327
340
341 if (!Array.isArray(step.itemTakes))
342 { step.itemTakes = []; }
343 const takeSearchWrap = document.createElement("div");
344 takeSearchWrap.className = "dialogue-reward-item-search";
345 takeSearchWrap.hidden = true;
346 const takeSearchInput = document.createElement("input");
347 takeSearchInput.type = "search";
348 takeSearchInput.placeholder = "Search items…";
349 takeSearchInput.autocomplete = "off";
350 takeSearchInput.addEventListener("input", () => renderInlineItemSearch(takeSearchInput.value));
351 const takeSearchResults = document.createElement("div");
352 takeSearchResults.className = "dialogue-reward-item-results";
353 takeSearchWrap.append(takeSearchInput, takeSearchResults);
354 const takesHead = sectionHeader("Item takes", () =>
355 {
356 takeSearchWrap.hidden = false;
357 openInlineItemSearch(step, "itemTakes", takeSearchInput, takeSearchResults);
358 });
359 box.append(takesHead);
360 const takesHint = document.createElement("p");
361 takesHint.className = "content-editor-hint";
362 takesHint.textContent = "Removed from the bag after all lines (soft: takes what the player has). Yellow = branch/trigger path does not guarantee the player has them.";
363 box.append(takesHint);
364 if (!step.itemTakes.length)
365 {
366 const empty = document.createElement("p");
367 empty.className = "content-editor-hint";
368 empty.textContent = "No item takes.";
369 box.append(empty);
370 }
371 step.itemTakes.forEach((take, takeIndex) =>
372 {
373 const def = itemDefinition(take.itemId);
374 const row = document.createElement("div");
375 row.className = "spawner-drops-row";
376 if (dialogueTakeIsUnguaranteed(takeWarnings, step.stepId, take.itemId))
377 {
378 row.classList.add("dialogue-item-take-unguaranteed");
379 row.title = "Not guaranteed by every branch/trigger path to this step.";
380 }
381 const name = document.createElement("span");
382 name.className = "spawner-sells-name";
383 name.textContent = def?.displayName ?? `Item ${take.itemId}`;
384 const qty = document.createElement("input");
385 qty.type = "number";
386 qty.min = "1";
387 qty.step = "1";
388 qty.value = String(Math.max(1, take.quantity | 0 || 1));
389 qty.title = "Quantity";
390 qty.addEventListener("input", () =>
391 {
392 step.itemTakes[takeIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
393 renderEditor();
394 });
395 row.append(name, qty, removeButton(() =>
396 {
397 step.itemTakes.splice(takeIndex, 1);
398 renderEditor();
399 }));
400 box.append(row);
401 });
402 box.append(takeSearchWrap);
403
328 if (!Array.isArray(step.questRewards))
404 if (!Array.isArray(step.questRewards))
329 { step.questRewards = []; }
405 { step.questRewards = []; }
330 const questRewardsHead = sectionHeader("Quest rewards", () =>
406 const questRewardsHead = sectionHeader("Quest rewards", () =>
client/ui/editor.css +11 −0
@@ -1717,3 +1717,14 @@ label {
1717 1717 border-radius: 4px;
1718 1718 background: #12151c;
1719 1719 }
1720
1721 .dialogue-item-take-unguaranteed {
1722 background: rgba(224, 168, 74, 0.18);
1723 border: 1px solid #e0a84a;
1724 border-radius: 4px;
1725 padding: 0.2rem 0.35rem;
1726 }
1727
1728 .dialogue-item-take-unguaranteed .spawner-sells-name {
1729 color: #e8c84a;
1730 }
@@ -1717,3 +1717,14 @@ label {
1717 border-radius: 4px;
1717 border-radius: 4px;
1718 background: #12151c;
1718 background: #12151c;
1719}
1719}
1720
1721.dialogue-item-take-unguaranteed {
1722 background: rgba(224, 168, 74, 0.18);
1723 border: 1px solid #e0a84a;
1724 border-radius: 4px;
1725 padding: 0.2rem 0.35rem;
1726}
1727
1728.dialogue-item-take-unguaranteed .spawner-sells-name {
1729 color: #e8c84a;
1730}
server/src/quests/runtime.js +41 −2
@@ -4,12 +4,16 @@ import {
4 4 countableObjectiveProgress,
5 5 objectiveProgressFingerprint
6 6 } from "../../../shared/quests/objectiveProgress.js";
7 import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
7 import { countItemInSlots, insertStack, takeMatchingFromSlots, takeMatchingUpToFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
8 8 import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
9 9 import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
10 10 import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";
11 11 import { skillLevel, SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";
12 import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../../shared/quests/dialogueRewards.js";
12 import {
13 formatDialogueRewardMessage,
14 formatDialogueQuestRewardMessage,
15 formatDialogueTakeMessage
16 } from "../../../shared/quests/dialogueRewards.js";
13 17 import {
14 18 formatQuestBankRewardLetterBody,
15 19 QUESTWARD_GIFT_AUTHOR,
@@ -328,6 +332,7 @@ export class QuestRuntime
328 332 {
329 333 const step = tree.steps.find((s) => s.stepId === session.stepId);
330 334 const rewardMessages = [
335 ...this.#takeStepItems(characterId, step, events),
331 336 ...this.#grantStepItemRewards(characterId, step, events),
332 337 ...this.#grantStepQuestRewards(characterId, step, playerView, events)
333 338 ];
@@ -408,6 +413,40 @@ export class QuestRuntime
408 413 return { ok: true, events };
409 414 }
410 415
416 /**
417 * Soft-take step.itemTakes from the bag (min(have, required)). Returns player-facing notices.
418 */
419 #takeStepItems (characterId, step, events)
420 {
421 const takes = step?.itemTakes ?? [];
422 if (!takes.length)
423 { return []; }
424 const parts = [];
425 for (const take of takes)
426 {
427 const bag = this.#loadBag(characterId);
428 if (!bag)
429 { continue; }
430 const itemId = take.itemId | 0;
431 const want = Math.max(1, Number(take.quantity) || 1);
432 const def = itemDefinition(itemId);
433 const displayName = def?.displayName ?? `Item ${itemId}`;
434 const result = takeMatchingUpToFromSlots(bag.inventory, {
435 itemId,
436 quantity: want,
437 compact: false
438 });
439 if (!result.ok || result.takenQuantity <= 0)
440 { continue; }
441 bag.inventory = result.slots;
442 this.#persistBag(characterId, bag);
443 events.push({ type: "inventoryDirty" });
444 parts.push({ displayName, quantity: result.takenQuantity });
445 }
446 const message = formatDialogueTakeMessage(parts);
447 return message ? [message] : [];
448 }
449
411 450 /**
412 451 * Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.
413 452 */
@@ -4,12 +4,16 @@ import {
4 countableObjectiveProgress,
4 countableObjectiveProgress,
5 objectiveProgressFingerprint
5 objectiveProgressFingerprint
6} from "../../../shared/quests/objectiveProgress.js";
6} from "../../../shared/quests/objectiveProgress.js";
7import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
7import { countItemInSlots, insertStack, takeMatchingFromSlots, takeMatchingUpToFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
8import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
8import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
9import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
9import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
10import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";
10import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";
11import { skillLevel, SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";
11import { skillLevel, SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";
12import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../../shared/quests/dialogueRewards.js";
12import {
13 formatDialogueRewardMessage,
14 formatDialogueQuestRewardMessage,
15 formatDialogueTakeMessage
16} from "../../../shared/quests/dialogueRewards.js";
13import {
17import {
14 formatQuestBankRewardLetterBody,
18 formatQuestBankRewardLetterBody,
15 QUESTWARD_GIFT_AUTHOR,
19 QUESTWARD_GIFT_AUTHOR,
@@ -328,6 +332,7 @@ export class QuestRuntime
328 {
332 {
329 const step = tree.steps.find((s) => s.stepId === session.stepId);
333 const step = tree.steps.find((s) => s.stepId === session.stepId);
330 const rewardMessages = [
334 const rewardMessages = [
335 ...this.#takeStepItems(characterId, step, events),
331 ...this.#grantStepItemRewards(characterId, step, events),
336 ...this.#grantStepItemRewards(characterId, step, events),
332 ...this.#grantStepQuestRewards(characterId, step, playerView, events)
337 ...this.#grantStepQuestRewards(characterId, step, playerView, events)
333 ];
338 ];
@@ -408,6 +413,40 @@ export class QuestRuntime
408 return { ok: true, events };
413 return { ok: true, events };
409 }
414 }
410
415
416 /**
417 * Soft-take step.itemTakes from the bag (min(have, required)). Returns player-facing notices.
418 */
419 #takeStepItems (characterId, step, events)
420 {
421 const takes = step?.itemTakes ?? [];
422 if (!takes.length)
423 { return []; }
424 const parts = [];
425 for (const take of takes)
426 {
427 const bag = this.#loadBag(characterId);
428 if (!bag)
429 { continue; }
430 const itemId = take.itemId | 0;
431 const want = Math.max(1, Number(take.quantity) || 1);
432 const def = itemDefinition(itemId);
433 const displayName = def?.displayName ?? `Item ${itemId}`;
434 const result = takeMatchingUpToFromSlots(bag.inventory, {
435 itemId,
436 quantity: want,
437 compact: false
438 });
439 if (!result.ok || result.takenQuantity <= 0)
440 { continue; }
441 bag.inventory = result.slots;
442 this.#persistBag(characterId, bag);
443 events.push({ type: "inventoryDirty" });
444 parts.push({ displayName, quantity: result.takenQuantity });
445 }
446 const message = formatDialogueTakeMessage(parts);
447 return message ? [message] : [];
448 }
449
411 /**
450 /**
412 * Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.
451 * Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.
413 */
452 */
server/tests/dialogue-takes.test.js added +168 −0
@@ -0,0 +1,168 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { normalizeDialogueTree } from "../../shared/quests/normalize.js";
4 import { ConditionKind } from "../../shared/quests/conditions.js";
5 import { formatDialogueTakeMessage } from "../../shared/quests/dialogueRewards.js";
6 import { unguaranteedDialogueTakes } from "../../shared/quests/dialoguePathTakes.js";
7 import {
8 countItemInSlots,
9 emptyEquipment,
10 emptySlots,
11 INVENTORY_SLOTS,
12 takeMatchingUpToFromSlots
13 } from "../../shared/items/inventory.js";
14 import { ItemId } from "../../shared/definitions/items.js";
15 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
16
17 test("normalizeDialogueTree keeps itemTakes", () =>
18 {
19 const tree = normalizeDialogueTree({
20 dialogueId: "Take Tin",
21 steps: [{
22 stepId: "ask",
23 lines: [{ speaker: "npc", text: "Pay up." }],
24 itemTakes: [{ itemId: ItemId.tinOre, quantity: 3 }, { itemId: ItemId.tinOre, quantity: 9 }]
25 }]
26 });
27 assert.deepEqual(tree.steps[0].itemTakes, [{ itemId: ItemId.tinOre, quantity: 3 }]);
28 });
29
30 test("formatDialogueTakeMessage lists removed bag items", () =>
31 {
32 assert.equal(
33 formatDialogueTakeMessage([{ displayName: "Tin ore", quantity: 1 }]),
34 "Tin ore has been removed from your bag."
35 );
36 assert.equal(
37 formatDialogueTakeMessage([{ displayName: "Tin ore", quantity: 3 }]),
38 "3 Tin ore have been removed from your bag."
39 );
40 });
41
42 test("takeMatchingUpToFromSlots soft-takes what is available", () =>
43 {
44 const slots = emptySlots(4);
45 slots[0] = { itemId: ItemId.bones, quantity: 2 };
46 const result = takeMatchingUpToFromSlots(slots, {
47 itemId: ItemId.bones,
48 quantity: 5,
49 compact: false
50 });
51 assert.equal(result.ok, true);
52 assert.equal(result.takenQuantity, 2);
53 assert.equal(countItemInSlots(result.slots, ItemId.bones), 0);
54 });
55
56 test("unguaranteedDialogueTakes warns unless every path guarantees hasItem", () =>
57 {
58 const unguaranteed = normalizeDialogueTree({
59 dialogueId: "unguarded-take",
60 entryStepId: "start",
61 steps: [
62 {
63 stepId: "start",
64 lines: [{ text: "Hi" }],
65 exit: {
66 kind: "branches",
67 branches: [{
68 label: "go",
69 when: { all: [] },
70 nextStepId: "pay"
71 }]
72 }
73 },
74 {
75 stepId: "pay",
76 lines: [{ text: "Hand it over." }],
77 itemTakes: [{ itemId: ItemId.bones, quantity: 2 }]
78 }
79 ]
80 });
81 const warn = unguaranteedDialogueTakes(unguaranteed);
82 assert.equal(warn.get("pay")?.has(ItemId.bones), true);
83
84 const guaranteed = normalizeDialogueTree({
85 dialogueId: "guarded-take",
86 entryStepId: "start",
87 steps: [
88 {
89 stepId: "start",
90 lines: [{ text: "Hi" }],
91 exit: {
92 kind: "branches",
93 branches: [{
94 label: "go",
95 when: {
96 all: [{
97 condition: {
98 kind: ConditionKind.hasItem,
99 itemId: ItemId.bones,
100 quantity: 2
101 }
102 }]
103 },
104 nextStepId: "pay"
105 }]
106 }
107 },
108 {
109 stepId: "pay",
110 lines: [{ text: "Hand it over." }],
111 itemTakes: [{ itemId: ItemId.bones, quantity: 2 }]
112 }
113 ]
114 });
115 const ok = unguaranteedDialogueTakes(guaranteed);
116 assert.equal(ok.has("pay"), false);
117 });
118
119 test("dialogue advance soft-takes itemTakes then reports a notice", () =>
120 {
121 const harness = makeSimulation({ workerCount: 1 });
122 try
123 {
124 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
125 const playerId = harness.simulation.spawnCharacter(1, character);
126 harness.simulation.step();
127
128 const tree = normalizeDialogueTree({
129 dialogueId: "collect-bones",
130 steps: [{
131 stepId: "greeting",
132 lines: [{ speaker: "npc", text: "Those bones look useful." }],
133 itemTakes: [{ itemId: ItemId.bones, quantity: 5 }]
134 }]
135 });
136 const revisionId = harness.worldDb.getActiveRevisionId();
137 harness.worldDb.saveDialogueTree(revisionId, tree);
138 harness.simulation.questContent.reload();
139
140 const inventory = emptySlots(INVENTORY_SLOTS);
141 inventory[0] = { itemId: ItemId.bones, quantity: 2 };
142 harness.simulation.applyBag(playerId, {
143 inventory,
144 equipment: emptyEquipment(),
145 vault: [],
146 vaultReserved: []
147 });
148
149 const npcId = 9001;
150 const opened = harness.simulation.quests.tryOpenDialogue(
151 character.character_id,
152 npcId,
153 "collect-bones"
154 );
155 assert.equal(opened.ok, true);
156
157 const advanced = harness.simulation.quests.advanceDialogue(character.character_id);
158 assert.equal(advanced.ok, true);
159 const notice = (advanced.events ?? []).find((e) => e.type === "dialogueItemRewards");
160 assert.ok(notice);
161 assert.match(notice.messages.join(" "), /2 Bones have been removed from your bag/);
162
163 const bag = harness.simulation.bagOf(playerId);
164 assert.equal(countItemInSlots(bag.inventory, ItemId.bones), 0);
165 }
166 finally
167 { harness.close(); }
168 });
@@ -0,0 +1,168 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { normalizeDialogueTree } from "../../shared/quests/normalize.js";
4import { ConditionKind } from "../../shared/quests/conditions.js";
5import { formatDialogueTakeMessage } from "../../shared/quests/dialogueRewards.js";
6import { unguaranteedDialogueTakes } from "../../shared/quests/dialoguePathTakes.js";
7import {
8 countItemInSlots,
9 emptyEquipment,
10 emptySlots,
11 INVENTORY_SLOTS,
12 takeMatchingUpToFromSlots
13} from "../../shared/items/inventory.js";
14import { ItemId } from "../../shared/definitions/items.js";
15import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
16
17test("normalizeDialogueTree keeps itemTakes", () =>
18{
19 const tree = normalizeDialogueTree({
20 dialogueId: "Take Tin",
21 steps: [{
22 stepId: "ask",
23 lines: [{ speaker: "npc", text: "Pay up." }],
24 itemTakes: [{ itemId: ItemId.tinOre, quantity: 3 }, { itemId: ItemId.tinOre, quantity: 9 }]
25 }]
26 });
27 assert.deepEqual(tree.steps[0].itemTakes, [{ itemId: ItemId.tinOre, quantity: 3 }]);
28});
29
30test("formatDialogueTakeMessage lists removed bag items", () =>
31{
32 assert.equal(
33 formatDialogueTakeMessage([{ displayName: "Tin ore", quantity: 1 }]),
34 "Tin ore has been removed from your bag."
35 );
36 assert.equal(
37 formatDialogueTakeMessage([{ displayName: "Tin ore", quantity: 3 }]),
38 "3 Tin ore have been removed from your bag."
39 );
40});
41
42test("takeMatchingUpToFromSlots soft-takes what is available", () =>
43{
44 const slots = emptySlots(4);
45 slots[0] = { itemId: ItemId.bones, quantity: 2 };
46 const result = takeMatchingUpToFromSlots(slots, {
47 itemId: ItemId.bones,
48 quantity: 5,
49 compact: false
50 });
51 assert.equal(result.ok, true);
52 assert.equal(result.takenQuantity, 2);
53 assert.equal(countItemInSlots(result.slots, ItemId.bones), 0);
54});
55
56test("unguaranteedDialogueTakes warns unless every path guarantees hasItem", () =>
57{
58 const unguaranteed = normalizeDialogueTree({
59 dialogueId: "unguarded-take",
60 entryStepId: "start",
61 steps: [
62 {
63 stepId: "start",
64 lines: [{ text: "Hi" }],
65 exit: {
66 kind: "branches",
67 branches: [{
68 label: "go",
69 when: { all: [] },
70 nextStepId: "pay"
71 }]
72 }
73 },
74 {
75 stepId: "pay",
76 lines: [{ text: "Hand it over." }],
77 itemTakes: [{ itemId: ItemId.bones, quantity: 2 }]
78 }
79 ]
80 });
81 const warn = unguaranteedDialogueTakes(unguaranteed);
82 assert.equal(warn.get("pay")?.has(ItemId.bones), true);
83
84 const guaranteed = normalizeDialogueTree({
85 dialogueId: "guarded-take",
86 entryStepId: "start",
87 steps: [
88 {
89 stepId: "start",
90 lines: [{ text: "Hi" }],
91 exit: {
92 kind: "branches",
93 branches: [{
94 label: "go",
95 when: {
96 all: [{
97 condition: {
98 kind: ConditionKind.hasItem,
99 itemId: ItemId.bones,
100 quantity: 2
101 }
102 }]
103 },
104 nextStepId: "pay"
105 }]
106 }
107 },
108 {
109 stepId: "pay",
110 lines: [{ text: "Hand it over." }],
111 itemTakes: [{ itemId: ItemId.bones, quantity: 2 }]
112 }
113 ]
114 });
115 const ok = unguaranteedDialogueTakes(guaranteed);
116 assert.equal(ok.has("pay"), false);
117});
118
119test("dialogue advance soft-takes itemTakes then reports a notice", () =>
120{
121 const harness = makeSimulation({ workerCount: 1 });
122 try
123 {
124 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
125 const playerId = harness.simulation.spawnCharacter(1, character);
126 harness.simulation.step();
127
128 const tree = normalizeDialogueTree({
129 dialogueId: "collect-bones",
130 steps: [{
131 stepId: "greeting",
132 lines: [{ speaker: "npc", text: "Those bones look useful." }],
133 itemTakes: [{ itemId: ItemId.bones, quantity: 5 }]
134 }]
135 });
136 const revisionId = harness.worldDb.getActiveRevisionId();
137 harness.worldDb.saveDialogueTree(revisionId, tree);
138 harness.simulation.questContent.reload();
139
140 const inventory = emptySlots(INVENTORY_SLOTS);
141 inventory[0] = { itemId: ItemId.bones, quantity: 2 };
142 harness.simulation.applyBag(playerId, {
143 inventory,
144 equipment: emptyEquipment(),
145 vault: [],
146 vaultReserved: []
147 });
148
149 const npcId = 9001;
150 const opened = harness.simulation.quests.tryOpenDialogue(
151 character.character_id,
152 npcId,
153 "collect-bones"
154 );
155 assert.equal(opened.ok, true);
156
157 const advanced = harness.simulation.quests.advanceDialogue(character.character_id);
158 assert.equal(advanced.ok, true);
159 const notice = (advanced.events ?? []).find((e) => e.type === "dialogueItemRewards");
160 assert.ok(notice);
161 assert.match(notice.messages.join(" "), /2 Bones have been removed from your bag/);
162
163 const bag = harness.simulation.bagOf(playerId);
164 assert.equal(countItemInSlots(bag.inventory, ItemId.bones), 0);
165 }
166 finally
167 { harness.close(); }
168});
server/tests/quests-conditions.test.js +5 −1
@@ -10,7 +10,7 @@ import {
10 10 formatObjectiveDisplayText
11 11 } from "../../shared/quests/objectiveProgress.js";
12 12 import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";
13 import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../shared/quests/dialogueRewards.js";
13 import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage, formatDialogueTakeMessage } from "../../shared/quests/dialogueRewards.js";
14 14
15 15 test("ConditionSet AND + NOT", () =>
16 16 {
@@ -96,6 +96,10 @@ test("dialogue reward messages bag vs bank and lists", () =>
96 96 formatDialogueQuestRewardMessage(["Alpha", "Beta"]),
97 97 "The Alpha and Beta quests have been added to your journal."
98 98 );
99 assert.equal(
100 formatDialogueTakeMessage([{ displayName: "Copper ore", quantity: 2 }]),
101 "2 Copper ore have been removed from your bag."
102 );
99 103 });
100 104
101 105 test("countable objective progress for hasItem killCount and skillLevelAtLeast", () =>
@@ -10,7 +10,7 @@ import {
10 formatObjectiveDisplayText
10 formatObjectiveDisplayText
11} from "../../shared/quests/objectiveProgress.js";
11} from "../../shared/quests/objectiveProgress.js";
12import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";
12import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";
13import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../shared/quests/dialogueRewards.js";
13import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage, formatDialogueTakeMessage } from "../../shared/quests/dialogueRewards.js";
14
14
15test("ConditionSet AND + NOT", () =>
15test("ConditionSet AND + NOT", () =>
16{
16{
@@ -96,6 +96,10 @@ test("dialogue reward messages bag vs bank and lists", () =>
96 formatDialogueQuestRewardMessage(["Alpha", "Beta"]),
96 formatDialogueQuestRewardMessage(["Alpha", "Beta"]),
97 "The Alpha and Beta quests have been added to your journal."
97 "The Alpha and Beta quests have been added to your journal."
98 );
98 );
99 assert.equal(
100 formatDialogueTakeMessage([{ displayName: "Copper ore", quantity: 2 }]),
101 "2 Copper ore have been removed from your bag."
102 );
99});
103});
100
104
101test("countable objective progress for hasItem killCount and skillLevelAtLeast", () =>
105test("countable objective progress for hasItem killCount and skillLevelAtLeast", () =>
shared/items/inventory.js +27 −6
@@ -470,14 +470,15 @@ export function insertStackGrowable (slots, stack, definition)
470 470 return { ok: remaining === 0, slots: next, remainder: remaining };
471 471 }
472 472
473 /** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
474 export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true })
473 /** Take up to `quantity` of matching goods (partial OK). Inventory should pass `{ compact: false }`. */
474 export function takeMatchingUpToFromSlots (slots, { itemId, quantity, instance = null, compact = true })
475 475 {
476 476 let remaining = Math.max(0, stackQuantity(quantity));
477 477 if (!remaining)
478 { return { ok: false, slots, taken: null }; }
478 { return { ok: false, slots, taken: null, takenQuantity: 0 }; }
479 479 const next = (slots ?? []).map(cloneStack);
480 480 const takenOrigins = [];
481 let takenQuantity = 0;
481 482 for (let i = 0; i < next.length && remaining > 0; i++)
482 483 {
483 484 const slot = next[i];
@@ -489,6 +490,8 @@ export function takeMatchingFromSlots (slots, { itemId, quantity, instance = nul
489 490 { continue; }
490 491 }
491 492 const amount = Math.min(stackQuantity(slot.quantity), remaining);
493 if (amount <= 0)
494 { continue; }
492 495 const split = splitOrigins(normalizeOrigins(slot), amount);
493 496 takenOrigins.push(...split.taken);
494 497 if (amount >= stackQuantity(slot.quantity))
@@ -500,21 +503,39 @@ export function takeMatchingFromSlots (slots, { itemId, quantity, instance = nul
500 503 delete slot.origin;
501 504 }
502 505 remaining -= amount;
506 takenQuantity += amount;
503 507 }
504 if (remaining > 0)
505 { return { ok: false, slots, taken: null }; }
508 if (takenQuantity <= 0)
509 { return { ok: false, slots, taken: null, takenQuantity: 0 }; }
506 510 return {
507 511 ok: true,
508 512 slots: compact ? next.filter((slot) => slot) : next,
513 takenQuantity,
509 514 taken: attachOrigins({
510 515 itemId,
511 quantity: stackQuantity(quantity),
516 quantity: takenQuantity,
512 517 instance: instance ?? null,
513 518 origins: mergeOriginLists([], takenOrigins)
514 519 })
515 520 };
516 521 }
517 522
523 /** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
524 export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true })
525 {
526 const want = Math.max(0, stackQuantity(quantity));
527 if (!want)
528 { return { ok: false, slots, taken: null }; }
529 const soft = takeMatchingUpToFromSlots(slots, { itemId, quantity: want, instance, compact });
530 if (!soft.ok || soft.takenQuantity < want)
531 { return { ok: false, slots, taken: null }; }
532 return {
533 ok: true,
534 slots: soft.slots,
535 taken: soft.taken
536 };
537 }
538
518 539 export function countItemInSlots (slots, itemId)
519 540 {
520 541 let total = 0;
@@ -470,14 +470,15 @@ export function insertStackGrowable (slots, stack, definition)
470 return { ok: remaining === 0, slots: next, remainder: remaining };
470 return { ok: remaining === 0, slots: next, remainder: remaining };
471}
471}
472
472
473/** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
473/** Take up to `quantity` of matching goods (partial OK). Inventory should pass `{ compact: false }`. */
474export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true })
474export function takeMatchingUpToFromSlots (slots, { itemId, quantity, instance = null, compact = true })
475{
475{
476 let remaining = Math.max(0, stackQuantity(quantity));
476 let remaining = Math.max(0, stackQuantity(quantity));
477 if (!remaining)
477 if (!remaining)
478 { return { ok: false, slots, taken: null }; }
478 { return { ok: false, slots, taken: null, takenQuantity: 0 }; }
479 const next = (slots ?? []).map(cloneStack);
479 const next = (slots ?? []).map(cloneStack);
480 const takenOrigins = [];
480 const takenOrigins = [];
481 let takenQuantity = 0;
481 for (let i = 0; i < next.length && remaining > 0; i++)
482 for (let i = 0; i < next.length && remaining > 0; i++)
482 {
483 {
483 const slot = next[i];
484 const slot = next[i];
@@ -489,6 +490,8 @@ export function takeMatchingFromSlots (slots, { itemId, quantity, instance = nul
489 { continue; }
490 { continue; }
490 }
491 }
491 const amount = Math.min(stackQuantity(slot.quantity), remaining);
492 const amount = Math.min(stackQuantity(slot.quantity), remaining);
493 if (amount <= 0)
494 { continue; }
492 const split = splitOrigins(normalizeOrigins(slot), amount);
495 const split = splitOrigins(normalizeOrigins(slot), amount);
493 takenOrigins.push(...split.taken);
496 takenOrigins.push(...split.taken);
494 if (amount >= stackQuantity(slot.quantity))
497 if (amount >= stackQuantity(slot.quantity))
@@ -500,21 +503,39 @@ export function takeMatchingFromSlots (slots, { itemId, quantity, instance = nul
500 delete slot.origin;
503 delete slot.origin;
501 }
504 }
502 remaining -= amount;
505 remaining -= amount;
506 takenQuantity += amount;
503 }
507 }
504 if (remaining > 0)
508 if (takenQuantity <= 0)
505 { return { ok: false, slots, taken: null }; }
509 { return { ok: false, slots, taken: null, takenQuantity: 0 }; }
506 return {
510 return {
507 ok: true,
511 ok: true,
508 slots: compact ? next.filter((slot) => slot) : next,
512 slots: compact ? next.filter((slot) => slot) : next,
513 takenQuantity,
509 taken: attachOrigins({
514 taken: attachOrigins({
510 itemId,
515 itemId,
511 quantity: stackQuantity(quantity),
516 quantity: takenQuantity,
512 instance: instance ?? null,
517 instance: instance ?? null,
513 origins: mergeOriginLists([], takenOrigins)
518 origins: mergeOriginLists([], takenOrigins)
514 })
519 })
515 };
520 };
516}
521}
517
522
523/** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
524export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true })
525{
526 const want = Math.max(0, stackQuantity(quantity));
527 if (!want)
528 { return { ok: false, slots, taken: null }; }
529 const soft = takeMatchingUpToFromSlots(slots, { itemId, quantity: want, instance, compact });
530 if (!soft.ok || soft.takenQuantity < want)
531 { return { ok: false, slots, taken: null }; }
532 return {
533 ok: true,
534 slots: soft.slots,
535 taken: soft.taken
536 };
537}
538
518export function countItemInSlots (slots, itemId)
539export function countItemInSlots (slots, itemId)
519{
540{
520 let total = 0;
541 let total = 0;
shared/quests/dialoguePathTakes.js added +133 −0
@@ -0,0 +1,133 @@
1 import { ConditionKind } from "./conditions.js";
2
3 /**
4 * Positive hasItem floors implied by a ConditionSet (ignores `not` clauses).
5 * @returns {Map<number, number>} itemId → minimum quantity
6 */
7 export function hasItemGuaranteesFromWhen (when)
8 {
9 /** @type {Map<number, number>} */
10 const out = new Map();
11 for (const clause of when?.all ?? [])
12 {
13 if (clause?.not)
14 { continue; }
15 const condition = clause?.condition;
16 if (condition?.kind !== ConditionKind.hasItem)
17 { continue; }
18 const itemId = Number(condition.itemId) | 0;
19 if (itemId <= 0)
20 { continue; }
21 const quantity = Math.max(1, Number(condition.quantity) || 1) | 0;
22 out.set(itemId, Math.max(out.get(itemId) ?? 0, quantity));
23 }
24 return out;
25 }
26
27 /**
28 * Outgoing dialogue edges from a step exit (branches + player triggers).
29 * @returns {{ nextStepId: string, when: object }[]}
30 */
31 export function dialogueExitEdges (exit)
32 {
33 const edges = [];
34 if (exit?.kind === "branches")
35 {
36 for (const branch of exit.branches ?? [])
37 {
38 if (!branch?.nextStepId)
39 { continue; }
40 edges.push({ nextStepId: branch.nextStepId, when: branch.when ?? { all: [] } });
41 }
42 }
43 else if (exit?.kind === "triggers")
44 {
45 for (const trigger of exit.triggers ?? [])
46 {
47 if (!trigger?.nextStepId)
48 { continue; }
49 edges.push({ nextStepId: trigger.nextStepId, when: trigger.when ?? { all: [] } });
50 }
51 }
52 return edges;
53 }
54
55 /**
56 * Item takes on a step that are not guaranteed on every path from the dialogue entry
57 * (via branch/trigger hasItem conditions + earlier step rewards/takes).
58 * @returns {Map<string, Set<number>>} stepId → unguaranteed itemIds
59 */
60 export function unguaranteedDialogueTakes (tree)
61 {
62 /** @type {Map<string, Set<number>>} */
63 const warnings = new Map();
64 const steps = Array.isArray(tree?.steps) ? tree.steps : [];
65 if (!steps.length)
66 { return warnings; }
67 const byId = new Map(steps.map((step) => [step.stepId, step]));
68 const entryStepId = tree.entryStepId && byId.has(tree.entryStepId)
69 ? tree.entryStepId
70 : steps[0].stepId;
71
72 function note (stepId, itemId)
73 {
74 let set = warnings.get(stepId);
75 if (!set)
76 {
77 set = new Set();
78 warnings.set(stepId, set);
79 }
80 set.add(itemId | 0);
81 }
82
83 /**
84 * @param {string} stepId
85 * @param {Map<number, number>} bag
86 * @param {Set<string>} path
87 */
88 function visit (stepId, bag, path)
89 {
90 if (path.has(stepId))
91 { return; }
92 const step = byId.get(stepId);
93 if (!step)
94 { return; }
95 const nextPath = new Set(path);
96 nextPath.add(stepId);
97 /** @type {Map<number, number>} */
98 const local = new Map(bag);
99
100 for (const take of step.itemTakes ?? [])
101 {
102 const itemId = take.itemId | 0;
103 const need = Math.max(1, Number(take.quantity) || 1) | 0;
104 if ((local.get(itemId) ?? 0) < need)
105 { note(stepId, itemId); }
106 local.set(itemId, Math.max(0, (local.get(itemId) ?? 0) - need));
107 }
108 for (const reward of step.itemRewards ?? [])
109 {
110 const itemId = reward.itemId | 0;
111 const qty = Math.max(1, Number(reward.quantity) || 1) | 0;
112 local.set(itemId, (local.get(itemId) ?? 0) + qty);
113 }
114
115 for (const edge of dialogueExitEdges(step.exit))
116 {
117 /** @type {Map<number, number>} */
118 const child = new Map(local);
119 for (const [itemId, qty] of hasItemGuaranteesFromWhen(edge.when))
120 { child.set(itemId, Math.max(child.get(itemId) ?? 0, qty)); }
121 visit(edge.nextStepId, child, nextPath);
122 }
123 }
124
125 visit(entryStepId, new Map(), new Set());
126 return warnings;
127 }
128
129 /** True when this take row should highlight yellow in the editor. */
130 export function dialogueTakeIsUnguaranteed (warnings, stepId, itemId)
131 {
132 return !!warnings?.get?.(stepId)?.has?.(itemId | 0);
133 }
@@ -0,0 +1,133 @@
1import { ConditionKind } from "./conditions.js";
2
3/**
4 * Positive hasItem floors implied by a ConditionSet (ignores `not` clauses).
5 * @returns {Map<number, number>} itemId → minimum quantity
6 */
7export function hasItemGuaranteesFromWhen (when)
8{
9 /** @type {Map<number, number>} */
10 const out = new Map();
11 for (const clause of when?.all ?? [])
12 {
13 if (clause?.not)
14 { continue; }
15 const condition = clause?.condition;
16 if (condition?.kind !== ConditionKind.hasItem)
17 { continue; }
18 const itemId = Number(condition.itemId) | 0;
19 if (itemId <= 0)
20 { continue; }
21 const quantity = Math.max(1, Number(condition.quantity) || 1) | 0;
22 out.set(itemId, Math.max(out.get(itemId) ?? 0, quantity));
23 }
24 return out;
25}
26
27/**
28 * Outgoing dialogue edges from a step exit (branches + player triggers).
29 * @returns {{ nextStepId: string, when: object }[]}
30 */
31export function dialogueExitEdges (exit)
32{
33 const edges = [];
34 if (exit?.kind === "branches")
35 {
36 for (const branch of exit.branches ?? [])
37 {
38 if (!branch?.nextStepId)
39 { continue; }
40 edges.push({ nextStepId: branch.nextStepId, when: branch.when ?? { all: [] } });
41 }
42 }
43 else if (exit?.kind === "triggers")
44 {
45 for (const trigger of exit.triggers ?? [])
46 {
47 if (!trigger?.nextStepId)
48 { continue; }
49 edges.push({ nextStepId: trigger.nextStepId, when: trigger.when ?? { all: [] } });
50 }
51 }
52 return edges;
53}
54
55/**
56 * Item takes on a step that are not guaranteed on every path from the dialogue entry
57 * (via branch/trigger hasItem conditions + earlier step rewards/takes).
58 * @returns {Map<string, Set<number>>} stepId → unguaranteed itemIds
59 */
60export function unguaranteedDialogueTakes (tree)
61{
62 /** @type {Map<string, Set<number>>} */
63 const warnings = new Map();
64 const steps = Array.isArray(tree?.steps) ? tree.steps : [];
65 if (!steps.length)
66 { return warnings; }
67 const byId = new Map(steps.map((step) => [step.stepId, step]));
68 const entryStepId = tree.entryStepId && byId.has(tree.entryStepId)
69 ? tree.entryStepId
70 : steps[0].stepId;
71
72 function note (stepId, itemId)
73 {
74 let set = warnings.get(stepId);
75 if (!set)
76 {
77 set = new Set();
78 warnings.set(stepId, set);
79 }
80 set.add(itemId | 0);
81 }
82
83 /**
84 * @param {string} stepId
85 * @param {Map<number, number>} bag
86 * @param {Set<string>} path
87 */
88 function visit (stepId, bag, path)
89 {
90 if (path.has(stepId))
91 { return; }
92 const step = byId.get(stepId);
93 if (!step)
94 { return; }
95 const nextPath = new Set(path);
96 nextPath.add(stepId);
97 /** @type {Map<number, number>} */
98 const local = new Map(bag);
99
100 for (const take of step.itemTakes ?? [])
101 {
102 const itemId = take.itemId | 0;
103 const need = Math.max(1, Number(take.quantity) || 1) | 0;
104 if ((local.get(itemId) ?? 0) < need)
105 { note(stepId, itemId); }
106 local.set(itemId, Math.max(0, (local.get(itemId) ?? 0) - need));
107 }
108 for (const reward of step.itemRewards ?? [])
109 {
110 const itemId = reward.itemId | 0;
111 const qty = Math.max(1, Number(reward.quantity) || 1) | 0;
112 local.set(itemId, (local.get(itemId) ?? 0) + qty);
113 }
114
115 for (const edge of dialogueExitEdges(step.exit))
116 {
117 /** @type {Map<number, number>} */
118 const child = new Map(local);
119 for (const [itemId, qty] of hasItemGuaranteesFromWhen(edge.when))
120 { child.set(itemId, Math.max(child.get(itemId) ?? 0, qty)); }
121 visit(edge.nextStepId, child, nextPath);
122 }
123 }
124
125 visit(entryStepId, new Map(), new Set());
126 return warnings;
127}
128
129/** True when this take row should highlight yellow in the editor. */
130export function dialogueTakeIsUnguaranteed (warnings, stepId, itemId)
131{
132 return !!warnings?.get?.(stepId)?.has?.(itemId | 0);
133}
shared/quests/dialogueRewards.js +26 −0
@@ -28,6 +28,32 @@ export function formatDialogueRewardMessage (items, destination)
28 28 return `${subject} ${verb} been ${where}.`;
29 29 }
30 30
31 /**
32 * Format dialogue step item-take notices (removed from bag).
33 * @param {{ displayName: string, quantity: number }[]} items
34 */
35 export function formatDialogueTakeMessage (items)
36 {
37 const list = (Array.isArray(items) ? items : [])
38 .filter((entry) => entry && entry.displayName && (Number(entry.quantity) || 0) > 0);
39 if (!list.length)
40 { return null; }
41 const labels = list.map((entry) =>
42 {
43 const qty = Math.max(1, Number(entry.quantity) || 1);
44 const name = String(entry.displayName);
45 return qty > 1 ? `${qty} ${name}` : name;
46 });
47 const subject = labels.length === 1
48 ? labels[0]
49 : labels.length === 2
50 ? `${labels[0]} and ${labels[1]}`
51 : `${labels.slice(0, -1).join(", ")} and ${labels[labels.length - 1]}`;
52 const plural = labels.length > 1 || (list[0].quantity | 0) > 1;
53 const verb = plural ? "have" : "has";
54 return `${subject} ${verb} been removed from your bag.`;
55 }
56
31 57 /**
32 58 * Format dialogue step quest-reward notices (player-facing).
33 59 * @param {string[]} questTitles
@@ -28,6 +28,32 @@ export function formatDialogueRewardMessage (items, destination)
28 return `${subject} ${verb} been ${where}.`;
28 return `${subject} ${verb} been ${where}.`;
29}
29}
30
30
31/**
32 * Format dialogue step item-take notices (removed from bag).
33 * @param {{ displayName: string, quantity: number }[]} items
34 */
35export function formatDialogueTakeMessage (items)
36{
37 const list = (Array.isArray(items) ? items : [])
38 .filter((entry) => entry && entry.displayName && (Number(entry.quantity) || 0) > 0);
39 if (!list.length)
40 { return null; }
41 const labels = list.map((entry) =>
42 {
43 const qty = Math.max(1, Number(entry.quantity) || 1);
44 const name = String(entry.displayName);
45 return qty > 1 ? `${qty} ${name}` : name;
46 });
47 const subject = labels.length === 1
48 ? labels[0]
49 : labels.length === 2
50 ? `${labels[0]} and ${labels[1]}`
51 : `${labels.slice(0, -1).join(", ")} and ${labels[labels.length - 1]}`;
52 const plural = labels.length > 1 || (list[0].quantity | 0) > 1;
53 const verb = plural ? "have" : "has";
54 return `${subject} ${verb} been removed from your bag.`;
55}
56
31/**
57/**
32 * Format dialogue step quest-reward notices (player-facing).
58 * Format dialogue step quest-reward notices (player-facing).
33 * @param {string[]} questTitles
59 * @param {string[]} questTitles
shared/quests/normalize.js +1 −0
@@ -85,6 +85,7 @@ function normalizeDialogueStep (raw, index)
85 85 label: String(raw?.label ?? stepId).trim().slice(0, 80) || stepId,
86 86 lines: lines.length > 0 ? lines : [{ speaker: "npc", text: "…", effects: [] }],
87 87 itemRewards: normalizeItemRewards(raw?.itemRewards),
88 itemTakes: normalizeItemRewards(raw?.itemTakes),
88 89 questRewards: normalizeQuestRewards(raw?.questRewards),
89 90 exit
90 91 };
@@ -85,6 +85,7 @@ function normalizeDialogueStep (raw, index)
85 label: String(raw?.label ?? stepId).trim().slice(0, 80) || stepId,
85 label: String(raw?.label ?? stepId).trim().slice(0, 80) || stepId,
86 lines: lines.length > 0 ? lines : [{ speaker: "npc", text: "…", effects: [] }],
86 lines: lines.length > 0 ? lines : [{ speaker: "npc", text: "…", effects: [] }],
87 itemRewards: normalizeItemRewards(raw?.itemRewards),
87 itemRewards: normalizeItemRewards(raw?.itemRewards),
88 itemTakes: normalizeItemRewards(raw?.itemTakes),
88 questRewards: normalizeQuestRewards(raw?.questRewards),
89 questRewards: normalizeQuestRewards(raw?.questRewards),
89 exit
90 exit
90 };
91 };