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.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -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>@@ -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
*/4
import { listSpawnableMobTypes, normalizeSpawnerConfig } from "/shared/definitions/mobs.js";4
import {5
listSpawnableMobTypes,6
normalizeSpawnerConfig,7
MobId,8
isHumanoidMob9
} 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
export function initTileConfigModal ({ onSave, onRemove })31
export 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.humanoid95
}, "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
90
function numberInput (name, value, min, max)188
function 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
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
function mobSelect (name, value)249
function mobSelect (name, value)112
{250
{113
const select = document.createElement("select");251
const select = document.createElement("select");@@ -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
recipesForStation13
recipesForStation14
} from "/shared/crafting/recipes.js";14
} from "/shared/crafting/recipes.js";15
import { craftDurationMs } from "/shared/definitions/gathering.js";15
import { applyItemIcon } from "../render/potionIcon.js";16
import { applyItemIcon } from "../render/potionIcon.js";16
17
17
export function initCrafting ({18
export 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.recipeId216
recipeId: recipe.recipeId214
});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); }@@ -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";12
import { initStamina } from "./stamina.js";12
import { initStamina } from "./stamina.js";13
import { initContextMenu } from "./contextMenu.js";13
import { initContextMenu } from "./contextMenu.js";14
import { initDeath } from "./death.js";14
import { initDeath } from "./death.js";15
import { initToasts } from "./toasts.js";16
import { initShop } from "./shop.js";15
import { CraftingStationId } from "/shared/definitions/craftingStations.js";17
import { CraftingStationId } from "/shared/definitions/craftingStations.js";16
import { isOreBoulderState } from "/shared/definitions/materialTiers.js";18
import { isOreBoulderState } from "/shared/definitions/materialTiers.js";17
import { formatQuantity } from "/shared/items/formatQuantity.js";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
const game = new Game();23
const game = new Game();20
const hud = document.getElementById("hud");24
const hud = document.getElementById("hud");@@ -39,8 +43,10 @@ let alchemy;39
let staminaUi;43
let staminaUi;40
let contextMenu;44
let contextMenu;41
let death;45
let death;46
let toasts;47
let shop;42
let pendingPickup = null;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
let pendingInteract = null;50
let 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. */46
let leftClickConsumed = false;52
let leftClickConsumed = false;@@ -154,9 +160,14 @@ function requestOpenCauldron (tileX, tileY)154
}160
}155
161
156
function requestOpenFurnace (tileX, tileY)162
function requestOpenFurnace (tileX, tileY)163
{164
requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY);165
}166
167
function 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.stationId239
});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
else372
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
else835
{ 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
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
function isOreBoulderTile (view, tileX, tileY)935
function isOreBoulderTile (view, tileX, tileY)876
{936
{877
const block = blockAt(view, tileX, tileY);937
const block = blockAt(view, tileX, tileY);@@ -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 @@1
import {2
itemDefinition,3
itemDisplayName,4
itemAssetPathForStack,5
formatQuantity6
} from "/shared/definitions/items.js";7
import { applyItemIcon } from "../render/potionIcon.js";8
9
export function initShop ({10
socket,11
MessageType,12
getCoinCount,13
onError14
})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: 184
});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.hidden107
};108
}@@ -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 @@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
}@@ -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;@@ -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 fi228
## Equipment tiers and worn stat bonuses228
## Equipment tiers and worn stat bonuses229
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 skills236
## Gathering, crafting, and production skills237
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 stations242
## Crafting stations243
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 running249
## Stamina and running250
250
@@ -293,9 +293,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi293
293
294
## Banking, cheques, shops, player-driven marketplace294
## Banking, cheques, shops, player-driven marketplace295
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 hooks300
## Player scripting hooks301
301
@@ -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,@@ -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
hasRecipeInputs11
hasRecipeInputs12
} from "../../../shared/crafting/recipes.js";12
} from "../../../shared/crafting/recipes.js";13
import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";13
import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";14
import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";14
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";15
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";15
import { smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";16
import { bagView } from "../items/bags.js";16
import { bagView } from "../items/bags.js";17
import { tileToChunk, tileToLocal } from "../world/coordinates.js";17
import { tileToChunk, tileToLocal } from "../world/coordinates.js";18
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";18
import { 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_MS132
finishesAt: now + durationMs128
});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
durationMs153
});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
@@ -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
});@@ -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,@@ -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";3
import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";3
import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";4
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";4
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";5
import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";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
import { publicSkillsView } from "../../../shared/skills/state.js";7
import { publicSkillsView } from "../../../shared/skills/state.js";8
8
9
let nextSessionId = 1;9
let nextSessionId = 1;@@ -208,6 +208,21 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,208
stationId: CraftingStationId.furnace208
stationId: CraftingStationId.furnace209
});209
});210
break;210
break;211
case MessageType.openStation:212
{213
requirePlaying(session);214
const stationId = typeof message.stationId === "string"215
? message.stationId216
: null;217
if (!stationId || !craftingStationDefinition(stationId))218
{ break; }219
simulation.enqueue(session.id, {220
type: "open-station",221
characterId: session.characterId,222
stationId223
});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 | 0395
targetEntityId: message.targetEntityId | 0381
});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 || 1406
});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(@@ -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 @@1
import { Component } from "../ecs/components.js";1
import { Component } from "../ecs/components.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";3
import { itemDefinition } from "../../../shared/definitions/items.js";3
import { itemDefinition } from "../../../shared/definitions/items.js";4
import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";4
import { SkillId } from "../../../shared/definitions/skills.js";5
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";6
import {5
import {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_STATE12
EXHAUSTED_ORE_BOULDER_STATE,13
resolveMiningPickaxe15
} from "../../../shared/definitions/gathering.js";14
} from "../../../shared/definitions/gathering.js";16
import { insertStack } from "../../../shared/items/inventory.js";15
import { insertStack } from "../../../shared/items/inventory.js";17
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";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);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
materialId79
});80
}80
}81
81
82
function clearGather (ecs, handle)82
function 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: now173
nextSwingAt: now@@ -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 @@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
takeCoinsFromSlots9
} 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?.shopPriceLerpDurationMs29
?? 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 ?? 146
})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.displayName78
|| [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?.shopPriceLerpDurationMs125
?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;126
const unitPrice = shopUnitPrice(itemId, {127
lastSale: lastSaleFor(world, itemId),128
now,129
lerpDurationMs,130
hiddenDiscount: shop.hiddenDiscount ?? 1131
});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.displayName145
|| [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: qty153
}]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
now186
);187
default:188
return null;189
}190
}@@ -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
mobSpriteName7
mobSpriteName8
} from "../../../shared/definitions/mobs.js";8
} from "../../../shared/definitions/mobs.js";9
import { emptyEquipment } from "../../../shared/items/inventory.js";10
import { itemDefinition } from "../../../shared/definitions/items.js";9
import { Component } from "../ecs/components.js";11
import { Component } from "../ecs/components.js";10
import { tileToChunk, tileToRegion } from "../world/coordinates.js";12
import { 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
persistent50
persistent,51
sex: config.sex,52
displayName: config.displayName,53
equipment: config.equipment,54
sells: config.sells,55
hiddenDiscount: config.hiddenDiscount49
});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)58
export function mobComponents (request)65
export 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.sex70
: (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.length137
? request.sells138
: [...(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
displayName145
};146
}102
return components;147
return components;103
}148
}104
149
@@ -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
clearOreRespawnsForChunk38
clearOreRespawnsForChunk39
} from "../gathering/service.js";39
} from "../gathering/service.js";40
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";40
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";41
import { handleShopCommand, openShop } from "../shop/service.js";41
import {42
import {42
applyRemoteMeleeSwing,43
applyRemoteMeleeSwing,43
clearEngage,44
clearEngage,@@ -396,6 +397,9 @@ export class WorkerWorld396
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 WorkerWorld745
}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
@@ -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";4
import { CraftingStationId, CRAFT_DURATION_MS } from "../../shared/definitions/craftingStations.js";4
import { CraftingStationId, CRAFT_DURATION_MS } from "../../shared/definitions/craftingStations.js";5
import { ItemId } from "../../shared/definitions/items.js";5
import { ItemId } from "../../shared/definitions/items.js";6
import { SkillId } from "../../shared/definitions/skills.js";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
associatedBarTier13
} from "../../shared/definitions/materialTiers.js";14
import { craftDurationMs } from "../../shared/definitions/gathering.js";8
import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";15
import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";9
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";16
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";10
import { totalXpForLevel } from "../../shared/skills/progression.js";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
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.tinOre82
].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.ironOre91
ItemId.ironOre77
].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
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
test("open furnace near station emits shove and station-open", () =>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
{ harness.close(); }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
const harness = makeSimulation({ workerCount: 1 });136
const harness = makeSimulation({ workerCount: 1 });110
try137
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
finally282
finally249
{ harness.close(); }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: null295
};296
}297
298
test("bronze pickaxe chain: pine log → handle, bar → head, assemble pickaxe", () =>299
{300
const harness = makeSimulation({ workerCount: 1 });301
try302
{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
finally349
{ harness.close(); }350
});@@ -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
82
test("crafting item stubs are registered", () =>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
assert.equal(itemDefinition(CraftingItemId.bronzeBar)?.key, "bronze-bar");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.bronzePickaxeHead105
].sort());106
assert.equal(pickaxe.output.itemId, ItemId.bronzePickaxe);107
});@@ -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
oreItemIdForMaterial18
oreItemIdForMaterial19
} from "../../shared/definitions/gathering.js";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
import { SkillId } from "../../shared/definitions/skills.js";21
import { SkillId } from "../../shared/definitions/skills.js";22
import { canEquipItem } from "../../shared/equipment/stats.js";22
import { canEquipItem } from "../../shared/equipment/stats.js";23
import { normalizePlayerSkills } from "../../shared/skills/state.js";23
import { 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
49
function equipPickaxe (worker, playerId, itemId)49
function 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
56
function setSkillLevel (worker, playerId, skillId, level)56
function 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
92
test("ore exhaust duration is 10s times material rank", () =>92
test("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
100
test("ore boulder states map to materials", () =>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
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
finally155
finally151
{ 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
finally211
{ harness.close(); }212
});213
214
test("mining uses the best pickaxe in inventory without equipping", () =>215
{216
const harness = makeSimulation({ workerCount: 1 });217
try218
{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: 8235
});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
finally242
finally205
{ 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
finally289
finally252
{ 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: 8310
tileY: 8273
});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);@@ -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 @@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.8533
}, "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
try46
{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: npcId105
});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: 1117
});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
finally126
{ harness.close(); }127
});@@ -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
resolveItemTint7
resolveItemTint8
} from "../../shared/render/tint.js";8
} from "../../shared/render/tint.js";9
import { MaterialTier } from "../../shared/definitions/materialTiers.js";9
import { MaterialTier, GatherMaterialId } from "../../shared/definitions/materialTiers.js";10
import { ItemId } from "../../shared/definitions/items.js";10
import { ItemId } from "../../shared/definitions/items.js";11
11
12
test("magenta tintable when R==B and G < R", () =>12
test("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
});