BlueGit

timfa questward

Add shopkeeper NPCs and the wood/metal pickaxe craft chain.

Humanoid spawners sell stock at marketplace-style prices; woodworking and anvil stations turn tinted logs, handles, and bars into tiered pickaxes.

timfa Tim Falken · pushed by timfa

Authored 2026-08-25 · 2 months ago

Hash
3f4548bec72cd3148456d824519da7eb0c48c815
Parent
8cdfc957
39 files changed +1889 −165
client/assets/blocks/anvil/anvil.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/woodworking-bench/woodworking-bench.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/wood/handle.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/wood/log.png added Binary file +0 −0

The contents of this binary file are not shown.

client/index.html +11 −0
@@ -15,6 +15,7 @@
15 15 <button id="bag-toggle" type="button">Bag</button>
16 16 <button id="leave" type="button">Leave world</button>
17 17 </div>
18 <div id="toast-stack" aria-live="polite"></div>
18 19 <aside id="bag-panel" hidden>
19 20 <h2>Bag</h2>
20 21 <p id="bag-coins" hidden>0 coins</p>
@@ -172,6 +173,16 @@
172 173 </div>
173 174 </aside>
174 175
176 <div id="shop-backdrop" class="modal-backdrop" hidden></div>
177 <aside id="shop-panel" hidden>
178 <header>
179 <h2 id="shop-title">Shop</h2>
180 <button id="shop-close" type="button">Close</button>
181 </header>
182 <div id="shop-stock" class="shop-stock"></div>
183 <p id="shop-status" class="hint"></p>
184 </aside>
185
175 186 <div id="cauldron-backdrop" class="modal-backdrop" hidden></div>
176 187 <aside id="cauldron-panel" hidden>
177 188 <header>
@@ -15,6 +15,7 @@
15 <button id="bag-toggle" type="button">Bag</button>
15 <button id="bag-toggle" type="button">Bag</button>
16 <button id="leave" type="button">Leave world</button>
16 <button id="leave" type="button">Leave world</button>
17 </div>
17 </div>
18 <div id="toast-stack" aria-live="polite"></div>
18 <aside id="bag-panel" hidden>
19 <aside id="bag-panel" hidden>
19 <h2>Bag</h2>
20 <h2>Bag</h2>
20 <p id="bag-coins" hidden>0 coins</p>
21 <p id="bag-coins" hidden>0 coins</p>
@@ -172,6 +173,16 @@
172 </div>
173 </div>
173 </aside>
174 </aside>
174
175
176 <div id="shop-backdrop" class="modal-backdrop" hidden></div>
177 <aside id="shop-panel" hidden>
178 <header>
179 <h2 id="shop-title">Shop</h2>
180 <button id="shop-close" type="button">Close</button>
181 </header>
182 <div id="shop-stock" class="shop-stock"></div>
183 <p id="shop-status" class="hint"></p>
184 </aside>
185
175 <div id="cauldron-backdrop" class="modal-backdrop" hidden></div>
186 <div id="cauldron-backdrop" class="modal-backdrop" hidden></div>
176 <aside id="cauldron-panel" hidden>
187 <aside id="cauldron-panel" hidden>
177 <header>
188 <header>
client/src/editor/tileConfigModal.js +142 −4
@@ -1,7 +1,32 @@
1 1 /**
2 2 * Right-click config modal for editor tiles that have configurable data (spawners).
3 3 */
4 import { listSpawnableMobTypes, normalizeSpawnerConfig } from "/shared/definitions/mobs.js";
4 import {
5 listSpawnableMobTypes,
6 normalizeSpawnerConfig,
7 MobId,
8 isHumanoidMob
9 } from "/shared/definitions/mobs.js";
10 import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";
11 import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
12
13 const SHOP_STOCK_PRESETS = Object.freeze([
14 { itemId: ItemId.copperOre, label: "Copper ore" },
15 { itemId: ItemId.tinOre, label: "Tin ore" },
16 { itemId: ItemId.coal, label: "Coal" },
17 { itemId: ItemId.ironOre, label: "Iron ore" },
18 { itemId: ItemId.pineLog, label: "Pine log" },
19 { itemId: ItemId.birchLog, label: "Birch log" },
20 { itemId: ItemId.oakLog, label: "Oak log" }
21 ]);
22
23 const EQUIP_PRESETS = Object.freeze([
24 { itemId: ItemId.clothShirt, slot: EQUIPMENT_SLOT.chest },
25 { itemId: ItemId.stick, slot: EQUIPMENT_SLOT.weapon },
26 { itemId: ItemId.bronzePickaxe, slot: EQUIPMENT_SLOT.weapon },
27 { itemId: ItemId.bronzeAxe, slot: EQUIPMENT_SLOT.weapon },
28 { itemId: ItemId.lantern, slot: EQUIPMENT_SLOT.offhand }
29 ]);
5 30
6 31 export function initTileConfigModal ({ onSave, onRemove })
7 32 {
@@ -21,14 +46,64 @@ export function initTileConfigModal ({ onSave, onRemove })
21 46 { context = null; }
22 47 }
23 48
49 function renderHumanoidFields (config)
50 {
51 const wrap = document.createElement("div");
52 wrap.className = "spawner-humanoid-fields";
53 wrap.dataset.humanoid = "1";
54 wrap.append(
55 field("Display name", textInput("displayName", config.displayName || "Shopkeeper")),
56 field("Sex", sexSelect("sex", config.sex))
57 );
58 for (const slot of EQUIPMENT_SLOTS)
59 {
60 wrap.append(field(
61 `Equip ${slot}`,
62 equipSelect(`equipment.${slot}`, slot, config.equipment?.[slot] ?? null)
63 ));
64 }
65 wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
66 const stockLabel = document.createElement("div");
67 stockLabel.textContent = "Sells";
68 stockLabel.style.marginTop = "0.5rem";
69 wrap.append(stockLabel);
70 for (const preset of SHOP_STOCK_PRESETS)
71 {
72 const row = document.createElement("label");
73 row.style.display = "flex";
74 row.style.gap = "0.4rem";
75 row.style.alignItems = "center";
76 const box = document.createElement("input");
77 box.type = "checkbox";
78 box.name = "sells";
79 box.value = String(preset.itemId);
80 box.checked = (config.sells ?? []).includes(preset.itemId);
81 row.append(box, document.createTextNode(preset.label));
82 wrap.append(row);
83 }
84 return wrap;
85 }
86
87 function syncHumanoidSection (config)
88 {
89 form.querySelector("[data-humanoid]")?.remove();
90 const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value;
91 if (!isHumanoidMob(mobTypeId))
92 { return; }
93 form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({
94 mobTypeId: MobId.humanoid
95 }, "spawner")));
96 }
97
24 98 function openSpawner (ctx)
25 99 {
26 100 context = { kind: "spawner", ...ctx };
27 101 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
28 102 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
29 103 form.innerHTML = "";
104 const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));
30 105 form.append(
31 field("Mob type", mobSelect("mobTypeId", config.mobTypeId)),
106 mobField,
32 107 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
33 108 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
34 109 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
@@ -45,6 +120,17 @@ export function initTileConfigModal ({ onSave, onRemove })
45 120 };
46 121 spawnInput.addEventListener("input", syncWanderMin);
47 122 syncWanderMin();
123 form.querySelector('[name="mobTypeId"]').addEventListener("change", () =>
124 {
125 const nextType = form.querySelector('[name="mobTypeId"]').value;
126 const defaults = normalizeSpawnerConfig({ mobTypeId: nextType }, config.spawnerId);
127 form.querySelector('[name="maxAlive"]').value = String(defaults.maxAlive);
128 form.querySelector('[name="spawnRangeTiles"]').value = String(defaults.spawnRangeTiles);
129 form.querySelector('[name="maxWanderRangeTiles"]').value = String(defaults.maxWanderRangeTiles);
130 syncWanderMin();
131 syncHumanoidSection(defaults);
132 });
133 syncHumanoidSection(config);
48 134 show(true);
49 135 }
50 136
@@ -56,12 +142,24 @@ export function initTileConfigModal ({ onSave, onRemove })
56 142 if (!context)
57 143 { return; }
58 144 const data = new FormData(form);
145 const sells = data.getAll("sells").map((value) => Number(value)).filter((id) => id > 0);
146 const equipment = {};
147 for (const slot of EQUIPMENT_SLOTS)
148 {
149 const raw = data.get(`equipment.${slot}`);
150 equipment[slot] = raw ? Number(raw) : null;
151 }
59 152 onSave?.(context, normalizeSpawnerConfig({
60 153 mobTypeId: String(data.get("mobTypeId") || "deer"),
61 154 maxAlive: Number(data.get("maxAlive") || 3),
62 155 spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
63 156 maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
64 spawnerId: String(data.get("spawnerId") || context.config.spawnerId)
157 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
158 sex: String(data.get("sex") || "male"),
159 displayName: String(data.get("displayName") || ""),
160 equipment,
161 sells,
162 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9)
65 163 }, context.config.spawnerId));
66 164 show(false);
67 165 });
@@ -87,13 +185,14 @@ function field (label, input)
87 185 return wrap;
88 186 }
89 187
90 function numberInput (name, value, min, max)
188 function numberInput (name, value, min, max, step = 1)
91 189 {
92 190 const input = document.createElement("input");
93 191 input.type = "number";
94 192 input.name = name;
95 193 input.min = String(min);
96 194 input.max = String(max);
195 input.step = String(step);
97 196 input.value = String(value);
98 197 return input;
99 198 }
@@ -108,6 +207,45 @@ function textInput (name, value, readOnly = false)
108 207 return input;
109 208 }
110 209
210 function sexSelect (name, value)
211 {
212 const select = document.createElement("select");
213 select.name = name;
214 for (const sex of ["male", "female"])
215 {
216 const option = document.createElement("option");
217 option.value = sex;
218 option.textContent = sex;
219 if (sex === value)
220 { option.selected = true; }
221 select.append(option);
222 }
223 return select;
224 }
225
226 function equipSelect (name, slot, value)
227 {
228 const select = document.createElement("select");
229 select.name = name;
230 const none = document.createElement("option");
231 none.value = "";
232 none.textContent = "(none)";
233 select.append(none);
234 for (const preset of EQUIP_PRESETS)
235 {
236 if (preset.slot !== slot)
237 { continue; }
238 const def = itemDefinition(preset.itemId);
239 const option = document.createElement("option");
240 option.value = String(preset.itemId);
241 option.textContent = def?.displayName ?? String(preset.itemId);
242 if (preset.itemId === value)
243 { option.selected = true; }
244 select.append(option);
245 }
246 return select;
247 }
248
111 249 function mobSelect (name, value)
112 250 {
113 251 const select = document.createElement("select");
@@ -1,7 +1,32 @@
1/**
1/**
2 * Right-click config modal for editor tiles that have configurable data (spawners).
2 * Right-click config modal for editor tiles that have configurable data (spawners).
3 */
3 */
4import { listSpawnableMobTypes, normalizeSpawnerConfig } from "/shared/definitions/mobs.js";
4import {
5 listSpawnableMobTypes,
6 normalizeSpawnerConfig,
7 MobId,
8 isHumanoidMob
9} from "/shared/definitions/mobs.js";
10import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";
11import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
12
13const SHOP_STOCK_PRESETS = Object.freeze([
14 { itemId: ItemId.copperOre, label: "Copper ore" },
15 { itemId: ItemId.tinOre, label: "Tin ore" },
16 { itemId: ItemId.coal, label: "Coal" },
17 { itemId: ItemId.ironOre, label: "Iron ore" },
18 { itemId: ItemId.pineLog, label: "Pine log" },
19 { itemId: ItemId.birchLog, label: "Birch log" },
20 { itemId: ItemId.oakLog, label: "Oak log" }
21]);
22
23const EQUIP_PRESETS = Object.freeze([
24 { itemId: ItemId.clothShirt, slot: EQUIPMENT_SLOT.chest },
25 { itemId: ItemId.stick, slot: EQUIPMENT_SLOT.weapon },
26 { itemId: ItemId.bronzePickaxe, slot: EQUIPMENT_SLOT.weapon },
27 { itemId: ItemId.bronzeAxe, slot: EQUIPMENT_SLOT.weapon },
28 { itemId: ItemId.lantern, slot: EQUIPMENT_SLOT.offhand }
29]);
5
30
6export function initTileConfigModal ({ onSave, onRemove })
31export function initTileConfigModal ({ onSave, onRemove })
7{
32{
@@ -21,14 +46,64 @@ export function initTileConfigModal ({ onSave, onRemove })
21 { context = null; }
46 { context = null; }
22 }
47 }
23
48
49 function renderHumanoidFields (config)
50 {
51 const wrap = document.createElement("div");
52 wrap.className = "spawner-humanoid-fields";
53 wrap.dataset.humanoid = "1";
54 wrap.append(
55 field("Display name", textInput("displayName", config.displayName || "Shopkeeper")),
56 field("Sex", sexSelect("sex", config.sex))
57 );
58 for (const slot of EQUIPMENT_SLOTS)
59 {
60 wrap.append(field(
61 `Equip ${slot}`,
62 equipSelect(`equipment.${slot}`, slot, config.equipment?.[slot] ?? null)
63 ));
64 }
65 wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
66 const stockLabel = document.createElement("div");
67 stockLabel.textContent = "Sells";
68 stockLabel.style.marginTop = "0.5rem";
69 wrap.append(stockLabel);
70 for (const preset of SHOP_STOCK_PRESETS)
71 {
72 const row = document.createElement("label");
73 row.style.display = "flex";
74 row.style.gap = "0.4rem";
75 row.style.alignItems = "center";
76 const box = document.createElement("input");
77 box.type = "checkbox";
78 box.name = "sells";
79 box.value = String(preset.itemId);
80 box.checked = (config.sells ?? []).includes(preset.itemId);
81 row.append(box, document.createTextNode(preset.label));
82 wrap.append(row);
83 }
84 return wrap;
85 }
86
87 function syncHumanoidSection (config)
88 {
89 form.querySelector("[data-humanoid]")?.remove();
90 const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value;
91 if (!isHumanoidMob(mobTypeId))
92 { return; }
93 form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({
94 mobTypeId: MobId.humanoid
95 }, "spawner")));
96 }
97
24 function openSpawner (ctx)
98 function openSpawner (ctx)
25 {
99 {
26 context = { kind: "spawner", ...ctx };
100 context = { kind: "spawner", ...ctx };
27 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
101 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
28 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
102 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
29 form.innerHTML = "";
103 form.innerHTML = "";
104 const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));
30 form.append(
105 form.append(
31 field("Mob type", mobSelect("mobTypeId", config.mobTypeId)),
106 mobField,
32 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
107 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
33 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
108 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
34 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
109 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
@@ -45,6 +120,17 @@ export function initTileConfigModal ({ onSave, onRemove })
45 };
120 };
46 spawnInput.addEventListener("input", syncWanderMin);
121 spawnInput.addEventListener("input", syncWanderMin);
47 syncWanderMin();
122 syncWanderMin();
123 form.querySelector('[name="mobTypeId"]').addEventListener("change", () =>
124 {
125 const nextType = form.querySelector('[name="mobTypeId"]').value;
126 const defaults = normalizeSpawnerConfig({ mobTypeId: nextType }, config.spawnerId);
127 form.querySelector('[name="maxAlive"]').value = String(defaults.maxAlive);
128 form.querySelector('[name="spawnRangeTiles"]').value = String(defaults.spawnRangeTiles);
129 form.querySelector('[name="maxWanderRangeTiles"]').value = String(defaults.maxWanderRangeTiles);
130 syncWanderMin();
131 syncHumanoidSection(defaults);
132 });
133 syncHumanoidSection(config);
48 show(true);
134 show(true);
49 }
135 }
50
136
@@ -56,12 +142,24 @@ export function initTileConfigModal ({ onSave, onRemove })
56 if (!context)
142 if (!context)
57 { return; }
143 { return; }
58 const data = new FormData(form);
144 const data = new FormData(form);
145 const sells = data.getAll("sells").map((value) => Number(value)).filter((id) => id > 0);
146 const equipment = {};
147 for (const slot of EQUIPMENT_SLOTS)
148 {
149 const raw = data.get(`equipment.${slot}`);
150 equipment[slot] = raw ? Number(raw) : null;
151 }
59 onSave?.(context, normalizeSpawnerConfig({
152 onSave?.(context, normalizeSpawnerConfig({
60 mobTypeId: String(data.get("mobTypeId") || "deer"),
153 mobTypeId: String(data.get("mobTypeId") || "deer"),
61 maxAlive: Number(data.get("maxAlive") || 3),
154 maxAlive: Number(data.get("maxAlive") || 3),
62 spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
155 spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
63 maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
156 maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
64 spawnerId: String(data.get("spawnerId") || context.config.spawnerId)
157 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
158 sex: String(data.get("sex") || "male"),
159 displayName: String(data.get("displayName") || ""),
160 equipment,
161 sells,
162 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9)
65 }, context.config.spawnerId));
163 }, context.config.spawnerId));
66 show(false);
164 show(false);
67 });
165 });
@@ -87,13 +185,14 @@ function field (label, input)
87 return wrap;
185 return wrap;
88}
186}
89
187
90function numberInput (name, value, min, max)
188function numberInput (name, value, min, max, step = 1)
91{
189{
92 const input = document.createElement("input");
190 const input = document.createElement("input");
93 input.type = "number";
191 input.type = "number";
94 input.name = name;
192 input.name = name;
95 input.min = String(min);
193 input.min = String(min);
96 input.max = String(max);
194 input.max = String(max);
195 input.step = String(step);
97 input.value = String(value);
196 input.value = String(value);
98 return input;
197 return input;
99}
198}
@@ -108,6 +207,45 @@ function textInput (name, value, readOnly = false)
108 return input;
207 return input;
109}
208}
110
209
210function sexSelect (name, value)
211{
212 const select = document.createElement("select");
213 select.name = name;
214 for (const sex of ["male", "female"])
215 {
216 const option = document.createElement("option");
217 option.value = sex;
218 option.textContent = sex;
219 if (sex === value)
220 { option.selected = true; }
221 select.append(option);
222 }
223 return select;
224}
225
226function equipSelect (name, slot, value)
227{
228 const select = document.createElement("select");
229 select.name = name;
230 const none = document.createElement("option");
231 none.value = "";
232 none.textContent = "(none)";
233 select.append(none);
234 for (const preset of EQUIP_PRESETS)
235 {
236 if (preset.slot !== slot)
237 { continue; }
238 const def = itemDefinition(preset.itemId);
239 const option = document.createElement("option");
240 option.value = String(preset.itemId);
241 option.textContent = def?.displayName ?? String(preset.itemId);
242 if (preset.itemId === value)
243 { option.selected = true; }
244 select.append(option);
245 }
246 return select;
247}
248
111function mobSelect (name, value)
249function mobSelect (name, value)
112{
250{
113 const select = document.createElement("select");
251 const select = document.createElement("select");
client/src/play/crafting.js +8 −5
@@ -12,6 +12,7 @@ import {
12 12 hasRecipeInputs,
13 13 recipesForStation
14 14 } from "/shared/crafting/recipes.js";
15 import { craftDurationMs } from "/shared/definitions/gathering.js";
15 16 import { applyItemIcon } from "../render/potionIcon.js";
16 17
17 18 export function initCrafting ({
@@ -175,7 +176,8 @@ export function initCrafting ({
175 176 const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
176 177 if (canStartCraft(slotsSnapshot, recipe, skill))
177 178 {
178 statusEl.textContent = `Crafting takes ${CRAFT_DURATION_MS / 1000} seconds.`;
179 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
180 statusEl.textContent = `Crafting takes ${durationMs / 1000} seconds.`;
179 181 craftButton.disabled = false;
180 182 return;
181 183 }
@@ -207,23 +209,24 @@ export function initCrafting ({
207 209 progressFill.style.width = "0%";
208 210 statusEl.textContent = "Crafting…";
209 211 craftStartedAt = performance.now();
212 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
210 213 socket.send({
211 214 type: MessageType.startCraft,
212 215 stationId,
213 216 recipeId: recipe.recipeId
214 217 });
215 animateProgress();
216 craftTimer = window.setTimeout(() => finishCraft(true), CRAFT_DURATION_MS);
218 animateProgress(durationMs);
219 craftTimer = window.setTimeout(() => finishCraft(true), durationMs);
217 220 }
218 221
219 function animateProgress ()
222 function animateProgress (durationMs)
220 223 {
221 224 const tick = (now) =>
222 225 {
223 226 if (!crafting)
224 227 { return; }
225 228 const elapsed = now - craftStartedAt;
226 const pct = Math.min(100, (elapsed / CRAFT_DURATION_MS) * 100);
229 const pct = Math.min(100, (elapsed / durationMs) * 100);
227 230 progressFill.style.width = `${pct}%`;
228 231 if (pct < 100)
229 232 { craftAnimFrame = requestAnimationFrame(tick); }
@@ -12,6 +12,7 @@ import {
12 hasRecipeInputs,
12 hasRecipeInputs,
13 recipesForStation
13 recipesForStation
14} from "/shared/crafting/recipes.js";
14} from "/shared/crafting/recipes.js";
15import { craftDurationMs } from "/shared/definitions/gathering.js";
15import { applyItemIcon } from "../render/potionIcon.js";
16import { applyItemIcon } from "../render/potionIcon.js";
16
17
17export function initCrafting ({
18export function initCrafting ({
@@ -175,7 +176,8 @@ export function initCrafting ({
175 const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
176 const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
176 if (canStartCraft(slotsSnapshot, recipe, skill))
177 if (canStartCraft(slotsSnapshot, recipe, skill))
177 {
178 {
178 statusEl.textContent = `Crafting takes ${CRAFT_DURATION_MS / 1000} seconds.`;
179 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
180 statusEl.textContent = `Crafting takes ${durationMs / 1000} seconds.`;
179 craftButton.disabled = false;
181 craftButton.disabled = false;
180 return;
182 return;
181 }
183 }
@@ -207,23 +209,24 @@ export function initCrafting ({
207 progressFill.style.width = "0%";
209 progressFill.style.width = "0%";
208 statusEl.textContent = "Crafting…";
210 statusEl.textContent = "Crafting…";
209 craftStartedAt = performance.now();
211 craftStartedAt = performance.now();
212 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
210 socket.send({
213 socket.send({
211 type: MessageType.startCraft,
214 type: MessageType.startCraft,
212 stationId,
215 stationId,
213 recipeId: recipe.recipeId
216 recipeId: recipe.recipeId
214 });
217 });
215 animateProgress();
218 animateProgress(durationMs);
216 craftTimer = window.setTimeout(() => finishCraft(true), CRAFT_DURATION_MS);
219 craftTimer = window.setTimeout(() => finishCraft(true), durationMs);
217 }
220 }
218
221
219 function animateProgress ()
222 function animateProgress (durationMs)
220 {
223 {
221 const tick = (now) =>
224 const tick = (now) =>
222 {
225 {
223 if (!crafting)
226 if (!crafting)
224 { return; }
227 { return; }
225 const elapsed = now - craftStartedAt;
228 const elapsed = now - craftStartedAt;
226 const pct = Math.min(100, (elapsed / CRAFT_DURATION_MS) * 100);
229 const pct = Math.min(100, (elapsed / durationMs) * 100);
227 progressFill.style.width = `${pct}%`;
230 progressFill.style.width = `${pct}%`;
228 if (pct < 100)
231 if (pct < 100)
229 { craftAnimFrame = requestAnimationFrame(tick); }
232 { craftAnimFrame = requestAnimationFrame(tick); }
client/src/play/main.js +68 −8
@@ -12,9 +12,13 @@ import { initAlchemy } from "./alchemy.js";
12 12 import { initStamina } from "./stamina.js";
13 13 import { initContextMenu } from "./contextMenu.js";
14 14 import { initDeath } from "./death.js";
15 import { initToasts } from "./toasts.js";
16 import { initShop } from "./shop.js";
15 17 import { CraftingStationId } from "/shared/definitions/craftingStations.js";
16 18 import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
17 19 import { formatQuantity } from "/shared/items/formatQuantity.js";
20 import { ItemId } from "/shared/definitions/items.js";
21 import { countCoinsInSlots } from "/shared/items/inventory.js";
18 22
19 23 const game = new Game();
20 24 const hud = document.getElementById("hud");
@@ -39,8 +43,10 @@ let alchemy;
39 43 let staminaUi;
40 44 let contextMenu;
41 45 let death;
46 let toasts;
47 let shop;
42 48 let pendingPickup = null;
43 /** @type {{ kind: "bank" | "cauldron" | "furnace" | "mine", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
49 /** @type {{ kind: "bank" | "cauldron" | "station" | "mine", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
44 50 let pendingInteract = null;
45 51 /** Framework can report mousePressed for two frames; latch so one physical click is one command. */
46 52 let leftClickConsumed = false;
@@ -154,9 +160,14 @@ function requestOpenCauldron (tileX, tileY)
154 160 }
155 161
156 162 function requestOpenFurnace (tileX, tileY)
163 {
164 requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY);
165 }
166
167 function requestOpenCraftStation (stationId, tileX, tileY)
157 168 {
158 169 clearAllPendingActions();
159 pendingInteract = { kind: "furnace", tileX, tileY };
170 pendingInteract = { kind: "station", stationId, tileX, tileY };
160 171 const local = view?.entities.get(view.localEntityId);
161 172 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
162 173 { flushPendingInteract(); }
@@ -218,11 +229,14 @@ function flushPendingInteract ()
218 229 return;
219 230 }
220 231
221 if (pendingInteract.kind === "furnace")
232 if (pendingInteract.kind === "station")
222 233 {
223 234 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
224 235 { return; }
225 socket.send({ type: MessageType.openFurnace });
236 socket.send({
237 type: MessageType.openStation,
238 stationId: pendingInteract.stationId
239 });
226 240 clearPendingInteract();
227 241 return;
228 242 }
@@ -348,7 +362,11 @@ function handleLeftClick (mouseX, mouseY)
348 362 else if (isCauldronTile(view, tile.tileX, tile.tileY))
349 363 { requestOpenCauldron(tile.tileX, tile.tileY); }
350 364 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
351 { requestOpenFurnace(tile.tileX, tile.tileY); }
365 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
366 else if (isAnvilTile(view, tile.tileX, tile.tileY))
367 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
368 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
369 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
352 370 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
353 371 { requestMine(tile.tileX, tile.tileY); }
354 372 else
@@ -393,7 +411,7 @@ function handleRightClick (event, mouseX, mouseY)
393 411 if (entity.talkable)
394 412 {
395 413 items.push({
396 label: `Talk to ${targetName}`,
414 label: `Trade with ${targetName}`,
397 415 onSelect: () => requestTalk(entity.entityId)
398 416 });
399 417 }
@@ -447,7 +465,23 @@ function handleRightClick (event, mouseX, mouseY)
447 465 {
448 466 items.push({
449 467 label: "Smelt",
450 onSelect: () => requestOpenFurnace(tile.tileX, tile.tileY)
468 onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY)
469 });
470 }
471
472 if (isAnvilTile(view, tile.tileX, tile.tileY))
473 {
474 items.push({
475 label: "Smith",
476 onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY)
477 });
478 }
479
480 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
481 {
482 items.push({
483 label: "Woodwork",
484 onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY)
451 485 });
452 486 }
453 487
@@ -624,6 +658,15 @@ async function main ()
624 658 }
625 659 });
626 660 staminaUi = initStamina();
661 toasts = initToasts();
662 shop = initShop({
663 socket: { send (payload) { socket.send(payload); } },
664 MessageType,
665 getCoinCount ()
666 {
667 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
668 }
669 });
627 670 chat = initChat({
628 671 socket: { send (payload) { socket.send(payload); } },
629 672 MessageType,
@@ -698,6 +741,7 @@ async function main ()
698 741 inventory?.handleInventory(message);
699 742 crafting?.refresh();
700 743 alchemy?.refresh();
744 shop?.refresh();
701 745 break;
702 746 case MessageType.skills:
703 747 skills?.render(message.skills);
@@ -754,6 +798,9 @@ async function main ()
754 798 if (message.stationId)
755 799 { crafting?.openStation(message.stationId); }
756 800 break;
801 case MessageType.shopOpen:
802 shop?.handleShopOpen(message);
803 break;
757 804 case MessageType.itemBubble:
758 805 chat?.showItemBubble(message);
759 806 break;
@@ -782,7 +829,10 @@ async function main ()
782 829 }
783 830 break;
784 831 case MessageType.error:
785 showError(message.message);
832 if (playing)
833 { toasts?.show(message.message); }
834 else
835 { showError(message.message); }
786 836 social?.showError(message.message);
787 837 break;
788 838 case MessageType.forceLogout:
@@ -872,6 +922,16 @@ function isFurnaceTile (view, tileX, tileY)
872 922 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
873 923 }
874 924
925 function isAnvilTile (view, tileX, tileY)
926 {
927 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
928 }
929
930 function isWoodworkingBenchTile (view, tileX, tileY)
931 {
932 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
933 }
934
875 935 function isOreBoulderTile (view, tileX, tileY)
876 936 {
877 937 const block = blockAt(view, tileX, tileY);
@@ -12,9 +12,13 @@ import { initAlchemy } from "./alchemy.js";
12import { initStamina } from "./stamina.js";
12import { initStamina } from "./stamina.js";
13import { initContextMenu } from "./contextMenu.js";
13import { initContextMenu } from "./contextMenu.js";
14import { initDeath } from "./death.js";
14import { initDeath } from "./death.js";
15import { initToasts } from "./toasts.js";
16import { initShop } from "./shop.js";
15import { CraftingStationId } from "/shared/definitions/craftingStations.js";
17import { CraftingStationId } from "/shared/definitions/craftingStations.js";
16import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
18import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
17import { formatQuantity } from "/shared/items/formatQuantity.js";
19import { formatQuantity } from "/shared/items/formatQuantity.js";
20import { ItemId } from "/shared/definitions/items.js";
21import { countCoinsInSlots } from "/shared/items/inventory.js";
18
22
19const game = new Game();
23const game = new Game();
20const hud = document.getElementById("hud");
24const hud = document.getElementById("hud");
@@ -39,8 +43,10 @@ let alchemy;
39let staminaUi;
43let staminaUi;
40let contextMenu;
44let contextMenu;
41let death;
45let death;
46let toasts;
47let shop;
42let pendingPickup = null;
48let pendingPickup = null;
43/** @type {{ kind: "bank" | "cauldron" | "furnace" | "mine", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
49/** @type {{ kind: "bank" | "cauldron" | "station" | "mine", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
44let pendingInteract = null;
50let pendingInteract = null;
45/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
51/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
46let leftClickConsumed = false;
52let leftClickConsumed = false;
@@ -154,9 +160,14 @@ function requestOpenCauldron (tileX, tileY)
154}
160}
155
161
156function requestOpenFurnace (tileX, tileY)
162function requestOpenFurnace (tileX, tileY)
163{
164 requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY);
165}
166
167function requestOpenCraftStation (stationId, tileX, tileY)
157{
168{
158 clearAllPendingActions();
169 clearAllPendingActions();
159 pendingInteract = { kind: "furnace", tileX, tileY };
170 pendingInteract = { kind: "station", stationId, tileX, tileY };
160 const local = view?.entities.get(view.localEntityId);
171 const local = view?.entities.get(view.localEntityId);
161 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
172 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
162 { flushPendingInteract(); }
173 { flushPendingInteract(); }
@@ -218,11 +229,14 @@ function flushPendingInteract ()
218 return;
229 return;
219 }
230 }
220
231
221 if (pendingInteract.kind === "furnace")
232 if (pendingInteract.kind === "station")
222 {
233 {
223 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
234 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
224 { return; }
235 { return; }
225 socket.send({ type: MessageType.openFurnace });
236 socket.send({
237 type: MessageType.openStation,
238 stationId: pendingInteract.stationId
239 });
226 clearPendingInteract();
240 clearPendingInteract();
227 return;
241 return;
228 }
242 }
@@ -348,7 +362,11 @@ function handleLeftClick (mouseX, mouseY)
348 else if (isCauldronTile(view, tile.tileX, tile.tileY))
362 else if (isCauldronTile(view, tile.tileX, tile.tileY))
349 { requestOpenCauldron(tile.tileX, tile.tileY); }
363 { requestOpenCauldron(tile.tileX, tile.tileY); }
350 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
364 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
351 { requestOpenFurnace(tile.tileX, tile.tileY); }
365 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
366 else if (isAnvilTile(view, tile.tileX, tile.tileY))
367 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
368 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
369 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
352 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
370 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
353 { requestMine(tile.tileX, tile.tileY); }
371 { requestMine(tile.tileX, tile.tileY); }
354 else
372 else
@@ -393,7 +411,7 @@ function handleRightClick (event, mouseX, mouseY)
393 if (entity.talkable)
411 if (entity.talkable)
394 {
412 {
395 items.push({
413 items.push({
396 label: `Talk to ${targetName}`,
414 label: `Trade with ${targetName}`,
397 onSelect: () => requestTalk(entity.entityId)
415 onSelect: () => requestTalk(entity.entityId)
398 });
416 });
399 }
417 }
@@ -447,7 +465,23 @@ function handleRightClick (event, mouseX, mouseY)
447 {
465 {
448 items.push({
466 items.push({
449 label: "Smelt",
467 label: "Smelt",
450 onSelect: () => requestOpenFurnace(tile.tileX, tile.tileY)
468 onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY)
469 });
470 }
471
472 if (isAnvilTile(view, tile.tileX, tile.tileY))
473 {
474 items.push({
475 label: "Smith",
476 onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY)
477 });
478 }
479
480 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
481 {
482 items.push({
483 label: "Woodwork",
484 onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY)
451 });
485 });
452 }
486 }
453
487
@@ -624,6 +658,15 @@ async function main ()
624 }
658 }
625 });
659 });
626 staminaUi = initStamina();
660 staminaUi = initStamina();
661 toasts = initToasts();
662 shop = initShop({
663 socket: { send (payload) { socket.send(payload); } },
664 MessageType,
665 getCoinCount ()
666 {
667 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
668 }
669 });
627 chat = initChat({
670 chat = initChat({
628 socket: { send (payload) { socket.send(payload); } },
671 socket: { send (payload) { socket.send(payload); } },
629 MessageType,
672 MessageType,
@@ -698,6 +741,7 @@ async function main ()
698 inventory?.handleInventory(message);
741 inventory?.handleInventory(message);
699 crafting?.refresh();
742 crafting?.refresh();
700 alchemy?.refresh();
743 alchemy?.refresh();
744 shop?.refresh();
701 break;
745 break;
702 case MessageType.skills:
746 case MessageType.skills:
703 skills?.render(message.skills);
747 skills?.render(message.skills);
@@ -754,6 +798,9 @@ async function main ()
754 if (message.stationId)
798 if (message.stationId)
755 { crafting?.openStation(message.stationId); }
799 { crafting?.openStation(message.stationId); }
756 break;
800 break;
801 case MessageType.shopOpen:
802 shop?.handleShopOpen(message);
803 break;
757 case MessageType.itemBubble:
804 case MessageType.itemBubble:
758 chat?.showItemBubble(message);
805 chat?.showItemBubble(message);
759 break;
806 break;
@@ -782,7 +829,10 @@ async function main ()
782 }
829 }
783 break;
830 break;
784 case MessageType.error:
831 case MessageType.error:
785 showError(message.message);
832 if (playing)
833 { toasts?.show(message.message); }
834 else
835 { showError(message.message); }
786 social?.showError(message.message);
836 social?.showError(message.message);
787 break;
837 break;
788 case MessageType.forceLogout:
838 case MessageType.forceLogout:
@@ -872,6 +922,16 @@ function isFurnaceTile (view, tileX, tileY)
872 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
922 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
873}
923}
874
924
925function isAnvilTile (view, tileX, tileY)
926{
927 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
928}
929
930function isWoodworkingBenchTile (view, tileX, tileY)
931{
932 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
933}
934
875function isOreBoulderTile (view, tileX, tileY)
935function isOreBoulderTile (view, tileX, tileY)
876{
936{
877 const block = blockAt(view, tileX, tileY);
937 const block = blockAt(view, tileX, tileY);
client/src/play/shop.js added +108 −0
@@ -0,0 +1,108 @@
1 import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity
6 } from "/shared/definitions/items.js";
7 import { applyItemIcon } from "../render/potionIcon.js";
8
9 export function initShop ({
10 socket,
11 MessageType,
12 getCoinCount,
13 onError
14 })
15 {
16 const backdrop = document.getElementById("shop-backdrop");
17 const panel = document.getElementById("shop-panel");
18 const title = document.getElementById("shop-title");
19 const list = document.getElementById("shop-stock");
20 const statusEl = document.getElementById("shop-status");
21 let npcEntityId = null;
22 let stock = [];
23
24 document.getElementById("shop-close")?.addEventListener("click", () => close());
25 backdrop?.addEventListener("click", () => close());
26
27 function open (payload)
28 {
29 npcEntityId = payload.npcEntityId | 0;
30 title.textContent = payload.displayName || "Shop";
31 stock = Array.isArray(payload.stock) ? payload.stock : [];
32 statusEl.textContent = "";
33 render();
34 backdrop.hidden = false;
35 panel.hidden = false;
36 }
37
38 function close ()
39 {
40 backdrop.hidden = true;
41 panel.hidden = true;
42 npcEntityId = null;
43 stock = [];
44 }
45
46 function render ()
47 {
48 list.innerHTML = "";
49 if (!stock.length)
50 {
51 list.textContent = "Nothing for sale.";
52 return;
53 }
54 const coins = getCoinCount?.() ?? 0;
55 for (const entry of stock)
56 {
57 const def = itemDefinition(entry.itemId);
58 const row = document.createElement("div");
59 row.className = "shop-row";
60 const img = document.createElement("img");
61 img.alt = entry.displayName ?? def?.displayName ?? "item";
62 applyItemIcon(img, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));
63 const meta = document.createElement("div");
64 meta.className = "shop-row-meta";
65 const name = document.createElement("strong");
66 name.textContent = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });
67 const price = document.createElement("span");
68 price.className = "hint";
69 price.textContent = `${formatQuantity(entry.unitPrice)} coins`;
70 meta.append(name, price);
71 const buy = document.createElement("button");
72 buy.type = "button";
73 buy.textContent = "Buy";
74 buy.disabled = coins < (entry.unitPrice | 0);
75 buy.addEventListener("click", () =>
76 {
77 if (!npcEntityId)
78 { return; }
79 socket.send({
80 type: MessageType.buyFromShop,
81 npcEntityId,
82 itemId: entry.itemId,
83 quantity: 1
84 });
85 });
86 row.append(img, meta, buy);
87 list.append(row);
88 }
89 }
90
91 function handleShopOpen (message)
92 {
93 open(message);
94 }
95
96 function refresh ()
97 {
98 if (npcEntityId != null && !panel.hidden)
99 { render(); }
100 }
101
102 return {
103 handleShopOpen,
104 refresh,
105 close,
106 isOpen: () => !panel.hidden
107 };
108 }
@@ -0,0 +1,108 @@
1import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity
6} from "/shared/definitions/items.js";
7import { applyItemIcon } from "../render/potionIcon.js";
8
9export function initShop ({
10 socket,
11 MessageType,
12 getCoinCount,
13 onError
14})
15{
16 const backdrop = document.getElementById("shop-backdrop");
17 const panel = document.getElementById("shop-panel");
18 const title = document.getElementById("shop-title");
19 const list = document.getElementById("shop-stock");
20 const statusEl = document.getElementById("shop-status");
21 let npcEntityId = null;
22 let stock = [];
23
24 document.getElementById("shop-close")?.addEventListener("click", () => close());
25 backdrop?.addEventListener("click", () => close());
26
27 function open (payload)
28 {
29 npcEntityId = payload.npcEntityId | 0;
30 title.textContent = payload.displayName || "Shop";
31 stock = Array.isArray(payload.stock) ? payload.stock : [];
32 statusEl.textContent = "";
33 render();
34 backdrop.hidden = false;
35 panel.hidden = false;
36 }
37
38 function close ()
39 {
40 backdrop.hidden = true;
41 panel.hidden = true;
42 npcEntityId = null;
43 stock = [];
44 }
45
46 function render ()
47 {
48 list.innerHTML = "";
49 if (!stock.length)
50 {
51 list.textContent = "Nothing for sale.";
52 return;
53 }
54 const coins = getCoinCount?.() ?? 0;
55 for (const entry of stock)
56 {
57 const def = itemDefinition(entry.itemId);
58 const row = document.createElement("div");
59 row.className = "shop-row";
60 const img = document.createElement("img");
61 img.alt = entry.displayName ?? def?.displayName ?? "item";
62 applyItemIcon(img, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));
63 const meta = document.createElement("div");
64 meta.className = "shop-row-meta";
65 const name = document.createElement("strong");
66 name.textContent = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });
67 const price = document.createElement("span");
68 price.className = "hint";
69 price.textContent = `${formatQuantity(entry.unitPrice)} coins`;
70 meta.append(name, price);
71 const buy = document.createElement("button");
72 buy.type = "button";
73 buy.textContent = "Buy";
74 buy.disabled = coins < (entry.unitPrice | 0);
75 buy.addEventListener("click", () =>
76 {
77 if (!npcEntityId)
78 { return; }
79 socket.send({
80 type: MessageType.buyFromShop,
81 npcEntityId,
82 itemId: entry.itemId,
83 quantity: 1
84 });
85 });
86 row.append(img, meta, buy);
87 list.append(row);
88 }
89 }
90
91 function handleShopOpen (message)
92 {
93 open(message);
94 }
95
96 function refresh ()
97 {
98 if (npcEntityId != null && !panel.hidden)
99 { render(); }
100 }
101
102 return {
103 handleShopOpen,
104 refresh,
105 close,
106 isOpen: () => !panel.hidden
107 };
108}
client/src/play/toasts.js added +42 −0
@@ -0,0 +1,42 @@
1 const DEFAULT_DURATION_MS = 3500;
2 const LEAVE_MS = 280;
3
4 /**
5 * Temporary top-of-screen toast messages (play HUD).
6 */
7 export function initToasts ()
8 {
9 const root = document.getElementById("toast-stack");
10 if (!root)
11 {
12 return {
13 show ()
14 {}
15 };
16 }
17
18 function show (message, options = {})
19 {
20 const text = String(message ?? "").trim();
21 if (!text)
22 { return; }
23 const durationMs = Math.max(800, options.durationMs ?? DEFAULT_DURATION_MS);
24 const el = document.createElement("div");
25 el.className = "toast";
26 el.setAttribute("role", "status");
27 el.textContent = text;
28 root.appendChild(el);
29 requestAnimationFrame(() =>
30 {
31 el.classList.add("toast-visible");
32 });
33 window.setTimeout(() =>
34 {
35 el.classList.remove("toast-visible");
36 el.classList.add("toast-leaving");
37 window.setTimeout(() => el.remove(), LEAVE_MS);
38 }, durationMs);
39 }
40
41 return { show };
42 }
@@ -0,0 +1,42 @@
1const DEFAULT_DURATION_MS = 3500;
2const LEAVE_MS = 280;
3
4/**
5 * Temporary top-of-screen toast messages (play HUD).
6 */
7export function initToasts ()
8{
9 const root = document.getElementById("toast-stack");
10 if (!root)
11 {
12 return {
13 show ()
14 {}
15 };
16 }
17
18 function show (message, options = {})
19 {
20 const text = String(message ?? "").trim();
21 if (!text)
22 { return; }
23 const durationMs = Math.max(800, options.durationMs ?? DEFAULT_DURATION_MS);
24 const el = document.createElement("div");
25 el.className = "toast";
26 el.setAttribute("role", "status");
27 el.textContent = text;
28 root.appendChild(el);
29 requestAnimationFrame(() =>
30 {
31 el.classList.add("toast-visible");
32 });
33 window.setTimeout(() =>
34 {
35 el.classList.remove("toast-visible");
36 el.classList.add("toast-leaving");
37 window.setTimeout(() => el.remove(), LEAVE_MS);
38 }, durationMs);
39 }
40
41 return { show };
42}
client/ui/play.css +88 −0
@@ -37,6 +37,45 @@ html, body {
37 37 display: none !important;
38 38 }
39 39
40 #toast-stack {
41 position: fixed;
42 top: 3.4rem;
43 left: 50%;
44 transform: translateX(-50%);
45 z-index: 25;
46 display: flex;
47 flex-direction: column;
48 align-items: center;
49 gap: 0.4rem;
50 pointer-events: none;
51 max-width: min(440px, 92vw);
52 width: max-content;
53 }
54
55 .toast {
56 box-sizing: border-box;
57 width: 100%;
58 background: rgba(12, 14, 18, 0.94);
59 border: 1px solid #4a5568;
60 padding: 0.5rem 0.9rem;
61 font-size: 0.95rem;
62 text-align: center;
63 color: #f0ebe0;
64 opacity: 0;
65 transform: translateY(-8px);
66 transition: opacity 0.22s ease, transform 0.22s ease;
67 }
68
69 .toast.toast-visible {
70 opacity: 1;
71 transform: translateY(0);
72 }
73
74 .toast.toast-leaving {
75 opacity: 0;
76 transform: translateY(-4px);
77 }
78
40 79 .panel {
41 80 width: min(420px, 92vw);
42 81 background: #1a1e26;
@@ -869,6 +908,55 @@ a { color: #d4c48a; }
869 908 user-select: none;
870 909 }
871 910
911 #shop-panel {
912 position: fixed;
913 z-index: 6;
914 top: 50%;
915 left: 50%;
916 transform: translate(-50%, -50%);
917 width: min(420px, 92vw);
918 max-height: min(70vh, 520px);
919 overflow: auto;
920 background: #1a1e26;
921 border: 1px solid #2c3340;
922 padding: 0.75rem 1rem 1rem;
923 }
924
925 #shop-panel header {
926 display: flex;
927 justify-content: space-between;
928 align-items: center;
929 gap: 0.75rem;
930 margin-bottom: 0.75rem;
931 }
932
933 .shop-stock {
934 display: flex;
935 flex-direction: column;
936 gap: 0.5rem;
937 }
938
939 .shop-row {
940 display: grid;
941 grid-template-columns: 32px 1fr auto;
942 gap: 0.65rem;
943 align-items: center;
944 padding: 0.35rem 0.25rem;
945 border-bottom: 1px solid #2c3340;
946 }
947
948 .shop-row img {
949 width: 32px;
950 height: 32px;
951 image-rendering: pixelated;
952 }
953
954 .shop-row-meta {
955 display: flex;
956 flex-direction: column;
957 gap: 0.15rem;
958 }
959
872 960 .chat-bubble {
873 961 position: fixed;
874 962 z-index: 4;
@@ -37,6 +37,45 @@ html, body {
37 display: none !important;
37 display: none !important;
38}
38}
39
39
40#toast-stack {
41 position: fixed;
42 top: 3.4rem;
43 left: 50%;
44 transform: translateX(-50%);
45 z-index: 25;
46 display: flex;
47 flex-direction: column;
48 align-items: center;
49 gap: 0.4rem;
50 pointer-events: none;
51 max-width: min(440px, 92vw);
52 width: max-content;
53}
54
55.toast {
56 box-sizing: border-box;
57 width: 100%;
58 background: rgba(12, 14, 18, 0.94);
59 border: 1px solid #4a5568;
60 padding: 0.5rem 0.9rem;
61 font-size: 0.95rem;
62 text-align: center;
63 color: #f0ebe0;
64 opacity: 0;
65 transform: translateY(-8px);
66 transition: opacity 0.22s ease, transform 0.22s ease;
67}
68
69.toast.toast-visible {
70 opacity: 1;
71 transform: translateY(0);
72}
73
74.toast.toast-leaving {
75 opacity: 0;
76 transform: translateY(-4px);
77}
78
40.panel {
79.panel {
41 width: min(420px, 92vw);
80 width: min(420px, 92vw);
42 background: #1a1e26;
81 background: #1a1e26;
@@ -869,6 +908,55 @@ a { color: #d4c48a; }
869 user-select: none;
908 user-select: none;
870}
909}
871
910
911#shop-panel {
912 position: fixed;
913 z-index: 6;
914 top: 50%;
915 left: 50%;
916 transform: translate(-50%, -50%);
917 width: min(420px, 92vw);
918 max-height: min(70vh, 520px);
919 overflow: auto;
920 background: #1a1e26;
921 border: 1px solid #2c3340;
922 padding: 0.75rem 1rem 1rem;
923}
924
925#shop-panel header {
926 display: flex;
927 justify-content: space-between;
928 align-items: center;
929 gap: 0.75rem;
930 margin-bottom: 0.75rem;
931}
932
933.shop-stock {
934 display: flex;
935 flex-direction: column;
936 gap: 0.5rem;
937}
938
939.shop-row {
940 display: grid;
941 grid-template-columns: 32px 1fr auto;
942 gap: 0.65rem;
943 align-items: center;
944 padding: 0.35rem 0.25rem;
945 border-bottom: 1px solid #2c3340;
946}
947
948.shop-row img {
949 width: 32px;
950 height: 32px;
951 image-rendering: pixelated;
952}
953
954.shop-row-meta {
955 display: flex;
956 flex-direction: column;
957 gap: 0.15rem;
958}
959
872.chat-bubble {
960.chat-bubble {
873 position: fixed;
961 position: fixed;
874 z-index: 4;
962 z-index: 4;
docs/FEATURES.md +14 −14
@@ -228,23 +228,23 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
228 228 ## Equipment tiers and worn stat bonuses
229 229
230 230 **Status:** partial
231 **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. Coal is a gather material (dark gray tint, iron-tier mine gate) with no bar of its own.
232 **Shared sprites + magenta tint:** one base sprite per shape (ore, bar, pickaxe, boulder-ore); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint.
233 **TODO:** full combat gear catalog; woodcutting wood tiers; tooltips.
234 **Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
231 **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; trees/axes later — logs may be bought from NPC shops for now.
232 **Shared sprites + magenta tint:** one base sprite per shape (ore, bar, pickaxe, log, handle, boulder-ore); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint.
233 **TODO:** full combat gear catalog; tree nodes / woodcutting gather; tooltips.
234 **Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
235 235
236 236 ## Gathering, crafting, and production skills
237 237
238 **Status:** partial (mining + smelting live)
239 **Spec:** **Mining:** LMB/RMB on ore boulder (states `bronze-ore` … `dragon-ore`, `coal`). Requires equipped pickaxe with tool rank ≥ resource rank and Mining ≥ mine gate. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX. Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × material rank`, then restores its ore state via runtime `CHUNK_DELTA`. **Smelting:** furnace block opens craft UI; recipes 1 ore → 1 bar except **steel** = 1 iron ore + 1 coal. Smithing XP on success. Server-authoritative `START_CRAFT` / timer. Woodcutting / fishing / other stations later.
240 **Code:** `shared/definitions/gathering.js`, `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`
238 **Status:** partial (mining + smelting + pickaxe craft chain live)
239 **Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX. Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper and **steel** = 1 iron ore + 1 coal. Smithing XP on success. **Pickaxe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head; woodworking assembles matching-tier handle + head → pickaxe (pine↔bronze … elder↔dragon). Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. Woodcutting trees / fishing / other stations later.
240 **Code:** `shared/definitions/gathering.js`, `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/crafting.test.js`
241 241
242 242 ## Crafting stations
243 243
244 **Status:** partial (furnace smelting live; UI shell for others)
245 **Spec:** Furnace block (placeholder sprite) + adjacency craft panel. Recipes in `stationRecipes.js`. Server craft timer = `CRAFT_DURATION_MS` (2s). Other stations still UI/dev only (`__craftDev`).
246 **TODO:** anvil smithing recipes, oven/campfire burn, spinning wheel once sheep exist.
247 **Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace`), `server/src/crafting/service.js`, `client/src/play/crafting.js`
244 **Status:** partial (furnace, anvil, woodworking bench live; UI shell for others)
245 **Spec:** Furnace / anvil / woodworking-bench blocks (anvil & woodworking use furnace placeholder art for now) + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`).
246 **TODO:** oven/campfire burn, spinning wheel once sheep exist; dedicated anvil/woodworking sprites.
247 **Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace` / `anvil` / `woodworkingBench`), `server/src/crafting/service.js`, `client/src/play/crafting.js`
248 248
249 249 ## Stamina and running
250 250
@@ -293,9 +293,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
293 293
294 294 ## Banking, cheques, shops, player-driven marketplace
295 295
296 **Status:** partial
297 **Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. NPC shops and the player marketplace UI remain later; marketplace sell rules for cheques are already enforced in shared item definitions.
298 **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/origins.test.js`
296 **Status:** partial (banks/cheques/origins live; NPC shops sell stock; player marketplace UI later)
297 **Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment slots, `sells[]`, hidden discount) spawn talkable shopkeepers using player body sprites + equipment overlays. Interact / Trade opens a buy panel; prices use `seedValue` with market last-sale lerp × discount (`shared/shop/pricing.js`). Buying stamps shop origin. Player marketplace order book remains later; marketplace sell rules for cheques are already enforced in shared item definitions.
298 **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
299 299
300 300 ## Player scripting hooks
301 301
@@ -228,23 +228,23 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
228## Equipment tiers and worn stat bonuses
228## Equipment tiers and worn stat bonuses
229
229
230**Status:** partial
230**Status:** partial
231**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. Coal is a gather material (dark gray tint, iron-tier mine gate) with no bar of its own.
231**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; trees/axes later — logs may be bought from NPC shops for now.
232**Shared sprites + magenta tint:** one base sprite per shape (ore, bar, pickaxe, boulder-ore); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint.
232**Shared sprites + magenta tint:** one base sprite per shape (ore, bar, pickaxe, log, handle, boulder-ore); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint.
233**TODO:** full combat gear catalog; woodcutting wood tiers; tooltips.
233**TODO:** full combat gear catalog; tree nodes / woodcutting gather; tooltips.
234**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
234**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
235
235
236## Gathering, crafting, and production skills
236## Gathering, crafting, and production skills
237
237
238**Status:** partial (mining + smelting live)
238**Status:** partial (mining + smelting + pickaxe craft chain live)
239**Spec:** **Mining:** LMB/RMB on ore boulder (states `bronze-ore` … `dragon-ore`, `coal`). Requires equipped pickaxe with tool rank ≥ resource rank and Mining ≥ mine gate. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX. Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × material rank`, then restores its ore state via runtime `CHUNK_DELTA`. **Smelting:** furnace block opens craft UI; recipes 1 ore → 1 bar except **steel** = 1 iron ore + 1 coal. Smithing XP on success. Server-authoritative `START_CRAFT` / timer. Woodcutting / fishing / other stations later.
239**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX. Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper and **steel** = 1 iron ore + 1 coal. Smithing XP on success. **Pickaxe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head; woodworking assembles matching-tier handle + head → pickaxe (pine↔bronze … elder↔dragon). Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. Woodcutting trees / fishing / other stations later.
240**Code:** `shared/definitions/gathering.js`, `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`
240**Code:** `shared/definitions/gathering.js`, `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/crafting.test.js`
241
241
242## Crafting stations
242## Crafting stations
243
243
244**Status:** partial (furnace smelting live; UI shell for others)
244**Status:** partial (furnace, anvil, woodworking bench live; UI shell for others)
245**Spec:** Furnace block (placeholder sprite) + adjacency craft panel. Recipes in `stationRecipes.js`. Server craft timer = `CRAFT_DURATION_MS` (2s). Other stations still UI/dev only (`__craftDev`).
245**Spec:** Furnace / anvil / woodworking-bench blocks (anvil & woodworking use furnace placeholder art for now) + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`).
246**TODO:** anvil smithing recipes, oven/campfire burn, spinning wheel once sheep exist.
246**TODO:** oven/campfire burn, spinning wheel once sheep exist; dedicated anvil/woodworking sprites.
247**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace`), `server/src/crafting/service.js`, `client/src/play/crafting.js`
247**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace` / `anvil` / `woodworkingBench`), `server/src/crafting/service.js`, `client/src/play/crafting.js`
248
248
249## Stamina and running
249## Stamina and running
250
250
@@ -293,9 +293,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
293
293
294## Banking, cheques, shops, player-driven marketplace
294## Banking, cheques, shops, player-driven marketplace
295
295
296**Status:** partial
296**Status:** partial (banks/cheques/origins live; NPC shops sell stock; player marketplace UI later)
297**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. NPC shops and the player marketplace UI remain later; marketplace sell rules for cheques are already enforced in shared item definitions.
297**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment slots, `sells[]`, hidden discount) spawn talkable shopkeepers using player body sprites + equipment overlays. Interact / Trade opens a buy panel; prices use `seedValue` with market last-sale lerp × discount (`shared/shop/pricing.js`). Buying stamps shop origin. Player marketplace order book remains later; marketplace sell rules for cheques are already enforced in shared item definitions.
298**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/origins.test.js`
298**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
299
299
300## Player scripting hooks
300## Player scripting hooks
301
301
server/src/assets/spriteCatalog.js +2 −0
@@ -72,6 +72,8 @@ function mobScanDefs ()
72 72 const defs = {};
73 73 for (const def of Object.values(MOB_DEFINITIONS))
74 74 {
75 if (def.usePlayerBody)
76 { continue; }
75 77 const key = def.key ?? def.mobTypeId;
76 78 defs[key] = {
77 79 key,
@@ -72,6 +72,8 @@ function mobScanDefs ()
72 const defs = {};
72 const defs = {};
73 for (const def of Object.values(MOB_DEFINITIONS))
73 for (const def of Object.values(MOB_DEFINITIONS))
74 {
74 {
75 if (def.usePlayerBody)
76 { continue; }
75 const key = def.key ?? def.mobTypeId;
77 const key = def.key ?? def.mobTypeId;
76 defs[key] = {
78 defs[key] = {
77 key,
79 key,
server/src/crafting/service.js +16 −4
@@ -10,9 +10,9 @@ import {
10 10 canCraftFitInventory,
11 11 hasRecipeInputs
12 12 } from "../../../shared/crafting/recipes.js";
13 import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
13 14 import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
14 15 import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
15 import { smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
16 16 import { bagView } from "../items/bags.js";
17 17 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
18 18 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
@@ -51,6 +51,10 @@ function stationBlockType (stationId)
51 51 {
52 52 if (stationId === CraftingStationId.furnace)
53 53 { return BlockType.furnace; }
54 if (stationId === CraftingStationId.anvil)
55 { return BlockType.anvil; }
56 if (stationId === CraftingStationId.woodworkingBench)
57 { return BlockType.woodworkingBench; }
54 58 return null;
55 59 }
56 60
@@ -120,11 +124,12 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
120 124 }
121 125
122 126 const sessions = ensureCraftSessions(world);
127 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
123 128 sessions.set(characterId, {
124 129 sessionId,
125 130 stationId,
126 131 recipeId,
127 finishesAt: now + CRAFT_DURATION_MS
132 finishesAt: now + durationMs
128 133 });
129 134 const events = [];
130 135 if (blockType)
@@ -139,6 +144,13 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
139 144 itemId: recipe.output.itemId,
140 145 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
141 146 });
147 events.push({
148 type: "craft-started",
149 sessionId,
150 characterId,
151 recipeId,
152 durationMs
153 });
142 154 return { events };
143 155 }
144 156
@@ -273,9 +285,9 @@ export function stepCrafting (world, now)
273 285 inventory.slots = added.slots;
274 286
275 287 let skillsChanged = false;
276 if (skills?.xp && recipe.xpMaterial && stationDef.skillId === SkillId.smithing)
288 if (skills?.xp && recipe.xpMaterial && stationDef?.skillId)
277 289 {
278 if (addSkillXp(skills, SkillId.smithing, smeltingXpForMaterial(recipe.xpMaterial)))
290 if (addSkillXp(skills, stationDef.skillId, smeltingXpForMaterial(recipe.xpMaterial)))
279 291 { skillsChanged = true; }
280 292 }
281 293
@@ -10,9 +10,9 @@ import {
10 canCraftFitInventory,
10 canCraftFitInventory,
11 hasRecipeInputs
11 hasRecipeInputs
12} from "../../../shared/crafting/recipes.js";
12} from "../../../shared/crafting/recipes.js";
13import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
13import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
14import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
14import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
15import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
15import { smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
16import { bagView } from "../items/bags.js";
16import { bagView } from "../items/bags.js";
17import { tileToChunk, tileToLocal } from "../world/coordinates.js";
17import { tileToChunk, tileToLocal } from "../world/coordinates.js";
18import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
18import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
@@ -51,6 +51,10 @@ function stationBlockType (stationId)
51{
51{
52 if (stationId === CraftingStationId.furnace)
52 if (stationId === CraftingStationId.furnace)
53 { return BlockType.furnace; }
53 { return BlockType.furnace; }
54 if (stationId === CraftingStationId.anvil)
55 { return BlockType.anvil; }
56 if (stationId === CraftingStationId.woodworkingBench)
57 { return BlockType.woodworkingBench; }
54 return null;
58 return null;
55}
59}
56
60
@@ -120,11 +124,12 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
120 }
124 }
121
125
122 const sessions = ensureCraftSessions(world);
126 const sessions = ensureCraftSessions(world);
127 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
123 sessions.set(characterId, {
128 sessions.set(characterId, {
124 sessionId,
129 sessionId,
125 stationId,
130 stationId,
126 recipeId,
131 recipeId,
127 finishesAt: now + CRAFT_DURATION_MS
132 finishesAt: now + durationMs
128 });
133 });
129 const events = [];
134 const events = [];
130 if (blockType)
135 if (blockType)
@@ -139,6 +144,13 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
139 itemId: recipe.output.itemId,
144 itemId: recipe.output.itemId,
140 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
145 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
141 });
146 });
147 events.push({
148 type: "craft-started",
149 sessionId,
150 characterId,
151 recipeId,
152 durationMs
153 });
142 return { events };
154 return { events };
143}
155}
144
156
@@ -273,9 +285,9 @@ export function stepCrafting (world, now)
273 inventory.slots = added.slots;
285 inventory.slots = added.slots;
274
286
275 let skillsChanged = false;
287 let skillsChanged = false;
276 if (skills?.xp && recipe.xpMaterial && stationDef.skillId === SkillId.smithing)
288 if (skills?.xp && recipe.xpMaterial && stationDef?.skillId)
277 {
289 {
278 if (addSkillXp(skills, SkillId.smithing, smeltingXpForMaterial(recipe.xpMaterial)))
290 if (addSkillXp(skills, stationDef.skillId, smeltingXpForMaterial(recipe.xpMaterial)))
279 { skillsChanged = true; }
291 { skillsChanged = true; }
280 }
292 }
281
293
server/src/ecs/components.js +2 −1
@@ -19,5 +19,6 @@ export const Component = Object.freeze({
19 19 follow: "follow",
20 20 dead: "dead",
21 21 stamina: "stamina",
22 gather: "gather"
22 gather: "gather",
23 shop: "shop"
23 24 });
@@ -19,5 +19,6 @@ export const Component = Object.freeze({
19 follow: "follow",
19 follow: "follow",
20 dead: "dead",
20 dead: "dead",
21 stamina: "stamina",
21 stamina: "stamina",
22 gather: "gather"
22 gather: "gather",
23 shop: "shop"
23});
24});
server/src/ecs/serialize.js +1 −1
@@ -83,7 +83,7 @@ export function publicEntityView (ecs, entityId)
83 83 mobTypeId: creature?.mobTypeId ?? null,
84 84 canFight: mob ? mobCanFight(mob) : !!character,
85 85 hostile: !!mob?.hostile,
86 talkable: !!mob?.talkable,
86 talkable: !!mob?.talkable || !!ecs.get(handle, Component.shop)?.stock?.length,
87 87 untargetable: !!mob?.untargetable,
88 88 freeFlight: !!mob?.freeFlight,
89 89 health: health ? health.current : undefined,
@@ -83,7 +83,7 @@ export function publicEntityView (ecs, entityId)
83 mobTypeId: creature?.mobTypeId ?? null,
83 mobTypeId: creature?.mobTypeId ?? null,
84 canFight: mob ? mobCanFight(mob) : !!character,
84 canFight: mob ? mobCanFight(mob) : !!character,
85 hostile: !!mob?.hostile,
85 hostile: !!mob?.hostile,
86 talkable: !!mob?.talkable,
86 talkable: !!mob?.talkable || !!ecs.get(handle, Component.shop)?.stock?.length,
87 untargetable: !!mob?.untargetable,
87 untargetable: !!mob?.untargetable,
88 freeFlight: !!mob?.freeFlight,
88 freeFlight: !!mob?.freeFlight,
89 health: health ? health.current : undefined,
89 health: health ? health.current : undefined,
server/src/gateway/websocket.js +40 −1
@@ -3,7 +3,7 @@ import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3 3 import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4 4 import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5 5 import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
6 import { CraftingStationId } from "../../../shared/definitions/craftingStations.js";
6 import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7 7 import { publicSkillsView } from "../../../shared/skills/state.js";
8 8
9 9 let nextSessionId = 1;
@@ -208,6 +208,21 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
208 208 stationId: CraftingStationId.furnace
209 209 });
210 210 break;
211 case MessageType.openStation:
212 {
213 requirePlaying(session);
214 const stationId = typeof message.stationId === "string"
215 ? message.stationId
216 : null;
217 if (!stationId || !craftingStationDefinition(stationId))
218 { break; }
219 simulation.enqueue(session.id, {
220 type: "open-station",
221 characterId: session.characterId,
222 stationId
223 });
224 break;
225 }
211 226 case MessageType.mine:
212 227 requirePlaying(session);
213 228 simulation.enqueue(session.id, {
@@ -380,6 +395,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
380 395 targetEntityId: message.targetEntityId | 0
381 396 });
382 397 break;
398 case MessageType.buyFromShop:
399 requirePlaying(session);
400 simulation.enqueue(session.id, {
401 type: "buy-from-shop",
402 characterId: session.characterId,
403 npcEntityId: message.npcEntityId | 0,
404 itemId: message.itemId | 0,
405 quantity: message.quantity | 0 || 1
406 });
407 break;
383 408 case MessageType.follow:
384 409 requirePlaying(session);
385 410 simulation.enqueue(session.id, {
@@ -812,6 +837,20 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
812 837 }
813 838 continue;
814 839 }
840 if (event.type === "shop-open")
841 {
842 const session = sessions.get(event.sessionId);
843 if (session)
844 {
845 send(session, {
846 type: MessageType.shopOpen,
847 npcEntityId: event.npcEntityId,
848 displayName: event.displayName,
849 stock: event.stock ?? []
850 });
851 }
852 continue;
853 }
815 854 if (event.type === "item-bubble")
816 855 {
817 856 broadcastItemBubble(
@@ -3,7 +3,7 @@ import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
3import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
4import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
5import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
6import { CraftingStationId } from "../../../shared/definitions/craftingStations.js";
6import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7import { publicSkillsView } from "../../../shared/skills/state.js";
7import { publicSkillsView } from "../../../shared/skills/state.js";
8
8
9let nextSessionId = 1;
9let nextSessionId = 1;
@@ -208,6 +208,21 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
208 stationId: CraftingStationId.furnace
208 stationId: CraftingStationId.furnace
209 });
209 });
210 break;
210 break;
211 case MessageType.openStation:
212 {
213 requirePlaying(session);
214 const stationId = typeof message.stationId === "string"
215 ? message.stationId
216 : null;
217 if (!stationId || !craftingStationDefinition(stationId))
218 { break; }
219 simulation.enqueue(session.id, {
220 type: "open-station",
221 characterId: session.characterId,
222 stationId
223 });
224 break;
225 }
211 case MessageType.mine:
226 case MessageType.mine:
212 requirePlaying(session);
227 requirePlaying(session);
213 simulation.enqueue(session.id, {
228 simulation.enqueue(session.id, {
@@ -380,6 +395,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
380 targetEntityId: message.targetEntityId | 0
395 targetEntityId: message.targetEntityId | 0
381 });
396 });
382 break;
397 break;
398 case MessageType.buyFromShop:
399 requirePlaying(session);
400 simulation.enqueue(session.id, {
401 type: "buy-from-shop",
402 characterId: session.characterId,
403 npcEntityId: message.npcEntityId | 0,
404 itemId: message.itemId | 0,
405 quantity: message.quantity | 0 || 1
406 });
407 break;
383 case MessageType.follow:
408 case MessageType.follow:
384 requirePlaying(session);
409 requirePlaying(session);
385 simulation.enqueue(session.id, {
410 simulation.enqueue(session.id, {
@@ -812,6 +837,20 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
812 }
837 }
813 continue;
838 continue;
814 }
839 }
840 if (event.type === "shop-open")
841 {
842 const session = sessions.get(event.sessionId);
843 if (session)
844 {
845 send(session, {
846 type: MessageType.shopOpen,
847 npcEntityId: event.npcEntityId,
848 displayName: event.displayName,
849 stock: event.stock ?? []
850 });
851 }
852 continue;
853 }
815 if (event.type === "item-bubble")
854 if (event.type === "item-bubble")
816 {
855 {
817 broadcastItemBubble(
856 broadcastItemBubble(
server/src/gathering/service.js +18 −23
@@ -1,17 +1,16 @@
1 1 import { Component } from "../ecs/components.js";
2 2 import { BlockType } from "../../../shared/definitions/tiles.js";
3 3 import { itemDefinition } from "../../../shared/definitions/items.js";
4 import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
5 import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
4 import { SkillId } from "../../../shared/definitions/skills.js";
6 5 import {
7 6 materialFromOreBoulderState,
8 canMineMaterial,
9 7 oreItemIdForMaterial,
10 8 miningDurationMs,
11 9 miningXpForMaterial,
12 10 oreExhaustDurationMs,
13 11 oreBoulderState,
14 EXHAUSTED_ORE_BOULDER_STATE
12 EXHAUSTED_ORE_BOULDER_STATE,
13 resolveMiningPickaxe
15 14 } from "../../../shared/definitions/gathering.js";
16 15 import { insertStack } from "../../../shared/items/inventory.js";
17 16 import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
@@ -67,16 +66,17 @@ function setBoulderState (world, tileX, tileY, state)
67 66 };
68 67 }
69 68
70 function equippedPickaxe (ecs, handle)
69 function pickaxeForOre (world, handle, materialId)
71 70 {
72 const equipment = ecs.get(handle, Component.equipment);
73 const stack = equipment?.slots?.weapon;
74 if (!stack?.itemId)
75 { return null; }
76 const def = itemDefinition(stack.itemId);
77 if (def?.equipment?.kind !== EquipmentKind.pickaxeTool)
78 { return null; }
79 return { stack, def, tier: def.equipment.tier };
71 const inventory = world.ecs.get(handle, Component.inventory);
72 const equipment = world.ecs.get(handle, Component.equipment);
73 const skills = world.ecs.get(handle, Component.skills);
74 return resolveMiningPickaxe({
75 inventorySlots: inventory?.slots,
76 equipmentSlots: equipment?.slots,
77 skills,
78 materialId
79 });
80 80 }
81 81
82 82 function clearGather (ecs, handle)
@@ -153,17 +153,11 @@ export function startMine (world, sessionId, characterId, tileX, tileY, now)
153 153 ? "That rock is exhausted."
154 154 : "That rock has no ore."); }
155 155
156 const pickaxe = equippedPickaxe(world.ecs, handle);
157 if (!pickaxe)
158 { throw userError("Equip a pickaxe to mine."); }
159
160 const skills = world.ecs.get(handle, Component.skills);
161 const miningLevel = skillLevel(skills, SkillId.mining);
162 const gate = canMineMaterial(miningLevel, pickaxe.tier, materialId);
163 if (!gate.ok)
164 { throw userError(gate.reason); }
156 const pickaxe = pickaxeForOre(world, handle, materialId);
157 if (!pickaxe.ok)
158 { throw userError(pickaxe.reason); }
165 159
166 const durationMs = miningDurationMs(materialId, pickaxe.tier);
160 const durationMs = miningDurationMs(materialId, pickaxe.tool.tier);
167 161 clearEngage(world.ecs, entityId);
168 162 const path = world.ecs.get(handle, Component.path);
169 163 if (path)
@@ -173,6 +167,7 @@ export function startMine (world, sessionId, characterId, tileX, tileY, now)
173 167 tileX,
174 168 tileY,
175 169 materialId,
170 toolTier: pickaxe.tool.tier,
176 171 startedAt: now,
177 172 finishesAt: now + durationMs,
178 173 nextSwingAt: now
@@ -1,17 +1,16 @@
1import { Component } from "../ecs/components.js";
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { itemDefinition } from "../../../shared/definitions/items.js";
3import { itemDefinition } from "../../../shared/definitions/items.js";
4import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
4import { SkillId } from "../../../shared/definitions/skills.js";
5import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6import {
5import {
7 materialFromOreBoulderState,
6 materialFromOreBoulderState,
8 canMineMaterial,
9 oreItemIdForMaterial,
7 oreItemIdForMaterial,
10 miningDurationMs,
8 miningDurationMs,
11 miningXpForMaterial,
9 miningXpForMaterial,
12 oreExhaustDurationMs,
10 oreExhaustDurationMs,
13 oreBoulderState,
11 oreBoulderState,
14 EXHAUSTED_ORE_BOULDER_STATE
12 EXHAUSTED_ORE_BOULDER_STATE,
13 resolveMiningPickaxe
15} from "../../../shared/definitions/gathering.js";
14} from "../../../shared/definitions/gathering.js";
16import { insertStack } from "../../../shared/items/inventory.js";
15import { insertStack } from "../../../shared/items/inventory.js";
17import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
16import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
@@ -67,16 +66,17 @@ function setBoulderState (world, tileX, tileY, state)
67 };
66 };
68}
67}
69
68
70function equippedPickaxe (ecs, handle)
69function pickaxeForOre (world, handle, materialId)
71{
70{
72 const equipment = ecs.get(handle, Component.equipment);
71 const inventory = world.ecs.get(handle, Component.inventory);
73 const stack = equipment?.slots?.weapon;
72 const equipment = world.ecs.get(handle, Component.equipment);
74 if (!stack?.itemId)
73 const skills = world.ecs.get(handle, Component.skills);
75 { return null; }
74 return resolveMiningPickaxe({
76 const def = itemDefinition(stack.itemId);
75 inventorySlots: inventory?.slots,
77 if (def?.equipment?.kind !== EquipmentKind.pickaxeTool)
76 equipmentSlots: equipment?.slots,
78 { return null; }
77 skills,
79 return { stack, def, tier: def.equipment.tier };
78 materialId
79 });
80}
80}
81
81
82function clearGather (ecs, handle)
82function clearGather (ecs, handle)
@@ -153,17 +153,11 @@ export function startMine (world, sessionId, characterId, tileX, tileY, now)
153 ? "That rock is exhausted."
153 ? "That rock is exhausted."
154 : "That rock has no ore."); }
154 : "That rock has no ore."); }
155
155
156 const pickaxe = equippedPickaxe(world.ecs, handle);
156 const pickaxe = pickaxeForOre(world, handle, materialId);
157 if (!pickaxe)
157 if (!pickaxe.ok)
158 { throw userError("Equip a pickaxe to mine."); }
158 { throw userError(pickaxe.reason); }
159
160 const skills = world.ecs.get(handle, Component.skills);
161 const miningLevel = skillLevel(skills, SkillId.mining);
162 const gate = canMineMaterial(miningLevel, pickaxe.tier, materialId);
163 if (!gate.ok)
164 { throw userError(gate.reason); }
165
159
166 const durationMs = miningDurationMs(materialId, pickaxe.tier);
160 const durationMs = miningDurationMs(materialId, pickaxe.tool.tier);
167 clearEngage(world.ecs, entityId);
161 clearEngage(world.ecs, entityId);
168 const path = world.ecs.get(handle, Component.path);
162 const path = world.ecs.get(handle, Component.path);
169 if (path)
163 if (path)
@@ -173,6 +167,7 @@ export function startMine (world, sessionId, characterId, tileX, tileY, now)
173 tileX,
167 tileX,
174 tileY,
168 tileY,
175 materialId,
169 materialId,
170 toolTier: pickaxe.tool.tier,
176 startedAt: now,
171 startedAt: now,
177 finishesAt: now + durationMs,
172 finishesAt: now + durationMs,
178 nextSwingAt: now
173 nextSwingAt: now
server/src/shop/service.js added +190 −0
@@ -0,0 +1,190 @@
1 import { Component } from "../ecs/components.js";
2 import { bagView } from "../items/bags.js";
3 import { itemDefinition } from "../../../shared/definitions/items.js";
4 import { ItemOriginKind, attachOrigins } from "../../../shared/items/origin.js";
5 import {
6 countCoinsInSlots,
7 insertStack,
8 takeCoinsFromSlots
9 } from "../../../shared/items/inventory.js";
10 import { canSellInNpcShop, shopUnitPrice } from "../../../shared/shop/pricing.js";
11 import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
12 import { chebyshev } from "../combat/service.js";
13
14 function userError (message)
15 {
16 const error = new Error(message);
17 error.userFacing = true;
18 return error;
19 }
20
21 function lastSaleFor (world, itemId)
22 {
23 return world.itemLastSales?.get(itemId) ?? null;
24 }
25
26 function shopStockView (world, shop, now)
27 {
28 const lerpDurationMs = world.settings?.shopPriceLerpDurationMs
29 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
30 const stock = [];
31 for (const itemId of shop.stock ?? [])
32 {
33 if (!canSellInNpcShop(itemId))
34 { continue; }
35 const def = itemDefinition(itemId);
36 if (!def)
37 { continue; }
38 stock.push({
39 itemId,
40 displayName: def.displayName,
41 unitPrice: shopUnitPrice(itemId, {
42 lastSale: lastSaleFor(world, itemId),
43 now,
44 lerpDurationMs,
45 hiddenDiscount: shop.hiddenDiscount ?? 1
46 })
47 });
48 }
49 return stock;
50 }
51
52 export function openShop (world, sessionId, characterId, npcEntityId, now = Date.now())
53 {
54 const entityId = world.characterEntities.get(characterId);
55 if (entityId == null)
56 { throw userError("Character is not in the world."); }
57 const handle = world.ecs.handleOf(entityId);
58 const identity = world.ecs.get(handle, Component.networkIdentity);
59 if (!identity || identity.sessionId !== sessionId)
60 { throw userError("Character is not in the world."); }
61 if (world.ecs.has(handle, Component.dead))
62 { throw userError("You are dead."); }
63
64 const npcHandle = world.ecs.handleOf(npcEntityId);
65 if (npcHandle == null)
66 { throw userError("Target is not here."); }
67 const shop = world.ecs.get(npcHandle, Component.shop);
68 if (!shop?.stock?.length)
69 { throw userError("They are not selling anything."); }
70
71 const playerPos = world.ecs.get(handle, Component.position);
72 const npcPos = world.ecs.get(npcHandle, Component.position);
73 if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1)
74 { throw userError("You need to stand next to them."); }
75
76 const appearance = world.ecs.get(npcHandle, Component.appearance);
77 const displayName = shop.displayName
78 || [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")
79 || "Shopkeeper";
80
81 return {
82 events: [{
83 type: "shop-open",
84 sessionId,
85 characterId,
86 npcEntityId,
87 displayName,
88 stock: shopStockView(world, shop, now)
89 }]
90 };
91 }
92
93 export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now())
94 {
95 const entityId = world.characterEntities.get(characterId);
96 if (entityId == null)
97 { throw userError("Character is not in the world."); }
98 const handle = world.ecs.handleOf(entityId);
99 const identity = world.ecs.get(handle, Component.networkIdentity);
100 if (!identity || identity.sessionId !== sessionId)
101 { throw userError("Character is not in the world."); }
102 if (world.ecs.has(handle, Component.dead))
103 { throw userError("You are dead."); }
104
105 const npcHandle = world.ecs.handleOf(npcEntityId);
106 if (npcHandle == null)
107 { throw userError("Target is not here."); }
108 const shop = world.ecs.get(npcHandle, Component.shop);
109 if (!shop?.stock?.includes(itemId | 0))
110 { throw userError("They do not sell that."); }
111 if (!canSellInNpcShop(itemId))
112 { throw userError("That item cannot be sold here."); }
113
114 const playerPos = world.ecs.get(handle, Component.position);
115 const npcPos = world.ecs.get(npcHandle, Component.position);
116 if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1)
117 { throw userError("You need to stand next to them."); }
118
119 const qty = Math.max(1, Math.min(99, quantity | 0 || 1));
120 const def = itemDefinition(itemId);
121 if (!def)
122 { throw userError("Unknown item."); }
123
124 const lerpDurationMs = world.settings?.shopPriceLerpDurationMs
125 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
126 const unitPrice = shopUnitPrice(itemId, {
127 lastSale: lastSaleFor(world, itemId),
128 now,
129 lerpDurationMs,
130 hiddenDiscount: shop.hiddenDiscount ?? 1
131 });
132 const total = unitPrice * qty;
133 const inventory = world.ecs.get(handle, Component.inventory);
134 if (!inventory)
135 { throw userError("No inventory."); }
136 if (countCoinsInSlots(inventory.slots) < total)
137 { throw userError("You cannot afford that."); }
138
139 const paid = takeCoinsFromSlots(inventory.slots, total);
140 if (!paid.ok)
141 { throw userError("You cannot afford that."); }
142
143 const appearance = world.ecs.get(npcHandle, Component.appearance);
144 const displayName = shop.displayName
145 || [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")
146 || "Shopkeeper";
147 const stack = attachOrigins({
148 itemId,
149 quantity: qty,
150 origins: [{
151 origin: { kind: ItemOriginKind.shop, displayName },
152 quantity: qty
153 }]
154 });
155 const added = insertStack(paid.slots, stack, def);
156 if (!added.ok || added.remainder > 0)
157 { throw userError("Not enough bag space."); }
158
159 inventory.slots = added.slots;
160 return {
161 events: [{
162 type: "shop-open",
163 sessionId,
164 characterId,
165 npcEntityId,
166 displayName,
167 stock: shopStockView(world, shop, now)
168 }],
169 private: bagView(world.ecs, handle)
170 };
171 }
172
173 export function handleShopCommand (world, sessionId, command, now)
174 {
175 switch (command.type)
176 {
177 case "buy-from-shop":
178 return buyFromShop(
179 world,
180 sessionId,
181 command.characterId,
182 command.npcEntityId | 0,
183 command.itemId | 0,
184 command.quantity | 0 || 1,
185 now
186 );
187 default:
188 return null;
189 }
190 }
@@ -0,0 +1,190 @@
1import { Component } from "../ecs/components.js";
2import { bagView } from "../items/bags.js";
3import { itemDefinition } from "../../../shared/definitions/items.js";
4import { ItemOriginKind, attachOrigins } from "../../../shared/items/origin.js";
5import {
6 countCoinsInSlots,
7 insertStack,
8 takeCoinsFromSlots
9} from "../../../shared/items/inventory.js";
10import { canSellInNpcShop, shopUnitPrice } from "../../../shared/shop/pricing.js";
11import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
12import { chebyshev } from "../combat/service.js";
13
14function userError (message)
15{
16 const error = new Error(message);
17 error.userFacing = true;
18 return error;
19}
20
21function lastSaleFor (world, itemId)
22{
23 return world.itemLastSales?.get(itemId) ?? null;
24}
25
26function shopStockView (world, shop, now)
27{
28 const lerpDurationMs = world.settings?.shopPriceLerpDurationMs
29 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
30 const stock = [];
31 for (const itemId of shop.stock ?? [])
32 {
33 if (!canSellInNpcShop(itemId))
34 { continue; }
35 const def = itemDefinition(itemId);
36 if (!def)
37 { continue; }
38 stock.push({
39 itemId,
40 displayName: def.displayName,
41 unitPrice: shopUnitPrice(itemId, {
42 lastSale: lastSaleFor(world, itemId),
43 now,
44 lerpDurationMs,
45 hiddenDiscount: shop.hiddenDiscount ?? 1
46 })
47 });
48 }
49 return stock;
50}
51
52export function openShop (world, sessionId, characterId, npcEntityId, now = Date.now())
53{
54 const entityId = world.characterEntities.get(characterId);
55 if (entityId == null)
56 { throw userError("Character is not in the world."); }
57 const handle = world.ecs.handleOf(entityId);
58 const identity = world.ecs.get(handle, Component.networkIdentity);
59 if (!identity || identity.sessionId !== sessionId)
60 { throw userError("Character is not in the world."); }
61 if (world.ecs.has(handle, Component.dead))
62 { throw userError("You are dead."); }
63
64 const npcHandle = world.ecs.handleOf(npcEntityId);
65 if (npcHandle == null)
66 { throw userError("Target is not here."); }
67 const shop = world.ecs.get(npcHandle, Component.shop);
68 if (!shop?.stock?.length)
69 { throw userError("They are not selling anything."); }
70
71 const playerPos = world.ecs.get(handle, Component.position);
72 const npcPos = world.ecs.get(npcHandle, Component.position);
73 if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1)
74 { throw userError("You need to stand next to them."); }
75
76 const appearance = world.ecs.get(npcHandle, Component.appearance);
77 const displayName = shop.displayName
78 || [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")
79 || "Shopkeeper";
80
81 return {
82 events: [{
83 type: "shop-open",
84 sessionId,
85 characterId,
86 npcEntityId,
87 displayName,
88 stock: shopStockView(world, shop, now)
89 }]
90 };
91}
92
93export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now())
94{
95 const entityId = world.characterEntities.get(characterId);
96 if (entityId == null)
97 { throw userError("Character is not in the world."); }
98 const handle = world.ecs.handleOf(entityId);
99 const identity = world.ecs.get(handle, Component.networkIdentity);
100 if (!identity || identity.sessionId !== sessionId)
101 { throw userError("Character is not in the world."); }
102 if (world.ecs.has(handle, Component.dead))
103 { throw userError("You are dead."); }
104
105 const npcHandle = world.ecs.handleOf(npcEntityId);
106 if (npcHandle == null)
107 { throw userError("Target is not here."); }
108 const shop = world.ecs.get(npcHandle, Component.shop);
109 if (!shop?.stock?.includes(itemId | 0))
110 { throw userError("They do not sell that."); }
111 if (!canSellInNpcShop(itemId))
112 { throw userError("That item cannot be sold here."); }
113
114 const playerPos = world.ecs.get(handle, Component.position);
115 const npcPos = world.ecs.get(npcHandle, Component.position);
116 if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1)
117 { throw userError("You need to stand next to them."); }
118
119 const qty = Math.max(1, Math.min(99, quantity | 0 || 1));
120 const def = itemDefinition(itemId);
121 if (!def)
122 { throw userError("Unknown item."); }
123
124 const lerpDurationMs = world.settings?.shopPriceLerpDurationMs
125 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
126 const unitPrice = shopUnitPrice(itemId, {
127 lastSale: lastSaleFor(world, itemId),
128 now,
129 lerpDurationMs,
130 hiddenDiscount: shop.hiddenDiscount ?? 1
131 });
132 const total = unitPrice * qty;
133 const inventory = world.ecs.get(handle, Component.inventory);
134 if (!inventory)
135 { throw userError("No inventory."); }
136 if (countCoinsInSlots(inventory.slots) < total)
137 { throw userError("You cannot afford that."); }
138
139 const paid = takeCoinsFromSlots(inventory.slots, total);
140 if (!paid.ok)
141 { throw userError("You cannot afford that."); }
142
143 const appearance = world.ecs.get(npcHandle, Component.appearance);
144 const displayName = shop.displayName
145 || [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")
146 || "Shopkeeper";
147 const stack = attachOrigins({
148 itemId,
149 quantity: qty,
150 origins: [{
151 origin: { kind: ItemOriginKind.shop, displayName },
152 quantity: qty
153 }]
154 });
155 const added = insertStack(paid.slots, stack, def);
156 if (!added.ok || added.remainder > 0)
157 { throw userError("Not enough bag space."); }
158
159 inventory.slots = added.slots;
160 return {
161 events: [{
162 type: "shop-open",
163 sessionId,
164 characterId,
165 npcEntityId,
166 displayName,
167 stock: shopStockView(world, shop, now)
168 }],
169 private: bagView(world.ecs, handle)
170 };
171}
172
173export function handleShopCommand (world, sessionId, command, now)
174{
175 switch (command.type)
176 {
177 case "buy-from-shop":
178 return buyFromShop(
179 world,
180 sessionId,
181 command.characterId,
182 command.npcEntityId | 0,
183 command.itemId | 0,
184 command.quantity | 0 || 1,
185 now
186 );
187 default:
188 return null;
189 }
190}
server/src/simulation/spawners.js +52 −7
@@ -6,6 +6,8 @@ import {
6 6 mobDefinition,
7 7 mobSpriteName
8 8 } from "../../../shared/definitions/mobs.js";
9 import { emptyEquipment } from "../../../shared/items/inventory.js";
10 import { itemDefinition } from "../../../shared/definitions/items.js";
9 11 import { Component } from "../ecs/components.js";
10 12 import { tileToChunk, tileToRegion } from "../world/coordinates.js";
11 13
@@ -45,7 +47,12 @@ export function collectSpawnRequests (world)
45 47 originTileX: originX,
46 48 originTileY: originY,
47 49 wanderRangeTiles: config.maxWanderRangeTiles,
48 persistent
50 persistent,
51 sex: config.sex,
52 displayName: config.displayName,
53 equipment: config.equipment,
54 sells: config.sells,
55 hiddenDiscount: config.hiddenDiscount
49 56 });
50 57 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
51 58 }
@@ -58,16 +65,27 @@ export function collectSpawnRequests (world)
58 65 export function mobComponents (request)
59 66 {
60 67 const def = mobDefinition(request.mobTypeId) ?? mobDefinition("deer");
68 const sex = request.sex === "female" || request.sex === "male"
69 ? request.sex
70 : (def.sex ?? "male");
71 const displayName = String(request.displayName || def.displayName || "NPC").trim() || def.displayName;
72 const appearance = {
73 sex,
74 firstName: displayName,
75 lastName: ""
76 };
77 if (!def.usePlayerBody)
78 {
79 const sprite = mobSpriteName(def.mobTypeId);
80 if (sprite)
81 { appearance.sprite = sprite; }
82 }
83
61 84 const components = {
62 85 position: { tileX: request.tileX, tileY: request.tileY },
63 86 movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
64 87 path: { tiles: [] },
65 appearance: {
66 sex: def.sex ?? "male",
67 firstName: def.displayName,
68 lastName: "",
69 sprite: mobSpriteName(def.mobTypeId)
70 },
88 appearance,
71 89 creature: { mobTypeId: def.mobTypeId },
72 90 health: { current: def.health ?? 8, max: def.health ?? 8 }
73 91 };
@@ -99,6 +117,33 @@ export function mobComponents (request)
99 117 components.combat = { targetEntityId: null, nextSwingAt: 0 };
100 118 components.skills = { levels: mobSkillLevels(def) };
101 119 }
120
121 const equipmentSlots = emptyEquipment().slots;
122 const authored = request.equipment ?? {};
123 for (const slot of Object.keys(equipmentSlots))
124 {
125 const itemId = authored[slot] | 0;
126 if (!itemId)
127 { continue; }
128 const itemDef = itemDefinition(itemId);
129 if (!itemDef?.equipment || itemDef.equipment.slot !== slot)
130 { continue; }
131 equipmentSlots[slot] = { itemId, quantity: 1 };
132 }
133 if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean))
134 { components.equipment = { slots: equipmentSlots }; }
135
136 const stock = Array.isArray(request.sells) && request.sells.length
137 ? request.sells
138 : [...(def.sells ?? [])];
139 if (stock.length || def.talkable)
140 {
141 components.shop = {
142 stock: stock.map((id) => id | 0).filter((id) => id > 0),
143 hiddenDiscount: Number(request.hiddenDiscount) || 0.9,
144 displayName
145 };
146 }
102 147 return components;
103 148 }
104 149
@@ -6,6 +6,8 @@ import {
6 mobDefinition,
6 mobDefinition,
7 mobSpriteName
7 mobSpriteName
8} from "../../../shared/definitions/mobs.js";
8} from "../../../shared/definitions/mobs.js";
9import { emptyEquipment } from "../../../shared/items/inventory.js";
10import { itemDefinition } from "../../../shared/definitions/items.js";
9import { Component } from "../ecs/components.js";
11import { Component } from "../ecs/components.js";
10import { tileToChunk, tileToRegion } from "../world/coordinates.js";
12import { tileToChunk, tileToRegion } from "../world/coordinates.js";
11
13
@@ -45,7 +47,12 @@ export function collectSpawnRequests (world)
45 originTileX: originX,
47 originTileX: originX,
46 originTileY: originY,
48 originTileY: originY,
47 wanderRangeTiles: config.maxWanderRangeTiles,
49 wanderRangeTiles: config.maxWanderRangeTiles,
48 persistent
50 persistent,
51 sex: config.sex,
52 displayName: config.displayName,
53 equipment: config.equipment,
54 sells: config.sells,
55 hiddenDiscount: config.hiddenDiscount
49 });
56 });
50 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
57 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
51 }
58 }
@@ -58,16 +65,27 @@ export function collectSpawnRequests (world)
58export function mobComponents (request)
65export function mobComponents (request)
59{
66{
60 const def = mobDefinition(request.mobTypeId) ?? mobDefinition("deer");
67 const def = mobDefinition(request.mobTypeId) ?? mobDefinition("deer");
68 const sex = request.sex === "female" || request.sex === "male"
69 ? request.sex
70 : (def.sex ?? "male");
71 const displayName = String(request.displayName || def.displayName || "NPC").trim() || def.displayName;
72 const appearance = {
73 sex,
74 firstName: displayName,
75 lastName: ""
76 };
77 if (!def.usePlayerBody)
78 {
79 const sprite = mobSpriteName(def.mobTypeId);
80 if (sprite)
81 { appearance.sprite = sprite; }
82 }
83
61 const components = {
84 const components = {
62 position: { tileX: request.tileX, tileY: request.tileY },
85 position: { tileX: request.tileX, tileY: request.tileY },
63 movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
86 movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
64 path: { tiles: [] },
87 path: { tiles: [] },
65 appearance: {
88 appearance,
66 sex: def.sex ?? "male",
67 firstName: def.displayName,
68 lastName: "",
69 sprite: mobSpriteName(def.mobTypeId)
70 },
71 creature: { mobTypeId: def.mobTypeId },
89 creature: { mobTypeId: def.mobTypeId },
72 health: { current: def.health ?? 8, max: def.health ?? 8 }
90 health: { current: def.health ?? 8, max: def.health ?? 8 }
73 };
91 };
@@ -99,6 +117,33 @@ export function mobComponents (request)
99 components.combat = { targetEntityId: null, nextSwingAt: 0 };
117 components.combat = { targetEntityId: null, nextSwingAt: 0 };
100 components.skills = { levels: mobSkillLevels(def) };
118 components.skills = { levels: mobSkillLevels(def) };
101 }
119 }
120
121 const equipmentSlots = emptyEquipment().slots;
122 const authored = request.equipment ?? {};
123 for (const slot of Object.keys(equipmentSlots))
124 {
125 const itemId = authored[slot] | 0;
126 if (!itemId)
127 { continue; }
128 const itemDef = itemDefinition(itemId);
129 if (!itemDef?.equipment || itemDef.equipment.slot !== slot)
130 { continue; }
131 equipmentSlots[slot] = { itemId, quantity: 1 };
132 }
133 if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean))
134 { components.equipment = { slots: equipmentSlots }; }
135
136 const stock = Array.isArray(request.sells) && request.sells.length
137 ? request.sells
138 : [...(def.sells ?? [])];
139 if (stock.length || def.talkable)
140 {
141 components.shop = {
142 stock: stock.map((id) => id | 0).filter((id) => id > 0),
143 hiddenDiscount: Number(request.hiddenDiscount) || 0.9,
144 displayName
145 };
146 }
102 return components;
147 return components;
103}
148}
104
149
server/src/simulation/workerWorld.js +8 −0
@@ -38,6 +38,7 @@ import {
38 38 clearOreRespawnsForChunk
39 39 } from "../gathering/service.js";
40 40 import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
41 import { handleShopCommand, openShop } from "../shop/service.js";
41 42 import {
42 43 applyRemoteMeleeSwing,
43 44 clearEngage,
@@ -396,6 +397,9 @@ export class WorkerWorld
396 397 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
397 398 if (craft)
398 399 { return craft; }
400 const shop = handleShopCommand(this, sessionId, command, message.now ?? Date.now());
401 if (shop)
402 { return shop; }
399 403 const alchemy = handleAlchemyCommand(this, sessionId, command);
400 404 if (alchemy)
401 405 { return alchemy; }
@@ -745,12 +749,16 @@ export class WorkerWorld
745 749 }
746 750 const creature = this.ecs.get(targetHandle, Component.creature);
747 751 const def = creature ? mobDefinition(creature.mobTypeId) : null;
752 const shop = this.ecs.get(targetHandle, Component.shop);
753 if (shop?.stock?.length)
754 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
748 755 if (!def?.talkable)
749 756 {
750 757 const error = new Error("They have nothing to say.");
751 758 error.userFacing = true;
752 759 throw error;
753 760 }
761 // Dialogue comes later; talkable NPCs without stock are a no-op for now.
754 762 return { events: [] };
755 763 }
756 764
@@ -38,6 +38,7 @@ import {
38 clearOreRespawnsForChunk
38 clearOreRespawnsForChunk
39} from "../gathering/service.js";
39} from "../gathering/service.js";
40import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
40import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
41import { handleShopCommand, openShop } from "../shop/service.js";
41import {
42import {
42 applyRemoteMeleeSwing,
43 applyRemoteMeleeSwing,
43 clearEngage,
44 clearEngage,
@@ -396,6 +397,9 @@ export class WorkerWorld
396 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
397 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
397 if (craft)
398 if (craft)
398 { return craft; }
399 { return craft; }
400 const shop = handleShopCommand(this, sessionId, command, message.now ?? Date.now());
401 if (shop)
402 { return shop; }
399 const alchemy = handleAlchemyCommand(this, sessionId, command);
403 const alchemy = handleAlchemyCommand(this, sessionId, command);
400 if (alchemy)
404 if (alchemy)
401 { return alchemy; }
405 { return alchemy; }
@@ -745,12 +749,16 @@ export class WorkerWorld
745 }
749 }
746 const creature = this.ecs.get(targetHandle, Component.creature);
750 const creature = this.ecs.get(targetHandle, Component.creature);
747 const def = creature ? mobDefinition(creature.mobTypeId) : null;
751 const def = creature ? mobDefinition(creature.mobTypeId) : null;
752 const shop = this.ecs.get(targetHandle, Component.shop);
753 if (shop?.stock?.length)
754 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
748 if (!def?.talkable)
755 if (!def?.talkable)
749 {
756 {
750 const error = new Error("They have nothing to say.");
757 const error = new Error("They have nothing to say.");
751 error.userFacing = true;
758 error.userFacing = true;
752 throw error;
759 throw error;
753 }
760 }
761 // Dialogue comes later; talkable NPCs without stock are a no-op for now.
754 return { events: [] };
762 return { events: [] };
755 }
763 }
756
764
server/tests/crafting.test.js +112 −12
@@ -4,7 +4,14 @@ import { BlockType, blockDefinition } from "../../shared/definitions/tiles.js";
4 4 import { CraftingStationId, CRAFT_DURATION_MS } from "../../shared/definitions/craftingStations.js";
5 5 import { ItemId } from "../../shared/definitions/items.js";
6 6 import { SkillId } from "../../shared/definitions/skills.js";
7 import { MaterialTier, tierSmeltSkillLevel } from "../../shared/definitions/materialTiers.js";
7 import {
8 MaterialTier,
9 GatherMaterialId,
10 tierSmeltSkillLevel,
11 smeltingDurationMs,
12 associatedBarTier
13 } from "../../shared/definitions/materialTiers.js";
14 import { craftDurationMs } from "../../shared/definitions/gathering.js";
8 15 import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
9 16 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
10 17 import { totalXpForLevel } from "../../shared/skills/progression.js";
@@ -65,18 +72,38 @@ function advanceMs (harness, ms)
65 72 }
66 73 }
67 74
68 test("furnace block and steel recipe exist", () =>
75 test("furnace recipes: bronze is tin+copper; steel is iron+coal", () =>
69 76 {
70 77 assert.equal(blockDefinition(BlockType.furnace)?.key, "furnace");
71 const recipes = recipesForStation(CraftingStationId.furnace);
72 const steel = recipes.find((recipe) => recipe.recipeId === "smelt-steel");
78 const bronze = recipeDefinition("smelt-bronze");
79 assert.deepEqual(bronze.inputs.map((row) => row.itemId).sort(), [
80 ItemId.copperOre,
81 ItemId.tinOre
82 ].sort());
83 assert.equal(bronze.output.itemId, ItemId.bronzeBar);
84 assert.equal(bronze.minSkillLevel, tierSmeltSkillLevel(MaterialTier.bronze));
85
86 const steel = recipesForStation(CraftingStationId.furnace)
87 .find((recipe) => recipe.recipeId === "smelt-steel");
73 88 assert.ok(steel);
74 89 assert.deepEqual(steel.inputs.map((row) => row.itemId).sort(), [
75 90 ItemId.coal,
76 91 ItemId.ironOre
77 92 ].sort());
78 93 assert.equal(steel.output.itemId, ItemId.steelBar);
79 assert.equal(recipeDefinition("smelt-bronze")?.minSkillLevel, tierSmeltSkillLevel(MaterialTier.bronze));
94 });
95
96 test("tin copper coal map to associated bar tiers for smelt duration", () =>
97 {
98 assert.equal(associatedBarTier(GatherMaterialId.tin), MaterialTier.bronze);
99 assert.equal(associatedBarTier(GatherMaterialId.copper), MaterialTier.bronze);
100 assert.equal(associatedBarTier(GatherMaterialId.coal), MaterialTier.steel);
101 assert.equal(smeltingDurationMs(MaterialTier.bronze), 2000);
102 assert.equal(smeltingDurationMs(GatherMaterialId.tin), 2000);
103 assert.equal(smeltingDurationMs(MaterialTier.steel), 6000);
104 assert.equal(smeltingDurationMs(GatherMaterialId.coal), 6000);
105 assert.equal(craftDurationMs(recipeDefinition("smelt-bronze"), CRAFT_DURATION_MS), 2000);
106 assert.equal(craftDurationMs(recipeDefinition("smelt-steel"), CRAFT_DURATION_MS), 6000);
80 107 });
81 108
82 109 test("open furnace near station emits shove and station-open", () =>
@@ -104,7 +131,7 @@ test("open furnace near station emits shove and station-open", () =>
104 131 { harness.close(); }
105 132 });
106 133
107 test("smelting bronze consumes ore, grants bar and Smithing XP", () =>
134 test("smelting bronze consumes tin and copper, grants bar and Smithing XP", () =>
108 135 {
109 136 const harness = makeSimulation({ workerCount: 1 });
110 137 try
@@ -114,7 +141,10 @@ test("smelting bronze consumes ore, grants bar and Smithing XP", () =>
114 141 const record = harness.simulation.entityRecord(playerId);
115 142 const worker = harness.simulation.workers[record.workerId];
116 143 placeFurnace(worker, 9, 8);
117 giveInventory(harness, playerId, [{ itemId: ItemId.bronzeOre, quantity: 1 }]);
144 giveInventory(harness, playerId, [
145 { itemId: ItemId.tinOre, quantity: 1 },
146 { itemId: ItemId.copperOre, quantity: 1 }
147 ]);
118 148
119 149 harness.simulation.enqueue(1, {
120 150 type: "start-craft",
@@ -128,10 +158,11 @@ test("smelting bronze consumes ore, grants bar and Smithing XP", () =>
128 158 event.type === "item-bubble" && event.itemId === ItemId.bronzeBar));
129 159
130 160 const smithingBefore = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
131 advanceMs(harness, CRAFT_DURATION_MS);
161 advanceMs(harness, craftDurationMs(recipeDefinition("smelt-bronze"), CRAFT_DURATION_MS));
132 162
133 163 const bag = harness.simulation.bagOf(playerId);
134 assert.equal(countItem(bag.inventory, ItemId.bronzeOre), 0);
164 assert.equal(countItem(bag.inventory, ItemId.tinOre), 0);
165 assert.equal(countItem(bag.inventory, ItemId.copperOre), 0);
135 166 assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 1);
136 167 const smithingAfter = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
137 168 assert.ok(smithingAfter > smithingBefore);
@@ -163,7 +194,7 @@ test("smelting steel requires iron ore and coal", () =>
163 194 recipeId: "smelt-steel"
164 195 });
165 196 harness.simulation.step();
166 advanceMs(harness, CRAFT_DURATION_MS);
197 advanceMs(harness, craftDurationMs(recipeDefinition("smelt-steel"), CRAFT_DURATION_MS));
167 198
168 199 const bag = harness.simulation.bagOf(playerId);
169 200 assert.equal(countItem(bag.inventory, ItemId.ironOre), 0);
@@ -184,7 +215,7 @@ test("craft rejects missing materials", () =>
184 215 const record = harness.simulation.entityRecord(playerId);
185 216 const worker = harness.simulation.workers[record.workerId];
186 217 placeFurnace(worker, 9, 8);
187 giveInventory(harness, playerId, []);
218 giveInventory(harness, playerId, [{ itemId: ItemId.copperOre, quantity: 1 }]);
188 219
189 220 harness.simulation.enqueue(1, {
190 221 type: "start-craft",
@@ -233,7 +264,10 @@ test("craft rejects furnace recipes when not next to a furnace", () =>
233 264 {
234 265 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
235 266 const playerId = harness.simulation.spawnCharacter(1, character);
236 giveInventory(harness, playerId, [{ itemId: ItemId.bronzeOre, quantity: 1 }]);
267 giveInventory(harness, playerId, [
268 { itemId: ItemId.tinOre, quantity: 1 },
269 { itemId: ItemId.copperOre, quantity: 1 }
270 ]);
237 271
238 272 harness.simulation.enqueue(1, {
239 273 type: "start-craft",
@@ -248,3 +282,69 @@ test("craft rejects furnace recipes when not next to a furnace", () =>
248 282 finally
249 283 { harness.close(); }
250 284 });
285
286 function placeStation (worker, tileX, tileY, typeId, state)
287 {
288 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
289 const localX = tileX % 16;
290 const localY = tileY % 16;
291 data.blocks[localY * 16 + localX] = {
292 typeId,
293 state,
294 config: null
295 };
296 }
297
298 test("bronze pickaxe chain: pine log → handle, bar → head, assemble pickaxe", () =>
299 {
300 const harness = makeSimulation({ workerCount: 1 });
301 try
302 {
303 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
304 const playerId = harness.simulation.spawnCharacter(1, character);
305 const record = harness.simulation.entityRecord(playerId);
306 const worker = harness.simulation.workers[record.workerId];
307 placeStation(worker, 9, 8, BlockType.woodworkingBench, "woodworking-bench");
308 placeStation(worker, 9, 9, BlockType.anvil, "anvil");
309 giveInventory(harness, playerId, [
310 { itemId: ItemId.pineLog, quantity: 1 },
311 { itemId: ItemId.bronzeBar, quantity: 1 }
312 ]);
313
314 harness.simulation.enqueue(1, {
315 type: "start-craft",
316 characterId: character.character_id,
317 stationId: CraftingStationId.woodworkingBench,
318 recipeId: "handle-pine"
319 });
320 advanceMs(harness, craftDurationMs(recipeDefinition("handle-pine"), CRAFT_DURATION_MS));
321 let bag = harness.simulation.bagOf(playerId);
322 assert.equal(countItem(bag.inventory, ItemId.pineHandle), 1);
323 assert.equal(countItem(bag.inventory, ItemId.pineLog), 0);
324
325 harness.simulation.enqueue(1, {
326 type: "start-craft",
327 characterId: character.character_id,
328 stationId: CraftingStationId.anvil,
329 recipeId: "pickaxe-head-bronze"
330 });
331 advanceMs(harness, craftDurationMs(recipeDefinition("pickaxe-head-bronze"), CRAFT_DURATION_MS));
332 bag = harness.simulation.bagOf(playerId);
333 assert.equal(countItem(bag.inventory, ItemId.bronzePickaxeHead), 1);
334 assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 0);
335
336 harness.simulation.enqueue(1, {
337 type: "start-craft",
338 characterId: character.character_id,
339 stationId: CraftingStationId.woodworkingBench,
340 recipeId: "pickaxe-bronze"
341 });
342 advanceMs(harness, craftDurationMs(recipeDefinition("pickaxe-bronze"), CRAFT_DURATION_MS));
343 bag = harness.simulation.bagOf(playerId);
344 assert.equal(countItem(bag.inventory, ItemId.bronzePickaxe), 1);
345 assert.equal(countItem(bag.inventory, ItemId.pineHandle), 0);
346 assert.equal(countItem(bag.inventory, ItemId.bronzePickaxeHead), 0);
347 }
348 finally
349 { harness.close(); }
350 });
@@ -4,7 +4,14 @@ import { BlockType, blockDefinition } from "../../shared/definitions/tiles.js";
4import { CraftingStationId, CRAFT_DURATION_MS } from "../../shared/definitions/craftingStations.js";
4import { CraftingStationId, CRAFT_DURATION_MS } from "../../shared/definitions/craftingStations.js";
5import { ItemId } from "../../shared/definitions/items.js";
5import { ItemId } from "../../shared/definitions/items.js";
6import { SkillId } from "../../shared/definitions/skills.js";
6import { SkillId } from "../../shared/definitions/skills.js";
7import { MaterialTier, tierSmeltSkillLevel } from "../../shared/definitions/materialTiers.js";
7import {
8 MaterialTier,
9 GatherMaterialId,
10 tierSmeltSkillLevel,
11 smeltingDurationMs,
12 associatedBarTier
13} from "../../shared/definitions/materialTiers.js";
14import { craftDurationMs } from "../../shared/definitions/gathering.js";
8import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
15import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
9import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
16import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
10import { totalXpForLevel } from "../../shared/skills/progression.js";
17import { totalXpForLevel } from "../../shared/skills/progression.js";
@@ -65,18 +72,38 @@ function advanceMs (harness, ms)
65 }
72 }
66}
73}
67
74
68test("furnace block and steel recipe exist", () =>
75test("furnace recipes: bronze is tin+copper; steel is iron+coal", () =>
69{
76{
70 assert.equal(blockDefinition(BlockType.furnace)?.key, "furnace");
77 assert.equal(blockDefinition(BlockType.furnace)?.key, "furnace");
71 const recipes = recipesForStation(CraftingStationId.furnace);
78 const bronze = recipeDefinition("smelt-bronze");
72 const steel = recipes.find((recipe) => recipe.recipeId === "smelt-steel");
79 assert.deepEqual(bronze.inputs.map((row) => row.itemId).sort(), [
80 ItemId.copperOre,
81 ItemId.tinOre
82 ].sort());
83 assert.equal(bronze.output.itemId, ItemId.bronzeBar);
84 assert.equal(bronze.minSkillLevel, tierSmeltSkillLevel(MaterialTier.bronze));
85
86 const steel = recipesForStation(CraftingStationId.furnace)
87 .find((recipe) => recipe.recipeId === "smelt-steel");
73 assert.ok(steel);
88 assert.ok(steel);
74 assert.deepEqual(steel.inputs.map((row) => row.itemId).sort(), [
89 assert.deepEqual(steel.inputs.map((row) => row.itemId).sort(), [
75 ItemId.coal,
90 ItemId.coal,
76 ItemId.ironOre
91 ItemId.ironOre
77 ].sort());
92 ].sort());
78 assert.equal(steel.output.itemId, ItemId.steelBar);
93 assert.equal(steel.output.itemId, ItemId.steelBar);
79 assert.equal(recipeDefinition("smelt-bronze")?.minSkillLevel, tierSmeltSkillLevel(MaterialTier.bronze));
94});
95
96test("tin copper coal map to associated bar tiers for smelt duration", () =>
97{
98 assert.equal(associatedBarTier(GatherMaterialId.tin), MaterialTier.bronze);
99 assert.equal(associatedBarTier(GatherMaterialId.copper), MaterialTier.bronze);
100 assert.equal(associatedBarTier(GatherMaterialId.coal), MaterialTier.steel);
101 assert.equal(smeltingDurationMs(MaterialTier.bronze), 2000);
102 assert.equal(smeltingDurationMs(GatherMaterialId.tin), 2000);
103 assert.equal(smeltingDurationMs(MaterialTier.steel), 6000);
104 assert.equal(smeltingDurationMs(GatherMaterialId.coal), 6000);
105 assert.equal(craftDurationMs(recipeDefinition("smelt-bronze"), CRAFT_DURATION_MS), 2000);
106 assert.equal(craftDurationMs(recipeDefinition("smelt-steel"), CRAFT_DURATION_MS), 6000);
80});
107});
81
108
82test("open furnace near station emits shove and station-open", () =>
109test("open furnace near station emits shove and station-open", () =>
@@ -104,7 +131,7 @@ test("open furnace near station emits shove and station-open", () =>
104 { harness.close(); }
131 { harness.close(); }
105});
132});
106
133
107test("smelting bronze consumes ore, grants bar and Smithing XP", () =>
134test("smelting bronze consumes tin and copper, grants bar and Smithing XP", () =>
108{
135{
109 const harness = makeSimulation({ workerCount: 1 });
136 const harness = makeSimulation({ workerCount: 1 });
110 try
137 try
@@ -114,7 +141,10 @@ test("smelting bronze consumes ore, grants bar and Smithing XP", () =>
114 const record = harness.simulation.entityRecord(playerId);
141 const record = harness.simulation.entityRecord(playerId);
115 const worker = harness.simulation.workers[record.workerId];
142 const worker = harness.simulation.workers[record.workerId];
116 placeFurnace(worker, 9, 8);
143 placeFurnace(worker, 9, 8);
117 giveInventory(harness, playerId, [{ itemId: ItemId.bronzeOre, quantity: 1 }]);
144 giveInventory(harness, playerId, [
145 { itemId: ItemId.tinOre, quantity: 1 },
146 { itemId: ItemId.copperOre, quantity: 1 }
147 ]);
118
148
119 harness.simulation.enqueue(1, {
149 harness.simulation.enqueue(1, {
120 type: "start-craft",
150 type: "start-craft",
@@ -128,10 +158,11 @@ test("smelting bronze consumes ore, grants bar and Smithing XP", () =>
128 event.type === "item-bubble" && event.itemId === ItemId.bronzeBar));
158 event.type === "item-bubble" && event.itemId === ItemId.bronzeBar));
129
159
130 const smithingBefore = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
160 const smithingBefore = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
131 advanceMs(harness, CRAFT_DURATION_MS);
161 advanceMs(harness, craftDurationMs(recipeDefinition("smelt-bronze"), CRAFT_DURATION_MS));
132
162
133 const bag = harness.simulation.bagOf(playerId);
163 const bag = harness.simulation.bagOf(playerId);
134 assert.equal(countItem(bag.inventory, ItemId.bronzeOre), 0);
164 assert.equal(countItem(bag.inventory, ItemId.tinOre), 0);
165 assert.equal(countItem(bag.inventory, ItemId.copperOre), 0);
135 assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 1);
166 assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 1);
136 const smithingAfter = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
167 const smithingAfter = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
137 assert.ok(smithingAfter > smithingBefore);
168 assert.ok(smithingAfter > smithingBefore);
@@ -163,7 +194,7 @@ test("smelting steel requires iron ore and coal", () =>
163 recipeId: "smelt-steel"
194 recipeId: "smelt-steel"
164 });
195 });
165 harness.simulation.step();
196 harness.simulation.step();
166 advanceMs(harness, CRAFT_DURATION_MS);
197 advanceMs(harness, craftDurationMs(recipeDefinition("smelt-steel"), CRAFT_DURATION_MS));
167
198
168 const bag = harness.simulation.bagOf(playerId);
199 const bag = harness.simulation.bagOf(playerId);
169 assert.equal(countItem(bag.inventory, ItemId.ironOre), 0);
200 assert.equal(countItem(bag.inventory, ItemId.ironOre), 0);
@@ -184,7 +215,7 @@ test("craft rejects missing materials", () =>
184 const record = harness.simulation.entityRecord(playerId);
215 const record = harness.simulation.entityRecord(playerId);
185 const worker = harness.simulation.workers[record.workerId];
216 const worker = harness.simulation.workers[record.workerId];
186 placeFurnace(worker, 9, 8);
217 placeFurnace(worker, 9, 8);
187 giveInventory(harness, playerId, []);
218 giveInventory(harness, playerId, [{ itemId: ItemId.copperOre, quantity: 1 }]);
188
219
189 harness.simulation.enqueue(1, {
220 harness.simulation.enqueue(1, {
190 type: "start-craft",
221 type: "start-craft",
@@ -233,7 +264,10 @@ test("craft rejects furnace recipes when not next to a furnace", () =>
233 {
264 {
234 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
265 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
235 const playerId = harness.simulation.spawnCharacter(1, character);
266 const playerId = harness.simulation.spawnCharacter(1, character);
236 giveInventory(harness, playerId, [{ itemId: ItemId.bronzeOre, quantity: 1 }]);
267 giveInventory(harness, playerId, [
268 { itemId: ItemId.tinOre, quantity: 1 },
269 { itemId: ItemId.copperOre, quantity: 1 }
270 ]);
237
271
238 harness.simulation.enqueue(1, {
272 harness.simulation.enqueue(1, {
239 type: "start-craft",
273 type: "start-craft",
@@ -248,3 +282,69 @@ test("craft rejects furnace recipes when not next to a furnace", () =>
248 finally
282 finally
249 { harness.close(); }
283 { harness.close(); }
250});
284});
285
286function placeStation (worker, tileX, tileY, typeId, state)
287{
288 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
289 const localX = tileX % 16;
290 const localY = tileY % 16;
291 data.blocks[localY * 16 + localX] = {
292 typeId,
293 state,
294 config: null
295 };
296}
297
298test("bronze pickaxe chain: pine log → handle, bar → head, assemble pickaxe", () =>
299{
300 const harness = makeSimulation({ workerCount: 1 });
301 try
302 {
303 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
304 const playerId = harness.simulation.spawnCharacter(1, character);
305 const record = harness.simulation.entityRecord(playerId);
306 const worker = harness.simulation.workers[record.workerId];
307 placeStation(worker, 9, 8, BlockType.woodworkingBench, "woodworking-bench");
308 placeStation(worker, 9, 9, BlockType.anvil, "anvil");
309 giveInventory(harness, playerId, [
310 { itemId: ItemId.pineLog, quantity: 1 },
311 { itemId: ItemId.bronzeBar, quantity: 1 }
312 ]);
313
314 harness.simulation.enqueue(1, {
315 type: "start-craft",
316 characterId: character.character_id,
317 stationId: CraftingStationId.woodworkingBench,
318 recipeId: "handle-pine"
319 });
320 advanceMs(harness, craftDurationMs(recipeDefinition("handle-pine"), CRAFT_DURATION_MS));
321 let bag = harness.simulation.bagOf(playerId);
322 assert.equal(countItem(bag.inventory, ItemId.pineHandle), 1);
323 assert.equal(countItem(bag.inventory, ItemId.pineLog), 0);
324
325 harness.simulation.enqueue(1, {
326 type: "start-craft",
327 characterId: character.character_id,
328 stationId: CraftingStationId.anvil,
329 recipeId: "pickaxe-head-bronze"
330 });
331 advanceMs(harness, craftDurationMs(recipeDefinition("pickaxe-head-bronze"), CRAFT_DURATION_MS));
332 bag = harness.simulation.bagOf(playerId);
333 assert.equal(countItem(bag.inventory, ItemId.bronzePickaxeHead), 1);
334 assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 0);
335
336 harness.simulation.enqueue(1, {
337 type: "start-craft",
338 characterId: character.character_id,
339 stationId: CraftingStationId.woodworkingBench,
340 recipeId: "pickaxe-bronze"
341 });
342 advanceMs(harness, craftDurationMs(recipeDefinition("pickaxe-bronze"), CRAFT_DURATION_MS));
343 bag = harness.simulation.bagOf(playerId);
344 assert.equal(countItem(bag.inventory, ItemId.bronzePickaxe), 1);
345 assert.equal(countItem(bag.inventory, ItemId.pineHandle), 0);
346 assert.equal(countItem(bag.inventory, ItemId.bronzePickaxeHead), 0);
347 }
348 finally
349 { harness.close(); }
350});
server/tests/craftingStations.test.js +22 −1
@@ -81,6 +81,27 @@ test("canStartCraft enforces minimum skill level", () =>
81 81
82 82 test("crafting item stubs are registered", () =>
83 83 {
84 assert.equal(itemDefinition(CraftingItemId.log)?.stub, true);
84 assert.equal(itemDefinition(ItemId.pineLog)?.key, "pine-log");
85 assert.equal(itemDefinition(ItemId.pineHandle)?.defaultState, "handle");
85 86 assert.equal(itemDefinition(CraftingItemId.bronzeBar)?.key, "bronze-bar");
86 87 });
88
89 test("woodworking and anvil expose pickaxe chain recipes", () =>
90 {
91 assert.equal(craftingStationDefinition(CraftingStationId.woodworkingBench).skillId, SkillId.crafting);
92 const handle = recipeDefinition("handle-pine");
93 assert.ok(handle);
94 assert.equal(handle.stationId, CraftingStationId.woodworkingBench);
95 assert.equal(handle.output.itemId, ItemId.pineHandle);
96 const head = recipeDefinition("pickaxe-head-bronze");
97 assert.ok(head);
98 assert.equal(head.stationId, CraftingStationId.anvil);
99 assert.equal(head.output.itemId, ItemId.bronzePickaxeHead);
100 const pickaxe = recipeDefinition("pickaxe-bronze");
101 assert.ok(pickaxe);
102 assert.deepEqual(pickaxe.inputs.map((row) => row.itemId).sort(), [
103 ItemId.pineHandle,
104 ItemId.bronzePickaxeHead
105 ].sort());
106 assert.equal(pickaxe.output.itemId, ItemId.bronzePickaxe);
107 });
@@ -81,6 +81,27 @@ test("canStartCraft enforces minimum skill level", () =>
81
81
82test("crafting item stubs are registered", () =>
82test("crafting item stubs are registered", () =>
83{
83{
84 assert.equal(itemDefinition(CraftingItemId.log)?.stub, true);
84 assert.equal(itemDefinition(ItemId.pineLog)?.key, "pine-log");
85 assert.equal(itemDefinition(ItemId.pineHandle)?.defaultState, "handle");
85 assert.equal(itemDefinition(CraftingItemId.bronzeBar)?.key, "bronze-bar");
86 assert.equal(itemDefinition(CraftingItemId.bronzeBar)?.key, "bronze-bar");
86});
87});
88
89test("woodworking and anvil expose pickaxe chain recipes", () =>
90{
91 assert.equal(craftingStationDefinition(CraftingStationId.woodworkingBench).skillId, SkillId.crafting);
92 const handle = recipeDefinition("handle-pine");
93 assert.ok(handle);
94 assert.equal(handle.stationId, CraftingStationId.woodworkingBench);
95 assert.equal(handle.output.itemId, ItemId.pineHandle);
96 const head = recipeDefinition("pickaxe-head-bronze");
97 assert.ok(head);
98 assert.equal(head.stationId, CraftingStationId.anvil);
99 assert.equal(head.output.itemId, ItemId.bronzePickaxeHead);
100 const pickaxe = recipeDefinition("pickaxe-bronze");
101 assert.ok(pickaxe);
102 assert.deepEqual(pickaxe.inputs.map((row) => row.itemId).sort(), [
103 ItemId.pineHandle,
104 ItemId.bronzePickaxeHead
105 ].sort());
106 assert.equal(pickaxe.output.itemId, ItemId.bronzePickaxe);
107});
server/tests/mining.test.js +60 −22
@@ -17,7 +17,7 @@ import {
17 17 canMineMaterial,
18 18 oreItemIdForMaterial
19 19 } from "../../shared/definitions/gathering.js";
20 import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
20 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
21 21 import { SkillId } from "../../shared/definitions/skills.js";
22 22 import { canEquipItem } from "../../shared/equipment/stats.js";
23 23 import { normalizePlayerSkills } from "../../shared/skills/state.js";
@@ -46,11 +46,11 @@ function placeOre (worker, tileX, tileY, state)
46 46 return { data, index };
47 47 }
48 48
49 function equipPickaxe (worker, playerId, itemId)
49 function bagPickaxe (worker, playerId, itemId)
50 50 {
51 51 const handle = worker.world.ecs.handleOf(playerId);
52 const equipment = worker.world.ecs.get(handle, Component.equipment);
53 equipment.slots[EQUIPMENT_SLOT.weapon] = { itemId, quantity: 1 };
52 const inventory = worker.world.ecs.get(handle, Component.inventory);
53 inventory.slots[0] = { itemId, quantity: 1 };
54 54 }
55 55
56 56 function setSkillLevel (worker, playerId, skillId, level)
@@ -89,19 +89,23 @@ test("mining duration uses resource and tool ranks", () =>
89 89 assert.ok(miningDurationMs(MaterialTier.bronze, MaterialTier.dragon) >= 500);
90 90 });
91 91
92 test("ore exhaust duration is 10s times material rank", () =>
92 test("ore exhaust duration is 10s times associated bar rank", () =>
93 93 {
94 94 assert.equal(oreExhaustDurationMs(MaterialTier.bronze), 10_000);
95 95 assert.equal(oreExhaustDurationMs(MaterialTier.iron), 20_000);
96 assert.equal(oreExhaustDurationMs(GatherMaterialId.coal), 20_000);
96 assert.equal(oreExhaustDurationMs(GatherMaterialId.tin), 10_000);
97 assert.equal(oreExhaustDurationMs(GatherMaterialId.copper), 10_000);
98 assert.equal(oreExhaustDurationMs(GatherMaterialId.coal), 30_000);
97 99 assert.equal(oreExhaustDurationMs(MaterialTier.dragon), 70_000);
98 100 });
99 101
100 102 test("ore boulder states map to materials", () =>
101 103 {
102 assert.equal(materialFromOreBoulderState("bronze-ore"), MaterialTier.bronze);
104 assert.equal(materialFromOreBoulderState("tin-ore"), GatherMaterialId.tin);
105 assert.equal(materialFromOreBoulderState("copper-ore"), GatherMaterialId.copper);
103 106 assert.equal(materialFromOreBoulderState("coal"), GatherMaterialId.coal);
104 107 assert.equal(materialFromOreBoulderState("boulder"), null);
108 assert.equal(materialFromOreBoulderState("bronze-ore"), null);
105 109 assert.equal(oreBoulderState(MaterialTier.mithril), "mithril-ore");
106 110 });
107 111
@@ -135,7 +139,7 @@ test("mining without a pickaxe is rejected", () =>
135 139 const playerId = harness.simulation.spawnCharacter(1, character);
136 140 const record = harness.simulation.entityRecord(playerId);
137 141 const worker = harness.simulation.workers[record.workerId];
138 placeOre(worker, 9, 8, "bronze-ore");
142 placeOre(worker, 9, 8, "copper-ore");
139 143
140 144 harness.simulation.enqueue(1, {
141 145 type: "mine",
@@ -145,7 +149,8 @@ test("mining without a pickaxe is rejected", () =>
145 149 });
146 150 const result = harness.simulation.step();
147 151 assert.ok(result.events.some((event) =>
148 event.type === "command-error" && /pickaxe/i.test(event.message ?? "")));
152 event.type === "command-error"
153 && event.message === "You need a pickaxe to mine this!"));
149 154 }
150 155 finally
151 156 { harness.close(); }
@@ -160,7 +165,7 @@ test("plain boulder cannot be mined", () =>
160 165 const playerId = harness.simulation.spawnCharacter(1, character);
161 166 const record = harness.simulation.entityRecord(playerId);
162 167 const worker = harness.simulation.workers[record.workerId];
163 equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
168 bagPickaxe(worker, playerId, ItemId.bronzePickaxe);
164 169 placeOre(worker, 9, 8, EXHAUSTED_ORE_BOULDER_STATE);
165 170
166 171 harness.simulation.enqueue(1, {
@@ -187,7 +192,7 @@ test("weak pickaxe cannot mine higher-tier ore", () =>
187 192 const playerId = harness.simulation.spawnCharacter(1, character);
188 193 const record = harness.simulation.entityRecord(playerId);
189 194 const worker = harness.simulation.workers[record.workerId];
190 equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
195 bagPickaxe(worker, playerId, ItemId.bronzePickaxe);
191 196 setSkillLevel(worker, playerId, SkillId.mining, 10);
192 197 placeOre(worker, 9, 8, "iron-ore");
193 198
@@ -199,7 +204,40 @@ test("weak pickaxe cannot mine higher-tier ore", () =>
199 204 });
200 205 const result = harness.simulation.step();
201 206 assert.ok(result.events.some((event) =>
202 event.type === "command-error" && /too weak|pickaxe/i.test(event.message ?? "")));
207 event.type === "command-error"
208 && event.message === "You need a pickaxe to mine this!"));
209 }
210 finally
211 { harness.close(); }
212 });
213
214 test("mining uses the best pickaxe in inventory without equipping", () =>
215 {
216 const harness = makeSimulation({ workerCount: 1 });
217 try
218 {
219 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
220 const playerId = harness.simulation.spawnCharacter(1, character);
221 const record = harness.simulation.entityRecord(playerId);
222 const worker = harness.simulation.workers[record.workerId];
223 setSkillLevel(worker, playerId, SkillId.mining, 10);
224 const handle = worker.world.ecs.handleOf(playerId);
225 const inventory = worker.world.ecs.get(handle, Component.inventory);
226 inventory.slots[0] = { itemId: ItemId.bronzePickaxe, quantity: 1 };
227 inventory.slots[1] = { itemId: ItemId.ironPickaxe, quantity: 1 };
228 placeOre(worker, 9, 8, "iron-ore");
229
230 harness.simulation.enqueue(1, {
231 type: "mine",
232 characterId: character.character_id,
233 tileX: 9,
234 tileY: 8
235 });
236 harness.simulation.step();
237 advanceMs(harness, miningDurationMs(MaterialTier.iron, MaterialTier.iron));
238
239 const bag = harness.simulation.bagOf(playerId);
240 assert.ok(countItem(bag.inventory, ItemId.ironOre) >= 1);
203 241 }
204 242 finally
205 243 { harness.close(); }
@@ -214,8 +252,8 @@ test("mining grants ore and Mining XP then exhausts and respawns the node", () =
214 252 const playerId = harness.simulation.spawnCharacter(1, character);
215 253 const record = harness.simulation.entityRecord(playerId);
216 254 const worker = harness.simulation.workers[record.workerId];
217 equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
218 const { data, index } = placeOre(worker, 9, 8, "bronze-ore");
255 bagPickaxe(worker, playerId, ItemId.bronzePickaxe);
256 const { data, index } = placeOre(worker, 9, 8, "copper-ore");
219 257
220 258 harness.simulation.enqueue(1, {
221 259 type: "mine",
@@ -226,13 +264,13 @@ test("mining grants ore and Mining XP then exhausts and respawns the node", () =
226 264 const start = harness.simulation.step();
227 265 assert.ok(start.events.some((event) => event.type === "gather-swing" || event.type === "tile-shove"));
228 266
229 advanceMs(harness, miningDurationMs(MaterialTier.bronze, MaterialTier.bronze));
267 advanceMs(harness, miningDurationMs(GatherMaterialId.copper, MaterialTier.bronze));
230 268
231 269 const bag = harness.simulation.bagOf(playerId);
232 assert.ok(countItem(bag.inventory, ItemId.bronzeOre) >= 1);
270 assert.ok(countItem(bag.inventory, ItemId.copperOre) >= 1);
233 271 const skills = harness.stateDb.getSkills(character.character_id);
234 272 assert.ok(skills.xp.mining > 0);
235 assert.equal(oreItemIdForMaterial(MaterialTier.bronze), ItemId.bronzeOre);
273 assert.equal(oreItemIdForMaterial(GatherMaterialId.copper), ItemId.copperOre);
236 274 assert.equal(data.blocks[index].state, EXHAUSTED_ORE_BOULDER_STATE);
237 275
238 276 harness.simulation.enqueue(1, {
@@ -245,8 +283,8 @@ test("mining grants ore and Mining XP then exhausts and respawns the node", () =
245 283 assert.ok(exhaustedResult.events.some((event) =>
246 284 event.type === "command-error" && /exhausted/i.test(event.message ?? "")));
247 285
248 advanceMs(harness, oreExhaustDurationMs(MaterialTier.bronze));
249 assert.equal(data.blocks[index].state, "bronze-ore");
286 advanceMs(harness, oreExhaustDurationMs(GatherMaterialId.copper));
287 assert.equal(data.blocks[index].state, "copper-ore");
250 288 }
251 289 finally
252 290 { harness.close(); }
@@ -261,8 +299,8 @@ test("coal mining yields coal and exhausts the node", () =>
261 299 const playerId = harness.simulation.spawnCharacter(1, character);
262 300 const record = harness.simulation.entityRecord(playerId);
263 301 const worker = harness.simulation.workers[record.workerId];
264 setSkillLevel(worker, playerId, SkillId.mining, 10);
265 equipPickaxe(worker, playerId, ItemId.ironPickaxe);
302 setSkillLevel(worker, playerId, SkillId.mining, 20);
303 bagPickaxe(worker, playerId, ItemId.steelPickaxe);
266 304 const { data, index } = placeOre(worker, 9, 8, "coal");
267 305
268 306 harness.simulation.enqueue(1, {
@@ -272,7 +310,7 @@ test("coal mining yields coal and exhausts the node", () =>
272 310 tileY: 8
273 311 });
274 312 harness.simulation.step();
275 advanceMs(harness, miningDurationMs(GatherMaterialId.coal, MaterialTier.iron));
313 advanceMs(harness, miningDurationMs(GatherMaterialId.coal, MaterialTier.steel));
276 314
277 315 const bag = harness.simulation.bagOf(playerId);
278 316 assert.ok(countItem(bag.inventory, ItemId.coal) >= 1);
@@ -17,7 +17,7 @@ import {
17 canMineMaterial,
17 canMineMaterial,
18 oreItemIdForMaterial
18 oreItemIdForMaterial
19} from "../../shared/definitions/gathering.js";
19} from "../../shared/definitions/gathering.js";
20import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
20import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
21import { SkillId } from "../../shared/definitions/skills.js";
21import { SkillId } from "../../shared/definitions/skills.js";
22import { canEquipItem } from "../../shared/equipment/stats.js";
22import { canEquipItem } from "../../shared/equipment/stats.js";
23import { normalizePlayerSkills } from "../../shared/skills/state.js";
23import { normalizePlayerSkills } from "../../shared/skills/state.js";
@@ -46,11 +46,11 @@ function placeOre (worker, tileX, tileY, state)
46 return { data, index };
46 return { data, index };
47}
47}
48
48
49function equipPickaxe (worker, playerId, itemId)
49function bagPickaxe (worker, playerId, itemId)
50{
50{
51 const handle = worker.world.ecs.handleOf(playerId);
51 const handle = worker.world.ecs.handleOf(playerId);
52 const equipment = worker.world.ecs.get(handle, Component.equipment);
52 const inventory = worker.world.ecs.get(handle, Component.inventory);
53 equipment.slots[EQUIPMENT_SLOT.weapon] = { itemId, quantity: 1 };
53 inventory.slots[0] = { itemId, quantity: 1 };
54}
54}
55
55
56function setSkillLevel (worker, playerId, skillId, level)
56function setSkillLevel (worker, playerId, skillId, level)
@@ -89,19 +89,23 @@ test("mining duration uses resource and tool ranks", () =>
89 assert.ok(miningDurationMs(MaterialTier.bronze, MaterialTier.dragon) >= 500);
89 assert.ok(miningDurationMs(MaterialTier.bronze, MaterialTier.dragon) >= 500);
90});
90});
91
91
92test("ore exhaust duration is 10s times material rank", () =>
92test("ore exhaust duration is 10s times associated bar rank", () =>
93{
93{
94 assert.equal(oreExhaustDurationMs(MaterialTier.bronze), 10_000);
94 assert.equal(oreExhaustDurationMs(MaterialTier.bronze), 10_000);
95 assert.equal(oreExhaustDurationMs(MaterialTier.iron), 20_000);
95 assert.equal(oreExhaustDurationMs(MaterialTier.iron), 20_000);
96 assert.equal(oreExhaustDurationMs(GatherMaterialId.coal), 20_000);
96 assert.equal(oreExhaustDurationMs(GatherMaterialId.tin), 10_000);
97 assert.equal(oreExhaustDurationMs(GatherMaterialId.copper), 10_000);
98 assert.equal(oreExhaustDurationMs(GatherMaterialId.coal), 30_000);
97 assert.equal(oreExhaustDurationMs(MaterialTier.dragon), 70_000);
99 assert.equal(oreExhaustDurationMs(MaterialTier.dragon), 70_000);
98});
100});
99
101
100test("ore boulder states map to materials", () =>
102test("ore boulder states map to materials", () =>
101{
103{
102 assert.equal(materialFromOreBoulderState("bronze-ore"), MaterialTier.bronze);
104 assert.equal(materialFromOreBoulderState("tin-ore"), GatherMaterialId.tin);
105 assert.equal(materialFromOreBoulderState("copper-ore"), GatherMaterialId.copper);
103 assert.equal(materialFromOreBoulderState("coal"), GatherMaterialId.coal);
106 assert.equal(materialFromOreBoulderState("coal"), GatherMaterialId.coal);
104 assert.equal(materialFromOreBoulderState("boulder"), null);
107 assert.equal(materialFromOreBoulderState("boulder"), null);
108 assert.equal(materialFromOreBoulderState("bronze-ore"), null);
105 assert.equal(oreBoulderState(MaterialTier.mithril), "mithril-ore");
109 assert.equal(oreBoulderState(MaterialTier.mithril), "mithril-ore");
106});
110});
107
111
@@ -135,7 +139,7 @@ test("mining without a pickaxe is rejected", () =>
135 const playerId = harness.simulation.spawnCharacter(1, character);
139 const playerId = harness.simulation.spawnCharacter(1, character);
136 const record = harness.simulation.entityRecord(playerId);
140 const record = harness.simulation.entityRecord(playerId);
137 const worker = harness.simulation.workers[record.workerId];
141 const worker = harness.simulation.workers[record.workerId];
138 placeOre(worker, 9, 8, "bronze-ore");
142 placeOre(worker, 9, 8, "copper-ore");
139
143
140 harness.simulation.enqueue(1, {
144 harness.simulation.enqueue(1, {
141 type: "mine",
145 type: "mine",
@@ -145,7 +149,8 @@ test("mining without a pickaxe is rejected", () =>
145 });
149 });
146 const result = harness.simulation.step();
150 const result = harness.simulation.step();
147 assert.ok(result.events.some((event) =>
151 assert.ok(result.events.some((event) =>
148 event.type === "command-error" && /pickaxe/i.test(event.message ?? "")));
152 event.type === "command-error"
153 && event.message === "You need a pickaxe to mine this!"));
149 }
154 }
150 finally
155 finally
151 { harness.close(); }
156 { harness.close(); }
@@ -160,7 +165,7 @@ test("plain boulder cannot be mined", () =>
160 const playerId = harness.simulation.spawnCharacter(1, character);
165 const playerId = harness.simulation.spawnCharacter(1, character);
161 const record = harness.simulation.entityRecord(playerId);
166 const record = harness.simulation.entityRecord(playerId);
162 const worker = harness.simulation.workers[record.workerId];
167 const worker = harness.simulation.workers[record.workerId];
163 equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
168 bagPickaxe(worker, playerId, ItemId.bronzePickaxe);
164 placeOre(worker, 9, 8, EXHAUSTED_ORE_BOULDER_STATE);
169 placeOre(worker, 9, 8, EXHAUSTED_ORE_BOULDER_STATE);
165
170
166 harness.simulation.enqueue(1, {
171 harness.simulation.enqueue(1, {
@@ -187,7 +192,7 @@ test("weak pickaxe cannot mine higher-tier ore", () =>
187 const playerId = harness.simulation.spawnCharacter(1, character);
192 const playerId = harness.simulation.spawnCharacter(1, character);
188 const record = harness.simulation.entityRecord(playerId);
193 const record = harness.simulation.entityRecord(playerId);
189 const worker = harness.simulation.workers[record.workerId];
194 const worker = harness.simulation.workers[record.workerId];
190 equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
195 bagPickaxe(worker, playerId, ItemId.bronzePickaxe);
191 setSkillLevel(worker, playerId, SkillId.mining, 10);
196 setSkillLevel(worker, playerId, SkillId.mining, 10);
192 placeOre(worker, 9, 8, "iron-ore");
197 placeOre(worker, 9, 8, "iron-ore");
193
198
@@ -199,7 +204,40 @@ test("weak pickaxe cannot mine higher-tier ore", () =>
199 });
204 });
200 const result = harness.simulation.step();
205 const result = harness.simulation.step();
201 assert.ok(result.events.some((event) =>
206 assert.ok(result.events.some((event) =>
202 event.type === "command-error" && /too weak|pickaxe/i.test(event.message ?? "")));
207 event.type === "command-error"
208 && event.message === "You need a pickaxe to mine this!"));
209 }
210 finally
211 { harness.close(); }
212});
213
214test("mining uses the best pickaxe in inventory without equipping", () =>
215{
216 const harness = makeSimulation({ workerCount: 1 });
217 try
218 {
219 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
220 const playerId = harness.simulation.spawnCharacter(1, character);
221 const record = harness.simulation.entityRecord(playerId);
222 const worker = harness.simulation.workers[record.workerId];
223 setSkillLevel(worker, playerId, SkillId.mining, 10);
224 const handle = worker.world.ecs.handleOf(playerId);
225 const inventory = worker.world.ecs.get(handle, Component.inventory);
226 inventory.slots[0] = { itemId: ItemId.bronzePickaxe, quantity: 1 };
227 inventory.slots[1] = { itemId: ItemId.ironPickaxe, quantity: 1 };
228 placeOre(worker, 9, 8, "iron-ore");
229
230 harness.simulation.enqueue(1, {
231 type: "mine",
232 characterId: character.character_id,
233 tileX: 9,
234 tileY: 8
235 });
236 harness.simulation.step();
237 advanceMs(harness, miningDurationMs(MaterialTier.iron, MaterialTier.iron));
238
239 const bag = harness.simulation.bagOf(playerId);
240 assert.ok(countItem(bag.inventory, ItemId.ironOre) >= 1);
203 }
241 }
204 finally
242 finally
205 { harness.close(); }
243 { harness.close(); }
@@ -214,8 +252,8 @@ test("mining grants ore and Mining XP then exhausts and respawns the node", () =
214 const playerId = harness.simulation.spawnCharacter(1, character);
252 const playerId = harness.simulation.spawnCharacter(1, character);
215 const record = harness.simulation.entityRecord(playerId);
253 const record = harness.simulation.entityRecord(playerId);
216 const worker = harness.simulation.workers[record.workerId];
254 const worker = harness.simulation.workers[record.workerId];
217 equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
255 bagPickaxe(worker, playerId, ItemId.bronzePickaxe);
218 const { data, index } = placeOre(worker, 9, 8, "bronze-ore");
256 const { data, index } = placeOre(worker, 9, 8, "copper-ore");
219
257
220 harness.simulation.enqueue(1, {
258 harness.simulation.enqueue(1, {
221 type: "mine",
259 type: "mine",
@@ -226,13 +264,13 @@ test("mining grants ore and Mining XP then exhausts and respawns the node", () =
226 const start = harness.simulation.step();
264 const start = harness.simulation.step();
227 assert.ok(start.events.some((event) => event.type === "gather-swing" || event.type === "tile-shove"));
265 assert.ok(start.events.some((event) => event.type === "gather-swing" || event.type === "tile-shove"));
228
266
229 advanceMs(harness, miningDurationMs(MaterialTier.bronze, MaterialTier.bronze));
267 advanceMs(harness, miningDurationMs(GatherMaterialId.copper, MaterialTier.bronze));
230
268
231 const bag = harness.simulation.bagOf(playerId);
269 const bag = harness.simulation.bagOf(playerId);
232 assert.ok(countItem(bag.inventory, ItemId.bronzeOre) >= 1);
270 assert.ok(countItem(bag.inventory, ItemId.copperOre) >= 1);
233 const skills = harness.stateDb.getSkills(character.character_id);
271 const skills = harness.stateDb.getSkills(character.character_id);
234 assert.ok(skills.xp.mining > 0);
272 assert.ok(skills.xp.mining > 0);
235 assert.equal(oreItemIdForMaterial(MaterialTier.bronze), ItemId.bronzeOre);
273 assert.equal(oreItemIdForMaterial(GatherMaterialId.copper), ItemId.copperOre);
236 assert.equal(data.blocks[index].state, EXHAUSTED_ORE_BOULDER_STATE);
274 assert.equal(data.blocks[index].state, EXHAUSTED_ORE_BOULDER_STATE);
237
275
238 harness.simulation.enqueue(1, {
276 harness.simulation.enqueue(1, {
@@ -245,8 +283,8 @@ test("mining grants ore and Mining XP then exhausts and respawns the node", () =
245 assert.ok(exhaustedResult.events.some((event) =>
283 assert.ok(exhaustedResult.events.some((event) =>
246 event.type === "command-error" && /exhausted/i.test(event.message ?? "")));
284 event.type === "command-error" && /exhausted/i.test(event.message ?? "")));
247
285
248 advanceMs(harness, oreExhaustDurationMs(MaterialTier.bronze));
286 advanceMs(harness, oreExhaustDurationMs(GatherMaterialId.copper));
249 assert.equal(data.blocks[index].state, "bronze-ore");
287 assert.equal(data.blocks[index].state, "copper-ore");
250 }
288 }
251 finally
289 finally
252 { harness.close(); }
290 { harness.close(); }
@@ -261,8 +299,8 @@ test("coal mining yields coal and exhausts the node", () =>
261 const playerId = harness.simulation.spawnCharacter(1, character);
299 const playerId = harness.simulation.spawnCharacter(1, character);
262 const record = harness.simulation.entityRecord(playerId);
300 const record = harness.simulation.entityRecord(playerId);
263 const worker = harness.simulation.workers[record.workerId];
301 const worker = harness.simulation.workers[record.workerId];
264 setSkillLevel(worker, playerId, SkillId.mining, 10);
302 setSkillLevel(worker, playerId, SkillId.mining, 20);
265 equipPickaxe(worker, playerId, ItemId.ironPickaxe);
303 bagPickaxe(worker, playerId, ItemId.steelPickaxe);
266 const { data, index } = placeOre(worker, 9, 8, "coal");
304 const { data, index } = placeOre(worker, 9, 8, "coal");
267
305
268 harness.simulation.enqueue(1, {
306 harness.simulation.enqueue(1, {
@@ -272,7 +310,7 @@ test("coal mining yields coal and exhausts the node", () =>
272 tileY: 8
310 tileY: 8
273 });
311 });
274 harness.simulation.step();
312 harness.simulation.step();
275 advanceMs(harness, miningDurationMs(GatherMaterialId.coal, MaterialTier.iron));
313 advanceMs(harness, miningDurationMs(GatherMaterialId.coal, MaterialTier.steel));
276
314
277 const bag = harness.simulation.bagOf(playerId);
315 const bag = harness.simulation.bagOf(playerId);
278 assert.ok(countItem(bag.inventory, ItemId.coal) >= 1);
316 assert.ok(countItem(bag.inventory, ItemId.coal) >= 1);
server/tests/shop.test.js added +127 −0
@@ -0,0 +1,127 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { shopUnitPrice, undiscountedMarketValue, canSellInNpcShop, lerp } from "../../shared/shop/pricing.js";
4 import { ItemId } from "../../shared/definitions/items.js";
5 import { MobId, normalizeSpawnerConfig, isHumanoidMob } from "../../shared/definitions/mobs.js";
6 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
7 import { Component } from "../src/ecs/components.js";
8 import { emptyEquipment, emptySlots, addCoinsToSlots } from "../../shared/items/inventory.js";
9 import { ItemOriginKind } from "../../shared/items/origin.js";
10 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
11
12 test("shop prices fall back to seedValue and apply hidden discount", () =>
13 {
14 assert.equal(undiscountedMarketValue(ItemId.copperOre), 2);
15 assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.9 }), 2);
16 assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.5 }), 1);
17 assert.equal(lerp(10, 20, 0.5), 15);
18 assert.equal(canSellInNpcShop(ItemId.copperOre), true);
19 assert.equal(canSellInNpcShop(ItemId.tinOre), true);
20 assert.equal(canSellInNpcShop(ItemId.stick), false);
21 });
22
23 test("humanoid spawner config keeps sex equipment and sells", () =>
24 {
25 assert.equal(isHumanoidMob(MobId.humanoid), true);
26 const config = normalizeSpawnerConfig({
27 mobTypeId: MobId.humanoid,
28 sex: "female",
29 displayName: "Ore trader",
30 equipment: { chest: ItemId.clothShirt, weapon: ItemId.stick },
31 sells: [ItemId.copperOre, ItemId.tinOre, ItemId.copperOre],
32 hiddenDiscount: 0.85
33 }, "shop-1");
34 assert.equal(config.sex, "female");
35 assert.equal(config.displayName, "Ore trader");
36 assert.equal(config.equipment.chest, ItemId.clothShirt);
37 assert.deepEqual(config.sells, [ItemId.copperOre, ItemId.tinOre]);
38 assert.equal(config.hiddenDiscount, 0.85);
39 assert.equal(config.maxAlive, 1);
40 });
41
42 test("buy copper ore from a spawned shopkeeper", () =>
43 {
44 const harness = makeSimulation({ workerCount: 1 });
45 try
46 {
47 const data = createEmptyChunkData();
48 data.open = true;
49 data.spawners = [{
50 localX: 9,
51 localY: 8,
52 config: {
53 mobTypeId: MobId.humanoid,
54 maxAlive: 1,
55 spawnRangeTiles: 1,
56 maxWanderRangeTiles: 1,
57 sex: "male",
58 displayName: "Ore trader",
59 sells: [ItemId.copperOre, ItemId.tinOre],
60 hiddenDiscount: 1,
61 equipment: { chest: ItemId.clothShirt }
62 }
63 }];
64 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
65 harness.simulation.reloadWorld();
66
67 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
68 const funded = addCoinsToSlots(emptySlots(), 50);
69 assert.equal(funded.ok, true);
70 harness.stateDb.saveBag(character.character_id, {
71 inventory: funded.slots,
72 equipment: emptyEquipment(),
73 vault: [],
74 vaultReserved: []
75 });
76 const playerId = harness.simulation.spawnCharacter(1, character);
77 harness.simulation.step();
78 harness.advance(50);
79 harness.simulation.step();
80
81 const record = harness.simulation.entityRecord(playerId);
82 const worker = harness.simulation.workers[record.workerId];
83 let npcId = null;
84 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
85 {
86 if (entity.creature.mobTypeId === MobId.humanoid)
87 {
88 npcId = entity.entityId;
89 break;
90 }
91 }
92 assert.ok(npcId, "expected a humanoid shopkeeper");
93
94 const npcHandle = worker.world.ecs.handleOf(npcId);
95 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
96 const playerHandle = worker.world.ecs.handleOf(playerId);
97 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
98 playerPos.tileX = npcPos.tileX;
99 playerPos.tileY = npcPos.tileY;
100
101 harness.simulation.enqueue(1, {
102 type: "interact",
103 characterId: character.character_id,
104 targetEntityId: npcId
105 });
106 const open = harness.simulation.step();
107 const shopOpen = open.events.find((event) => event.type === "shop-open");
108 assert.ok(shopOpen, JSON.stringify(open.events));
109 assert.ok(shopOpen.stock.some((row) => row.itemId === ItemId.copperOre));
110
111 harness.simulation.enqueue(1, {
112 type: "buy-from-shop",
113 characterId: character.character_id,
114 npcEntityId: npcId,
115 itemId: ItemId.copperOre,
116 quantity: 1
117 });
118 const buy = harness.simulation.step();
119 assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));
120 const bag = harness.simulation.bagOf(playerId);
121 const ore = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.copperOre);
122 assert.ok(ore, JSON.stringify(bag.inventory));
123 assert.equal(ore.origins?.[0]?.origin?.kind, ItemOriginKind.shop);
124 }
125 finally
126 { harness.close(); }
127 });
@@ -0,0 +1,127 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { shopUnitPrice, undiscountedMarketValue, canSellInNpcShop, lerp } from "../../shared/shop/pricing.js";
4import { ItemId } from "../../shared/definitions/items.js";
5import { MobId, normalizeSpawnerConfig, isHumanoidMob } from "../../shared/definitions/mobs.js";
6import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
7import { Component } from "../src/ecs/components.js";
8import { emptyEquipment, emptySlots, addCoinsToSlots } from "../../shared/items/inventory.js";
9import { ItemOriginKind } from "../../shared/items/origin.js";
10import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
11
12test("shop prices fall back to seedValue and apply hidden discount", () =>
13{
14 assert.equal(undiscountedMarketValue(ItemId.copperOre), 2);
15 assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.9 }), 2);
16 assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.5 }), 1);
17 assert.equal(lerp(10, 20, 0.5), 15);
18 assert.equal(canSellInNpcShop(ItemId.copperOre), true);
19 assert.equal(canSellInNpcShop(ItemId.tinOre), true);
20 assert.equal(canSellInNpcShop(ItemId.stick), false);
21});
22
23test("humanoid spawner config keeps sex equipment and sells", () =>
24{
25 assert.equal(isHumanoidMob(MobId.humanoid), true);
26 const config = normalizeSpawnerConfig({
27 mobTypeId: MobId.humanoid,
28 sex: "female",
29 displayName: "Ore trader",
30 equipment: { chest: ItemId.clothShirt, weapon: ItemId.stick },
31 sells: [ItemId.copperOre, ItemId.tinOre, ItemId.copperOre],
32 hiddenDiscount: 0.85
33 }, "shop-1");
34 assert.equal(config.sex, "female");
35 assert.equal(config.displayName, "Ore trader");
36 assert.equal(config.equipment.chest, ItemId.clothShirt);
37 assert.deepEqual(config.sells, [ItemId.copperOre, ItemId.tinOre]);
38 assert.equal(config.hiddenDiscount, 0.85);
39 assert.equal(config.maxAlive, 1);
40});
41
42test("buy copper ore from a spawned shopkeeper", () =>
43{
44 const harness = makeSimulation({ workerCount: 1 });
45 try
46 {
47 const data = createEmptyChunkData();
48 data.open = true;
49 data.spawners = [{
50 localX: 9,
51 localY: 8,
52 config: {
53 mobTypeId: MobId.humanoid,
54 maxAlive: 1,
55 spawnRangeTiles: 1,
56 maxWanderRangeTiles: 1,
57 sex: "male",
58 displayName: "Ore trader",
59 sells: [ItemId.copperOre, ItemId.tinOre],
60 hiddenDiscount: 1,
61 equipment: { chest: ItemId.clothShirt }
62 }
63 }];
64 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
65 harness.simulation.reloadWorld();
66
67 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
68 const funded = addCoinsToSlots(emptySlots(), 50);
69 assert.equal(funded.ok, true);
70 harness.stateDb.saveBag(character.character_id, {
71 inventory: funded.slots,
72 equipment: emptyEquipment(),
73 vault: [],
74 vaultReserved: []
75 });
76 const playerId = harness.simulation.spawnCharacter(1, character);
77 harness.simulation.step();
78 harness.advance(50);
79 harness.simulation.step();
80
81 const record = harness.simulation.entityRecord(playerId);
82 const worker = harness.simulation.workers[record.workerId];
83 let npcId = null;
84 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
85 {
86 if (entity.creature.mobTypeId === MobId.humanoid)
87 {
88 npcId = entity.entityId;
89 break;
90 }
91 }
92 assert.ok(npcId, "expected a humanoid shopkeeper");
93
94 const npcHandle = worker.world.ecs.handleOf(npcId);
95 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
96 const playerHandle = worker.world.ecs.handleOf(playerId);
97 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
98 playerPos.tileX = npcPos.tileX;
99 playerPos.tileY = npcPos.tileY;
100
101 harness.simulation.enqueue(1, {
102 type: "interact",
103 characterId: character.character_id,
104 targetEntityId: npcId
105 });
106 const open = harness.simulation.step();
107 const shopOpen = open.events.find((event) => event.type === "shop-open");
108 assert.ok(shopOpen, JSON.stringify(open.events));
109 assert.ok(shopOpen.stock.some((row) => row.itemId === ItemId.copperOre));
110
111 harness.simulation.enqueue(1, {
112 type: "buy-from-shop",
113 characterId: character.character_id,
114 npcEntityId: npcId,
115 itemId: ItemId.copperOre,
116 quantity: 1
117 });
118 const buy = harness.simulation.step();
119 assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));
120 const bag = harness.simulation.bagOf(playerId);
121 const ore = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.copperOre);
122 assert.ok(ore, JSON.stringify(bag.inventory));
123 assert.equal(ore.origins?.[0]?.origin?.kind, ItemOriginKind.shop);
124 }
125 finally
126 { harness.close(); }
127});
server/tests/tint.test.js +5 −3
@@ -6,7 +6,7 @@ import {
6 6 tierTintColor,
7 7 resolveItemTint
8 8 } from "../../shared/render/tint.js";
9 import { MaterialTier } from "../../shared/definitions/materialTiers.js";
9 import { MaterialTier, GatherMaterialId } from "../../shared/definitions/materialTiers.js";
10 10 import { ItemId } from "../../shared/definitions/items.js";
11 11
12 12 test("magenta tintable when R==B and G < R", () =>
@@ -38,6 +38,8 @@ test("resolveItemTint uses potion instance color and tier tints", () =>
38 38 assert.equal(potionTint.g, 0.72);
39 39 const bronze = tierTintColor(MaterialTier.bronze);
40 40 assert.ok(bronze.r > bronze.b);
41 const oreTint = resolveItemTint({ itemId: ItemId.bronzeOre });
42 assert.deepEqual(oreTint, bronze);
41 const barTint = resolveItemTint({ itemId: ItemId.bronzeBar });
42 assert.deepEqual(barTint, bronze);
43 const copper = tierTintColor(GatherMaterialId.copper);
44 assert.deepEqual(resolveItemTint({ itemId: ItemId.copperOre }), copper);
43 45 });
@@ -6,7 +6,7 @@ import {
6 tierTintColor,
6 tierTintColor,
7 resolveItemTint
7 resolveItemTint
8} from "../../shared/render/tint.js";
8} from "../../shared/render/tint.js";
9import { MaterialTier } from "../../shared/definitions/materialTiers.js";
9import { MaterialTier, GatherMaterialId } from "../../shared/definitions/materialTiers.js";
10import { ItemId } from "../../shared/definitions/items.js";
10import { ItemId } from "../../shared/definitions/items.js";
11
11
12test("magenta tintable when R==B and G < R", () =>
12test("magenta tintable when R==B and G < R", () =>
@@ -38,6 +38,8 @@ test("resolveItemTint uses potion instance color and tier tints", () =>
38 assert.equal(potionTint.g, 0.72);
38 assert.equal(potionTint.g, 0.72);
39 const bronze = tierTintColor(MaterialTier.bronze);
39 const bronze = tierTintColor(MaterialTier.bronze);
40 assert.ok(bronze.r > bronze.b);
40 assert.ok(bronze.r > bronze.b);
41 const oreTint = resolveItemTint({ itemId: ItemId.bronzeOre });
41 const barTint = resolveItemTint({ itemId: ItemId.bronzeBar });
42 assert.deepEqual(oreTint, bronze);
42 assert.deepEqual(barTint, bronze);
43 const copper = tierTintColor(GatherMaterialId.copper);
44 assert.deepEqual(resolveItemTint({ itemId: ItemId.copperOre }), copper);
43});
45});
shared/crafting/stationRecipes.js +100 −4
@@ -1,8 +1,23 @@
1 1 import { CraftingStationId } from "../definitions/craftingStations.js";
2 2 import { ItemId } from "../definitions/items.js";
3 3 import { CraftingItemId } from "../definitions/craftingItems.js";
4 import { MetalItemId } from "../definitions/metalItems.js";
5 import { MaterialTier, tierSmeltSkillLevel } from "../definitions/materialTiers.js";
4 import {
5 MetalItemId,
6 PICKAXE_HEAD_ITEM_BY_METAL,
7 PICKAXE_ITEM_BY_METAL
8 } from "../definitions/metalItems.js";
9 import {
10 WOOD_TIER_ORDER,
11 MaterialTier,
12 MATERIAL_TIER_ORDER,
13 woodTierForMetal,
14 tierSmeltSkillLevel,
15 tierCraftSkillLevel
16 } from "../definitions/materialTiers.js";
17 import {
18 logItemIdForWood,
19 handleItemIdForWood
20 } from "../definitions/woodItems.js";
6 21
7 22 /**
8 23 * Craft recipe schema (shared client + server):
@@ -12,6 +27,7 @@ import { MaterialTier, tierSmeltSkillLevel } from "../definitions/materialTiers.
12 27 * - output: { itemId, quantity }
13 28 * - inputs: [{ itemId, quantity }, ...]
14 29 * - minSkillLevel: minimum linked station skill (default 1)
30 * - xpMaterial: tier id for duration + XP scaling
15 31 */
16 32
17 33 function smelt (tier, recipeId, inputs, outputItemId)
@@ -27,6 +43,81 @@ function smelt (tier, recipeId, inputs, outputItemId)
27 43 });
28 44 }
29 45
46 function handleRecipe (woodTier)
47 {
48 const logId = logItemIdForWood(woodTier);
49 const handleId = handleItemIdForWood(woodTier);
50 return Object.freeze({
51 recipeId: `handle-${woodTier}`,
52 stationId: CraftingStationId.woodworkingBench,
53 output: { itemId: handleId, quantity: 1 },
54 inputs: [{ itemId: logId, quantity: 1 }],
55 minSkillLevel: tierCraftSkillLevel(woodTier),
56 skillId: "crafting",
57 xpMaterial: woodTier
58 });
59 }
60
61 function pickaxeHeadRecipe (metalTier, barItemId, headItemId)
62 {
63 return Object.freeze({
64 recipeId: `pickaxe-head-${metalTier}`,
65 stationId: CraftingStationId.anvil,
66 output: { itemId: headItemId, quantity: 1 },
67 inputs: [{ itemId: barItemId, quantity: 1 }],
68 minSkillLevel: tierSmeltSkillLevel(metalTier),
69 skillId: "smithing",
70 xpMaterial: metalTier
71 });
72 }
73
74 function pickaxeAssembleRecipe (metalTier, handleItemId, headItemId, pickaxeItemId)
75 {
76 return Object.freeze({
77 recipeId: `pickaxe-${metalTier}`,
78 stationId: CraftingStationId.woodworkingBench,
79 output: { itemId: pickaxeItemId, quantity: 1 },
80 inputs: [
81 { itemId: handleItemId, quantity: 1 },
82 { itemId: headItemId, quantity: 1 }
83 ],
84 minSkillLevel: tierCraftSkillLevel(metalTier),
85 skillId: "crafting",
86 xpMaterial: metalTier
87 });
88 }
89
90 const BAR_BY_METAL = Object.freeze({
91 [MaterialTier.bronze]: CraftingItemId.bronzeBar,
92 [MaterialTier.iron]: MetalItemId.ironBar,
93 [MaterialTier.steel]: MetalItemId.steelBar,
94 [MaterialTier.mithril]: MetalItemId.mithrilBar,
95 [MaterialTier.adamantium]: MetalItemId.adamantiumBar,
96 [MaterialTier.orichalcum]: MetalItemId.orichalcumBar,
97 [MaterialTier.dragon]: MetalItemId.dragonBar
98 });
99
100 const PICKAXE_BY_METAL = Object.freeze({
101 [MaterialTier.bronze]: CraftingItemId.bronzePickaxe,
102 ...PICKAXE_ITEM_BY_METAL
103 });
104
105 const WOOD_HANDLE_RECIPES = WOOD_TIER_ORDER.map((tier) => handleRecipe(tier));
106
107 const PICKAXE_HEAD_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
108 pickaxeHeadRecipe(tier, BAR_BY_METAL[tier], PICKAXE_HEAD_ITEM_BY_METAL[tier]));
109
110 const PICKAXE_ASSEMBLE_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
111 {
112 const wood = woodTierForMetal(tier);
113 return pickaxeAssembleRecipe(
114 tier,
115 handleItemIdForWood(wood),
116 PICKAXE_HEAD_ITEM_BY_METAL[tier],
117 PICKAXE_BY_METAL[tier]
118 );
119 });
120
30 121 /** @type {ReadonlyArray<object>} */
31 122 export const CRAFT_RECIPES = Object.freeze([
32 123 Object.freeze({
@@ -38,7 +129,8 @@ export const CRAFT_RECIPES = Object.freeze([
38 129 }),
39 130
40 131 smelt(MaterialTier.bronze, "smelt-bronze", [
41 { itemId: CraftingItemId.bronzeOre, quantity: 1 }
132 { itemId: CraftingItemId.tinOre, quantity: 1 },
133 { itemId: CraftingItemId.copperOre, quantity: 1 }
42 134 ], CraftingItemId.bronzeBar),
43 135
44 136 smelt(MaterialTier.iron, "smelt-iron", [
@@ -64,7 +156,11 @@ export const CRAFT_RECIPES = Object.freeze([
64 156
65 157 smelt(MaterialTier.dragon, "smelt-dragon", [
66 158 { itemId: MetalItemId.dragonOre, quantity: 1 }
67 ], MetalItemId.dragonBar)
159 ], MetalItemId.dragonBar),
160
161 ...WOOD_HANDLE_RECIPES,
162 ...PICKAXE_HEAD_RECIPES,
163 ...PICKAXE_ASSEMBLE_RECIPES
68 164 ]);
69 165
70 166 const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
@@ -1,8 +1,23 @@
1import { CraftingStationId } from "../definitions/craftingStations.js";
1import { CraftingStationId } from "../definitions/craftingStations.js";
2import { ItemId } from "../definitions/items.js";
2import { ItemId } from "../definitions/items.js";
3import { CraftingItemId } from "../definitions/craftingItems.js";
3import { CraftingItemId } from "../definitions/craftingItems.js";
4import { MetalItemId } from "../definitions/metalItems.js";
4import {
5import { MaterialTier, tierSmeltSkillLevel } from "../definitions/materialTiers.js";
5 MetalItemId,
6 PICKAXE_HEAD_ITEM_BY_METAL,
7 PICKAXE_ITEM_BY_METAL
8} from "../definitions/metalItems.js";
9import {
10 WOOD_TIER_ORDER,
11 MaterialTier,
12 MATERIAL_TIER_ORDER,
13 woodTierForMetal,
14 tierSmeltSkillLevel,
15 tierCraftSkillLevel
16} from "../definitions/materialTiers.js";
17import {
18 logItemIdForWood,
19 handleItemIdForWood
20} from "../definitions/woodItems.js";
6
21
7/**
22/**
8 * Craft recipe schema (shared client + server):
23 * Craft recipe schema (shared client + server):
@@ -12,6 +27,7 @@ import { MaterialTier, tierSmeltSkillLevel } from "../definitions/materialTiers.
12 * - output: { itemId, quantity }
27 * - output: { itemId, quantity }
13 * - inputs: [{ itemId, quantity }, ...]
28 * - inputs: [{ itemId, quantity }, ...]
14 * - minSkillLevel: minimum linked station skill (default 1)
29 * - minSkillLevel: minimum linked station skill (default 1)
30 * - xpMaterial: tier id for duration + XP scaling
15 */
31 */
16
32
17function smelt (tier, recipeId, inputs, outputItemId)
33function smelt (tier, recipeId, inputs, outputItemId)
@@ -27,6 +43,81 @@ function smelt (tier, recipeId, inputs, outputItemId)
27 });
43 });
28}
44}
29
45
46function handleRecipe (woodTier)
47{
48 const logId = logItemIdForWood(woodTier);
49 const handleId = handleItemIdForWood(woodTier);
50 return Object.freeze({
51 recipeId: `handle-${woodTier}`,
52 stationId: CraftingStationId.woodworkingBench,
53 output: { itemId: handleId, quantity: 1 },
54 inputs: [{ itemId: logId, quantity: 1 }],
55 minSkillLevel: tierCraftSkillLevel(woodTier),
56 skillId: "crafting",
57 xpMaterial: woodTier
58 });
59}
60
61function pickaxeHeadRecipe (metalTier, barItemId, headItemId)
62{
63 return Object.freeze({
64 recipeId: `pickaxe-head-${metalTier}`,
65 stationId: CraftingStationId.anvil,
66 output: { itemId: headItemId, quantity: 1 },
67 inputs: [{ itemId: barItemId, quantity: 1 }],
68 minSkillLevel: tierSmeltSkillLevel(metalTier),
69 skillId: "smithing",
70 xpMaterial: metalTier
71 });
72}
73
74function pickaxeAssembleRecipe (metalTier, handleItemId, headItemId, pickaxeItemId)
75{
76 return Object.freeze({
77 recipeId: `pickaxe-${metalTier}`,
78 stationId: CraftingStationId.woodworkingBench,
79 output: { itemId: pickaxeItemId, quantity: 1 },
80 inputs: [
81 { itemId: handleItemId, quantity: 1 },
82 { itemId: headItemId, quantity: 1 }
83 ],
84 minSkillLevel: tierCraftSkillLevel(metalTier),
85 skillId: "crafting",
86 xpMaterial: metalTier
87 });
88}
89
90const BAR_BY_METAL = Object.freeze({
91 [MaterialTier.bronze]: CraftingItemId.bronzeBar,
92 [MaterialTier.iron]: MetalItemId.ironBar,
93 [MaterialTier.steel]: MetalItemId.steelBar,
94 [MaterialTier.mithril]: MetalItemId.mithrilBar,
95 [MaterialTier.adamantium]: MetalItemId.adamantiumBar,
96 [MaterialTier.orichalcum]: MetalItemId.orichalcumBar,
97 [MaterialTier.dragon]: MetalItemId.dragonBar
98});
99
100const PICKAXE_BY_METAL = Object.freeze({
101 [MaterialTier.bronze]: CraftingItemId.bronzePickaxe,
102 ...PICKAXE_ITEM_BY_METAL
103});
104
105const WOOD_HANDLE_RECIPES = WOOD_TIER_ORDER.map((tier) => handleRecipe(tier));
106
107const PICKAXE_HEAD_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
108 pickaxeHeadRecipe(tier, BAR_BY_METAL[tier], PICKAXE_HEAD_ITEM_BY_METAL[tier]));
109
110const PICKAXE_ASSEMBLE_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
111{
112 const wood = woodTierForMetal(tier);
113 return pickaxeAssembleRecipe(
114 tier,
115 handleItemIdForWood(wood),
116 PICKAXE_HEAD_ITEM_BY_METAL[tier],
117 PICKAXE_BY_METAL[tier]
118 );
119});
120
30/** @type {ReadonlyArray<object>} */
121/** @type {ReadonlyArray<object>} */
31export const CRAFT_RECIPES = Object.freeze([
122export const CRAFT_RECIPES = Object.freeze([
32 Object.freeze({
123 Object.freeze({
@@ -38,7 +129,8 @@ export const CRAFT_RECIPES = Object.freeze([
38 }),
129 }),
39
130
40 smelt(MaterialTier.bronze, "smelt-bronze", [
131 smelt(MaterialTier.bronze, "smelt-bronze", [
41 { itemId: CraftingItemId.bronzeOre, quantity: 1 }
132 { itemId: CraftingItemId.tinOre, quantity: 1 },
133 { itemId: CraftingItemId.copperOre, quantity: 1 }
42 ], CraftingItemId.bronzeBar),
134 ], CraftingItemId.bronzeBar),
43
135
44 smelt(MaterialTier.iron, "smelt-iron", [
136 smelt(MaterialTier.iron, "smelt-iron", [
@@ -64,7 +156,11 @@ export const CRAFT_RECIPES = Object.freeze([
64
156
65 smelt(MaterialTier.dragon, "smelt-dragon", [
157 smelt(MaterialTier.dragon, "smelt-dragon", [
66 { itemId: MetalItemId.dragonOre, quantity: 1 }
158 { itemId: MetalItemId.dragonOre, quantity: 1 }
67 ], MetalItemId.dragonBar)
159 ], MetalItemId.dragonBar),
160
161 ...WOOD_HANDLE_RECIPES,
162 ...PICKAXE_HEAD_RECIPES,
163 ...PICKAXE_ASSEMBLE_RECIPES
68]);
164]);
69
165
70const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
166const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
shared/definitions/craftingItems.js +26 −14
@@ -1,5 +1,5 @@
1 1 import { ItemCategory } from "./itemCategories.js";
2 import { MaterialTier } from "./materialTiers.js";
2 import { MaterialTier, GatherMaterialId } from "./materialTiers.js";
3 3 import { EquipmentKind } from "./equipmentKinds.js";
4 4
5 5 const DEFAULT_STACK = 99;
@@ -9,11 +9,10 @@ const DEFAULT_STACK = 99;
9 9 * Metal ores/bars/pickaxes above bronze live in metalItems.js (35+).
10 10 */
11 11 export const CraftingItemId = Object.freeze({
12 log: 9,
13 12 tinderbox: 10,
14 13 wool: 11,
15 14 thread: 12,
16 bronzeOre: 13,
15 copperOre: 13,
17 16 bronzeBar: 14,
18 17 rawMeat: 15,
19 18 cookedMeat: 16,
@@ -25,7 +24,8 @@ export const CraftingItemId = Object.freeze({
25 24 fishingRod: 22,
26 25 fishingNet: 23,
27 26 rawFish: 24,
28 cloth: 25
27 cloth: 25,
28 tinOre: 53
29 29 });
30 30
31 31 function stub (itemId, key, displayName, category, extra = {})
@@ -48,9 +48,6 @@ function stub (itemId, key, displayName, category, extra = {})
48 48
49 49 /** Minimal defs so recipes and the craft UI can resolve names/icons before art exists. */
50 50 export const CRAFTING_ITEM_STUBS = Object.freeze({
51 [CraftingItemId.log]: stub(CraftingItemId.log, "log", "Log", ItemCategory.ingredient, {
52 description: "Firewood. Drop on the ground and light with a tinderbox (see Crafting stations)."
53 }),
54 51 [CraftingItemId.tinderbox]: stub(CraftingItemId.tinderbox, "tinderbox", "Tinderbox", ItemCategory.tool, {
55 52 stackable: false,
56 53 maxStackSize: 1,
@@ -62,11 +59,11 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
62 59 [CraftingItemId.thread]: stub(CraftingItemId.thread, "thread", "Thread", ItemCategory.intermediate, {
63 60 description: "Spun wool. Used at a loom."
64 61 }),
65 [CraftingItemId.bronzeOre]: Object.freeze({
66 itemId: CraftingItemId.bronzeOre,
67 key: "bronze-ore",
68 displayName: "Bronze ore",
69 description: "Mined ore. Smelt at a furnace into bars.",
62 [CraftingItemId.copperOre]: Object.freeze({
63 itemId: CraftingItemId.copperOre,
64 key: "copper-ore",
65 displayName: "Copper ore",
66 description: "Mined copper. Smelt with tin at a furnace into bronze bars.",
70 67 seedValue: 2,
71 68 stackable: true,
72 69 maxStackSize: DEFAULT_STACK,
@@ -74,14 +71,29 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
74 71 category: ItemCategory.ingredient,
75 72 iconKey: "ore",
76 73 defaultState: "ore",
77 tier: MaterialTier.bronze,
74 tier: GatherMaterialId.copper,
75 tintFromTier: true
76 }),
77 [CraftingItemId.tinOre]: Object.freeze({
78 itemId: CraftingItemId.tinOre,
79 key: "tin-ore",
80 displayName: "Tin ore",
81 description: "Mined tin. Smelt with copper at a furnace into bronze bars.",
82 seedValue: 2,
83 stackable: true,
84 maxStackSize: DEFAULT_STACK,
85 uniqueInstance: false,
86 category: ItemCategory.ingredient,
87 iconKey: "ore",
88 defaultState: "ore",
89 tier: GatherMaterialId.tin,
78 90 tintFromTier: true
79 91 }),
80 92 [CraftingItemId.bronzeBar]: Object.freeze({
81 93 itemId: CraftingItemId.bronzeBar,
82 94 key: "bronze-bar",
83 95 displayName: "Bronze bar",
84 description: "Smelted metal. Smith at an anvil.",
96 description: "Smelted from tin and copper. Smith at an anvil.",
85 97 seedValue: 4,
86 98 stackable: true,
87 99 maxStackSize: DEFAULT_STACK,
@@ -1,5 +1,5 @@
1import { ItemCategory } from "./itemCategories.js";
1import { ItemCategory } from "./itemCategories.js";
2import { MaterialTier } from "./materialTiers.js";
2import { MaterialTier, GatherMaterialId } from "./materialTiers.js";
3import { EquipmentKind } from "./equipmentKinds.js";
3import { EquipmentKind } from "./equipmentKinds.js";
4
4
5const DEFAULT_STACK = 99;
5const DEFAULT_STACK = 99;
@@ -9,11 +9,10 @@ const DEFAULT_STACK = 99;
9 * Metal ores/bars/pickaxes above bronze live in metalItems.js (35+).
9 * Metal ores/bars/pickaxes above bronze live in metalItems.js (35+).
10 */
10 */
11export const CraftingItemId = Object.freeze({
11export const CraftingItemId = Object.freeze({
12 log: 9,
13 tinderbox: 10,
12 tinderbox: 10,
14 wool: 11,
13 wool: 11,
15 thread: 12,
14 thread: 12,
16 bronzeOre: 13,
15 copperOre: 13,
17 bronzeBar: 14,
16 bronzeBar: 14,
18 rawMeat: 15,
17 rawMeat: 15,
19 cookedMeat: 16,
18 cookedMeat: 16,
@@ -25,7 +24,8 @@ export const CraftingItemId = Object.freeze({
25 fishingRod: 22,
24 fishingRod: 22,
26 fishingNet: 23,
25 fishingNet: 23,
27 rawFish: 24,
26 rawFish: 24,
28 cloth: 25
27 cloth: 25,
28 tinOre: 53
29});
29});
30
30
31function stub (itemId, key, displayName, category, extra = {})
31function stub (itemId, key, displayName, category, extra = {})
@@ -48,9 +48,6 @@ function stub (itemId, key, displayName, category, extra = {})
48
48
49/** Minimal defs so recipes and the craft UI can resolve names/icons before art exists. */
49/** Minimal defs so recipes and the craft UI can resolve names/icons before art exists. */
50export const CRAFTING_ITEM_STUBS = Object.freeze({
50export const CRAFTING_ITEM_STUBS = Object.freeze({
51 [CraftingItemId.log]: stub(CraftingItemId.log, "log", "Log", ItemCategory.ingredient, {
52 description: "Firewood. Drop on the ground and light with a tinderbox (see Crafting stations)."
53 }),
54 [CraftingItemId.tinderbox]: stub(CraftingItemId.tinderbox, "tinderbox", "Tinderbox", ItemCategory.tool, {
51 [CraftingItemId.tinderbox]: stub(CraftingItemId.tinderbox, "tinderbox", "Tinderbox", ItemCategory.tool, {
55 stackable: false,
52 stackable: false,
56 maxStackSize: 1,
53 maxStackSize: 1,
@@ -62,11 +59,11 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
62 [CraftingItemId.thread]: stub(CraftingItemId.thread, "thread", "Thread", ItemCategory.intermediate, {
59 [CraftingItemId.thread]: stub(CraftingItemId.thread, "thread", "Thread", ItemCategory.intermediate, {
63 description: "Spun wool. Used at a loom."
60 description: "Spun wool. Used at a loom."
64 }),
61 }),
65 [CraftingItemId.bronzeOre]: Object.freeze({
62 [CraftingItemId.copperOre]: Object.freeze({
66 itemId: CraftingItemId.bronzeOre,
63 itemId: CraftingItemId.copperOre,
67 key: "bronze-ore",
64 key: "copper-ore",
68 displayName: "Bronze ore",
65 displayName: "Copper ore",
69 description: "Mined ore. Smelt at a furnace into bars.",
66 description: "Mined copper. Smelt with tin at a furnace into bronze bars.",
70 seedValue: 2,
67 seedValue: 2,
71 stackable: true,
68 stackable: true,
72 maxStackSize: DEFAULT_STACK,
69 maxStackSize: DEFAULT_STACK,
@@ -74,14 +71,29 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
74 category: ItemCategory.ingredient,
71 category: ItemCategory.ingredient,
75 iconKey: "ore",
72 iconKey: "ore",
76 defaultState: "ore",
73 defaultState: "ore",
77 tier: MaterialTier.bronze,
74 tier: GatherMaterialId.copper,
75 tintFromTier: true
76 }),
77 [CraftingItemId.tinOre]: Object.freeze({
78 itemId: CraftingItemId.tinOre,
79 key: "tin-ore",
80 displayName: "Tin ore",
81 description: "Mined tin. Smelt with copper at a furnace into bronze bars.",
82 seedValue: 2,
83 stackable: true,
84 maxStackSize: DEFAULT_STACK,
85 uniqueInstance: false,
86 category: ItemCategory.ingredient,
87 iconKey: "ore",
88 defaultState: "ore",
89 tier: GatherMaterialId.tin,
78 tintFromTier: true
90 tintFromTier: true
79 }),
91 }),
80 [CraftingItemId.bronzeBar]: Object.freeze({
92 [CraftingItemId.bronzeBar]: Object.freeze({
81 itemId: CraftingItemId.bronzeBar,
93 itemId: CraftingItemId.bronzeBar,
82 key: "bronze-bar",
94 key: "bronze-bar",
83 displayName: "Bronze bar",
95 displayName: "Bronze bar",
84 description: "Smelted metal. Smith at an anvil.",
96 description: "Smelted from tin and copper. Smith at an anvil.",
85 seedValue: 4,
97 seedValue: 4,
86 stackable: true,
98 stackable: true,
87 maxStackSize: DEFAULT_STACK,
99 maxStackSize: DEFAULT_STACK,
shared/definitions/craftingStations.js +7 −0
@@ -8,6 +8,7 @@ export const CraftingStationId = Object.freeze({
8 8 anvil: "anvil",
9 9 leatherworkingStation: "leatherworking-station",
10 10 craftingBench: "crafting-bench",
11 woodworkingBench: "woodworking-bench",
11 12 oven: "oven",
12 13 fireplace: "fireplace"
13 14 });
@@ -55,6 +56,12 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
55 56 skillId: SkillId.crafting,
56 57 description: "General crafting (e.g. fletching arrows from smithed tips)."
57 58 }),
59 [CraftingStationId.woodworkingBench]: Object.freeze({
60 stationId: CraftingStationId.woodworkingBench,
61 displayName: "Woodworking bench",
62 skillId: SkillId.crafting,
63 description: "Shape logs into handles and assemble hafted tools."
64 }),
58 65 [CraftingStationId.oven]: Object.freeze({
59 66 stationId: CraftingStationId.oven,
60 67 displayName: "Oven",
@@ -8,6 +8,7 @@ export const CraftingStationId = Object.freeze({
8 anvil: "anvil",
8 anvil: "anvil",
9 leatherworkingStation: "leatherworking-station",
9 leatherworkingStation: "leatherworking-station",
10 craftingBench: "crafting-bench",
10 craftingBench: "crafting-bench",
11 woodworkingBench: "woodworking-bench",
11 oven: "oven",
12 oven: "oven",
12 fireplace: "fireplace"
13 fireplace: "fireplace"
13});
14});
@@ -55,6 +56,12 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
55 skillId: SkillId.crafting,
56 skillId: SkillId.crafting,
56 description: "General crafting (e.g. fletching arrows from smithed tips)."
57 description: "General crafting (e.g. fletching arrows from smithed tips)."
57 }),
58 }),
59 [CraftingStationId.woodworkingBench]: Object.freeze({
60 stationId: CraftingStationId.woodworkingBench,
61 displayName: "Woodworking bench",
62 skillId: SkillId.crafting,
63 description: "Shape logs into handles and assemble hafted tools."
64 }),
58 [CraftingStationId.oven]: Object.freeze({
65 [CraftingStationId.oven]: Object.freeze({
59 stationId: CraftingStationId.oven,
66 stationId: CraftingStationId.oven,
60 displayName: "Oven",
67 displayName: "Oven",
shared/definitions/gathering.js +76 −10
@@ -1,15 +1,21 @@
1 import { ItemId } from "./items.js";
1 import { ItemId, itemDefinition } from "./items.js";
2 2 import { CraftingItemId } from "./craftingItems.js";
3 3 import { MetalItemId } from "./metalItems.js";
4 import { EquipmentKind } from "./equipmentKinds.js";
5 import { canEquipItem } from "../equipment/stats.js";
6 import { SkillId, skillLevel } from "./skills.js";
4 7 import {
5 8 MaterialTier,
6 9 GatherMaterialId,
7 10 ORE_BEARING_MATERIALS,
11 associatedBarTier,
8 12 tierMineSkillLevel,
9 13 tierSmeltSkillLevel,
10 14 tierRank,
11 15 miningDurationMs,
12 16 oreExhaustDurationMs,
17 smeltingDurationMs,
18 SMELT_DURATION_PER_RANK_MS,
13 19 EXHAUSTED_ORE_BOULDER_STATE,
14 20 oreBoulderState,
15 21 materialFromOreBoulderState,
@@ -18,19 +24,24 @@ import {
18 24
19 25 export {
20 26 ORE_BEARING_MATERIALS,
27 associatedBarTier,
21 28 tierMineSkillLevel,
22 29 tierSmeltSkillLevel,
23 30 miningDurationMs,
24 31 oreExhaustDurationMs,
32 smeltingDurationMs,
33 SMELT_DURATION_PER_RANK_MS,
25 34 EXHAUSTED_ORE_BOULDER_STATE,
26 35 oreBoulderState,
27 36 materialFromOreBoulderState,
28 isOreBoulderState
37 isOreBoulderState,
38 EquipmentKind
29 39 };
30 40
31 41 /** Ore item produced when mining a material node. */
32 42 export const ORE_ITEM_BY_MATERIAL = Object.freeze({
33 [MaterialTier.bronze]: CraftingItemId.bronzeOre,
43 [GatherMaterialId.tin]: CraftingItemId.tinOre,
44 [GatherMaterialId.copper]: CraftingItemId.copperOre,
34 45 [MaterialTier.iron]: MetalItemId.ironOre,
35 46 [MaterialTier.mithril]: MetalItemId.mithrilOre,
36 47 [MaterialTier.adamantium]: MetalItemId.adamantiumOre,
@@ -59,24 +70,22 @@ export function barItemIdForMaterial (materialId)
59 70 return BAR_ITEM_BY_MATERIAL[materialId] ?? null;
60 71 }
61 72
62 /** Mining XP awarded per successful ore (scales with resource rank). */
73 /** Mining XP awarded per successful ore (scales with associated bar rank). */
63 74 export function miningXpForMaterial (materialId)
64 75 {
65 76 return Math.max(1, tierRank(materialId) * 5);
66 77 }
67 78
68 /** Smithing XP awarded per successful smelt. */
79 /** Smithing XP awarded per successful smelt (scales with bar rank). */
69 80 export function smeltingXpForMaterial (materialId)
70 81 {
71 82 return Math.max(1, tierRank(materialId) * 5);
72 83 }
73 84
74 /** Coal uses iron's equip gate for mining skill / tool checks. */
85 /** Mine skill / tool gates use the associated bar's equip tier. */
75 86 export function gatherEquipTier (materialId)
76 87 {
77 if (materialId === GatherMaterialId.coal)
78 { return MaterialTier.iron; }
79 return materialId;
88 return associatedBarTier(materialId);
80 89 }
81 90
82 91 export function canMineMaterial (miningLevel, toolTier, materialId)
@@ -89,10 +98,67 @@ export function canMineMaterial (miningLevel, toolTier, materialId)
89 98 }
90 99 if (tierRank(toolTier) < tierRank(gateTier))
91 100 {
92 return { ok: false, reason: "Your pickaxe is too weak for this rock." };
101 return { ok: false, reason: "You need a pickaxe to mine this!" };
93 102 }
94 103 return { ok: true };
95 104 }
96 105
106 /**
107 * Tools of a given equipment kind in bag slots and/or the weapon slot.
108 * Gathering uses inventory tools without requiring them to be equipped.
109 */
110 export function listGatherTools (inventorySlots, equipmentSlots, kind)
111 {
112 const tools = [];
113 for (const stack of inventorySlots ?? [])
114 {
115 if (!stack?.itemId)
116 { continue; }
117 const def = itemDefinition(stack.itemId);
118 if (def?.equipment?.kind !== kind)
119 { continue; }
120 tools.push({ stack, def, tier: def.equipment.tier, source: "inventory" });
121 }
122 const weapon = equipmentSlots?.weapon;
123 if (weapon?.itemId)
124 {
125 const def = itemDefinition(weapon.itemId);
126 if (def?.equipment?.kind === kind)
127 { tools.push({ stack: weapon, def, tier: def.equipment.tier, source: "equipment" }); }
128 }
129 return tools;
130 }
131
132 /**
133 * Best pickaxe the player can use for this ore (highest tier that meets gates).
134 * @returns {{ ok: true, tool: object } | { ok: false, reason: string }}
135 */
136 export function resolveMiningPickaxe ({ inventorySlots, equipmentSlots, skills, materialId })
137 {
138 const miningLevel = skillLevel(skills, SkillId.mining);
139 const gateTier = gatherEquipTier(materialId);
140 const needSkill = tierMineSkillLevel(gateTier);
141 if ((miningLevel | 0) < needSkill)
142 { return { ok: false, reason: `Requires Mining ${needSkill}.` }; }
143
144 const tools = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.pickaxeTool);
145 const usable = tools
146 .filter((tool) => canEquipItem(skills, tool.def).ok)
147 .filter((tool) => tierRank(tool.tier) >= tierRank(gateTier))
148 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
149
150 if (!usable.length)
151 { return { ok: false, reason: "You need a pickaxe to mine this!" }; }
152 return { ok: true, tool: usable[0] };
153 }
154
155 /** Craft duration: furnace recipes scale by bar tier; others use the fixed craft duration. */
156 export function craftDurationMs (recipe, fallbackMs = 2000)
157 {
158 if (recipe?.xpMaterial)
159 { return smeltingDurationMs(recipe.xpMaterial); }
160 return Math.max(1, fallbackMs | 0 || 2000);
161 }
162
97 163 /** Re-export ItemId helpers used by recipes. */
98 164 export { ItemId, MaterialTier, GatherMaterialId };
@@ -1,15 +1,21 @@
1import { ItemId } from "./items.js";
1import { ItemId, itemDefinition } from "./items.js";
2import { CraftingItemId } from "./craftingItems.js";
2import { CraftingItemId } from "./craftingItems.js";
3import { MetalItemId } from "./metalItems.js";
3import { MetalItemId } from "./metalItems.js";
4import { EquipmentKind } from "./equipmentKinds.js";
5import { canEquipItem } from "../equipment/stats.js";
6import { SkillId, skillLevel } from "./skills.js";
4import {
7import {
5 MaterialTier,
8 MaterialTier,
6 GatherMaterialId,
9 GatherMaterialId,
7 ORE_BEARING_MATERIALS,
10 ORE_BEARING_MATERIALS,
11 associatedBarTier,
8 tierMineSkillLevel,
12 tierMineSkillLevel,
9 tierSmeltSkillLevel,
13 tierSmeltSkillLevel,
10 tierRank,
14 tierRank,
11 miningDurationMs,
15 miningDurationMs,
12 oreExhaustDurationMs,
16 oreExhaustDurationMs,
17 smeltingDurationMs,
18 SMELT_DURATION_PER_RANK_MS,
13 EXHAUSTED_ORE_BOULDER_STATE,
19 EXHAUSTED_ORE_BOULDER_STATE,
14 oreBoulderState,
20 oreBoulderState,
15 materialFromOreBoulderState,
21 materialFromOreBoulderState,
@@ -18,19 +24,24 @@ import {
18
24
19export {
25export {
20 ORE_BEARING_MATERIALS,
26 ORE_BEARING_MATERIALS,
27 associatedBarTier,
21 tierMineSkillLevel,
28 tierMineSkillLevel,
22 tierSmeltSkillLevel,
29 tierSmeltSkillLevel,
23 miningDurationMs,
30 miningDurationMs,
24 oreExhaustDurationMs,
31 oreExhaustDurationMs,
32 smeltingDurationMs,
33 SMELT_DURATION_PER_RANK_MS,
25 EXHAUSTED_ORE_BOULDER_STATE,
34 EXHAUSTED_ORE_BOULDER_STATE,
26 oreBoulderState,
35 oreBoulderState,
27 materialFromOreBoulderState,
36 materialFromOreBoulderState,
28 isOreBoulderState
37 isOreBoulderState,
38 EquipmentKind
29};
39};
30
40
31/** Ore item produced when mining a material node. */
41/** Ore item produced when mining a material node. */
32export const ORE_ITEM_BY_MATERIAL = Object.freeze({
42export const ORE_ITEM_BY_MATERIAL = Object.freeze({
33 [MaterialTier.bronze]: CraftingItemId.bronzeOre,
43 [GatherMaterialId.tin]: CraftingItemId.tinOre,
44 [GatherMaterialId.copper]: CraftingItemId.copperOre,
34 [MaterialTier.iron]: MetalItemId.ironOre,
45 [MaterialTier.iron]: MetalItemId.ironOre,
35 [MaterialTier.mithril]: MetalItemId.mithrilOre,
46 [MaterialTier.mithril]: MetalItemId.mithrilOre,
36 [MaterialTier.adamantium]: MetalItemId.adamantiumOre,
47 [MaterialTier.adamantium]: MetalItemId.adamantiumOre,
@@ -59,24 +70,22 @@ export function barItemIdForMaterial (materialId)
59 return BAR_ITEM_BY_MATERIAL[materialId] ?? null;
70 return BAR_ITEM_BY_MATERIAL[materialId] ?? null;
60}
71}
61
72
62/** Mining XP awarded per successful ore (scales with resource rank). */
73/** Mining XP awarded per successful ore (scales with associated bar rank). */
63export function miningXpForMaterial (materialId)
74export function miningXpForMaterial (materialId)
64{
75{
65 return Math.max(1, tierRank(materialId) * 5);
76 return Math.max(1, tierRank(materialId) * 5);
66}
77}
67
78
68/** Smithing XP awarded per successful smelt. */
79/** Smithing XP awarded per successful smelt (scales with bar rank). */
69export function smeltingXpForMaterial (materialId)
80export function smeltingXpForMaterial (materialId)
70{
81{
71 return Math.max(1, tierRank(materialId) * 5);
82 return Math.max(1, tierRank(materialId) * 5);
72}
83}
73
84
74/** Coal uses iron's equip gate for mining skill / tool checks. */
85/** Mine skill / tool gates use the associated bar's equip tier. */
75export function gatherEquipTier (materialId)
86export function gatherEquipTier (materialId)
76{
87{
77 if (materialId === GatherMaterialId.coal)
88 return associatedBarTier(materialId);
78 { return MaterialTier.iron; }
79 return materialId;
80}
89}
81
90
82export function canMineMaterial (miningLevel, toolTier, materialId)
91export function canMineMaterial (miningLevel, toolTier, materialId)
@@ -89,10 +98,67 @@ export function canMineMaterial (miningLevel, toolTier, materialId)
89 }
98 }
90 if (tierRank(toolTier) < tierRank(gateTier))
99 if (tierRank(toolTier) < tierRank(gateTier))
91 {
100 {
92 return { ok: false, reason: "Your pickaxe is too weak for this rock." };
101 return { ok: false, reason: "You need a pickaxe to mine this!" };
93 }
102 }
94 return { ok: true };
103 return { ok: true };
95}
104}
96
105
106/**
107 * Tools of a given equipment kind in bag slots and/or the weapon slot.
108 * Gathering uses inventory tools without requiring them to be equipped.
109 */
110export function listGatherTools (inventorySlots, equipmentSlots, kind)
111{
112 const tools = [];
113 for (const stack of inventorySlots ?? [])
114 {
115 if (!stack?.itemId)
116 { continue; }
117 const def = itemDefinition(stack.itemId);
118 if (def?.equipment?.kind !== kind)
119 { continue; }
120 tools.push({ stack, def, tier: def.equipment.tier, source: "inventory" });
121 }
122 const weapon = equipmentSlots?.weapon;
123 if (weapon?.itemId)
124 {
125 const def = itemDefinition(weapon.itemId);
126 if (def?.equipment?.kind === kind)
127 { tools.push({ stack: weapon, def, tier: def.equipment.tier, source: "equipment" }); }
128 }
129 return tools;
130}
131
132/**
133 * Best pickaxe the player can use for this ore (highest tier that meets gates).
134 * @returns {{ ok: true, tool: object } | { ok: false, reason: string }}
135 */
136export function resolveMiningPickaxe ({ inventorySlots, equipmentSlots, skills, materialId })
137{
138 const miningLevel = skillLevel(skills, SkillId.mining);
139 const gateTier = gatherEquipTier(materialId);
140 const needSkill = tierMineSkillLevel(gateTier);
141 if ((miningLevel | 0) < needSkill)
142 { return { ok: false, reason: `Requires Mining ${needSkill}.` }; }
143
144 const tools = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.pickaxeTool);
145 const usable = tools
146 .filter((tool) => canEquipItem(skills, tool.def).ok)
147 .filter((tool) => tierRank(tool.tier) >= tierRank(gateTier))
148 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
149
150 if (!usable.length)
151 { return { ok: false, reason: "You need a pickaxe to mine this!" }; }
152 return { ok: true, tool: usable[0] };
153}
154
155/** Craft duration: furnace recipes scale by bar tier; others use the fixed craft duration. */
156export function craftDurationMs (recipe, fallbackMs = 2000)
157{
158 if (recipe?.xpMaterial)
159 { return smeltingDurationMs(recipe.xpMaterial); }
160 return Math.max(1, fallbackMs | 0 || 2000);
161}
162
97/** Re-export ItemId helpers used by recipes. */
163/** Re-export ItemId helpers used by recipes. */
98export { ItemId, MaterialTier, GatherMaterialId };
164export { ItemId, MaterialTier, GatherMaterialId };
shared/definitions/items.js +5 −2
@@ -7,6 +7,7 @@ import { formatQuantity } from "../items/formatQuantity.js";
7 7 import { formatOriginBreakdown } from "../items/origin.js";
8 8 import { CraftingItemId, CRAFTING_ITEM_STUBS } from "./craftingItems.js";
9 9 import { MetalItemId, METAL_ITEM_DEFINITIONS } from "./metalItems.js";
10 import { WoodItemId, WOOD_ITEM_DEFINITIONS } from "./woodItems.js";
10 11 import { POTION_MAX_STACK } from "./alchemy.js";
11 12
12 13 export const ItemId = Object.freeze({
@@ -28,7 +29,8 @@ export const ItemId = Object.freeze({
28 29 potion: 32,
29 30 recipePaper: 33,
30 31 bronzePlantClippers: 34,
31 ...MetalItemId
32 ...MetalItemId,
33 ...WoodItemId
32 34 });
33 35
34 36 export const EQUIPMENT_SLOT = Object.freeze({
@@ -291,7 +293,8 @@ export const ITEM_DEFINITIONS = Object.freeze({
291 293 })
292 294 }),
293 295 ...CRAFTING_ITEM_STUBS,
294 ...METAL_ITEM_DEFINITIONS
296 ...METAL_ITEM_DEFINITIONS,
297 ...WOOD_ITEM_DEFINITIONS
295 298 });
296 299
297 300 export function itemDefinition (itemId)
@@ -7,6 +7,7 @@ import { formatQuantity } from "../items/formatQuantity.js";
7import { formatOriginBreakdown } from "../items/origin.js";
7import { formatOriginBreakdown } from "../items/origin.js";
8import { CraftingItemId, CRAFTING_ITEM_STUBS } from "./craftingItems.js";
8import { CraftingItemId, CRAFTING_ITEM_STUBS } from "./craftingItems.js";
9import { MetalItemId, METAL_ITEM_DEFINITIONS } from "./metalItems.js";
9import { MetalItemId, METAL_ITEM_DEFINITIONS } from "./metalItems.js";
10import { WoodItemId, WOOD_ITEM_DEFINITIONS } from "./woodItems.js";
10import { POTION_MAX_STACK } from "./alchemy.js";
11import { POTION_MAX_STACK } from "./alchemy.js";
11
12
12export const ItemId = Object.freeze({
13export const ItemId = Object.freeze({
@@ -28,7 +29,8 @@ export const ItemId = Object.freeze({
28 potion: 32,
29 potion: 32,
29 recipePaper: 33,
30 recipePaper: 33,
30 bronzePlantClippers: 34,
31 bronzePlantClippers: 34,
31 ...MetalItemId
32 ...MetalItemId,
33 ...WoodItemId
32});
34});
33
35
34export const EQUIPMENT_SLOT = Object.freeze({
36export const EQUIPMENT_SLOT = Object.freeze({
@@ -291,7 +293,8 @@ export const ITEM_DEFINITIONS = Object.freeze({
291 })
293 })
292 }),
294 }),
293 ...CRAFTING_ITEM_STUBS,
295 ...CRAFTING_ITEM_STUBS,
294 ...METAL_ITEM_DEFINITIONS
296 ...METAL_ITEM_DEFINITIONS,
297 ...WOOD_ITEM_DEFINITIONS
295});
298});
296
299
297export function itemDefinition (itemId)
300export function itemDefinition (itemId)
shared/definitions/materialTiers.js +145 −15
@@ -12,6 +12,20 @@ export const MaterialTier = Object.freeze({
12 12 dragon: "dragon"
13 13 });
14 14
15 /**
16 * Wood materials — same ranks / skill gates as metals (gather with axe later).
17 * Matching metal: pine↔bronze … elder↔dragon.
18 */
19 export const WoodTier = Object.freeze({
20 pine: "pine",
21 birch: "birch",
22 oak: "oak",
23 ebony: "ebony",
24 lignum: "lignum",
25 heartwood: "heartwood",
26 elder: "elder"
27 });
28
15 29 /** Ordered low → high (metal smithing / tools). */
16 30 export const MATERIAL_TIER_ORDER = Object.freeze([
17 31 MaterialTier.bronze,
@@ -23,9 +37,26 @@ export const MATERIAL_TIER_ORDER = Object.freeze([
23 37 MaterialTier.dragon
24 38 ]);
25 39
26 /** Non-metal gatherable that shares ore-boulder art (dark gray tint). */
40 /** Ordered low → high (woodcutting / woodcraft). */
41 export const WOOD_TIER_ORDER = Object.freeze([
42 WoodTier.pine,
43 WoodTier.birch,
44 WoodTier.oak,
45 WoodTier.ebony,
46 WoodTier.lignum,
47 WoodTier.heartwood,
48 WoodTier.elder
49 ]);
50
51 /**
52 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
53 * Tin + copper smelt into bronze; coal fuels steel. Their mine/smelt timing
54 * uses {@link associatedBarTier}.
55 */
27 56 export const GatherMaterialId = Object.freeze({
28 57 ...MaterialTier,
58 tin: "tin",
59 copper: "copper",
29 60 coal: "coal"
30 61 });
31 62
@@ -37,10 +68,17 @@ export const TIER_MIN_SKILL_LEVEL = Object.freeze({
37 68 [MaterialTier.mithril]: 35,
38 69 [MaterialTier.adamantium]: 50,
39 70 [MaterialTier.orichalcum]: 70,
40 [MaterialTier.dragon]: 90
71 [MaterialTier.dragon]: 90,
72 [WoodTier.pine]: 1,
73 [WoodTier.birch]: 10,
74 [WoodTier.oak]: 20,
75 [WoodTier.ebony]: 35,
76 [WoodTier.lignum]: 50,
77 [WoodTier.heartwood]: 70,
78 [WoodTier.elder]: 90
41 79 });
42 80
43 /** Rank used for mining duration and relative power (1 = bronze … 7 = dragon). */
81 /** Rank used for mining duration and relative power (1 = bronze/pine … 7 = dragon/elder). */
44 82 export const TIER_RANK = Object.freeze({
45 83 [MaterialTier.bronze]: 1,
46 84 [MaterialTier.iron]: 2,
@@ -49,7 +87,13 @@ export const TIER_RANK = Object.freeze({
49 87 [MaterialTier.adamantium]: 5,
50 88 [MaterialTier.orichalcum]: 6,
51 89 [MaterialTier.dragon]: 7,
52 [GatherMaterialId.coal]: 2
90 [WoodTier.pine]: 1,
91 [WoodTier.birch]: 2,
92 [WoodTier.oak]: 3,
93 [WoodTier.ebony]: 4,
94 [WoodTier.lignum]: 5,
95 [WoodTier.heartwood]: 6,
96 [WoodTier.elder]: 7
53 97 });
54 98
55 99 /** Stat bonus granted by tier for the equipment's bonus category. */
@@ -60,7 +104,14 @@ export const TIER_STAT_BONUS = Object.freeze({
60 104 [MaterialTier.mithril]: 6,
61 105 [MaterialTier.adamantium]: 8,
62 106 [MaterialTier.orichalcum]: 10,
63 [MaterialTier.dragon]: 12
107 [MaterialTier.dragon]: 12,
108 [WoodTier.pine]: 1,
109 [WoodTier.birch]: 2,
110 [WoodTier.oak]: 4,
111 [WoodTier.ebony]: 6,
112 [WoodTier.lignum]: 8,
113 [WoodTier.heartwood]: 10,
114 [WoodTier.elder]: 12
64 115 });
65 116
66 117 /** Display names for UI / editor. */
@@ -72,7 +123,16 @@ export const MATERIAL_DISPLAY_NAME = Object.freeze({
72 123 [MaterialTier.adamantium]: "Adamantium",
73 124 [MaterialTier.orichalcum]: "Orichalcum",
74 125 [MaterialTier.dragon]: "Dragon",
75 [GatherMaterialId.coal]: "Coal"
126 [GatherMaterialId.tin]: "Tin",
127 [GatherMaterialId.copper]: "Copper",
128 [GatherMaterialId.coal]: "Coal",
129 [WoodTier.pine]: "Pine",
130 [WoodTier.birch]: "Birch",
131 [WoodTier.oak]: "Oak",
132 [WoodTier.ebony]: "Ebony",
133 [WoodTier.lignum]: "Lignum",
134 [WoodTier.heartwood]: "Heartwood",
135 [WoodTier.elder]: "Elder"
76 136 });
77 137
78 138 /**
@@ -87,9 +147,46 @@ export const MATERIAL_TINT_COLOR = Object.freeze({
87 147 [MaterialTier.adamantium]: Object.freeze({ r: 0.35, g: 0.75, b: 0.45 }),
88 148 [MaterialTier.orichalcum]: Object.freeze({ r: 0.90, g: 0.55, b: 0.22 }),
89 149 [MaterialTier.dragon]: Object.freeze({ r: 0.88, g: 0.18, b: 0.16 }),
90 [GatherMaterialId.coal]: Object.freeze({ r: 0.22, g: 0.22, b: 0.25 })
150 [GatherMaterialId.tin]: Object.freeze({ r: 0.78, g: 0.80, b: 0.82 }),
151 [GatherMaterialId.copper]: Object.freeze({ r: 0.85, g: 0.45, b: 0.22 }),
152 [GatherMaterialId.coal]: Object.freeze({ r: 0.22, g: 0.22, b: 0.25 }),
153 [WoodTier.pine]: Object.freeze({ r: 0.78, g: 0.62, b: 0.38 }),
154 [WoodTier.birch]: Object.freeze({ r: 0.88, g: 0.82, b: 0.68 }),
155 [WoodTier.oak]: Object.freeze({ r: 0.62, g: 0.42, b: 0.24 }),
156 [WoodTier.ebony]: Object.freeze({ r: 0.22, g: 0.16, b: 0.20 }),
157 [WoodTier.lignum]: Object.freeze({ r: 0.42, g: 0.38, b: 0.22 }),
158 [WoodTier.heartwood]: Object.freeze({ r: 0.72, g: 0.28, b: 0.22 }),
159 [WoodTier.elder]: Object.freeze({ r: 0.72, g: 0.74, b: 0.78 })
160 });
161
162 /** Wood tier that matches a metal tier's rank (for tool hafts). */
163 export const WOOD_TIER_FOR_METAL = Object.freeze({
164 [MaterialTier.bronze]: WoodTier.pine,
165 [MaterialTier.iron]: WoodTier.birch,
166 [MaterialTier.steel]: WoodTier.oak,
167 [MaterialTier.mithril]: WoodTier.ebony,
168 [MaterialTier.adamantium]: WoodTier.lignum,
169 [MaterialTier.orichalcum]: WoodTier.heartwood,
170 [MaterialTier.dragon]: WoodTier.elder
91 171 });
92 172
173 export const METAL_TIER_FOR_WOOD = Object.freeze(Object.fromEntries(
174 Object.entries(WOOD_TIER_FOR_METAL).map(([metal, wood]) => [wood, metal])
175 ));
176
177 /**
178 * Bar tier that drives mine/smelt duration and gates for a gatherable.
179 * Tin/copper → bronze; coal → steel; other metals map to themselves.
180 */
181 export function associatedBarTier (materialId)
182 {
183 if (materialId === GatherMaterialId.tin || materialId === GatherMaterialId.copper)
184 { return MaterialTier.bronze; }
185 if (materialId === GatherMaterialId.coal)
186 { return MaterialTier.steel; }
187 return materialId;
188 }
189
93 190 export function materialDisplayName (materialId)
94 191 {
95 192 return MATERIAL_DISPLAY_NAME[materialId] ?? materialId;
@@ -112,24 +209,41 @@ export function tierMinSkillLevel (tier)
112 209
113 210 export function tierRank (tier)
114 211 {
115 return TIER_RANK[tier] ?? 1;
212 return TIER_RANK[associatedBarTier(tier)] ?? TIER_RANK[tier] ?? 1;
116 213 }
117 214
118 /** Mining skill required to mine this material's ore (half of equip gate, ceil). */
215 /** Mining / woodcutting skill required (half of equip gate, ceil). */
119 216 export function tierMineSkillLevel (tier)
120 217 {
121 return Math.max(1, Math.ceil(tierMinSkillLevel(tier) / 2));
218 return Math.max(1, Math.ceil(tierMinSkillLevel(associatedBarTier(tier)) / 2));
122 219 }
123 220
124 /** Smithing skill required to smelt this metal (75% of equip gate, ceil). */
221 /** Smithing / woodcraft skill required to process this material (75% of equip gate, ceil). */
125 222 export function tierSmeltSkillLevel (tier)
126 223 {
127 return Math.max(1, Math.ceil(tierMinSkillLevel(tier) * 0.75));
224 return Math.max(1, Math.ceil(tierMinSkillLevel(associatedBarTier(tier)) * 0.75));
225 }
226
227 /** Alias for woodworking / general craft gates (same curve as smelting). */
228 export function tierCraftSkillLevel (tier)
229 {
230 return tierSmeltSkillLevel(tier);
231 }
232
233 export function woodTierForMetal (metalTier)
234 {
235 return WOOD_TIER_FOR_METAL[metalTier] ?? WoodTier.pine;
236 }
237
238 export function metalTierForWood (woodTier)
239 {
240 return METAL_TIER_FOR_WOOD[woodTier] ?? MaterialTier.bronze;
128 241 }
129 242
130 243 /**
131 244 * Mining action duration in ms.
132 245 * (resourceRank * 8s) − (toolRank * 3s), floored at 0.5s.
246 * Tin/copper/coal use their associated bar's rank.
133 247 */
134 248 export function miningDurationMs (resourceMaterialId, toolTier)
135 249 {
@@ -139,18 +253,34 @@ export function miningDurationMs (resourceMaterialId, toolTier)
139 253 return Math.round(seconds * 1000);
140 254 }
141 255
142 /** After a successful mine, nodes stay exhausted for 10s × material rank. */
256 /** After a successful mine, nodes stay exhausted for 10s × associated bar rank. */
143 257 export function oreExhaustDurationMs (materialId)
144 258 {
145 259 return Math.max(1, tierRank(materialId)) * 10_000;
146 260 }
147 261
262 /** Base craft duration per bar rank (bronze = 2s, iron = 4s, …). */
263 export const SMELT_DURATION_PER_RANK_MS = 2000;
264
265 /**
266 * Furnace smelt duration from the output bar's associated tier rank.
267 * Tin/copper/coal map to bronze/steel so ingredient timing matches that bar.
268 */
269 export function smeltingDurationMs (barOrMaterialId)
270 {
271 return Math.max(1, tierRank(barOrMaterialId)) * SMELT_DURATION_PER_RANK_MS;
272 }
273
148 274 /** Visual / interact state while an ore boulder is depleted (plain rock). */
149 275 export const EXHAUSTED_ORE_BOULDER_STATE = "boulder";
150 276
151 /** Metals that have an ore node (steel is smelted from iron + coal). */
277 /**
278 * Materials that have an ore boulder node.
279 * Bronze has no ore (tin + copper); steel has no ore (iron + coal).
280 */
152 281 export const ORE_BEARING_MATERIALS = Object.freeze([
153 MaterialTier.bronze,
282 GatherMaterialId.tin,
283 GatherMaterialId.copper,
154 284 MaterialTier.iron,
155 285 MaterialTier.mithril,
156 286 MaterialTier.adamantium,
@@ -12,6 +12,20 @@ export const MaterialTier = Object.freeze({
12 dragon: "dragon"
12 dragon: "dragon"
13});
13});
14
14
15/**
16 * Wood materials — same ranks / skill gates as metals (gather with axe later).
17 * Matching metal: pine↔bronze … elder↔dragon.
18 */
19export const WoodTier = Object.freeze({
20 pine: "pine",
21 birch: "birch",
22 oak: "oak",
23 ebony: "ebony",
24 lignum: "lignum",
25 heartwood: "heartwood",
26 elder: "elder"
27});
28
15/** Ordered low → high (metal smithing / tools). */
29/** Ordered low → high (metal smithing / tools). */
16export const MATERIAL_TIER_ORDER = Object.freeze([
30export const MATERIAL_TIER_ORDER = Object.freeze([
17 MaterialTier.bronze,
31 MaterialTier.bronze,
@@ -23,9 +37,26 @@ export const MATERIAL_TIER_ORDER = Object.freeze([
23 MaterialTier.dragon
37 MaterialTier.dragon
24]);
38]);
25
39
26/** Non-metal gatherable that shares ore-boulder art (dark gray tint). */
40/** Ordered low → high (woodcutting / woodcraft). */
41export const WOOD_TIER_ORDER = Object.freeze([
42 WoodTier.pine,
43 WoodTier.birch,
44 WoodTier.oak,
45 WoodTier.ebony,
46 WoodTier.lignum,
47 WoodTier.heartwood,
48 WoodTier.elder
49]);
50
51/**
52 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
53 * Tin + copper smelt into bronze; coal fuels steel. Their mine/smelt timing
54 * uses {@link associatedBarTier}.
55 */
27export const GatherMaterialId = Object.freeze({
56export const GatherMaterialId = Object.freeze({
28 ...MaterialTier,
57 ...MaterialTier,
58 tin: "tin",
59 copper: "copper",
29 coal: "coal"
60 coal: "coal"
30});
61});
31
62
@@ -37,10 +68,17 @@ export const TIER_MIN_SKILL_LEVEL = Object.freeze({
37 [MaterialTier.mithril]: 35,
68 [MaterialTier.mithril]: 35,
38 [MaterialTier.adamantium]: 50,
69 [MaterialTier.adamantium]: 50,
39 [MaterialTier.orichalcum]: 70,
70 [MaterialTier.orichalcum]: 70,
40 [MaterialTier.dragon]: 90
71 [MaterialTier.dragon]: 90,
72 [WoodTier.pine]: 1,
73 [WoodTier.birch]: 10,
74 [WoodTier.oak]: 20,
75 [WoodTier.ebony]: 35,
76 [WoodTier.lignum]: 50,
77 [WoodTier.heartwood]: 70,
78 [WoodTier.elder]: 90
41});
79});
42
80
43/** Rank used for mining duration and relative power (1 = bronze … 7 = dragon). */
81/** Rank used for mining duration and relative power (1 = bronze/pine … 7 = dragon/elder). */
44export const TIER_RANK = Object.freeze({
82export const TIER_RANK = Object.freeze({
45 [MaterialTier.bronze]: 1,
83 [MaterialTier.bronze]: 1,
46 [MaterialTier.iron]: 2,
84 [MaterialTier.iron]: 2,
@@ -49,7 +87,13 @@ export const TIER_RANK = Object.freeze({
49 [MaterialTier.adamantium]: 5,
87 [MaterialTier.adamantium]: 5,
50 [MaterialTier.orichalcum]: 6,
88 [MaterialTier.orichalcum]: 6,
51 [MaterialTier.dragon]: 7,
89 [MaterialTier.dragon]: 7,
52 [GatherMaterialId.coal]: 2
90 [WoodTier.pine]: 1,
91 [WoodTier.birch]: 2,
92 [WoodTier.oak]: 3,
93 [WoodTier.ebony]: 4,
94 [WoodTier.lignum]: 5,
95 [WoodTier.heartwood]: 6,
96 [WoodTier.elder]: 7
53});
97});
54
98
55/** Stat bonus granted by tier for the equipment's bonus category. */
99/** Stat bonus granted by tier for the equipment's bonus category. */
@@ -60,7 +104,14 @@ export const TIER_STAT_BONUS = Object.freeze({
60 [MaterialTier.mithril]: 6,
104 [MaterialTier.mithril]: 6,
61 [MaterialTier.adamantium]: 8,
105 [MaterialTier.adamantium]: 8,
62 [MaterialTier.orichalcum]: 10,
106 [MaterialTier.orichalcum]: 10,
63 [MaterialTier.dragon]: 12
107 [MaterialTier.dragon]: 12,
108 [WoodTier.pine]: 1,
109 [WoodTier.birch]: 2,
110 [WoodTier.oak]: 4,
111 [WoodTier.ebony]: 6,
112 [WoodTier.lignum]: 8,
113 [WoodTier.heartwood]: 10,
114 [WoodTier.elder]: 12
64});
115});
65
116
66/** Display names for UI / editor. */
117/** Display names for UI / editor. */
@@ -72,7 +123,16 @@ export const MATERIAL_DISPLAY_NAME = Object.freeze({
72 [MaterialTier.adamantium]: "Adamantium",
123 [MaterialTier.adamantium]: "Adamantium",
73 [MaterialTier.orichalcum]: "Orichalcum",
124 [MaterialTier.orichalcum]: "Orichalcum",
74 [MaterialTier.dragon]: "Dragon",
125 [MaterialTier.dragon]: "Dragon",
75 [GatherMaterialId.coal]: "Coal"
126 [GatherMaterialId.tin]: "Tin",
127 [GatherMaterialId.copper]: "Copper",
128 [GatherMaterialId.coal]: "Coal",
129 [WoodTier.pine]: "Pine",
130 [WoodTier.birch]: "Birch",
131 [WoodTier.oak]: "Oak",
132 [WoodTier.ebony]: "Ebony",
133 [WoodTier.lignum]: "Lignum",
134 [WoodTier.heartwood]: "Heartwood",
135 [WoodTier.elder]: "Elder"
76});
136});
77
137
78/**
138/**
@@ -87,9 +147,46 @@ export const MATERIAL_TINT_COLOR = Object.freeze({
87 [MaterialTier.adamantium]: Object.freeze({ r: 0.35, g: 0.75, b: 0.45 }),
147 [MaterialTier.adamantium]: Object.freeze({ r: 0.35, g: 0.75, b: 0.45 }),
88 [MaterialTier.orichalcum]: Object.freeze({ r: 0.90, g: 0.55, b: 0.22 }),
148 [MaterialTier.orichalcum]: Object.freeze({ r: 0.90, g: 0.55, b: 0.22 }),
89 [MaterialTier.dragon]: Object.freeze({ r: 0.88, g: 0.18, b: 0.16 }),
149 [MaterialTier.dragon]: Object.freeze({ r: 0.88, g: 0.18, b: 0.16 }),
90 [GatherMaterialId.coal]: Object.freeze({ r: 0.22, g: 0.22, b: 0.25 })
150 [GatherMaterialId.tin]: Object.freeze({ r: 0.78, g: 0.80, b: 0.82 }),
151 [GatherMaterialId.copper]: Object.freeze({ r: 0.85, g: 0.45, b: 0.22 }),
152 [GatherMaterialId.coal]: Object.freeze({ r: 0.22, g: 0.22, b: 0.25 }),
153 [WoodTier.pine]: Object.freeze({ r: 0.78, g: 0.62, b: 0.38 }),
154 [WoodTier.birch]: Object.freeze({ r: 0.88, g: 0.82, b: 0.68 }),
155 [WoodTier.oak]: Object.freeze({ r: 0.62, g: 0.42, b: 0.24 }),
156 [WoodTier.ebony]: Object.freeze({ r: 0.22, g: 0.16, b: 0.20 }),
157 [WoodTier.lignum]: Object.freeze({ r: 0.42, g: 0.38, b: 0.22 }),
158 [WoodTier.heartwood]: Object.freeze({ r: 0.72, g: 0.28, b: 0.22 }),
159 [WoodTier.elder]: Object.freeze({ r: 0.72, g: 0.74, b: 0.78 })
160});
161
162/** Wood tier that matches a metal tier's rank (for tool hafts). */
163export const WOOD_TIER_FOR_METAL = Object.freeze({
164 [MaterialTier.bronze]: WoodTier.pine,
165 [MaterialTier.iron]: WoodTier.birch,
166 [MaterialTier.steel]: WoodTier.oak,
167 [MaterialTier.mithril]: WoodTier.ebony,
168 [MaterialTier.adamantium]: WoodTier.lignum,
169 [MaterialTier.orichalcum]: WoodTier.heartwood,
170 [MaterialTier.dragon]: WoodTier.elder
91});
171});
92
172
173export const METAL_TIER_FOR_WOOD = Object.freeze(Object.fromEntries(
174 Object.entries(WOOD_TIER_FOR_METAL).map(([metal, wood]) => [wood, metal])
175));
176
177/**
178 * Bar tier that drives mine/smelt duration and gates for a gatherable.
179 * Tin/copper → bronze; coal → steel; other metals map to themselves.
180 */
181export function associatedBarTier (materialId)
182{
183 if (materialId === GatherMaterialId.tin || materialId === GatherMaterialId.copper)
184 { return MaterialTier.bronze; }
185 if (materialId === GatherMaterialId.coal)
186 { return MaterialTier.steel; }
187 return materialId;
188}
189
93export function materialDisplayName (materialId)
190export function materialDisplayName (materialId)
94{
191{
95 return MATERIAL_DISPLAY_NAME[materialId] ?? materialId;
192 return MATERIAL_DISPLAY_NAME[materialId] ?? materialId;
@@ -112,24 +209,41 @@ export function tierMinSkillLevel (tier)
112
209
113export function tierRank (tier)
210export function tierRank (tier)
114{
211{
115 return TIER_RANK[tier] ?? 1;
212 return TIER_RANK[associatedBarTier(tier)] ?? TIER_RANK[tier] ?? 1;
116}
213}
117
214
118/** Mining skill required to mine this material's ore (half of equip gate, ceil). */
215/** Mining / woodcutting skill required (half of equip gate, ceil). */
119export function tierMineSkillLevel (tier)
216export function tierMineSkillLevel (tier)
120{
217{
121 return Math.max(1, Math.ceil(tierMinSkillLevel(tier) / 2));
218 return Math.max(1, Math.ceil(tierMinSkillLevel(associatedBarTier(tier)) / 2));
122}
219}
123
220
124/** Smithing skill required to smelt this metal (75% of equip gate, ceil). */
221/** Smithing / woodcraft skill required to process this material (75% of equip gate, ceil). */
125export function tierSmeltSkillLevel (tier)
222export function tierSmeltSkillLevel (tier)
126{
223{
127 return Math.max(1, Math.ceil(tierMinSkillLevel(tier) * 0.75));
224 return Math.max(1, Math.ceil(tierMinSkillLevel(associatedBarTier(tier)) * 0.75));
225}
226
227/** Alias for woodworking / general craft gates (same curve as smelting). */
228export function tierCraftSkillLevel (tier)
229{
230 return tierSmeltSkillLevel(tier);
231}
232
233export function woodTierForMetal (metalTier)
234{
235 return WOOD_TIER_FOR_METAL[metalTier] ?? WoodTier.pine;
236}
237
238export function metalTierForWood (woodTier)
239{
240 return METAL_TIER_FOR_WOOD[woodTier] ?? MaterialTier.bronze;
128}
241}
129
242
130/**
243/**
131 * Mining action duration in ms.
244 * Mining action duration in ms.
132 * (resourceRank * 8s) − (toolRank * 3s), floored at 0.5s.
245 * (resourceRank * 8s) − (toolRank * 3s), floored at 0.5s.
246 * Tin/copper/coal use their associated bar's rank.
133 */
247 */
134export function miningDurationMs (resourceMaterialId, toolTier)
248export function miningDurationMs (resourceMaterialId, toolTier)
135{
249{
@@ -139,18 +253,34 @@ export function miningDurationMs (resourceMaterialId, toolTier)
139 return Math.round(seconds * 1000);
253 return Math.round(seconds * 1000);
140}
254}
141
255
142/** After a successful mine, nodes stay exhausted for 10s × material rank. */
256/** After a successful mine, nodes stay exhausted for 10s × associated bar rank. */
143export function oreExhaustDurationMs (materialId)
257export function oreExhaustDurationMs (materialId)
144{
258{
145 return Math.max(1, tierRank(materialId)) * 10_000;
259 return Math.max(1, tierRank(materialId)) * 10_000;
146}
260}
147
261
262/** Base craft duration per bar rank (bronze = 2s, iron = 4s, …). */
263export const SMELT_DURATION_PER_RANK_MS = 2000;
264
265/**
266 * Furnace smelt duration from the output bar's associated tier rank.
267 * Tin/copper/coal map to bronze/steel so ingredient timing matches that bar.
268 */
269export function smeltingDurationMs (barOrMaterialId)
270{
271 return Math.max(1, tierRank(barOrMaterialId)) * SMELT_DURATION_PER_RANK_MS;
272}
273
148/** Visual / interact state while an ore boulder is depleted (plain rock). */
274/** Visual / interact state while an ore boulder is depleted (plain rock). */
149export const EXHAUSTED_ORE_BOULDER_STATE = "boulder";
275export const EXHAUSTED_ORE_BOULDER_STATE = "boulder";
150
276
151/** Metals that have an ore node (steel is smelted from iron + coal). */
277/**
278 * Materials that have an ore boulder node.
279 * Bronze has no ore (tin + copper); steel has no ore (iron + coal).
280 */
152export const ORE_BEARING_MATERIALS = Object.freeze([
281export const ORE_BEARING_MATERIALS = Object.freeze([
153 MaterialTier.bronze,
282 GatherMaterialId.tin,
283 GatherMaterialId.copper,
154 MaterialTier.iron,
284 MaterialTier.iron,
155 MaterialTier.mithril,
285 MaterialTier.mithril,
156 MaterialTier.adamantium,
286 MaterialTier.adamantium,
shared/definitions/metalItems.js +61 −3
@@ -28,7 +28,14 @@ export const MetalItemId = Object.freeze({
28 28 orichalcumPickaxe: 49,
29 29 dragonOre: 50,
30 30 dragonBar: 51,
31 dragonPickaxe: 52
31 dragonPickaxe: 52,
32 bronzePickaxeHead: 67,
33 ironPickaxeHead: 68,
34 steelPickaxeHead: 69,
35 mithrilPickaxeHead: 70,
36 adamantiumPickaxeHead: 71,
37 orichalcumPickaxeHead: 72,
38 dragonPickaxeHead: 73
32 39 });
33 40
34 41 const DEFAULT_STACK = 99;
@@ -73,6 +80,26 @@ function barDef (itemId, tier, key)
73 80 });
74 81 }
75 82
83 function pickaxeHeadDef (itemId, tier, key)
84 {
85 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
86 return Object.freeze({
87 itemId,
88 key,
89 displayName: `${name} pickaxe head`,
90 description: `Smithed ${name.toLowerCase()} head. Attach a matching-tier handle at a woodworking bench.`,
91 seedValue: 5,
92 stackable: true,
93 maxStackSize: DEFAULT_STACK,
94 uniqueInstance: false,
95 category: ItemCategory.intermediate,
96 iconKey: "pickaxe",
97 defaultState: "pickaxe",
98 tier,
99 tintFromTier: true
100 });
101 }
102
76 103 function pickaxeDef (itemId, tier, key)
77 104 {
78 105 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
@@ -103,7 +130,7 @@ export const METAL_ITEM_DEFINITIONS = Object.freeze({
103 130 itemId: MetalItemId.coal,
104 131 key: "coal",
105 132 displayName: "Coal",
106 description: "Fuel for steel smelting. Mined from coal boulders.",
133 description: "Fuel for steel smelting. Mined from coal boulders (steel-tier timing).",
107 134 seedValue: 2,
108 135 stackable: true,
109 136 maxStackSize: DEFAULT_STACK,
@@ -114,21 +141,52 @@ export const METAL_ITEM_DEFINITIONS = Object.freeze({
114 141 tier: GatherMaterialId.coal,
115 142 tintFromTier: true
116 143 }),
144 [MetalItemId.bronzePickaxeHead]: pickaxeHeadDef(
145 MetalItemId.bronzePickaxeHead,
146 MaterialTier.bronze,
147 "bronze-pickaxe-head"
148 ),
117 149 [MetalItemId.ironOre]: oreDef(MetalItemId.ironOre, MaterialTier.iron, "iron-ore"),
118 150 [MetalItemId.ironBar]: barDef(MetalItemId.ironBar, MaterialTier.iron, "iron-bar"),
119 151 [MetalItemId.ironPickaxe]: pickaxeDef(MetalItemId.ironPickaxe, MaterialTier.iron, "iron-pickaxe"),
152 [MetalItemId.ironPickaxeHead]: pickaxeHeadDef(MetalItemId.ironPickaxeHead, MaterialTier.iron, "iron-pickaxe-head"),
120 153 [MetalItemId.steelBar]: barDef(MetalItemId.steelBar, MaterialTier.steel, "steel-bar"),
121 154 [MetalItemId.steelPickaxe]: pickaxeDef(MetalItemId.steelPickaxe, MaterialTier.steel, "steel-pickaxe"),
155 [MetalItemId.steelPickaxeHead]: pickaxeHeadDef(MetalItemId.steelPickaxeHead, MaterialTier.steel, "steel-pickaxe-head"),
122 156 [MetalItemId.mithrilOre]: oreDef(MetalItemId.mithrilOre, MaterialTier.mithril, "mithril-ore"),
123 157 [MetalItemId.mithrilBar]: barDef(MetalItemId.mithrilBar, MaterialTier.mithril, "mithril-bar"),
124 158 [MetalItemId.mithrilPickaxe]: pickaxeDef(MetalItemId.mithrilPickaxe, MaterialTier.mithril, "mithril-pickaxe"),
159 [MetalItemId.mithrilPickaxeHead]: pickaxeHeadDef(MetalItemId.mithrilPickaxeHead, MaterialTier.mithril, "mithril-pickaxe-head"),
125 160 [MetalItemId.adamantiumOre]: oreDef(MetalItemId.adamantiumOre, MaterialTier.adamantium, "adamantium-ore"),
126 161 [MetalItemId.adamantiumBar]: barDef(MetalItemId.adamantiumBar, MaterialTier.adamantium, "adamantium-bar"),
127 162 [MetalItemId.adamantiumPickaxe]: pickaxeDef(MetalItemId.adamantiumPickaxe, MaterialTier.adamantium, "adamantium-pickaxe"),
163 [MetalItemId.adamantiumPickaxeHead]: pickaxeHeadDef(MetalItemId.adamantiumPickaxeHead, MaterialTier.adamantium, "adamantium-pickaxe-head"),
128 164 [MetalItemId.orichalcumOre]: oreDef(MetalItemId.orichalcumOre, MaterialTier.orichalcum, "orichalcum-ore"),
129 165 [MetalItemId.orichalcumBar]: barDef(MetalItemId.orichalcumBar, MaterialTier.orichalcum, "orichalcum-bar"),
130 166 [MetalItemId.orichalcumPickaxe]: pickaxeDef(MetalItemId.orichalcumPickaxe, MaterialTier.orichalcum, "orichalcum-pickaxe"),
167 [MetalItemId.orichalcumPickaxeHead]: pickaxeHeadDef(MetalItemId.orichalcumPickaxeHead, MaterialTier.orichalcum, "orichalcum-pickaxe-head"),
131 168 [MetalItemId.dragonOre]: oreDef(MetalItemId.dragonOre, MaterialTier.dragon, "dragon-ore"),
132 169 [MetalItemId.dragonBar]: barDef(MetalItemId.dragonBar, MaterialTier.dragon, "dragon-bar"),
133 [MetalItemId.dragonPickaxe]: pickaxeDef(MetalItemId.dragonPickaxe, MaterialTier.dragon, "dragon-pickaxe")
170 [MetalItemId.dragonPickaxe]: pickaxeDef(MetalItemId.dragonPickaxe, MaterialTier.dragon, "dragon-pickaxe"),
171 [MetalItemId.dragonPickaxeHead]: pickaxeHeadDef(MetalItemId.dragonPickaxeHead, MaterialTier.dragon, "dragon-pickaxe-head")
172 });
173
174 /** Pickaxe head item id by metal tier. */
175 export const PICKAXE_HEAD_ITEM_BY_METAL = Object.freeze({
176 [MaterialTier.bronze]: MetalItemId.bronzePickaxeHead,
177 [MaterialTier.iron]: MetalItemId.ironPickaxeHead,
178 [MaterialTier.steel]: MetalItemId.steelPickaxeHead,
179 [MaterialTier.mithril]: MetalItemId.mithrilPickaxeHead,
180 [MaterialTier.adamantium]: MetalItemId.adamantiumPickaxeHead,
181 [MaterialTier.orichalcum]: MetalItemId.orichalcumPickaxeHead,
182 [MaterialTier.dragon]: MetalItemId.dragonPickaxeHead
183 });
184
185 export const PICKAXE_ITEM_BY_METAL = Object.freeze({
186 [MaterialTier.iron]: MetalItemId.ironPickaxe,
187 [MaterialTier.steel]: MetalItemId.steelPickaxe,
188 [MaterialTier.mithril]: MetalItemId.mithrilPickaxe,
189 [MaterialTier.adamantium]: MetalItemId.adamantiumPickaxe,
190 [MaterialTier.orichalcum]: MetalItemId.orichalcumPickaxe,
191 [MaterialTier.dragon]: MetalItemId.dragonPickaxe
134 192 });
@@ -28,7 +28,14 @@ export const MetalItemId = Object.freeze({
28 orichalcumPickaxe: 49,
28 orichalcumPickaxe: 49,
29 dragonOre: 50,
29 dragonOre: 50,
30 dragonBar: 51,
30 dragonBar: 51,
31 dragonPickaxe: 52
31 dragonPickaxe: 52,
32 bronzePickaxeHead: 67,
33 ironPickaxeHead: 68,
34 steelPickaxeHead: 69,
35 mithrilPickaxeHead: 70,
36 adamantiumPickaxeHead: 71,
37 orichalcumPickaxeHead: 72,
38 dragonPickaxeHead: 73
32});
39});
33
40
34const DEFAULT_STACK = 99;
41const DEFAULT_STACK = 99;
@@ -73,6 +80,26 @@ function barDef (itemId, tier, key)
73 });
80 });
74}
81}
75
82
83function pickaxeHeadDef (itemId, tier, key)
84{
85 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
86 return Object.freeze({
87 itemId,
88 key,
89 displayName: `${name} pickaxe head`,
90 description: `Smithed ${name.toLowerCase()} head. Attach a matching-tier handle at a woodworking bench.`,
91 seedValue: 5,
92 stackable: true,
93 maxStackSize: DEFAULT_STACK,
94 uniqueInstance: false,
95 category: ItemCategory.intermediate,
96 iconKey: "pickaxe",
97 defaultState: "pickaxe",
98 tier,
99 tintFromTier: true
100 });
101}
102
76function pickaxeDef (itemId, tier, key)
103function pickaxeDef (itemId, tier, key)
77{
104{
78 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
105 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
@@ -103,7 +130,7 @@ export const METAL_ITEM_DEFINITIONS = Object.freeze({
103 itemId: MetalItemId.coal,
130 itemId: MetalItemId.coal,
104 key: "coal",
131 key: "coal",
105 displayName: "Coal",
132 displayName: "Coal",
106 description: "Fuel for steel smelting. Mined from coal boulders.",
133 description: "Fuel for steel smelting. Mined from coal boulders (steel-tier timing).",
107 seedValue: 2,
134 seedValue: 2,
108 stackable: true,
135 stackable: true,
109 maxStackSize: DEFAULT_STACK,
136 maxStackSize: DEFAULT_STACK,
@@ -114,21 +141,52 @@ export const METAL_ITEM_DEFINITIONS = Object.freeze({
114 tier: GatherMaterialId.coal,
141 tier: GatherMaterialId.coal,
115 tintFromTier: true
142 tintFromTier: true
116 }),
143 }),
144 [MetalItemId.bronzePickaxeHead]: pickaxeHeadDef(
145 MetalItemId.bronzePickaxeHead,
146 MaterialTier.bronze,
147 "bronze-pickaxe-head"
148 ),
117 [MetalItemId.ironOre]: oreDef(MetalItemId.ironOre, MaterialTier.iron, "iron-ore"),
149 [MetalItemId.ironOre]: oreDef(MetalItemId.ironOre, MaterialTier.iron, "iron-ore"),
118 [MetalItemId.ironBar]: barDef(MetalItemId.ironBar, MaterialTier.iron, "iron-bar"),
150 [MetalItemId.ironBar]: barDef(MetalItemId.ironBar, MaterialTier.iron, "iron-bar"),
119 [MetalItemId.ironPickaxe]: pickaxeDef(MetalItemId.ironPickaxe, MaterialTier.iron, "iron-pickaxe"),
151 [MetalItemId.ironPickaxe]: pickaxeDef(MetalItemId.ironPickaxe, MaterialTier.iron, "iron-pickaxe"),
152 [MetalItemId.ironPickaxeHead]: pickaxeHeadDef(MetalItemId.ironPickaxeHead, MaterialTier.iron, "iron-pickaxe-head"),
120 [MetalItemId.steelBar]: barDef(MetalItemId.steelBar, MaterialTier.steel, "steel-bar"),
153 [MetalItemId.steelBar]: barDef(MetalItemId.steelBar, MaterialTier.steel, "steel-bar"),
121 [MetalItemId.steelPickaxe]: pickaxeDef(MetalItemId.steelPickaxe, MaterialTier.steel, "steel-pickaxe"),
154 [MetalItemId.steelPickaxe]: pickaxeDef(MetalItemId.steelPickaxe, MaterialTier.steel, "steel-pickaxe"),
155 [MetalItemId.steelPickaxeHead]: pickaxeHeadDef(MetalItemId.steelPickaxeHead, MaterialTier.steel, "steel-pickaxe-head"),
122 [MetalItemId.mithrilOre]: oreDef(MetalItemId.mithrilOre, MaterialTier.mithril, "mithril-ore"),
156 [MetalItemId.mithrilOre]: oreDef(MetalItemId.mithrilOre, MaterialTier.mithril, "mithril-ore"),
123 [MetalItemId.mithrilBar]: barDef(MetalItemId.mithrilBar, MaterialTier.mithril, "mithril-bar"),
157 [MetalItemId.mithrilBar]: barDef(MetalItemId.mithrilBar, MaterialTier.mithril, "mithril-bar"),
124 [MetalItemId.mithrilPickaxe]: pickaxeDef(MetalItemId.mithrilPickaxe, MaterialTier.mithril, "mithril-pickaxe"),
158 [MetalItemId.mithrilPickaxe]: pickaxeDef(MetalItemId.mithrilPickaxe, MaterialTier.mithril, "mithril-pickaxe"),
159 [MetalItemId.mithrilPickaxeHead]: pickaxeHeadDef(MetalItemId.mithrilPickaxeHead, MaterialTier.mithril, "mithril-pickaxe-head"),
125 [MetalItemId.adamantiumOre]: oreDef(MetalItemId.adamantiumOre, MaterialTier.adamantium, "adamantium-ore"),
160 [MetalItemId.adamantiumOre]: oreDef(MetalItemId.adamantiumOre, MaterialTier.adamantium, "adamantium-ore"),
126 [MetalItemId.adamantiumBar]: barDef(MetalItemId.adamantiumBar, MaterialTier.adamantium, "adamantium-bar"),
161 [MetalItemId.adamantiumBar]: barDef(MetalItemId.adamantiumBar, MaterialTier.adamantium, "adamantium-bar"),
127 [MetalItemId.adamantiumPickaxe]: pickaxeDef(MetalItemId.adamantiumPickaxe, MaterialTier.adamantium, "adamantium-pickaxe"),
162 [MetalItemId.adamantiumPickaxe]: pickaxeDef(MetalItemId.adamantiumPickaxe, MaterialTier.adamantium, "adamantium-pickaxe"),
163 [MetalItemId.adamantiumPickaxeHead]: pickaxeHeadDef(MetalItemId.adamantiumPickaxeHead, MaterialTier.adamantium, "adamantium-pickaxe-head"),
128 [MetalItemId.orichalcumOre]: oreDef(MetalItemId.orichalcumOre, MaterialTier.orichalcum, "orichalcum-ore"),
164 [MetalItemId.orichalcumOre]: oreDef(MetalItemId.orichalcumOre, MaterialTier.orichalcum, "orichalcum-ore"),
129 [MetalItemId.orichalcumBar]: barDef(MetalItemId.orichalcumBar, MaterialTier.orichalcum, "orichalcum-bar"),
165 [MetalItemId.orichalcumBar]: barDef(MetalItemId.orichalcumBar, MaterialTier.orichalcum, "orichalcum-bar"),
130 [MetalItemId.orichalcumPickaxe]: pickaxeDef(MetalItemId.orichalcumPickaxe, MaterialTier.orichalcum, "orichalcum-pickaxe"),
166 [MetalItemId.orichalcumPickaxe]: pickaxeDef(MetalItemId.orichalcumPickaxe, MaterialTier.orichalcum, "orichalcum-pickaxe"),
167 [MetalItemId.orichalcumPickaxeHead]: pickaxeHeadDef(MetalItemId.orichalcumPickaxeHead, MaterialTier.orichalcum, "orichalcum-pickaxe-head"),
131 [MetalItemId.dragonOre]: oreDef(MetalItemId.dragonOre, MaterialTier.dragon, "dragon-ore"),
168 [MetalItemId.dragonOre]: oreDef(MetalItemId.dragonOre, MaterialTier.dragon, "dragon-ore"),
132 [MetalItemId.dragonBar]: barDef(MetalItemId.dragonBar, MaterialTier.dragon, "dragon-bar"),
169 [MetalItemId.dragonBar]: barDef(MetalItemId.dragonBar, MaterialTier.dragon, "dragon-bar"),
133 [MetalItemId.dragonPickaxe]: pickaxeDef(MetalItemId.dragonPickaxe, MaterialTier.dragon, "dragon-pickaxe")
170 [MetalItemId.dragonPickaxe]: pickaxeDef(MetalItemId.dragonPickaxe, MaterialTier.dragon, "dragon-pickaxe"),
171 [MetalItemId.dragonPickaxeHead]: pickaxeHeadDef(MetalItemId.dragonPickaxeHead, MaterialTier.dragon, "dragon-pickaxe-head")
172});
173
174/** Pickaxe head item id by metal tier. */
175export const PICKAXE_HEAD_ITEM_BY_METAL = Object.freeze({
176 [MaterialTier.bronze]: MetalItemId.bronzePickaxeHead,
177 [MaterialTier.iron]: MetalItemId.ironPickaxeHead,
178 [MaterialTier.steel]: MetalItemId.steelPickaxeHead,
179 [MaterialTier.mithril]: MetalItemId.mithrilPickaxeHead,
180 [MaterialTier.adamantium]: MetalItemId.adamantiumPickaxeHead,
181 [MaterialTier.orichalcum]: MetalItemId.orichalcumPickaxeHead,
182 [MaterialTier.dragon]: MetalItemId.dragonPickaxeHead
183});
184
185export const PICKAXE_ITEM_BY_METAL = Object.freeze({
186 [MaterialTier.iron]: MetalItemId.ironPickaxe,
187 [MaterialTier.steel]: MetalItemId.steelPickaxe,
188 [MaterialTier.mithril]: MetalItemId.mithrilPickaxe,
189 [MaterialTier.adamantium]: MetalItemId.adamantiumPickaxe,
190 [MaterialTier.orichalcum]: MetalItemId.orichalcumPickaxe,
191 [MaterialTier.dragon]: MetalItemId.dragonPickaxe
134});
192});
shared/definitions/mobs.js +108 −9
@@ -3,7 +3,8 @@ import { spriteImageName } from "./tileSprites.js";
3 3 export const MobId = Object.freeze({
4 4 deer: "deer",
5 5 pigeon: "pigeon",
6 rat: "rat"
6 rat: "rat",
7 humanoid: "humanoid"
7 8 });
8 9
9 10 /** @typedef {{ itemId: number, chance: number }} MobDrop */
@@ -16,8 +17,9 @@ export const MobId = Object.freeze({
16 17 * - health / maxHealth: hit points
17 18 * - attackSkill: one skill level for hit chance and damage
18 19 * - drops: { itemId, chance } roll on death
19 * - sells: item IDs the mob shop stock (later)
20 * - sells: default item IDs for shop stock (overridable per spawner)
20 21 * - dialogue: branching trees with triggers, lines, responses, and action hooks (later)
22 * - usePlayerBody: draw male/female character body instead of a mob sprite
21 23 */
22 24 export const MOB_DEFINITIONS = Object.freeze({
23 25 [MobId.deer]: Object.freeze({
@@ -94,6 +96,30 @@ export const MOB_DEFINITIONS = Object.freeze({
94 96 frames: 1,
95 97 framesPerRow: 1,
96 98 animationSpeed: 0
99 }),
100 [MobId.humanoid]: Object.freeze({
101 mobTypeId: MobId.humanoid,
102 key: "humanoid",
103 assetFolder: "characters",
104 displayName: "Humanoid",
105 health: 10,
106 maxHealth: 10,
107 canFight: false,
108 drops: Object.freeze([]),
109 sells: Object.freeze([]),
110 dialogue: Object.freeze([]),
111 persistent: false,
112 flying: false,
113 freeFlight: false,
114 ambient: false,
115 talkable: true,
116 untargetable: false,
117 usePlayerBody: true,
118 gait: "walk",
119 sex: "male",
120 frames: 1,
121 framesPerRow: 1,
122 animationSpeed: 0
97 123 })
98 124 });
99 125
@@ -106,6 +132,11 @@ export function mobSpriteName (mobTypeId)
106 132 {
107 133 const def = mobDefinition(mobTypeId);
108 134 const key = def?.key ?? def?.mobTypeId ?? "deer";
135 if (def?.usePlayerBody)
136 {
137 // Editor palette preview; live entities use appearance.sex → bodySprite().
138 return spriteImageName("character", "player-body-male", "player-body-male");
139 }
109 140 if (def?.sprite)
110 141 { return def.sprite; }
111 142 const state = def?.defaultState ?? key;
@@ -114,31 +145,94 @@ export function mobSpriteName (mobTypeId)
114 145
115 146 export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
116 147 {
148 const humanoid = mobTypeId === MobId.humanoid;
117 149 return {
118 150 spawnerId,
119 151 mobTypeId,
120 maxAlive: 3,
121 spawnRangeTiles: 4,
122 maxWanderRangeTiles: 8
152 maxAlive: humanoid ? 1 : 3,
153 spawnRangeTiles: humanoid ? 1 : 4,
154 maxWanderRangeTiles: humanoid ? 1 : 8,
155 sex: "male",
156 displayName: humanoid ? "Shopkeeper" : "",
157 equipment: emptySpawnerEquipment(),
158 sells: [],
159 hiddenDiscount: 0.9
160 };
161 }
162
163 function emptySpawnerEquipment ()
164 {
165 return {
166 head: null,
167 chest: null,
168 legs: null,
169 boots: null,
170 weapon: null,
171 offhand: null
123 172 };
124 173 }
125 174
126 /** Clamp wander ≥ spawn; coerce numeric fields. */
175 function normalizeEquipment (raw)
176 {
177 const next = emptySpawnerEquipment();
178 if (!raw || typeof raw !== "object")
179 { return next; }
180 for (const slot of Object.keys(next))
181 {
182 const value = raw[slot];
183 if (value == null || value === "" || value === "0")
184 {
185 next[slot] = null;
186 continue;
187 }
188 const itemId = Number(value);
189 next[slot] = Number.isFinite(itemId) && itemId > 0 ? (itemId | 0) : null;
190 }
191 return next;
192 }
193
194 function normalizeSells (raw)
195 {
196 if (!Array.isArray(raw))
197 { return []; }
198 const ids = [];
199 const seen = new Set();
200 for (const entry of raw)
201 {
202 const itemId = Number(entry);
203 if (!Number.isFinite(itemId) || itemId <= 0 || seen.has(itemId | 0))
204 { continue; }
205 seen.add(itemId | 0);
206 ids.push(itemId | 0);
207 }
208 return ids;
209 }
210
211 /** Clamp wander ≥ spawn; coerce numeric fields; keep humanoid shop/appearance options. */
127 212 export function normalizeSpawnerConfig (config, spawnerId = "spawner")
128 213 {
129 const base = defaultSpawnerConfig(spawnerId, config?.mobTypeId ?? MobId.deer);
130 const merged = { ...base, ...(config ?? {}), spawnerId: config?.spawnerId || spawnerId };
214 const mobTypeId = config?.mobTypeId ?? MobId.deer;
215 const base = defaultSpawnerConfig(spawnerId, mobTypeId);
216 const merged = { ...base, ...(config ?? {}), spawnerId: config?.spawnerId || spawnerId, mobTypeId };
131 217 const spawnRangeTiles = Math.max(1, Math.min(32, Number(merged.spawnRangeTiles) || base.spawnRangeTiles));
132 218 const maxWanderRangeTiles = Math.max(
133 219 spawnRangeTiles,
134 220 Math.min(64, Number(merged.maxWanderRangeTiles) || spawnRangeTiles)
135 221 );
222 const sex = merged.sex === "female" ? "female" : "male";
223 const hiddenDiscount = Math.min(1, Math.max(0.01, Number(merged.hiddenDiscount) || base.hiddenDiscount));
224 const displayName = String(merged.displayName ?? "").trim().slice(0, 48);
136 225 return {
137 226 spawnerId: String(merged.spawnerId),
138 227 mobTypeId: merged.mobTypeId ?? MobId.deer,
139 228 maxAlive: Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
140 229 spawnRangeTiles,
141 maxWanderRangeTiles
230 maxWanderRangeTiles,
231 sex,
232 displayName,
233 equipment: normalizeEquipment(merged.equipment),
234 sells: normalizeSells(merged.sells),
235 hiddenDiscount
142 236 };
143 237 }
144 238
@@ -152,3 +246,8 @@ export function listSpawnableMobTypes ()
152 246 {
153 247 return Object.values(MOB_DEFINITIONS);
154 248 }
249
250 export function isHumanoidMob (mobTypeId)
251 {
252 return mobDefinition(mobTypeId)?.usePlayerBody === true;
253 }
@@ -3,7 +3,8 @@ import { spriteImageName } from "./tileSprites.js";
3export const MobId = Object.freeze({
3export const MobId = Object.freeze({
4 deer: "deer",
4 deer: "deer",
5 pigeon: "pigeon",
5 pigeon: "pigeon",
6 rat: "rat"
6 rat: "rat",
7 humanoid: "humanoid"
7});
8});
8
9
9/** @typedef {{ itemId: number, chance: number }} MobDrop */
10/** @typedef {{ itemId: number, chance: number }} MobDrop */
@@ -16,8 +17,9 @@ export const MobId = Object.freeze({
16 * - health / maxHealth: hit points
17 * - health / maxHealth: hit points
17 * - attackSkill: one skill level for hit chance and damage
18 * - attackSkill: one skill level for hit chance and damage
18 * - drops: { itemId, chance } roll on death
19 * - drops: { itemId, chance } roll on death
19 * - sells: item IDs the mob shop stock (later)
20 * - sells: default item IDs for shop stock (overridable per spawner)
20 * - dialogue: branching trees with triggers, lines, responses, and action hooks (later)
21 * - dialogue: branching trees with triggers, lines, responses, and action hooks (later)
22 * - usePlayerBody: draw male/female character body instead of a mob sprite
21 */
23 */
22export const MOB_DEFINITIONS = Object.freeze({
24export const MOB_DEFINITIONS = Object.freeze({
23 [MobId.deer]: Object.freeze({
25 [MobId.deer]: Object.freeze({
@@ -94,6 +96,30 @@ export const MOB_DEFINITIONS = Object.freeze({
94 frames: 1,
96 frames: 1,
95 framesPerRow: 1,
97 framesPerRow: 1,
96 animationSpeed: 0
98 animationSpeed: 0
99 }),
100 [MobId.humanoid]: Object.freeze({
101 mobTypeId: MobId.humanoid,
102 key: "humanoid",
103 assetFolder: "characters",
104 displayName: "Humanoid",
105 health: 10,
106 maxHealth: 10,
107 canFight: false,
108 drops: Object.freeze([]),
109 sells: Object.freeze([]),
110 dialogue: Object.freeze([]),
111 persistent: false,
112 flying: false,
113 freeFlight: false,
114 ambient: false,
115 talkable: true,
116 untargetable: false,
117 usePlayerBody: true,
118 gait: "walk",
119 sex: "male",
120 frames: 1,
121 framesPerRow: 1,
122 animationSpeed: 0
97 })
123 })
98});
124});
99
125
@@ -106,6 +132,11 @@ export function mobSpriteName (mobTypeId)
106{
132{
107 const def = mobDefinition(mobTypeId);
133 const def = mobDefinition(mobTypeId);
108 const key = def?.key ?? def?.mobTypeId ?? "deer";
134 const key = def?.key ?? def?.mobTypeId ?? "deer";
135 if (def?.usePlayerBody)
136 {
137 // Editor palette preview; live entities use appearance.sex → bodySprite().
138 return spriteImageName("character", "player-body-male", "player-body-male");
139 }
109 if (def?.sprite)
140 if (def?.sprite)
110 { return def.sprite; }
141 { return def.sprite; }
111 const state = def?.defaultState ?? key;
142 const state = def?.defaultState ?? key;
@@ -114,31 +145,94 @@ export function mobSpriteName (mobTypeId)
114
145
115export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
146export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
116{
147{
148 const humanoid = mobTypeId === MobId.humanoid;
117 return {
149 return {
118 spawnerId,
150 spawnerId,
119 mobTypeId,
151 mobTypeId,
120 maxAlive: 3,
152 maxAlive: humanoid ? 1 : 3,
121 spawnRangeTiles: 4,
153 spawnRangeTiles: humanoid ? 1 : 4,
122 maxWanderRangeTiles: 8
154 maxWanderRangeTiles: humanoid ? 1 : 8,
155 sex: "male",
156 displayName: humanoid ? "Shopkeeper" : "",
157 equipment: emptySpawnerEquipment(),
158 sells: [],
159 hiddenDiscount: 0.9
160 };
161}
162
163function emptySpawnerEquipment ()
164{
165 return {
166 head: null,
167 chest: null,
168 legs: null,
169 boots: null,
170 weapon: null,
171 offhand: null
123 };
172 };
124}
173}
125
174
126/** Clamp wander ≥ spawn; coerce numeric fields. */
175function normalizeEquipment (raw)
176{
177 const next = emptySpawnerEquipment();
178 if (!raw || typeof raw !== "object")
179 { return next; }
180 for (const slot of Object.keys(next))
181 {
182 const value = raw[slot];
183 if (value == null || value === "" || value === "0")
184 {
185 next[slot] = null;
186 continue;
187 }
188 const itemId = Number(value);
189 next[slot] = Number.isFinite(itemId) && itemId > 0 ? (itemId | 0) : null;
190 }
191 return next;
192}
193
194function normalizeSells (raw)
195{
196 if (!Array.isArray(raw))
197 { return []; }
198 const ids = [];
199 const seen = new Set();
200 for (const entry of raw)
201 {
202 const itemId = Number(entry);
203 if (!Number.isFinite(itemId) || itemId <= 0 || seen.has(itemId | 0))
204 { continue; }
205 seen.add(itemId | 0);
206 ids.push(itemId | 0);
207 }
208 return ids;
209}
210
211/** Clamp wander ≥ spawn; coerce numeric fields; keep humanoid shop/appearance options. */
127export function normalizeSpawnerConfig (config, spawnerId = "spawner")
212export function normalizeSpawnerConfig (config, spawnerId = "spawner")
128{
213{
129 const base = defaultSpawnerConfig(spawnerId, config?.mobTypeId ?? MobId.deer);
214 const mobTypeId = config?.mobTypeId ?? MobId.deer;
130 const merged = { ...base, ...(config ?? {}), spawnerId: config?.spawnerId || spawnerId };
215 const base = defaultSpawnerConfig(spawnerId, mobTypeId);
216 const merged = { ...base, ...(config ?? {}), spawnerId: config?.spawnerId || spawnerId, mobTypeId };
131 const spawnRangeTiles = Math.max(1, Math.min(32, Number(merged.spawnRangeTiles) || base.spawnRangeTiles));
217 const spawnRangeTiles = Math.max(1, Math.min(32, Number(merged.spawnRangeTiles) || base.spawnRangeTiles));
132 const maxWanderRangeTiles = Math.max(
218 const maxWanderRangeTiles = Math.max(
133 spawnRangeTiles,
219 spawnRangeTiles,
134 Math.min(64, Number(merged.maxWanderRangeTiles) || spawnRangeTiles)
220 Math.min(64, Number(merged.maxWanderRangeTiles) || spawnRangeTiles)
135 );
221 );
222 const sex = merged.sex === "female" ? "female" : "male";
223 const hiddenDiscount = Math.min(1, Math.max(0.01, Number(merged.hiddenDiscount) || base.hiddenDiscount));
224 const displayName = String(merged.displayName ?? "").trim().slice(0, 48);
136 return {
225 return {
137 spawnerId: String(merged.spawnerId),
226 spawnerId: String(merged.spawnerId),
138 mobTypeId: merged.mobTypeId ?? MobId.deer,
227 mobTypeId: merged.mobTypeId ?? MobId.deer,
139 maxAlive: Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
228 maxAlive: Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
140 spawnRangeTiles,
229 spawnRangeTiles,
141 maxWanderRangeTiles
230 maxWanderRangeTiles,
231 sex,
232 displayName,
233 equipment: normalizeEquipment(merged.equipment),
234 sells: normalizeSells(merged.sells),
235 hiddenDiscount
142 };
236 };
143}
237}
144
238
@@ -152,3 +246,8 @@ export function listSpawnableMobTypes ()
152{
246{
153 return Object.values(MOB_DEFINITIONS);
247 return Object.values(MOB_DEFINITIONS);
154}
248}
249
250export function isHumanoidMob (mobTypeId)
251{
252 return mobDefinition(mobTypeId)?.usePlayerBody === true;
253}
shared/definitions/tiles.js +25 −1
@@ -21,7 +21,9 @@ export const BlockType = Object.freeze({
21 21 churchAltar: 5,
22 22 cauldron: 6,
23 23 boulder: 7,
24 furnace: 8
24 furnace: 8,
25 anvil: 9,
26 woodworkingBench: 10
25 27 });
26 28
27 29 export const GROUND_DEFINITIONS = Object.freeze({
@@ -156,6 +158,28 @@ export const BLOCK_DEFINITIONS = Object.freeze({
156 158 framesPerRow: 1,
157 159 animationSpeed: 0,
158 160 craftingStationId: "furnace"
161 }),
162 [BlockType.anvil]: Object.freeze({
163 id: BlockType.anvil,
164 key: "anvil",
165 displayName: "Anvil",
166 passable: false,
167 lightRangeTiles: 0,
168 frames: 1,
169 framesPerRow: 1,
170 animationSpeed: 0,
171 craftingStationId: "anvil"
172 }),
173 [BlockType.woodworkingBench]: Object.freeze({
174 id: BlockType.woodworkingBench,
175 key: "woodworking-bench",
176 displayName: "Woodworking bench",
177 passable: false,
178 lightRangeTiles: 0,
179 frames: 1,
180 framesPerRow: 1,
181 animationSpeed: 0,
182 craftingStationId: "woodworking-bench"
159 183 })
160 184 });
161 185
@@ -21,7 +21,9 @@ export const BlockType = Object.freeze({
21 churchAltar: 5,
21 churchAltar: 5,
22 cauldron: 6,
22 cauldron: 6,
23 boulder: 7,
23 boulder: 7,
24 furnace: 8
24 furnace: 8,
25 anvil: 9,
26 woodworkingBench: 10
25});
27});
26
28
27export const GROUND_DEFINITIONS = Object.freeze({
29export const GROUND_DEFINITIONS = Object.freeze({
@@ -156,6 +158,28 @@ export const BLOCK_DEFINITIONS = Object.freeze({
156 framesPerRow: 1,
158 framesPerRow: 1,
157 animationSpeed: 0,
159 animationSpeed: 0,
158 craftingStationId: "furnace"
160 craftingStationId: "furnace"
161 }),
162 [BlockType.anvil]: Object.freeze({
163 id: BlockType.anvil,
164 key: "anvil",
165 displayName: "Anvil",
166 passable: false,
167 lightRangeTiles: 0,
168 frames: 1,
169 framesPerRow: 1,
170 animationSpeed: 0,
171 craftingStationId: "anvil"
172 }),
173 [BlockType.woodworkingBench]: Object.freeze({
174 id: BlockType.woodworkingBench,
175 key: "woodworking-bench",
176 displayName: "Woodworking bench",
177 passable: false,
178 lightRangeTiles: 0,
179 frames: 1,
180 framesPerRow: 1,
181 animationSpeed: 0,
182 craftingStationId: "woodworking-bench"
159 })
183 })
160});
184});
161
185
shared/definitions/woodItems.js added +117 −0
@@ -0,0 +1,117 @@
1 import { ItemCategory } from "./itemCategories.js";
2 import {
3 WoodTier,
4 WOOD_TIER_ORDER,
5 MATERIAL_DISPLAY_NAME
6 } from "./materialTiers.js";
7
8 /**
9 * Wood logs and handles.
10 * Shared magenta base sprites: iconKey wood, states log / handle.
11 * pineLog reuses former CraftingItemId.log (9).
12 */
13 export const WoodItemId = Object.freeze({
14 pineLog: 9,
15 pineHandle: 54,
16 birchLog: 55,
17 birchHandle: 56,
18 oakLog: 57,
19 oakHandle: 58,
20 ebonyLog: 59,
21 ebonyHandle: 60,
22 lignumLog: 61,
23 lignumHandle: 62,
24 heartwoodLog: 63,
25 heartwoodHandle: 64,
26 elderLog: 65,
27 elderHandle: 66
28 });
29
30 const DEFAULT_STACK = 99;
31
32 const LOG_IDS = Object.freeze({
33 [WoodTier.pine]: WoodItemId.pineLog,
34 [WoodTier.birch]: WoodItemId.birchLog,
35 [WoodTier.oak]: WoodItemId.oakLog,
36 [WoodTier.ebony]: WoodItemId.ebonyLog,
37 [WoodTier.lignum]: WoodItemId.lignumLog,
38 [WoodTier.heartwood]: WoodItemId.heartwoodLog,
39 [WoodTier.elder]: WoodItemId.elderLog
40 });
41
42 const HANDLE_IDS = Object.freeze({
43 [WoodTier.pine]: WoodItemId.pineHandle,
44 [WoodTier.birch]: WoodItemId.birchHandle,
45 [WoodTier.oak]: WoodItemId.oakHandle,
46 [WoodTier.ebony]: WoodItemId.ebonyHandle,
47 [WoodTier.lignum]: WoodItemId.lignumHandle,
48 [WoodTier.heartwood]: WoodItemId.heartwoodHandle,
49 [WoodTier.elder]: WoodItemId.elderHandle
50 });
51
52 function logDef (itemId, tier)
53 {
54 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
55 return Object.freeze({
56 itemId,
57 key: `${tier}-log`,
58 displayName: `${name} log`,
59 description: `Chopped ${name.toLowerCase()}. Shape into a handle at a woodworking bench.`,
60 seedValue: 2,
61 stackable: true,
62 maxStackSize: DEFAULT_STACK,
63 uniqueInstance: false,
64 category: ItemCategory.ingredient,
65 iconKey: "wood",
66 defaultState: "log",
67 tier,
68 tintFromTier: true,
69 npcShopAllowed: true
70 });
71 }
72
73 function handleDef (itemId, tier)
74 {
75 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
76 return Object.freeze({
77 itemId,
78 key: `${tier}-handle`,
79 displayName: `${name} handle`,
80 description: `Shaped ${name.toLowerCase()} haft. Combine with a matching-tier pickaxe head.`,
81 seedValue: 3,
82 stackable: true,
83 maxStackSize: DEFAULT_STACK,
84 uniqueInstance: false,
85 category: ItemCategory.intermediate,
86 iconKey: "wood",
87 defaultState: "handle",
88 tier,
89 tintFromTier: true
90 });
91 }
92
93 export const LOG_ITEM_BY_WOOD = LOG_IDS;
94 export const HANDLE_ITEM_BY_WOOD = HANDLE_IDS;
95
96 export function logItemIdForWood (woodTier)
97 {
98 return LOG_IDS[woodTier] ?? null;
99 }
100
101 export function handleItemIdForWood (woodTier)
102 {
103 return HANDLE_IDS[woodTier] ?? null;
104 }
105
106 /** Full defs for wood family (merged into ITEM_DEFINITIONS). */
107 export const WOOD_ITEM_DEFINITIONS = Object.freeze(Object.fromEntries(
108 WOOD_TIER_ORDER.flatMap((tier) =>
109 {
110 const logId = LOG_IDS[tier];
111 const handleId = HANDLE_IDS[tier];
112 return [
113 [logId, logDef(logId, tier)],
114 [handleId, handleDef(handleId, tier)]
115 ];
116 })
117 ));
@@ -0,0 +1,117 @@
1import { ItemCategory } from "./itemCategories.js";
2import {
3 WoodTier,
4 WOOD_TIER_ORDER,
5 MATERIAL_DISPLAY_NAME
6} from "./materialTiers.js";
7
8/**
9 * Wood logs and handles.
10 * Shared magenta base sprites: iconKey wood, states log / handle.
11 * pineLog reuses former CraftingItemId.log (9).
12 */
13export const WoodItemId = Object.freeze({
14 pineLog: 9,
15 pineHandle: 54,
16 birchLog: 55,
17 birchHandle: 56,
18 oakLog: 57,
19 oakHandle: 58,
20 ebonyLog: 59,
21 ebonyHandle: 60,
22 lignumLog: 61,
23 lignumHandle: 62,
24 heartwoodLog: 63,
25 heartwoodHandle: 64,
26 elderLog: 65,
27 elderHandle: 66
28});
29
30const DEFAULT_STACK = 99;
31
32const LOG_IDS = Object.freeze({
33 [WoodTier.pine]: WoodItemId.pineLog,
34 [WoodTier.birch]: WoodItemId.birchLog,
35 [WoodTier.oak]: WoodItemId.oakLog,
36 [WoodTier.ebony]: WoodItemId.ebonyLog,
37 [WoodTier.lignum]: WoodItemId.lignumLog,
38 [WoodTier.heartwood]: WoodItemId.heartwoodLog,
39 [WoodTier.elder]: WoodItemId.elderLog
40});
41
42const HANDLE_IDS = Object.freeze({
43 [WoodTier.pine]: WoodItemId.pineHandle,
44 [WoodTier.birch]: WoodItemId.birchHandle,
45 [WoodTier.oak]: WoodItemId.oakHandle,
46 [WoodTier.ebony]: WoodItemId.ebonyHandle,
47 [WoodTier.lignum]: WoodItemId.lignumHandle,
48 [WoodTier.heartwood]: WoodItemId.heartwoodHandle,
49 [WoodTier.elder]: WoodItemId.elderHandle
50});
51
52function logDef (itemId, tier)
53{
54 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
55 return Object.freeze({
56 itemId,
57 key: `${tier}-log`,
58 displayName: `${name} log`,
59 description: `Chopped ${name.toLowerCase()}. Shape into a handle at a woodworking bench.`,
60 seedValue: 2,
61 stackable: true,
62 maxStackSize: DEFAULT_STACK,
63 uniqueInstance: false,
64 category: ItemCategory.ingredient,
65 iconKey: "wood",
66 defaultState: "log",
67 tier,
68 tintFromTier: true,
69 npcShopAllowed: true
70 });
71}
72
73function handleDef (itemId, tier)
74{
75 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
76 return Object.freeze({
77 itemId,
78 key: `${tier}-handle`,
79 displayName: `${name} handle`,
80 description: `Shaped ${name.toLowerCase()} haft. Combine with a matching-tier pickaxe head.`,
81 seedValue: 3,
82 stackable: true,
83 maxStackSize: DEFAULT_STACK,
84 uniqueInstance: false,
85 category: ItemCategory.intermediate,
86 iconKey: "wood",
87 defaultState: "handle",
88 tier,
89 tintFromTier: true
90 });
91}
92
93export const LOG_ITEM_BY_WOOD = LOG_IDS;
94export const HANDLE_ITEM_BY_WOOD = HANDLE_IDS;
95
96export function logItemIdForWood (woodTier)
97{
98 return LOG_IDS[woodTier] ?? null;
99}
100
101export function handleItemIdForWood (woodTier)
102{
103 return HANDLE_IDS[woodTier] ?? null;
104}
105
106/** Full defs for wood family (merged into ITEM_DEFINITIONS). */
107export const WOOD_ITEM_DEFINITIONS = Object.freeze(Object.fromEntries(
108 WOOD_TIER_ORDER.flatMap((tier) =>
109 {
110 const logId = LOG_IDS[tier];
111 const handleId = HANDLE_IDS[tier];
112 return [
113 [logId, logDef(logId, tier)],
114 [handleId, handleDef(handleId, tier)]
115 ];
116 })
117));
shared/items/inventory.js +22 −0
@@ -276,6 +276,28 @@ export function countCoinsInSlots (slots)
276 276 return countItemInSlots(slots, ItemId.coins);
277 277 }
278 278
279 /** Remove coin quantity from bag slots (FIFO across coin stacks). */
280 export function takeCoinsFromSlots (slots, amount)
281 {
282 let remaining = stackQuantity(amount);
283 if (!remaining)
284 { return { ok: true, slots: (slots ?? []).map(cloneStack) }; }
285 if (countCoinsInSlots(slots) < remaining)
286 { return { ok: false, slots: (slots ?? []).map(cloneStack) }; }
287 let next = (slots ?? []).map(cloneStack);
288 for (let i = 0; i < next.length && remaining > 0; i++)
289 {
290 if (!next[i] || next[i].itemId !== ItemId.coins)
291 { continue; }
292 const taken = takeFromSlot(next, i, remaining);
293 if (!taken.ok)
294 { continue; }
295 next = taken.slots;
296 remaining -= stackQuantity(taken.taken?.quantity);
297 }
298 return { ok: remaining === 0, slots: next };
299 }
300
279 301 /** Add coin stacks, splitting at max stack size (999B). */
280 302 export function addCoinsToSlots (slots, amount, { growable = false } = {})
281 303 {
@@ -276,6 +276,28 @@ export function countCoinsInSlots (slots)
276 return countItemInSlots(slots, ItemId.coins);
276 return countItemInSlots(slots, ItemId.coins);
277}
277}
278
278
279/** Remove coin quantity from bag slots (FIFO across coin stacks). */
280export function takeCoinsFromSlots (slots, amount)
281{
282 let remaining = stackQuantity(amount);
283 if (!remaining)
284 { return { ok: true, slots: (slots ?? []).map(cloneStack) }; }
285 if (countCoinsInSlots(slots) < remaining)
286 { return { ok: false, slots: (slots ?? []).map(cloneStack) }; }
287 let next = (slots ?? []).map(cloneStack);
288 for (let i = 0; i < next.length && remaining > 0; i++)
289 {
290 if (!next[i] || next[i].itemId !== ItemId.coins)
291 { continue; }
292 const taken = takeFromSlot(next, i, remaining);
293 if (!taken.ok)
294 { continue; }
295 next = taken.slots;
296 remaining -= stackQuantity(taken.taken?.quantity);
297 }
298 return { ok: remaining === 0, slots: next };
299}
300
279/** Add coin stacks, splitting at max stack size (999B). */
301/** Add coin stacks, splitting at max stack size (999B). */
280export function addCoinsToSlots (slots, amount, { growable = false } = {})
302export function addCoinsToSlots (slots, amount, { growable = false } = {})
281{
303{
shared/protocol/constants.js +4 −1
@@ -149,8 +149,11 @@ export const MessageType = Object.freeze({
149 149 gatherSwing: "GATHER_SWING",
150 150 gatherComplete: "GATHER_COMPLETE",
151 151 openFurnace: "OPEN_FURNACE",
152 openStation: "OPEN_STATION",
152 153 stationOpen: "STATION_OPEN",
153 154 tileShove: "TILE_SHOVE",
154 itemBubble: "ITEM_BUBBLE"
155 itemBubble: "ITEM_BUBBLE",
156 shopOpen: "SHOP_OPEN",
157 buyFromShop: "BUY_FROM_SHOP"
155 158 });
156 159
@@ -149,8 +149,11 @@ export const MessageType = Object.freeze({
149 gatherSwing: "GATHER_SWING",
149 gatherSwing: "GATHER_SWING",
150 gatherComplete: "GATHER_COMPLETE",
150 gatherComplete: "GATHER_COMPLETE",
151 openFurnace: "OPEN_FURNACE",
151 openFurnace: "OPEN_FURNACE",
152 openStation: "OPEN_STATION",
152 stationOpen: "STATION_OPEN",
153 stationOpen: "STATION_OPEN",
153 tileShove: "TILE_SHOVE",
154 tileShove: "TILE_SHOVE",
154 itemBubble: "ITEM_BUBBLE"
155 itemBubble: "ITEM_BUBBLE",
156 shopOpen: "SHOP_OPEN",
157 buyFromShop: "BUY_FROM_SHOP"
155});
158});
156
159
shared/shop/pricing.js added +57 −0
@@ -0,0 +1,57 @@
1 /**
2 * Shop / tooltip pricing from seedValue and optional player-market last sale.
3 * Matches design §27.6 — lerp toward lastTradePrice over shopPriceLerpDurationMs.
4 */
5
6 import { itemDefinition } from "../definitions/items.js";
7 import { ItemCategory } from "../definitions/itemCategories.js";
8 import { DEFAULT_WORLD_SETTINGS } from "../protocol/constants.js";
9
10 export function lerp (a, b, t)
11 {
12 return a + (b - a) * t;
13 }
14
15 /**
16 * @param {object|null} lastSale `{ lastTradePrice, lastTradeAt, priceFrom }`
17 */
18 export function undiscountedMarketValue (itemId, lastSale = null, now = Date.now(), lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs)
19 {
20 const def = itemDefinition(itemId);
21 const seed = Math.max(1, Number(def?.seedValue) || 1);
22 if (!lastSale?.lastTradeAt || lastSale.lastTradePrice == null)
23 { return seed; }
24 const duration = Math.max(1, Number(lerpDurationMs) || DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs);
25 const t = Math.min(1, Math.max(0, (now - lastSale.lastTradeAt) / duration));
26 const from = lastSale.priceFrom != null ? Number(lastSale.priceFrom) : seed;
27 const to = Number(lastSale.lastTradePrice);
28 if (!Number.isFinite(from) || !Number.isFinite(to))
29 { return seed; }
30 return lerp(from, to, t);
31 }
32
33 /** Integer shop purchase price (server authority). */
34 export function shopUnitPrice (itemId, {
35 lastSale = null,
36 now = Date.now(),
37 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
38 hiddenDiscount = 1
39 } = {})
40 {
41 const undiscounted = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs);
42 const discount = Math.min(1, Math.max(0.01, Number(hiddenDiscount) || 1));
43 return Math.max(1, Math.round(undiscounted * discount));
44 }
45
46 /** NPC shops sell ingredients (and items explicitly flagged). */
47 export function canSellInNpcShop (itemId)
48 {
49 const def = itemDefinition(itemId);
50 if (!def)
51 { return false; }
52 if (def.npcShopAllowed === false)
53 { return false; }
54 if (def.npcShopAllowed === true)
55 { return true; }
56 return def.category === ItemCategory.ingredient || def.category === "ingredient";
57 }
@@ -0,0 +1,57 @@
1/**
2 * Shop / tooltip pricing from seedValue and optional player-market last sale.
3 * Matches design §27.6 — lerp toward lastTradePrice over shopPriceLerpDurationMs.
4 */
5
6import { itemDefinition } from "../definitions/items.js";
7import { ItemCategory } from "../definitions/itemCategories.js";
8import { DEFAULT_WORLD_SETTINGS } from "../protocol/constants.js";
9
10export function lerp (a, b, t)
11{
12 return a + (b - a) * t;
13}
14
15/**
16 * @param {object|null} lastSale `{ lastTradePrice, lastTradeAt, priceFrom }`
17 */
18export function undiscountedMarketValue (itemId, lastSale = null, now = Date.now(), lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs)
19{
20 const def = itemDefinition(itemId);
21 const seed = Math.max(1, Number(def?.seedValue) || 1);
22 if (!lastSale?.lastTradeAt || lastSale.lastTradePrice == null)
23 { return seed; }
24 const duration = Math.max(1, Number(lerpDurationMs) || DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs);
25 const t = Math.min(1, Math.max(0, (now - lastSale.lastTradeAt) / duration));
26 const from = lastSale.priceFrom != null ? Number(lastSale.priceFrom) : seed;
27 const to = Number(lastSale.lastTradePrice);
28 if (!Number.isFinite(from) || !Number.isFinite(to))
29 { return seed; }
30 return lerp(from, to, t);
31}
32
33/** Integer shop purchase price (server authority). */
34export function shopUnitPrice (itemId, {
35 lastSale = null,
36 now = Date.now(),
37 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
38 hiddenDiscount = 1
39} = {})
40{
41 const undiscounted = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs);
42 const discount = Math.min(1, Math.max(0.01, Number(hiddenDiscount) || 1));
43 return Math.max(1, Math.round(undiscounted * discount));
44}
45
46/** NPC shops sell ingredients (and items explicitly flagged). */
47export function canSellInNpcShop (itemId)
48{
49 const def = itemDefinition(itemId);
50 if (!def)
51 { return false; }
52 if (def.npcShopAllowed === false)
53 { return false; }
54 if (def.npcShopAllowed === true)
55 { return true; }
56 return def.category === ItemCategory.ingredient || def.category === "ingredient";
57}