BlueGit

timfa questward

Merge branch 'feature/quest-rewards-ui'

timfa Tim Falken · pushed by timfa

Authored 2026-09-06 · 2 months ago

Hash
0ee7253aac986152489b4ca31981b554fe948ed0
15 files changed +830 −60
client/index.html +11 −0
@@ -95,6 +95,17 @@
95 95 </div>
96 96 </div>
97 97
98 <div id="quest-complete-backdrop" class="modal-backdrop" hidden></div>
99 <div id="quest-complete-panel" hidden>
100 <header>
101 <h2 id="quest-complete-title">Quest Completed!</h2>
102 </header>
103 <div id="quest-complete-body" class="quest-complete-body"></div>
104 <footer>
105 <button id="quest-complete-ok" type="button">OK</button>
106 </footer>
107 </div>
108
98 109 <div id="dialogue-panel" hidden>
99 110 <header>
100 111 <h2 id="dialogue-title"></h2>
@@ -95,6 +95,17 @@
95 </div>
95 </div>
96 </div>
96 </div>
97
97
98 <div id="quest-complete-backdrop" class="modal-backdrop" hidden></div>
99 <div id="quest-complete-panel" hidden>
100 <header>
101 <h2 id="quest-complete-title">Quest Completed!</h2>
102 </header>
103 <div id="quest-complete-body" class="quest-complete-body"></div>
104 <footer>
105 <button id="quest-complete-ok" type="button">OK</button>
106 </footer>
107 </div>
108
98 <div id="dialogue-panel" hidden>
109 <div id="dialogue-panel" hidden>
99 <header>
110 <header>
100 <h2 id="dialogue-title"></h2>
111 <h2 id="dialogue-title"></h2>
client/src/editor/questsModal.js +267 −29
@@ -1,6 +1,8 @@
1 1 import { normalizeQuestDef, normalizeDialogueTree } from "/shared/quests/normalize.js";
2 import { emptyConditionSet } from "/shared/quests/conditions.js";
2 import { emptyConditionSet, EffectKind, normalizeEffects } from "/shared/quests/conditions.js";
3 3 import { renderConditionSet } from "./conditionSetEditor.js";
4 import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
5 import { ALL_SKILL_IDS, SKILL_DEFINITIONS } from "/shared/definitions/skills.js";
4 6
5 7 export function initQuestsModal ({
6 8 socket,
@@ -25,6 +27,9 @@ export function initQuestsModal ({
25 27 let draft = null;
26 28 let selectedId = null;
27 29
30 /** @type {null | { resultsEl: HTMLElement, inputEl: HTMLInputElement }} */
31 let itemPickContext = null;
32
28 33 function show (visible)
29 34 {
30 35 open = visible;
@@ -34,6 +39,79 @@ export function initQuestsModal ({
34 39 {
35 40 draft = null;
36 41 selectedId = null;
42 closeInlineItemSearch();
43 }
44 }
45
46 function closeInlineItemSearch ()
47 {
48 if (itemPickContext?.resultsEl)
49 { itemPickContext.resultsEl.replaceChildren(); }
50 itemPickContext = null;
51 }
52
53 function openInlineItemSearch (inputEl, resultsEl)
54 {
55 itemPickContext = { inputEl, resultsEl };
56 inputEl.value = "";
57 renderInlineItemSearch("");
58 inputEl.focus();
59 }
60
61 function renderInlineItemSearch (query)
62 {
63 if (!itemPickContext || !draft)
64 { return; }
65 const { resultsEl } = itemPickContext;
66 resultsEl.replaceChildren();
67 const q = String(query ?? "").trim().toLowerCase();
68 const taken = new Set(
69 (draft.rewards ?? [])
70 .filter((row) => row.kind === EffectKind.giveItem)
71 .map((row) => row.itemId)
72 );
73 const matches = listAllItemPickerEntries().filter((item) =>
74 {
75 if (taken.has(item.itemId))
76 { return false; }
77 if (!q)
78 { return true; }
79 return item.displayName.toLowerCase().includes(q)
80 || item.key.toLowerCase().includes(q)
81 || String(item.itemId).includes(q);
82 }).slice(0, 40);
83 if (!matches.length)
84 {
85 resultsEl.textContent = "No matching items.";
86 return;
87 }
88 for (const item of matches)
89 {
90 const row = document.createElement("button");
91 row.type = "button";
92 row.className = "shop-item-search-row";
93 const name = document.createElement("span");
94 name.className = "shop-item-search-row-name";
95 name.textContent = item.displayName;
96 const key = document.createElement("span");
97 key.className = "shop-item-search-row-key";
98 key.textContent = `${item.key} · #${item.itemId}`;
99 row.append(name, key);
100 row.addEventListener("click", () =>
101 {
102 if (!Array.isArray(draft.rewards))
103 { draft.rewards = []; }
104 draft.rewards.push({
105 kind: EffectKind.giveItem,
106 itemId: item.itemId,
107 quantity: 1,
108 toBank: false
109 });
110 draft.rewards = normalizeEffects(draft.rewards);
111 closeInlineItemSearch();
112 renderEditor();
113 });
114 resultsEl.append(row);
37 115 }
38 116 }
39 117
@@ -67,6 +145,24 @@ export function initQuestsModal ({
67 145 }
68 146 }
69 147
148 function addStep ()
149 {
150 draft.steps.push({
151 stepId: `step-${draft.steps.length + 1}`,
152 title: "New step",
153 description: "",
154 completionJournalText: "",
155 objectives: [{
156 objectiveId: "obj-1",
157 text: "Complete this step",
158 when: emptyConditionSet()
159 }],
160 onEnter: [],
161 onComplete: []
162 });
163 renderEditor();
164 }
165
70 166 function renderEditor ()
71 167 {
72 168 editorEl.replaceChildren();
@@ -81,30 +177,21 @@ export function initQuestsModal ({
81 177 return;
82 178 }
83 179
180 if (!Array.isArray(draft.rewards))
181 { draft.rewards = []; }
182
84 183 editorEl.append(
85 184 field("Quest id", textInput(draft.questId, (v) => { draft.questId = v; })),
86 185 field("Title", textInput(draft.title, (v) => { draft.title = v; })),
87 186 field("Description", textArea(draft.description, (v) => { draft.description = v; }, 3))
88 187 );
89 188
90 const stepsHeader = sectionHeader("Steps", () =>
91 {
92 draft.steps.push({
93 stepId: `step-${draft.steps.length + 1}`,
94 title: "New step",
95 description: "",
96 completionJournalText: "",
97 objectives: [{
98 objectiveId: "obj-1",
99 text: "Complete this step",
100 when: emptyConditionSet()
101 }],
102 onEnter: [],
103 onComplete: []
104 });
105 renderEditor();
106 });
107 editorEl.append(stepsHeader);
189 const stepsTitle = document.createElement("div");
190 stepsTitle.className = "content-editor-section-header";
191 const stepsStrong = document.createElement("strong");
192 stepsStrong.textContent = "Steps";
193 stepsTitle.append(stepsStrong);
194 editorEl.append(stepsTitle);
108 195
109 196 draft.steps.forEach((step, stepIndex) =>
110 197 {
@@ -171,6 +258,154 @@ export function initQuestsModal ({
171 258 });
172 259 editorEl.append(box);
173 260 });
261
262 const addStepBtn = document.createElement("button");
263 addStepBtn.type = "button";
264 addStepBtn.className = "content-editor-add-step";
265 addStepBtn.textContent = "(add step)";
266 addStepBtn.addEventListener("click", addStep);
267 editorEl.append(addStepBtn);
268
269 renderRewardsSection();
270 }
271
272 function renderRewardsSection ()
273 {
274 const box = document.createElement("div");
275 box.className = "content-editor-section";
276 const title = document.createElement("div");
277 title.className = "content-editor-section-header";
278 const strong = document.createElement("strong");
279 strong.textContent = "Completion rewards";
280 title.append(strong);
281 box.append(title);
282
283 const hint = document.createElement("p");
284 hint.className = "content-editor-hint";
285 hint.textContent = "Granted when the final step completes. Bank-checked items (or overflow) go to the bank with a Questward letter.";
286 box.append(hint);
287
288 const xpHead = sectionHeader("Skill XP", () =>
289 {
290 const skillId = ALL_SKILL_IDS.find((id) =>
291 !(draft.rewards ?? []).some((r) => r.kind === EffectKind.giveXp && r.skillId === id)
292 ) ?? ALL_SKILL_IDS[0];
293 draft.rewards.push({ kind: EffectKind.giveXp, skillId, amount: 15 });
294 draft.rewards = normalizeEffects(draft.rewards);
295 renderEditor();
296 });
297 box.append(xpHead);
298
299 const xpRows = (draft.rewards ?? []).filter((r) => r.kind === EffectKind.giveXp);
300 if (!xpRows.length)
301 {
302 const empty = document.createElement("p");
303 empty.className = "content-editor-hint";
304 empty.textContent = "No skill XP rewards.";
305 box.append(empty);
306 }
307 xpRows.forEach((reward) =>
308 {
309 const rewardIndex = draft.rewards.indexOf(reward);
310 const row = document.createElement("div");
311 row.className = "content-editor-row";
312 const skill = document.createElement("select");
313 for (const skillId of ALL_SKILL_IDS)
314 {
315 const opt = document.createElement("option");
316 opt.value = skillId;
317 opt.textContent = SKILL_DEFINITIONS[skillId]?.displayName ?? skillId;
318 if (reward.skillId === skillId)
319 { opt.selected = true; }
320 skill.append(opt);
321 }
322 skill.addEventListener("change", () =>
323 {
324 draft.rewards[rewardIndex].skillId = skill.value;
325 });
326 const amount = document.createElement("input");
327 amount.type = "number";
328 amount.min = "1";
329 amount.step = "1";
330 amount.value = String(Math.max(1, reward.amount | 0 || 1));
331 amount.title = "XP amount";
332 amount.addEventListener("input", () =>
333 {
334 draft.rewards[rewardIndex].amount = Math.max(1, Number(amount.value) || 1) | 0;
335 });
336 row.append(skill, amount, removeButton(() =>
337 {
338 draft.rewards.splice(rewardIndex, 1);
339 renderEditor();
340 }));
341 box.append(row);
342 });
343
344 const searchWrap = document.createElement("div");
345 searchWrap.className = "dialogue-reward-item-search";
346 searchWrap.hidden = true;
347 const searchInput = document.createElement("input");
348 searchInput.type = "search";
349 searchInput.placeholder = "Search items…";
350 searchInput.autocomplete = "off";
351 searchInput.addEventListener("input", () => renderInlineItemSearch(searchInput.value));
352 const searchResults = document.createElement("div");
353 searchResults.className = "dialogue-reward-item-results";
354 searchWrap.append(searchInput, searchResults);
355
356 const itemHead = sectionHeader("Items", () =>
357 {
358 searchWrap.hidden = false;
359 openInlineItemSearch(searchInput, searchResults);
360 });
361 box.append(itemHead);
362
363 const itemRows = (draft.rewards ?? []).filter((r) => r.kind === EffectKind.giveItem);
364 if (!itemRows.length)
365 {
366 const empty = document.createElement("p");
367 empty.className = "content-editor-hint";
368 empty.textContent = "No item rewards.";
369 box.append(empty);
370 }
371 itemRows.forEach((reward) =>
372 {
373 const rewardIndex = draft.rewards.indexOf(reward);
374 const def = itemDefinition(reward.itemId);
375 const row = document.createElement("div");
376 row.className = "spawner-drops-row";
377 const name = document.createElement("span");
378 name.className = "spawner-sells-name";
379 name.textContent = def?.displayName ?? `Item ${reward.itemId}`;
380 const qty = document.createElement("input");
381 qty.type = "number";
382 qty.min = "1";
383 qty.step = "1";
384 qty.value = String(Math.max(1, reward.quantity | 0 || 1));
385 qty.title = "Quantity";
386 qty.addEventListener("input", () =>
387 {
388 draft.rewards[rewardIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
389 });
390 const bankLabel = document.createElement("label");
391 bankLabel.className = "quest-reward-bank";
392 const bankBox = document.createElement("input");
393 bankBox.type = "checkbox";
394 bankBox.checked = !!reward.toBank;
395 bankBox.addEventListener("change", () =>
396 {
397 draft.rewards[rewardIndex].toBank = bankBox.checked;
398 });
399 bankLabel.append(bankBox, document.createTextNode(" Bank"));
400 row.append(name, qty, bankLabel, removeButton(() =>
401 {
402 draft.rewards.splice(rewardIndex, 1);
403 renderEditor();
404 }));
405 box.append(row);
406 });
407 box.append(searchWrap);
408 editorEl.append(box);
174 409 }
175 410
176 411 function render ()
@@ -203,6 +438,7 @@ export function initQuestsModal ({
203 438 {
204 439 if (!draft)
205 440 { return; }
441 draft.rewards = normalizeEffects(draft.rewards);
206 442 socket.send({ type: MessageType.editorSaveQuest, quest: draft });
207 443 });
208 444 deleteBtn.addEventListener("click", () =>
@@ -249,6 +485,17 @@ export function initQuestsModal ({
249 485 };
250 486 }
251 487
488 function removeButton (onClick)
489 {
490 const remove = document.createElement("button");
491 remove.type = "button";
492 remove.className = "content-editor-remove";
493 remove.textContent = "×";
494 remove.title = "Remove";
495 remove.addEventListener("click", onClick);
496 return remove;
497 }
498
252 499 function field (label, input)
253 500 {
254 501 const wrap = document.createElement("label");
@@ -293,16 +540,7 @@ function sectionHeader (title, onAdd, onRemove)
293 540 actions.append(add);
294 541 }
295 542 if (onRemove)
296 {
297 const remove = document.createElement("button");
298 remove.type = "button";
299 remove.textContent = "×";
300 remove.title = "Remove";
301 remove.addEventListener("click", onRemove);
302 actions.append(remove);
303 }
543 { actions.append(removeButton(onRemove)); }
304 544 head.append(actions);
305 545 return head;
306 546 }
307
308
@@ -1,6 +1,8 @@
1import { normalizeQuestDef, normalizeDialogueTree } from "/shared/quests/normalize.js";
1import { normalizeQuestDef, normalizeDialogueTree } from "/shared/quests/normalize.js";
2import { emptyConditionSet } from "/shared/quests/conditions.js";
2import { emptyConditionSet, EffectKind, normalizeEffects } from "/shared/quests/conditions.js";
3import { renderConditionSet } from "./conditionSetEditor.js";
3import { renderConditionSet } from "./conditionSetEditor.js";
4import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
5import { ALL_SKILL_IDS, SKILL_DEFINITIONS } from "/shared/definitions/skills.js";
4
6
5export function initQuestsModal ({
7export function initQuestsModal ({
6 socket,
8 socket,
@@ -25,6 +27,9 @@ export function initQuestsModal ({
25 let draft = null;
27 let draft = null;
26 let selectedId = null;
28 let selectedId = null;
27
29
30 /** @type {null | { resultsEl: HTMLElement, inputEl: HTMLInputElement }} */
31 let itemPickContext = null;
32
28 function show (visible)
33 function show (visible)
29 {
34 {
30 open = visible;
35 open = visible;
@@ -34,6 +39,79 @@ export function initQuestsModal ({
34 {
39 {
35 draft = null;
40 draft = null;
36 selectedId = null;
41 selectedId = null;
42 closeInlineItemSearch();
43 }
44 }
45
46 function closeInlineItemSearch ()
47 {
48 if (itemPickContext?.resultsEl)
49 { itemPickContext.resultsEl.replaceChildren(); }
50 itemPickContext = null;
51 }
52
53 function openInlineItemSearch (inputEl, resultsEl)
54 {
55 itemPickContext = { inputEl, resultsEl };
56 inputEl.value = "";
57 renderInlineItemSearch("");
58 inputEl.focus();
59 }
60
61 function renderInlineItemSearch (query)
62 {
63 if (!itemPickContext || !draft)
64 { return; }
65 const { resultsEl } = itemPickContext;
66 resultsEl.replaceChildren();
67 const q = String(query ?? "").trim().toLowerCase();
68 const taken = new Set(
69 (draft.rewards ?? [])
70 .filter((row) => row.kind === EffectKind.giveItem)
71 .map((row) => row.itemId)
72 );
73 const matches = listAllItemPickerEntries().filter((item) =>
74 {
75 if (taken.has(item.itemId))
76 { return false; }
77 if (!q)
78 { return true; }
79 return item.displayName.toLowerCase().includes(q)
80 || item.key.toLowerCase().includes(q)
81 || String(item.itemId).includes(q);
82 }).slice(0, 40);
83 if (!matches.length)
84 {
85 resultsEl.textContent = "No matching items.";
86 return;
87 }
88 for (const item of matches)
89 {
90 const row = document.createElement("button");
91 row.type = "button";
92 row.className = "shop-item-search-row";
93 const name = document.createElement("span");
94 name.className = "shop-item-search-row-name";
95 name.textContent = item.displayName;
96 const key = document.createElement("span");
97 key.className = "shop-item-search-row-key";
98 key.textContent = `${item.key} · #${item.itemId}`;
99 row.append(name, key);
100 row.addEventListener("click", () =>
101 {
102 if (!Array.isArray(draft.rewards))
103 { draft.rewards = []; }
104 draft.rewards.push({
105 kind: EffectKind.giveItem,
106 itemId: item.itemId,
107 quantity: 1,
108 toBank: false
109 });
110 draft.rewards = normalizeEffects(draft.rewards);
111 closeInlineItemSearch();
112 renderEditor();
113 });
114 resultsEl.append(row);
37 }
115 }
38 }
116 }
39
117
@@ -67,6 +145,24 @@ export function initQuestsModal ({
67 }
145 }
68 }
146 }
69
147
148 function addStep ()
149 {
150 draft.steps.push({
151 stepId: `step-${draft.steps.length + 1}`,
152 title: "New step",
153 description: "",
154 completionJournalText: "",
155 objectives: [{
156 objectiveId: "obj-1",
157 text: "Complete this step",
158 when: emptyConditionSet()
159 }],
160 onEnter: [],
161 onComplete: []
162 });
163 renderEditor();
164 }
165
70 function renderEditor ()
166 function renderEditor ()
71 {
167 {
72 editorEl.replaceChildren();
168 editorEl.replaceChildren();
@@ -81,30 +177,21 @@ export function initQuestsModal ({
81 return;
177 return;
82 }
178 }
83
179
180 if (!Array.isArray(draft.rewards))
181 { draft.rewards = []; }
182
84 editorEl.append(
183 editorEl.append(
85 field("Quest id", textInput(draft.questId, (v) => { draft.questId = v; })),
184 field("Quest id", textInput(draft.questId, (v) => { draft.questId = v; })),
86 field("Title", textInput(draft.title, (v) => { draft.title = v; })),
185 field("Title", textInput(draft.title, (v) => { draft.title = v; })),
87 field("Description", textArea(draft.description, (v) => { draft.description = v; }, 3))
186 field("Description", textArea(draft.description, (v) => { draft.description = v; }, 3))
88 );
187 );
89
188
90 const stepsHeader = sectionHeader("Steps", () =>
189 const stepsTitle = document.createElement("div");
91 {
190 stepsTitle.className = "content-editor-section-header";
92 draft.steps.push({
191 const stepsStrong = document.createElement("strong");
93 stepId: `step-${draft.steps.length + 1}`,
192 stepsStrong.textContent = "Steps";
94 title: "New step",
193 stepsTitle.append(stepsStrong);
95 description: "",
194 editorEl.append(stepsTitle);
96 completionJournalText: "",
97 objectives: [{
98 objectiveId: "obj-1",
99 text: "Complete this step",
100 when: emptyConditionSet()
101 }],
102 onEnter: [],
103 onComplete: []
104 });
105 renderEditor();
106 });
107 editorEl.append(stepsHeader);
108
195
109 draft.steps.forEach((step, stepIndex) =>
196 draft.steps.forEach((step, stepIndex) =>
110 {
197 {
@@ -171,6 +258,154 @@ export function initQuestsModal ({
171 });
258 });
172 editorEl.append(box);
259 editorEl.append(box);
173 });
260 });
261
262 const addStepBtn = document.createElement("button");
263 addStepBtn.type = "button";
264 addStepBtn.className = "content-editor-add-step";
265 addStepBtn.textContent = "(add step)";
266 addStepBtn.addEventListener("click", addStep);
267 editorEl.append(addStepBtn);
268
269 renderRewardsSection();
270 }
271
272 function renderRewardsSection ()
273 {
274 const box = document.createElement("div");
275 box.className = "content-editor-section";
276 const title = document.createElement("div");
277 title.className = "content-editor-section-header";
278 const strong = document.createElement("strong");
279 strong.textContent = "Completion rewards";
280 title.append(strong);
281 box.append(title);
282
283 const hint = document.createElement("p");
284 hint.className = "content-editor-hint";
285 hint.textContent = "Granted when the final step completes. Bank-checked items (or overflow) go to the bank with a Questward letter.";
286 box.append(hint);
287
288 const xpHead = sectionHeader("Skill XP", () =>
289 {
290 const skillId = ALL_SKILL_IDS.find((id) =>
291 !(draft.rewards ?? []).some((r) => r.kind === EffectKind.giveXp && r.skillId === id)
292 ) ?? ALL_SKILL_IDS[0];
293 draft.rewards.push({ kind: EffectKind.giveXp, skillId, amount: 15 });
294 draft.rewards = normalizeEffects(draft.rewards);
295 renderEditor();
296 });
297 box.append(xpHead);
298
299 const xpRows = (draft.rewards ?? []).filter((r) => r.kind === EffectKind.giveXp);
300 if (!xpRows.length)
301 {
302 const empty = document.createElement("p");
303 empty.className = "content-editor-hint";
304 empty.textContent = "No skill XP rewards.";
305 box.append(empty);
306 }
307 xpRows.forEach((reward) =>
308 {
309 const rewardIndex = draft.rewards.indexOf(reward);
310 const row = document.createElement("div");
311 row.className = "content-editor-row";
312 const skill = document.createElement("select");
313 for (const skillId of ALL_SKILL_IDS)
314 {
315 const opt = document.createElement("option");
316 opt.value = skillId;
317 opt.textContent = SKILL_DEFINITIONS[skillId]?.displayName ?? skillId;
318 if (reward.skillId === skillId)
319 { opt.selected = true; }
320 skill.append(opt);
321 }
322 skill.addEventListener("change", () =>
323 {
324 draft.rewards[rewardIndex].skillId = skill.value;
325 });
326 const amount = document.createElement("input");
327 amount.type = "number";
328 amount.min = "1";
329 amount.step = "1";
330 amount.value = String(Math.max(1, reward.amount | 0 || 1));
331 amount.title = "XP amount";
332 amount.addEventListener("input", () =>
333 {
334 draft.rewards[rewardIndex].amount = Math.max(1, Number(amount.value) || 1) | 0;
335 });
336 row.append(skill, amount, removeButton(() =>
337 {
338 draft.rewards.splice(rewardIndex, 1);
339 renderEditor();
340 }));
341 box.append(row);
342 });
343
344 const searchWrap = document.createElement("div");
345 searchWrap.className = "dialogue-reward-item-search";
346 searchWrap.hidden = true;
347 const searchInput = document.createElement("input");
348 searchInput.type = "search";
349 searchInput.placeholder = "Search items…";
350 searchInput.autocomplete = "off";
351 searchInput.addEventListener("input", () => renderInlineItemSearch(searchInput.value));
352 const searchResults = document.createElement("div");
353 searchResults.className = "dialogue-reward-item-results";
354 searchWrap.append(searchInput, searchResults);
355
356 const itemHead = sectionHeader("Items", () =>
357 {
358 searchWrap.hidden = false;
359 openInlineItemSearch(searchInput, searchResults);
360 });
361 box.append(itemHead);
362
363 const itemRows = (draft.rewards ?? []).filter((r) => r.kind === EffectKind.giveItem);
364 if (!itemRows.length)
365 {
366 const empty = document.createElement("p");
367 empty.className = "content-editor-hint";
368 empty.textContent = "No item rewards.";
369 box.append(empty);
370 }
371 itemRows.forEach((reward) =>
372 {
373 const rewardIndex = draft.rewards.indexOf(reward);
374 const def = itemDefinition(reward.itemId);
375 const row = document.createElement("div");
376 row.className = "spawner-drops-row";
377 const name = document.createElement("span");
378 name.className = "spawner-sells-name";
379 name.textContent = def?.displayName ?? `Item ${reward.itemId}`;
380 const qty = document.createElement("input");
381 qty.type = "number";
382 qty.min = "1";
383 qty.step = "1";
384 qty.value = String(Math.max(1, reward.quantity | 0 || 1));
385 qty.title = "Quantity";
386 qty.addEventListener("input", () =>
387 {
388 draft.rewards[rewardIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
389 });
390 const bankLabel = document.createElement("label");
391 bankLabel.className = "quest-reward-bank";
392 const bankBox = document.createElement("input");
393 bankBox.type = "checkbox";
394 bankBox.checked = !!reward.toBank;
395 bankBox.addEventListener("change", () =>
396 {
397 draft.rewards[rewardIndex].toBank = bankBox.checked;
398 });
399 bankLabel.append(bankBox, document.createTextNode(" Bank"));
400 row.append(name, qty, bankLabel, removeButton(() =>
401 {
402 draft.rewards.splice(rewardIndex, 1);
403 renderEditor();
404 }));
405 box.append(row);
406 });
407 box.append(searchWrap);
408 editorEl.append(box);
174 }
409 }
175
410
176 function render ()
411 function render ()
@@ -203,6 +438,7 @@ export function initQuestsModal ({
203 {
438 {
204 if (!draft)
439 if (!draft)
205 { return; }
440 { return; }
441 draft.rewards = normalizeEffects(draft.rewards);
206 socket.send({ type: MessageType.editorSaveQuest, quest: draft });
442 socket.send({ type: MessageType.editorSaveQuest, quest: draft });
207 });
443 });
208 deleteBtn.addEventListener("click", () =>
444 deleteBtn.addEventListener("click", () =>
@@ -249,6 +485,17 @@ export function initQuestsModal ({
249 };
485 };
250}
486}
251
487
488function removeButton (onClick)
489{
490 const remove = document.createElement("button");
491 remove.type = "button";
492 remove.className = "content-editor-remove";
493 remove.textContent = "×";
494 remove.title = "Remove";
495 remove.addEventListener("click", onClick);
496 return remove;
497}
498
252function field (label, input)
499function field (label, input)
253{
500{
254 const wrap = document.createElement("label");
501 const wrap = document.createElement("label");
@@ -293,16 +540,7 @@ function sectionHeader (title, onAdd, onRemove)
293 actions.append(add);
540 actions.append(add);
294 }
541 }
295 if (onRemove)
542 if (onRemove)
296 {
543 { actions.append(removeButton(onRemove)); }
297 const remove = document.createElement("button");
298 remove.type = "button";
299 remove.textContent = "×";
300 remove.title = "Remove";
301 remove.addEventListener("click", onRemove);
302 actions.append(remove);
303 }
304 head.append(actions);
544 head.append(actions);
305 return head;
545 return head;
306}
546}
307
308
client/src/play/main.js +3 −0
@@ -2526,6 +2526,9 @@ async function main ()
2526 2526 case MessageType.questStepComplete:
2527 2527 questsUi?.handleStepComplete(message);
2528 2528 break;
2529 case MessageType.questComplete:
2530 questsUi?.handleComplete?.(message);
2531 break;
2529 2532 case MessageType.dialogueStep:
2530 2533 if (message.npcEntityId != null)
2531 2534 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
@@ -2526,6 +2526,9 @@ async function main ()
2526 case MessageType.questStepComplete:
2526 case MessageType.questStepComplete:
2527 questsUi?.handleStepComplete(message);
2527 questsUi?.handleStepComplete(message);
2528 break;
2528 break;
2529 case MessageType.questComplete:
2530 questsUi?.handleComplete?.(message);
2531 break;
2529 case MessageType.dialogueStep:
2532 case MessageType.dialogueStep:
2530 if (message.npcEntityId != null)
2533 if (message.npcEntityId != null)
2531 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2534 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
client/src/play/quests.js +55 −2
@@ -1,5 +1,5 @@
1 1 /**
2 * Play HUD Quests list + detail modals.
2 * Play HUD Quests list + detail modals + completion popup.
3 3 */
4 4 export function initQuests ({ socket, MessageType, toasts })
5 5 {
@@ -11,10 +11,15 @@ export function initQuests ({ socket, MessageType, toasts })
11 11 const detailTitle = document.getElementById("quests-detail-title");
12 12 const journalEl = document.getElementById("quests-detail-journal");
13 13 const stepEl = document.getElementById("quests-detail-step");
14 const completeBackdrop = document.getElementById("quest-complete-backdrop");
15 const completePanel = document.getElementById("quest-complete-panel");
16 const completeTitle = document.getElementById("quest-complete-title");
17 const completeBody = document.getElementById("quest-complete-body");
14 18 /** @type {any[]} */
15 19 let quests = [];
16 20 let listOpen = false;
17 21 let detailOpen = false;
22 let completeOpen = false;
18 23 let detailQuestId = null;
19 24
20 25 function showList (visible)
@@ -40,6 +45,47 @@ export function initQuests ({ socket, MessageType, toasts })
40 45 { renderDetail(); }
41 46 }
42 47
48 function showComplete (visible, message = null)
49 {
50 completeOpen = visible;
51 if (completeBackdrop)
52 { completeBackdrop.hidden = !visible; }
53 if (completePanel)
54 { completePanel.hidden = !visible; }
55 if (!visible || !message)
56 { return; }
57 const title = String(message.title ?? "Quest").trim() || "Quest";
58 if (completeTitle)
59 { completeTitle.textContent = `"${title}" Completed!`; }
60 completeBody?.replaceChildren();
61 const ul = document.createElement("ul");
62 for (const entry of message.xp ?? [])
63 {
64 const li = document.createElement("li");
65 const amount = Math.max(0, Number(entry.amount) || 0);
66 const name = String(entry.displayName ?? entry.skillId ?? "Skill");
67 li.textContent = `+${amount} ${name} XP`;
68 ul.append(li);
69 }
70 for (const entry of message.items ?? [])
71 {
72 const li = document.createElement("li");
73 const qty = Math.max(1, Number(entry.quantity) || 1);
74 const name = String(entry.displayName ?? "Item");
75 li.textContent = qty > 1 ? `${qty}× ${name}` : name;
76 ul.append(li);
77 }
78 if (!ul.childElementCount)
79 {
80 const p = document.createElement("p");
81 p.className = "hint";
82 p.textContent = "Quest complete.";
83 completeBody?.append(p);
84 }
85 else
86 { completeBody?.append(ul); }
87 }
88
43 89 function renderList ()
44 90 {
45 91 if (!listBody)
@@ -159,11 +205,13 @@ export function initQuests ({ socket, MessageType, toasts })
159 205 showList(true);
160 206 });
161 207 detailBackdrop?.addEventListener("click", () => showDetail(false));
208 document.getElementById("quest-complete-ok")?.addEventListener("click", () => showComplete(false));
209 completeBackdrop?.addEventListener("click", () => showComplete(false));
162 210
163 211 return {
164 212 isBlocking ()
165 213 {
166 return listOpen || detailOpen;
214 return listOpen || detailOpen || completeOpen;
167 215 },
168 216 applySnapshot (message)
169 217 {
@@ -185,6 +233,10 @@ export function initQuests ({ socket, MessageType, toasts })
185 233 }
186 234 });
187 235 },
236 handleComplete (message)
237 {
238 showComplete(true, message);
239 },
188 240 openQuest (questId)
189 241 {
190 242 showList(false);
@@ -194,6 +246,7 @@ export function initQuests ({ socket, MessageType, toasts })
194 246 {
195 247 showList(false);
196 248 showDetail(false);
249 showComplete(false);
197 250 },
198 251 reset ()
199 252 {
@@ -1,5 +1,5 @@
1/**
1/**
2 * Play HUD Quests list + detail modals.
2 * Play HUD Quests list + detail modals + completion popup.
3 */
3 */
4export function initQuests ({ socket, MessageType, toasts })
4export function initQuests ({ socket, MessageType, toasts })
5{
5{
@@ -11,10 +11,15 @@ export function initQuests ({ socket, MessageType, toasts })
11 const detailTitle = document.getElementById("quests-detail-title");
11 const detailTitle = document.getElementById("quests-detail-title");
12 const journalEl = document.getElementById("quests-detail-journal");
12 const journalEl = document.getElementById("quests-detail-journal");
13 const stepEl = document.getElementById("quests-detail-step");
13 const stepEl = document.getElementById("quests-detail-step");
14 const completeBackdrop = document.getElementById("quest-complete-backdrop");
15 const completePanel = document.getElementById("quest-complete-panel");
16 const completeTitle = document.getElementById("quest-complete-title");
17 const completeBody = document.getElementById("quest-complete-body");
14 /** @type {any[]} */
18 /** @type {any[]} */
15 let quests = [];
19 let quests = [];
16 let listOpen = false;
20 let listOpen = false;
17 let detailOpen = false;
21 let detailOpen = false;
22 let completeOpen = false;
18 let detailQuestId = null;
23 let detailQuestId = null;
19
24
20 function showList (visible)
25 function showList (visible)
@@ -40,6 +45,47 @@ export function initQuests ({ socket, MessageType, toasts })
40 { renderDetail(); }
45 { renderDetail(); }
41 }
46 }
42
47
48 function showComplete (visible, message = null)
49 {
50 completeOpen = visible;
51 if (completeBackdrop)
52 { completeBackdrop.hidden = !visible; }
53 if (completePanel)
54 { completePanel.hidden = !visible; }
55 if (!visible || !message)
56 { return; }
57 const title = String(message.title ?? "Quest").trim() || "Quest";
58 if (completeTitle)
59 { completeTitle.textContent = `"${title}" Completed!`; }
60 completeBody?.replaceChildren();
61 const ul = document.createElement("ul");
62 for (const entry of message.xp ?? [])
63 {
64 const li = document.createElement("li");
65 const amount = Math.max(0, Number(entry.amount) || 0);
66 const name = String(entry.displayName ?? entry.skillId ?? "Skill");
67 li.textContent = `+${amount} ${name} XP`;
68 ul.append(li);
69 }
70 for (const entry of message.items ?? [])
71 {
72 const li = document.createElement("li");
73 const qty = Math.max(1, Number(entry.quantity) || 1);
74 const name = String(entry.displayName ?? "Item");
75 li.textContent = qty > 1 ? `${qty}× ${name}` : name;
76 ul.append(li);
77 }
78 if (!ul.childElementCount)
79 {
80 const p = document.createElement("p");
81 p.className = "hint";
82 p.textContent = "Quest complete.";
83 completeBody?.append(p);
84 }
85 else
86 { completeBody?.append(ul); }
87 }
88
43 function renderList ()
89 function renderList ()
44 {
90 {
45 if (!listBody)
91 if (!listBody)
@@ -159,11 +205,13 @@ export function initQuests ({ socket, MessageType, toasts })
159 showList(true);
205 showList(true);
160 });
206 });
161 detailBackdrop?.addEventListener("click", () => showDetail(false));
207 detailBackdrop?.addEventListener("click", () => showDetail(false));
208 document.getElementById("quest-complete-ok")?.addEventListener("click", () => showComplete(false));
209 completeBackdrop?.addEventListener("click", () => showComplete(false));
162
210
163 return {
211 return {
164 isBlocking ()
212 isBlocking ()
165 {
213 {
166 return listOpen || detailOpen;
214 return listOpen || detailOpen || completeOpen;
167 },
215 },
168 applySnapshot (message)
216 applySnapshot (message)
169 {
217 {
@@ -185,6 +233,10 @@ export function initQuests ({ socket, MessageType, toasts })
185 }
233 }
186 });
234 });
187 },
235 },
236 handleComplete (message)
237 {
238 showComplete(true, message);
239 },
188 openQuest (questId)
240 openQuest (questId)
189 {
241 {
190 showList(false);
242 showList(false);
@@ -194,6 +246,7 @@ export function initQuests ({ socket, MessageType, toasts })
194 {
246 {
195 showList(false);
247 showList(false);
196 showDetail(false);
248 showDetail(false);
249 showComplete(false);
197 },
250 },
198 reset ()
251 reset ()
199 {
252 {
client/ui/editor.css +14 −3
@@ -1535,19 +1535,22 @@ label {
1535 1535 }
1536 1536
1537 1537 .content-editor-remove,
1538 #dialogues-delete {
1538 #dialogues-delete,
1539 #quests-delete {
1539 1540 color: #f0e8e8;
1540 1541 background: #8a3030;
1541 1542 border-color: #a84848;
1542 1543 }
1543 1544
1544 1545 .content-editor-remove:hover,
1545 #dialogues-delete:hover:not(:disabled) {
1546 #dialogues-delete:hover:not(:disabled),
1547 #quests-delete:hover:not(:disabled) {
1546 1548 background: #a83838;
1547 1549 border-color: #c06060;
1548 1550 }
1549 1551
1550 #dialogues-delete:disabled {
1552 #dialogues-delete:disabled,
1553 #quests-delete:disabled {
1551 1554 opacity: 0.45;
1552 1555 }
1553 1556
@@ -1568,6 +1571,14 @@ label {
1568 1571 background: #1a2230;
1569 1572 }
1570 1573
1574 .quest-reward-bank {
1575 display: inline-flex;
1576 align-items: center;
1577 gap: 0.25rem;
1578 white-space: nowrap;
1579 font-size: 0.85rem;
1580 }
1581
1571 1582 .content-editor-clause {
1572 1583 border: 1px dashed #3a4250;
1573 1584 padding: 0.4rem;
@@ -1535,19 +1535,22 @@ label {
1535}
1535}
1536
1536
1537.content-editor-remove,
1537.content-editor-remove,
1538#dialogues-delete {
1538#dialogues-delete,
1539#quests-delete {
1539 color: #f0e8e8;
1540 color: #f0e8e8;
1540 background: #8a3030;
1541 background: #8a3030;
1541 border-color: #a84848;
1542 border-color: #a84848;
1542}
1543}
1543
1544
1544.content-editor-remove:hover,
1545.content-editor-remove:hover,
1545#dialogues-delete:hover:not(:disabled) {
1546#dialogues-delete:hover:not(:disabled),
1547#quests-delete:hover:not(:disabled) {
1546 background: #a83838;
1548 background: #a83838;
1547 border-color: #c06060;
1549 border-color: #c06060;
1548}
1550}
1549
1551
1550#dialogues-delete:disabled {
1552#dialogues-delete:disabled,
1553#quests-delete:disabled {
1551 opacity: 0.45;
1554 opacity: 0.45;
1552}
1555}
1553
1556
@@ -1568,6 +1571,14 @@ label {
1568 background: #1a2230;
1571 background: #1a2230;
1569}
1572}
1570
1573
1574.quest-reward-bank {
1575 display: inline-flex;
1576 align-items: center;
1577 gap: 0.25rem;
1578 white-space: nowrap;
1579 font-size: 0.85rem;
1580}
1581
1571.content-editor-clause {
1582.content-editor-clause {
1572 border: 1px dashed #3a4250;
1583 border: 1px dashed #3a4250;
1573 padding: 0.4rem;
1584 padding: 0.4rem;
client/ui/play.css +51 −2
@@ -2905,8 +2905,57 @@ button.friend-account-name:hover {
2905 2905
2906 2906 #quests-list-panel[hidden],
2907 2907 #quests-detail-panel[hidden],
2908 #quest-complete-panel[hidden],
2908 2909 #dialogue-panel[hidden],
2909 2910 #quests-list-backdrop[hidden],
2910 #quests-detail-backdrop[hidden] {
2911 #quests-detail-backdrop[hidden],
2912 #quest-complete-backdrop[hidden] {
2911 2913 display: none !important;
2912 }
2914 }
2915
2916 #quest-complete-panel {
2917 position: fixed;
2918 left: 50%;
2919 top: 40%;
2920 transform: translate(-50%, -50%);
2921 z-index: 70;
2922 min-width: min(22rem, 92vw);
2923 max-width: 28rem;
2924 background: #161a22;
2925 border: 1px solid #3a4558;
2926 border-radius: 6px;
2927 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
2928 padding: 0;
2929 }
2930
2931 #quest-complete-panel > header {
2932 padding: 0.85rem 1rem 0.35rem;
2933 }
2934
2935 #quest-complete-panel > header h2 {
2936 margin: 0;
2937 font-size: 1.15rem;
2938 }
2939
2940 .quest-complete-body {
2941 padding: 0.35rem 1rem 0.75rem;
2942 }
2943
2944 .quest-complete-body ul {
2945 margin: 0.35rem 0 0;
2946 padding-left: 1.2rem;
2947 }
2948
2949 .quest-complete-body li {
2950 margin: 0.2rem 0;
2951 }
2952
2953 #quest-complete-panel > footer {
2954 display: flex;
2955 justify-content: flex-end;
2956 padding: 0.5rem 1rem 0.85rem;
2957 }
2958
2959 #quest-complete-backdrop {
2960 z-index: 69;
2961 }
@@ -2905,8 +2905,57 @@ button.friend-account-name:hover {
2905
2905
2906#quests-list-panel[hidden],
2906#quests-list-panel[hidden],
2907#quests-detail-panel[hidden],
2907#quests-detail-panel[hidden],
2908#quest-complete-panel[hidden],
2908#dialogue-panel[hidden],
2909#dialogue-panel[hidden],
2909#quests-list-backdrop[hidden],
2910#quests-list-backdrop[hidden],
2910#quests-detail-backdrop[hidden] {
2911#quests-detail-backdrop[hidden],
2912#quest-complete-backdrop[hidden] {
2911 display: none !important;
2913 display: none !important;
2912}
2914}
2915
2916#quest-complete-panel {
2917 position: fixed;
2918 left: 50%;
2919 top: 40%;
2920 transform: translate(-50%, -50%);
2921 z-index: 70;
2922 min-width: min(22rem, 92vw);
2923 max-width: 28rem;
2924 background: #161a22;
2925 border: 1px solid #3a4558;
2926 border-radius: 6px;
2927 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
2928 padding: 0;
2929}
2930
2931#quest-complete-panel > header {
2932 padding: 0.85rem 1rem 0.35rem;
2933}
2934
2935#quest-complete-panel > header h2 {
2936 margin: 0;
2937 font-size: 1.15rem;
2938}
2939
2940.quest-complete-body {
2941 padding: 0.35rem 1rem 0.75rem;
2942}
2943
2944.quest-complete-body ul {
2945 margin: 0.35rem 0 0;
2946 padding-left: 1.2rem;
2947}
2948
2949.quest-complete-body li {
2950 margin: 0.2rem 0;
2951}
2952
2953#quest-complete-panel > footer {
2954 display: flex;
2955 justify-content: flex-end;
2956 padding: 0.5rem 1rem 0.85rem;
2957}
2958
2959#quest-complete-backdrop {
2960 z-index: 69;
2961}
server/src/gateway/websocket.js +17 −0
@@ -1783,6 +1783,23 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1783 1783 }
1784 1784 continue;
1785 1785 }
1786 if (event.type === "quest-complete")
1787 {
1788 const session = event.sessionId != null
1789 ? sessions.get(event.sessionId)
1790 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1791 if (session)
1792 {
1793 send(session, {
1794 type: MessageType.questComplete,
1795 questId: event.questId,
1796 title: event.title,
1797 xp: event.xp ?? [],
1798 items: event.items ?? []
1799 });
1800 }
1801 continue;
1802 }
1786 1803 if (event.type === "dialogue-step")
1787 1804 {
1788 1805 const session = event.sessionId != null
@@ -1783,6 +1783,23 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1783 }
1783 }
1784 continue;
1784 continue;
1785 }
1785 }
1786 if (event.type === "quest-complete")
1787 {
1788 const session = event.sessionId != null
1789 ? sessions.get(event.sessionId)
1790 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1791 if (session)
1792 {
1793 send(session, {
1794 type: MessageType.questComplete,
1795 questId: event.questId,
1796 title: event.title,
1797 xp: event.xp ?? [],
1798 items: event.items ?? []
1799 });
1800 }
1801 continue;
1802 }
1786 if (event.type === "dialogue-step")
1803 if (event.type === "dialogue-step")
1787 {
1804 {
1788 const session = event.sessionId != null
1805 const session = event.sessionId != null
server/src/quests/runtime.js +169 −22
@@ -2,10 +2,15 @@ import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditi
2 2 import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
3 3 import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
4 4 import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
5 import { itemDefinition } from "../../../shared/definitions/items.js";
6 import { applySkillXp } from "../../../shared/skills/state.js";
7 import { skillLevel } from "../../../shared/definitions/skills.js";
5 import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
6 import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";
7 import { skillLevel, SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";
8 8 import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../../shared/quests/dialogueRewards.js";
9 import {
10 formatQuestBankRewardLetterBody,
11 QUESTWARD_GIFT_AUTHOR,
12 QUESTWARD_GIFT_ORG
13 } from "../../../shared/courier/questRewardLetters.js";
9 14 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
10 15 import { floorDiv } from "../world/coordinates.js";
11 16 import { WorkerMessage } from "../simulation/protocol.js";
@@ -507,21 +512,29 @@ export class QuestRuntime
507 512 quantity,
508 513 origins: [{ origin: godsOrigin(), quantity }]
509 514 });
510 const result = insertStack(bag.inventory, stack, def);
511 bag.inventory = result.slots;
512 if (result.remainder > 0)
515 if (effect.toBank)
513 516 {
514 const vaultResult = insertStackGrowable(
515 bag.vault,
516 attachOrigins({
517 itemId: effect.itemId | 0,
518 quantity: result.remainder,
519 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
520 }),
521 def
522 );
517 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def);
523 518 bag.vault = vaultResult.slots;
524 519 }
520 else
521 {
522 const result = insertStack(bag.inventory, stack, def);
523 bag.inventory = result.slots;
524 if (result.remainder > 0)
525 {
526 const vaultResult = insertStackGrowable(
527 bag.vault ?? [],
528 attachOrigins({
529 itemId: effect.itemId | 0,
530 quantity: result.remainder,
531 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
532 }),
533 def
534 );
535 bag.vault = vaultResult.slots;
536 }
537 }
525 538 this.#persistBag(characterId, bag);
526 539 events.push({ type: "inventoryDirty" });
527 540 }
@@ -597,6 +610,133 @@ export class QuestRuntime
597 610 return events;
598 611 }
599 612
613 /**
614 * Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter.
615 * @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }}
616 */
617 #grantQuestCompletionRewards (characterId, def, playerView, events)
618 {
619 const xp = [];
620 const bagItems = [];
621 const bankItems = [];
622 const rewards = def?.rewards ?? [];
623 for (const effect of rewards)
624 {
625 if (effect.kind === EffectKind.giveXp)
626 {
627 const amount = Math.max(0, Number(effect.amount) || 0) | 0;
628 if (amount <= 0)
629 { continue; }
630 const skillId = String(effect.skillId ?? "").trim();
631 if (!skillId)
632 { continue; }
633 const onlineId = this.simulation.characterEntities.get(characterId | 0);
634 let skills = onlineId
635 ? this.simulation.skillsOf(onlineId)
636 : this.stateDb.getSkills(characterId);
637 if (!skills)
638 { skills = this.stateDb.getSkills(characterId); }
639 if (!skills)
640 { continue; }
641 applySkillXp(skills, skillId, amount);
642 this.stateDb.saveSkills(characterId, skills);
643 if (playerView)
644 { playerView.skills = skills; }
645 if (onlineId)
646 { this.simulation.applySkills?.(onlineId, skills); }
647 const payload = publicSkillsPayload(skills);
648 this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel);
649 xp.push({
650 skillId,
651 displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId,
652 amount
653 });
654 continue;
655 }
656 if (effect.kind !== EffectKind.giveItem)
657 { continue; }
658 const bag = this.#loadBag(characterId);
659 if (!bag)
660 { continue; }
661 const itemId = effect.itemId | 0;
662 const defItem = itemDefinition(itemId);
663 const quantity = Math.max(1, Number(effect.quantity) || 1) | 0;
664 const displayName = defItem
665 ? itemDisplayName({ itemId, quantity }, defItem)
666 : `Item ${itemId}`;
667 const stack = attachOrigins({
668 itemId,
669 quantity,
670 origins: [{ origin: godsOrigin(), quantity }]
671 });
672 let intoBag = 0;
673 let intoBank = 0;
674 if (effect.toBank)
675 {
676 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem);
677 bag.vault = vaultResult.slots;
678 intoBank = quantity - Math.max(0, vaultResult.remainder | 0);
679 }
680 else
681 {
682 const result = insertStack(bag.inventory, stack, defItem);
683 bag.inventory = result.slots;
684 intoBag = quantity - Math.max(0, result.remainder | 0);
685 if (result.remainder > 0)
686 {
687 const vaultResult = insertStackGrowable(
688 bag.vault ?? [],
689 attachOrigins({
690 itemId,
691 quantity: result.remainder,
692 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
693 }),
694 defItem
695 );
696 bag.vault = vaultResult.slots;
697 intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
698 }
699 }
700 this.#persistBag(characterId, bag);
701 events.push({ type: "inventoryDirty" });
702 if (intoBag > 0)
703 { bagItems.push({ displayName, quantity: intoBag, itemId }); }
704 if (intoBank > 0)
705 { bankItems.push({ displayName, quantity: intoBank, itemId }); }
706 }
707
708 if (bankItems.length)
709 { this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); }
710
711 return { xp, bagItems };
712 }
713
714 #dispatchQuestBankRewardLetter (characterId, def, bankItems)
715 {
716 const courier = this.simulation.courier;
717 if (!courier?.enqueueSystemLetter)
718 { return; }
719 const row = this.stateDb.getCharacter?.(characterId);
720 const characterDisplayName = row
721 ? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim()
722 : "Adventurer";
723 const originTileX = row?.tile_x | 0;
724 const originTileY = row?.tile_y | 0;
725 const bank = courier.nearestBank?.(originTileX, originTileY);
726 courier.enqueueSystemLetter({
727 characterId: characterId | 0,
728 originTileX: bank?.tileX ?? originTileX,
729 originTileY: bank?.tileY ?? originTileY,
730 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
731 authorOrganization: QUESTWARD_GIFT_ORG,
732 body: formatQuestBankRewardLetterBody({
733 characterDisplayName,
734 questTitle: def?.title ?? def?.questId,
735 items: bankItems
736 })
737 });
738 }
739
600 740 #reevaluateQuests (characterId, playerView, events)
601 741 {
602 742 const states = this.stateDb.listQuestStates(characterId)
@@ -645,8 +785,15 @@ export class QuestRuntime
645 785 const nextIndex = row.state + 1;
646 786 if (nextIndex > def.steps.length)
647 787 {
648 this.#applyEffects(characterId, def.rewards, playerView, events);
788 const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
649 789 this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
790 events.push({
791 type: "questComplete",
792 questId: row.questId,
793 title: def.title,
794 xp: summary.xp,
795 items: summary.bagItems
796 });
650 797 }
651 798 else
652 799 {
@@ -657,13 +804,13 @@ export class QuestRuntime
657 804 interacts: {}
658 805 }, row.startedAt, null);
659 806 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
807 events.push({
808 type: "questStepComplete",
809 questId: row.questId,
810 title: def.title,
811 journalText: journal?.text ?? null
812 });
660 813 }
661 events.push({
662 type: "questStepComplete",
663 questId: row.questId,
664 title: def.title,
665 journalText: journal?.text ?? null
666 });
667 814 events.push({ type: "questsDirty" });
668 815 }
669 816 }
@@ -2,10 +2,15 @@ import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditi
2import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
2import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
3import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
3import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
4import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
4import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
5import { itemDefinition } from "../../../shared/definitions/items.js";
5import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
6import { applySkillXp } from "../../../shared/skills/state.js";
6import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";
7import { skillLevel } from "../../../shared/definitions/skills.js";
7import { skillLevel, SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";
8import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../../shared/quests/dialogueRewards.js";
8import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../../shared/quests/dialogueRewards.js";
9import {
10 formatQuestBankRewardLetterBody,
11 QUESTWARD_GIFT_AUTHOR,
12 QUESTWARD_GIFT_ORG
13} from "../../../shared/courier/questRewardLetters.js";
9import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
14import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
10import { floorDiv } from "../world/coordinates.js";
15import { floorDiv } from "../world/coordinates.js";
11import { WorkerMessage } from "../simulation/protocol.js";
16import { WorkerMessage } from "../simulation/protocol.js";
@@ -507,21 +512,29 @@ export class QuestRuntime
507 quantity,
512 quantity,
508 origins: [{ origin: godsOrigin(), quantity }]
513 origins: [{ origin: godsOrigin(), quantity }]
509 });
514 });
510 const result = insertStack(bag.inventory, stack, def);
515 if (effect.toBank)
511 bag.inventory = result.slots;
512 if (result.remainder > 0)
513 {
516 {
514 const vaultResult = insertStackGrowable(
517 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def);
515 bag.vault,
516 attachOrigins({
517 itemId: effect.itemId | 0,
518 quantity: result.remainder,
519 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
520 }),
521 def
522 );
523 bag.vault = vaultResult.slots;
518 bag.vault = vaultResult.slots;
524 }
519 }
520 else
521 {
522 const result = insertStack(bag.inventory, stack, def);
523 bag.inventory = result.slots;
524 if (result.remainder > 0)
525 {
526 const vaultResult = insertStackGrowable(
527 bag.vault ?? [],
528 attachOrigins({
529 itemId: effect.itemId | 0,
530 quantity: result.remainder,
531 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
532 }),
533 def
534 );
535 bag.vault = vaultResult.slots;
536 }
537 }
525 this.#persistBag(characterId, bag);
538 this.#persistBag(characterId, bag);
526 events.push({ type: "inventoryDirty" });
539 events.push({ type: "inventoryDirty" });
527 }
540 }
@@ -597,6 +610,133 @@ export class QuestRuntime
597 return events;
610 return events;
598 }
611 }
599
612
613 /**
614 * Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter.
615 * @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }}
616 */
617 #grantQuestCompletionRewards (characterId, def, playerView, events)
618 {
619 const xp = [];
620 const bagItems = [];
621 const bankItems = [];
622 const rewards = def?.rewards ?? [];
623 for (const effect of rewards)
624 {
625 if (effect.kind === EffectKind.giveXp)
626 {
627 const amount = Math.max(0, Number(effect.amount) || 0) | 0;
628 if (amount <= 0)
629 { continue; }
630 const skillId = String(effect.skillId ?? "").trim();
631 if (!skillId)
632 { continue; }
633 const onlineId = this.simulation.characterEntities.get(characterId | 0);
634 let skills = onlineId
635 ? this.simulation.skillsOf(onlineId)
636 : this.stateDb.getSkills(characterId);
637 if (!skills)
638 { skills = this.stateDb.getSkills(characterId); }
639 if (!skills)
640 { continue; }
641 applySkillXp(skills, skillId, amount);
642 this.stateDb.saveSkills(characterId, skills);
643 if (playerView)
644 { playerView.skills = skills; }
645 if (onlineId)
646 { this.simulation.applySkills?.(onlineId, skills); }
647 const payload = publicSkillsPayload(skills);
648 this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel);
649 xp.push({
650 skillId,
651 displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId,
652 amount
653 });
654 continue;
655 }
656 if (effect.kind !== EffectKind.giveItem)
657 { continue; }
658 const bag = this.#loadBag(characterId);
659 if (!bag)
660 { continue; }
661 const itemId = effect.itemId | 0;
662 const defItem = itemDefinition(itemId);
663 const quantity = Math.max(1, Number(effect.quantity) || 1) | 0;
664 const displayName = defItem
665 ? itemDisplayName({ itemId, quantity }, defItem)
666 : `Item ${itemId}`;
667 const stack = attachOrigins({
668 itemId,
669 quantity,
670 origins: [{ origin: godsOrigin(), quantity }]
671 });
672 let intoBag = 0;
673 let intoBank = 0;
674 if (effect.toBank)
675 {
676 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem);
677 bag.vault = vaultResult.slots;
678 intoBank = quantity - Math.max(0, vaultResult.remainder | 0);
679 }
680 else
681 {
682 const result = insertStack(bag.inventory, stack, defItem);
683 bag.inventory = result.slots;
684 intoBag = quantity - Math.max(0, result.remainder | 0);
685 if (result.remainder > 0)
686 {
687 const vaultResult = insertStackGrowable(
688 bag.vault ?? [],
689 attachOrigins({
690 itemId,
691 quantity: result.remainder,
692 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
693 }),
694 defItem
695 );
696 bag.vault = vaultResult.slots;
697 intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
698 }
699 }
700 this.#persistBag(characterId, bag);
701 events.push({ type: "inventoryDirty" });
702 if (intoBag > 0)
703 { bagItems.push({ displayName, quantity: intoBag, itemId }); }
704 if (intoBank > 0)
705 { bankItems.push({ displayName, quantity: intoBank, itemId }); }
706 }
707
708 if (bankItems.length)
709 { this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); }
710
711 return { xp, bagItems };
712 }
713
714 #dispatchQuestBankRewardLetter (characterId, def, bankItems)
715 {
716 const courier = this.simulation.courier;
717 if (!courier?.enqueueSystemLetter)
718 { return; }
719 const row = this.stateDb.getCharacter?.(characterId);
720 const characterDisplayName = row
721 ? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim()
722 : "Adventurer";
723 const originTileX = row?.tile_x | 0;
724 const originTileY = row?.tile_y | 0;
725 const bank = courier.nearestBank?.(originTileX, originTileY);
726 courier.enqueueSystemLetter({
727 characterId: characterId | 0,
728 originTileX: bank?.tileX ?? originTileX,
729 originTileY: bank?.tileY ?? originTileY,
730 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
731 authorOrganization: QUESTWARD_GIFT_ORG,
732 body: formatQuestBankRewardLetterBody({
733 characterDisplayName,
734 questTitle: def?.title ?? def?.questId,
735 items: bankItems
736 })
737 });
738 }
739
600 #reevaluateQuests (characterId, playerView, events)
740 #reevaluateQuests (characterId, playerView, events)
601 {
741 {
602 const states = this.stateDb.listQuestStates(characterId)
742 const states = this.stateDb.listQuestStates(characterId)
@@ -645,8 +785,15 @@ export class QuestRuntime
645 const nextIndex = row.state + 1;
785 const nextIndex = row.state + 1;
646 if (nextIndex > def.steps.length)
786 if (nextIndex > def.steps.length)
647 {
787 {
648 this.#applyEffects(characterId, def.rewards, playerView, events);
788 const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
649 this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
789 this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
790 events.push({
791 type: "questComplete",
792 questId: row.questId,
793 title: def.title,
794 xp: summary.xp,
795 items: summary.bagItems
796 });
650 }
797 }
651 else
798 else
652 {
799 {
@@ -657,13 +804,13 @@ export class QuestRuntime
657 interacts: {}
804 interacts: {}
658 }, row.startedAt, null);
805 }, row.startedAt, null);
659 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
806 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
807 events.push({
808 type: "questStepComplete",
809 questId: row.questId,
810 title: def.title,
811 journalText: journal?.text ?? null
812 });
660 }
813 }
661 events.push({
662 type: "questStepComplete",
663 questId: row.questId,
664 title: def.title,
665 journalText: journal?.text ?? null
666 });
667 events.push({ type: "questsDirty" });
814 events.push({ type: "questsDirty" });
668 }
815 }
669 }
816 }
server/src/simulation/protocol.js +1 −0
@@ -24,6 +24,7 @@ export const WorkerMessage = Object.freeze({
24 24 inspectSkills: "inspectSkills",
25 25 inspectSpells: "inspectSpells",
26 26 applyBag: "applyBag",
27 applySkills: "applySkills",
27 28 updateFlight: "updateFlight",
28 29 chunkIsSimulating: "chunkIsSimulating",
29 30 setGroundItems: "setGroundItems",
@@ -24,6 +24,7 @@ export const WorkerMessage = Object.freeze({
24 inspectSkills: "inspectSkills",
24 inspectSkills: "inspectSkills",
25 inspectSpells: "inspectSpells",
25 inspectSpells: "inspectSpells",
26 applyBag: "applyBag",
26 applyBag: "applyBag",
27 applySkills: "applySkills",
27 updateFlight: "updateFlight",
28 updateFlight: "updateFlight",
28 chunkIsSimulating: "chunkIsSimulating",
29 chunkIsSimulating: "chunkIsSimulating",
29 setGroundItems: "setGroundItems",
30 setGroundItems: "setGroundItems",
server/src/simulation/simulation.js +42 −1
@@ -45,7 +45,7 @@ import { mobComponents } from "./spawners.js";
45 45 import { shadeSummonComponents } from "../spells/summons.js";
46 46 import { jadeiteFairyComponents } from "../spells/jadeiteFairy.js";
47 47 import { MobId } from "../../../shared/definitions/mobs.js";
48 import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
48 import { defaultPlayerSkills, enforceMinimumSkillLevels, publicSkillsPayload } from "../../../shared/skills/state.js";
49 49 import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
50 50 import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
51 51 import { BlockType } from "../../../shared/definitions/tiles.js";
@@ -1058,6 +1058,32 @@ export class Simulation
1058 1058 });
1059 1059 }
1060 1060
1061 applySkills (entityId, skills)
1062 {
1063 const record = this.directory.get(entityId);
1064 if (!record)
1065 { return null; }
1066 return this.workers[record.workerId].call({
1067 type: WorkerMessage.applySkills,
1068 entityId,
1069 skills
1070 });
1071 }
1072
1073 /** Persist skills from stateDb onto the live worker and push a client snapshot. */
1074 syncCharacterSkillsFromDb (characterId)
1075 {
1076 const id = characterId | 0;
1077 const skills = this.stateDb.getSkills(id);
1078 if (!skills)
1079 { return; }
1080 const entityId = this.characterEntities.get(id);
1081 if (entityId)
1082 { this.applySkills(entityId, skills); }
1083 const payload = publicSkillsPayload(skills);
1084 this.pushSkills(id, payload.skills, payload.combatLevel);
1085 }
1086
1061 1087 /**
1062 1088 * Persist hair + patch live appearance; returns public view.
1063 1089 */
@@ -2001,6 +2027,21 @@ export class Simulation
2001 2027 { this.pushInventory(cid, live); }
2002 2028 }
2003 2029 }
2030 else if (event.type === "skillsDirty" && cid != null)
2031 { this.syncCharacterSkillsFromDb(cid); }
2032 else if (event.type === "questComplete")
2033 {
2034 out.push({
2035 type: "quest-complete",
2036 sessionId: sid,
2037 characterId: cid,
2038 questId: event.questId,
2039 title: event.title,
2040 xp: event.xp ?? [],
2041 items: event.items ?? []
2042 });
2043 needSnapshot = true;
2044 }
2004 2045 }
2005 2046 if (needSnapshot && characterId != null)
2006 2047 {
@@ -45,7 +45,7 @@ import { mobComponents } from "./spawners.js";
45import { shadeSummonComponents } from "../spells/summons.js";
45import { shadeSummonComponents } from "../spells/summons.js";
46import { jadeiteFairyComponents } from "../spells/jadeiteFairy.js";
46import { jadeiteFairyComponents } from "../spells/jadeiteFairy.js";
47import { MobId } from "../../../shared/definitions/mobs.js";
47import { MobId } from "../../../shared/definitions/mobs.js";
48import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
48import { defaultPlayerSkills, enforceMinimumSkillLevels, publicSkillsPayload } from "../../../shared/skills/state.js";
49import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
49import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
50import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
50import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
51import { BlockType } from "../../../shared/definitions/tiles.js";
51import { BlockType } from "../../../shared/definitions/tiles.js";
@@ -1058,6 +1058,32 @@ export class Simulation
1058 });
1058 });
1059 }
1059 }
1060
1060
1061 applySkills (entityId, skills)
1062 {
1063 const record = this.directory.get(entityId);
1064 if (!record)
1065 { return null; }
1066 return this.workers[record.workerId].call({
1067 type: WorkerMessage.applySkills,
1068 entityId,
1069 skills
1070 });
1071 }
1072
1073 /** Persist skills from stateDb onto the live worker and push a client snapshot. */
1074 syncCharacterSkillsFromDb (characterId)
1075 {
1076 const id = characterId | 0;
1077 const skills = this.stateDb.getSkills(id);
1078 if (!skills)
1079 { return; }
1080 const entityId = this.characterEntities.get(id);
1081 if (entityId)
1082 { this.applySkills(entityId, skills); }
1083 const payload = publicSkillsPayload(skills);
1084 this.pushSkills(id, payload.skills, payload.combatLevel);
1085 }
1086
1061 /**
1087 /**
1062 * Persist hair + patch live appearance; returns public view.
1088 * Persist hair + patch live appearance; returns public view.
1063 */
1089 */
@@ -2001,6 +2027,21 @@ export class Simulation
2001 { this.pushInventory(cid, live); }
2027 { this.pushInventory(cid, live); }
2002 }
2028 }
2003 }
2029 }
2030 else if (event.type === "skillsDirty" && cid != null)
2031 { this.syncCharacterSkillsFromDb(cid); }
2032 else if (event.type === "questComplete")
2033 {
2034 out.push({
2035 type: "quest-complete",
2036 sessionId: sid,
2037 characterId: cid,
2038 questId: event.questId,
2039 title: event.title,
2040 xp: event.xp ?? [],
2041 items: event.items ?? []
2042 });
2043 needSnapshot = true;
2044 }
2004 }
2045 }
2005 if (needSnapshot && characterId != null)
2046 if (needSnapshot && characterId != null)
2006 {
2047 {
server/src/simulation/workerWorld.js +17 −0
@@ -184,6 +184,8 @@ export class WorkerWorld
184 184 return this.#inspectStamina(message.entityId);
185 185 case WorkerMessage.applyBag:
186 186 return this.#applyBag(message.entityId, message.bag);
187 case WorkerMessage.applySkills:
188 return this.#applySkills(message.entityId, message.skills);
187 189 case WorkerMessage.applyAppearance:
188 190 return this.#applyAppearance(message.entityId, message.appearance);
189 191 case WorkerMessage.applySkullValue:
@@ -879,6 +881,21 @@ export class WorkerWorld
879 881 return applyBagView(this.ecs, handle, bag);
880 882 }
881 883
884 #applySkills (entityId, skills)
885 {
886 const handle = this.ecs.handleOf(entityId);
887 if (handle == null)
888 { return null; }
889 if (!skills?.xp || typeof skills.xp !== "object")
890 { return null; }
891 const current = this.ecs.get(handle, Component.skills);
892 if (current)
893 { Object.assign(current, structuredClone(skills)); }
894 else
895 { this.ecs.add(handle, Component.skills, structuredClone(skills)); }
896 return { ok: true };
897 }
898
882 899 #applyAppearance (entityId, appearancePatch)
883 900 {
884 901 const handle = this.ecs.handleOf(entityId);
@@ -184,6 +184,8 @@ export class WorkerWorld
184 return this.#inspectStamina(message.entityId);
184 return this.#inspectStamina(message.entityId);
185 case WorkerMessage.applyBag:
185 case WorkerMessage.applyBag:
186 return this.#applyBag(message.entityId, message.bag);
186 return this.#applyBag(message.entityId, message.bag);
187 case WorkerMessage.applySkills:
188 return this.#applySkills(message.entityId, message.skills);
187 case WorkerMessage.applyAppearance:
189 case WorkerMessage.applyAppearance:
188 return this.#applyAppearance(message.entityId, message.appearance);
190 return this.#applyAppearance(message.entityId, message.appearance);
189 case WorkerMessage.applySkullValue:
191 case WorkerMessage.applySkullValue:
@@ -879,6 +881,21 @@ export class WorkerWorld
879 return applyBagView(this.ecs, handle, bag);
881 return applyBagView(this.ecs, handle, bag);
880 }
882 }
881
883
884 #applySkills (entityId, skills)
885 {
886 const handle = this.ecs.handleOf(entityId);
887 if (handle == null)
888 { return null; }
889 if (!skills?.xp || typeof skills.xp !== "object")
890 { return null; }
891 const current = this.ecs.get(handle, Component.skills);
892 if (current)
893 { Object.assign(current, structuredClone(skills)); }
894 else
895 { this.ecs.add(handle, Component.skills, structuredClone(skills)); }
896 return { ok: true };
897 }
898
882 #applyAppearance (entityId, appearancePatch)
899 #applyAppearance (entityId, appearancePatch)
883 {
900 {
884 const handle = this.ecs.handleOf(entityId);
901 const handle = this.ecs.handleOf(entityId);
server/tests/quest-rewards.test.js added +104 −0
@@ -0,0 +1,104 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { EffectKind, normalizeEffects } from "../../shared/quests/conditions.js";
4 import { normalizeQuestDef } from "../../shared/quests/normalize.js";
5 import { formatQuestBankRewardLetterBody } from "../../shared/courier/questRewardLetters.js";
6 import { ItemId } from "../../shared/definitions/items.js";
7 import { SkillId } from "../../shared/definitions/skills.js";
8 import { countItemInSlots } from "../../shared/items/inventory.js";
9 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
10
11 test("normalizeEffects keeps giveItem toBank and cleans giveXp", () =>
12 {
13 const effects = normalizeEffects([
14 { kind: EffectKind.giveItem, itemId: ItemId.bones, quantity: 2, toBank: true },
15 { kind: EffectKind.giveXp, skillId: SkillId.woodworking, amount: 15 },
16 { kind: EffectKind.giveXp, skillId: SkillId.swordfighting, amount: 0 },
17 { kind: "nope", itemId: 1 }
18 ]);
19 assert.deepEqual(effects, [
20 { kind: EffectKind.giveItem, itemId: ItemId.bones, quantity: 2, toBank: true },
21 { kind: EffectKind.giveXp, skillId: SkillId.woodworking, amount: 15 }
22 ]);
23 });
24
25 test("quest bank reward letter body names the quest and items", () =>
26 {
27 const body = formatQuestBankRewardLetterBody({
28 characterDisplayName: "Ada Worker",
29 questTitle: "Reward Test",
30 items: [{ itemId: ItemId.bones, quantity: 2 }]
31 });
32 assert.match(body, /^Dear Ada Worker,/);
33 assert.match(body, /quest Reward Test/);
34 assert.match(body, /• 2× Bones/);
35 assert.doesNotMatch(body, /Signed/);
36 });
37
38 test("quest completion grants XP, bags items, banks when flagged, and emits questComplete", () =>
39 {
40 const harness = makeSimulation({ workerCount: 1 });
41 try
42 {
43 const revisionId = harness.worldDb.getActiveRevisionId();
44 const quest = normalizeQuestDef({
45 questId: "reward-test",
46 title: "Reward Test",
47 steps: [{
48 stepId: "step-1",
49 objectives: [{ objectiveId: "obj-1", text: "Done", when: { all: [] } }],
50 completionJournalText: "Finished."
51 }],
52 rewards: [
53 { kind: EffectKind.giveXp, skillId: SkillId.woodworking, amount: 15 },
54 { kind: EffectKind.giveXp, skillId: SkillId.swordfighting, amount: 30 },
55 { kind: EffectKind.giveItem, itemId: ItemId.bones, quantity: 2, toBank: true },
56 { kind: EffectKind.giveItem, itemId: ItemId.glassBottle, quantity: 1, toBank: false }
57 ]
58 });
59 harness.worldDb.saveQuestDef(revisionId, quest);
60 harness.simulation.questContent.reload();
61
62 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
63 const entityId = harness.simulation.spawnCharacter(1, character);
64 harness.simulation.step();
65
66 const sticksBefore = countItemInSlots(
67 harness.simulation.bagOf(entityId).inventory,
68 ItemId.stick
69 );
70 const events = [];
71 harness.simulation.quests.startQuest(
72 character.character_id,
73 "reward-test",
74 harness.simulation.quests.playerViewFor(character.character_id),
75 events
76 );
77
78 const complete = events.find((e) => e.type === "questComplete");
79 assert.ok(complete);
80 assert.equal(complete.title, "Reward Test");
81 assert.deepEqual(complete.xp, [
82 { skillId: SkillId.woodworking, displayName: "Woodworking", amount: 15 },
83 { skillId: SkillId.swordfighting, displayName: "Swords", amount: 30 }
84 ]);
85 assert.deepEqual(complete.items, [
86 { displayName: "Glass bottle", quantity: 1, itemId: ItemId.glassBottle }
87 ]);
88
89 const bag = harness.simulation.bagOf(entityId);
90 assert.equal(countItemInSlots(bag.inventory, ItemId.bones), 0);
91 assert.equal(countItemInSlots(bag.vault, ItemId.bones), 2);
92 assert.equal(countItemInSlots(bag.inventory, ItemId.glassBottle), 1);
93 assert.equal(countItemInSlots(bag.inventory, ItemId.stick), sticksBefore);
94
95 const skills = harness.stateDb.getSkills(character.character_id);
96 assert.equal(skills.xp.woodworking, 15);
97 assert.equal(skills.xp.swordfighting, 30);
98
99 const state = harness.stateDb.getQuestState(character.character_id, "reward-test");
100 assert.equal(state.state, "completed");
101 }
102 finally
103 { harness.close(); }
104 });
@@ -0,0 +1,104 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { EffectKind, normalizeEffects } from "../../shared/quests/conditions.js";
4import { normalizeQuestDef } from "../../shared/quests/normalize.js";
5import { formatQuestBankRewardLetterBody } from "../../shared/courier/questRewardLetters.js";
6import { ItemId } from "../../shared/definitions/items.js";
7import { SkillId } from "../../shared/definitions/skills.js";
8import { countItemInSlots } from "../../shared/items/inventory.js";
9import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
10
11test("normalizeEffects keeps giveItem toBank and cleans giveXp", () =>
12{
13 const effects = normalizeEffects([
14 { kind: EffectKind.giveItem, itemId: ItemId.bones, quantity: 2, toBank: true },
15 { kind: EffectKind.giveXp, skillId: SkillId.woodworking, amount: 15 },
16 { kind: EffectKind.giveXp, skillId: SkillId.swordfighting, amount: 0 },
17 { kind: "nope", itemId: 1 }
18 ]);
19 assert.deepEqual(effects, [
20 { kind: EffectKind.giveItem, itemId: ItemId.bones, quantity: 2, toBank: true },
21 { kind: EffectKind.giveXp, skillId: SkillId.woodworking, amount: 15 }
22 ]);
23});
24
25test("quest bank reward letter body names the quest and items", () =>
26{
27 const body = formatQuestBankRewardLetterBody({
28 characterDisplayName: "Ada Worker",
29 questTitle: "Reward Test",
30 items: [{ itemId: ItemId.bones, quantity: 2 }]
31 });
32 assert.match(body, /^Dear Ada Worker,/);
33 assert.match(body, /quest Reward Test/);
34 assert.match(body, /• 2× Bones/);
35 assert.doesNotMatch(body, /Signed/);
36});
37
38test("quest completion grants XP, bags items, banks when flagged, and emits questComplete", () =>
39{
40 const harness = makeSimulation({ workerCount: 1 });
41 try
42 {
43 const revisionId = harness.worldDb.getActiveRevisionId();
44 const quest = normalizeQuestDef({
45 questId: "reward-test",
46 title: "Reward Test",
47 steps: [{
48 stepId: "step-1",
49 objectives: [{ objectiveId: "obj-1", text: "Done", when: { all: [] } }],
50 completionJournalText: "Finished."
51 }],
52 rewards: [
53 { kind: EffectKind.giveXp, skillId: SkillId.woodworking, amount: 15 },
54 { kind: EffectKind.giveXp, skillId: SkillId.swordfighting, amount: 30 },
55 { kind: EffectKind.giveItem, itemId: ItemId.bones, quantity: 2, toBank: true },
56 { kind: EffectKind.giveItem, itemId: ItemId.glassBottle, quantity: 1, toBank: false }
57 ]
58 });
59 harness.worldDb.saveQuestDef(revisionId, quest);
60 harness.simulation.questContent.reload();
61
62 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
63 const entityId = harness.simulation.spawnCharacter(1, character);
64 harness.simulation.step();
65
66 const sticksBefore = countItemInSlots(
67 harness.simulation.bagOf(entityId).inventory,
68 ItemId.stick
69 );
70 const events = [];
71 harness.simulation.quests.startQuest(
72 character.character_id,
73 "reward-test",
74 harness.simulation.quests.playerViewFor(character.character_id),
75 events
76 );
77
78 const complete = events.find((e) => e.type === "questComplete");
79 assert.ok(complete);
80 assert.equal(complete.title, "Reward Test");
81 assert.deepEqual(complete.xp, [
82 { skillId: SkillId.woodworking, displayName: "Woodworking", amount: 15 },
83 { skillId: SkillId.swordfighting, displayName: "Swords", amount: 30 }
84 ]);
85 assert.deepEqual(complete.items, [
86 { displayName: "Glass bottle", quantity: 1, itemId: ItemId.glassBottle }
87 ]);
88
89 const bag = harness.simulation.bagOf(entityId);
90 assert.equal(countItemInSlots(bag.inventory, ItemId.bones), 0);
91 assert.equal(countItemInSlots(bag.vault, ItemId.bones), 2);
92 assert.equal(countItemInSlots(bag.inventory, ItemId.glassBottle), 1);
93 assert.equal(countItemInSlots(bag.inventory, ItemId.stick), sticksBefore);
94
95 const skills = harness.stateDb.getSkills(character.character_id);
96 assert.equal(skills.xp.woodworking, 15);
97 assert.equal(skills.xp.swordfighting, 30);
98
99 const state = harness.stateDb.getQuestState(character.character_id, "reward-test");
100 assert.equal(state.state, "completed");
101 }
102 finally
103 { harness.close(); }
104});
shared/courier/questRewardLetters.js added +37 −0
@@ -0,0 +1,37 @@
1 import { LETTER_MAX_BODY_CHARS, itemDefinition, itemDisplayName } from "../definitions/items.js";
2 import { formatGiftItemBullet, QUESTWARD_GIFT_AUTHOR, QUESTWARD_GIFT_ORG } from "./giftLetters.js";
3
4 export { QUESTWARD_GIFT_AUTHOR, QUESTWARD_GIFT_ORG };
5
6 /**
7 * Bank letter when quest completion rewards land in the vault.
8 * Signature is applied separately via author fields (John Questward / CEO).
9 */
10 export function formatQuestBankRewardLetterBody ({
11 characterDisplayName,
12 questTitle,
13 items = []
14 })
15 {
16 const name = String(characterDisplayName ?? "").trim() || "Adventurer";
17 const title = String(questTitle ?? "").trim() || "a quest";
18 const lines = (items ?? []).map((row) =>
19 {
20 const def = row.itemId != null ? itemDefinition(row.itemId) : null;
21 const displayName = row.displayName
22 ?? (def ? itemDisplayName({ itemId: row.itemId, quantity: row.quantity }, def) : null)
23 ?? def?.displayName
24 ?? `Item ${row.itemId ?? "?"}`;
25 return formatGiftItemBullet({ displayName, quantity: row.quantity });
26 });
27 const itemBlock = lines.length
28 ? lines.join("\n")
29 : "• (no items)";
30 return [
31 `Dear ${name},`,
32 "",
33 `Congratulations on your completion of the quest ${title}.`,
34 "The following rewards have been added to your bank:",
35 itemBlock
36 ].join("\n").slice(0, LETTER_MAX_BODY_CHARS);
37 }
@@ -0,0 +1,37 @@
1import { LETTER_MAX_BODY_CHARS, itemDefinition, itemDisplayName } from "../definitions/items.js";
2import { formatGiftItemBullet, QUESTWARD_GIFT_AUTHOR, QUESTWARD_GIFT_ORG } from "./giftLetters.js";
3
4export { QUESTWARD_GIFT_AUTHOR, QUESTWARD_GIFT_ORG };
5
6/**
7 * Bank letter when quest completion rewards land in the vault.
8 * Signature is applied separately via author fields (John Questward / CEO).
9 */
10export function formatQuestBankRewardLetterBody ({
11 characterDisplayName,
12 questTitle,
13 items = []
14})
15{
16 const name = String(characterDisplayName ?? "").trim() || "Adventurer";
17 const title = String(questTitle ?? "").trim() || "a quest";
18 const lines = (items ?? []).map((row) =>
19 {
20 const def = row.itemId != null ? itemDefinition(row.itemId) : null;
21 const displayName = row.displayName
22 ?? (def ? itemDisplayName({ itemId: row.itemId, quantity: row.quantity }, def) : null)
23 ?? def?.displayName
24 ?? `Item ${row.itemId ?? "?"}`;
25 return formatGiftItemBullet({ displayName, quantity: row.quantity });
26 });
27 const itemBlock = lines.length
28 ? lines.join("\n")
29 : "• (no items)";
30 return [
31 `Dear ${name},`,
32 "",
33 `Congratulations on your completion of the quest ${title}.`,
34 "The following rewards have been added to your bank:",
35 itemBlock
36 ].join("\n").slice(0, LETTER_MAX_BODY_CHARS);
37}
shared/protocol/constants.js +1 −0
@@ -292,6 +292,7 @@ export const MessageType = Object.freeze({
292 292 requestQuests: "REQUEST_QUESTS",
293 293 questsSnapshot: "QUESTS_SNAPSHOT",
294 294 questStepComplete: "QUEST_STEP_COMPLETE",
295 questComplete: "QUEST_COMPLETE",
295 296 jewelryTeleport: "JEWELRY_TELEPORT",
296 297 tradeRequest: "TRADE_REQUEST",
297 298 tradeRespondInvite: "TRADE_RESPOND_INVITE",
@@ -292,6 +292,7 @@ export const MessageType = Object.freeze({
292 requestQuests: "REQUEST_QUESTS",
292 requestQuests: "REQUEST_QUESTS",
293 questsSnapshot: "QUESTS_SNAPSHOT",
293 questsSnapshot: "QUESTS_SNAPSHOT",
294 questStepComplete: "QUEST_STEP_COMPLETE",
294 questStepComplete: "QUEST_STEP_COMPLETE",
295 questComplete: "QUEST_COMPLETE",
295 jewelryTeleport: "JEWELRY_TELEPORT",
296 jewelryTeleport: "JEWELRY_TELEPORT",
296 tradeRequest: "TRADE_REQUEST",
297 tradeRequest: "TRADE_REQUEST",
297 tradeRespondInvite: "TRADE_RESPOND_INVITE",
298 tradeRespondInvite: "TRADE_RESPOND_INVITE",
shared/quests/conditions.js +41 −1
@@ -218,7 +218,47 @@ export function normalizeEffects (raw)
218 218 const kind = String(entry.kind ?? "").trim();
219 219 if (!Object.values(EffectKind).includes(kind))
220 220 { continue; }
221 out.push({ ...entry, kind });
221 if (kind === EffectKind.giveItem)
222 {
223 const itemId = Number(entry.itemId);
224 if (!Number.isFinite(itemId) || itemId <= 0)
225 { continue; }
226 out.push({
227 kind,
228 itemId: itemId | 0,
229 quantity: Math.max(1, Math.min(99_999, Number(entry.quantity) || 1)) | 0,
230 toBank: !!entry.toBank
231 });
232 continue;
233 }
234 if (kind === EffectKind.giveXp)
235 {
236 const skillId = String(entry.skillId ?? "").trim();
237 const amount = Math.max(0, Math.min(10_000_000, Number(entry.amount) || 0)) | 0;
238 if (!skillId || amount <= 0)
239 { continue; }
240 out.push({ kind, skillId, amount });
241 continue;
242 }
243 if (kind === EffectKind.takeItem)
244 {
245 const itemId = Number(entry.itemId);
246 if (!Number.isFinite(itemId) || itemId <= 0)
247 { continue; }
248 out.push({
249 kind,
250 itemId: itemId | 0,
251 quantity: Math.max(1, Math.min(99_999, Number(entry.quantity) || 1)) | 0
252 });
253 continue;
254 }
255 if (kind === EffectKind.startQuest)
256 {
257 const questId = String(entry.questId ?? "").trim().slice(0, 80);
258 if (!questId)
259 { continue; }
260 out.push({ kind, questId });
261 }
222 262 }
223 263 return out;
224 264 }
@@ -218,7 +218,47 @@ export function normalizeEffects (raw)
218 const kind = String(entry.kind ?? "").trim();
218 const kind = String(entry.kind ?? "").trim();
219 if (!Object.values(EffectKind).includes(kind))
219 if (!Object.values(EffectKind).includes(kind))
220 { continue; }
220 { continue; }
221 out.push({ ...entry, kind });
221 if (kind === EffectKind.giveItem)
222 {
223 const itemId = Number(entry.itemId);
224 if (!Number.isFinite(itemId) || itemId <= 0)
225 { continue; }
226 out.push({
227 kind,
228 itemId: itemId | 0,
229 quantity: Math.max(1, Math.min(99_999, Number(entry.quantity) || 1)) | 0,
230 toBank: !!entry.toBank
231 });
232 continue;
233 }
234 if (kind === EffectKind.giveXp)
235 {
236 const skillId = String(entry.skillId ?? "").trim();
237 const amount = Math.max(0, Math.min(10_000_000, Number(entry.amount) || 0)) | 0;
238 if (!skillId || amount <= 0)
239 { continue; }
240 out.push({ kind, skillId, amount });
241 continue;
242 }
243 if (kind === EffectKind.takeItem)
244 {
245 const itemId = Number(entry.itemId);
246 if (!Number.isFinite(itemId) || itemId <= 0)
247 { continue; }
248 out.push({
249 kind,
250 itemId: itemId | 0,
251 quantity: Math.max(1, Math.min(99_999, Number(entry.quantity) || 1)) | 0
252 });
253 continue;
254 }
255 if (kind === EffectKind.startQuest)
256 {
257 const questId = String(entry.questId ?? "").trim().slice(0, 80);
258 if (!questId)
259 { continue; }
260 out.push({ kind, questId });
261 }
222 }
262 }
223 return out;
263 return out;
224}
264}