BlueGit

timfa questward

Award craft/alchemy XP from ingredient tiers and approach via player BFS.

Potion bottling and station crafts grant XP per consumed item; dye is 1 XP per flower. Out-of-range combat and node/station approach flood from the player to the nearest valid stand tile instead of preferring top-left.

timfa Tim Falken · pushed by timfa

Authored 2026-08-28 · 2 months ago

Hash
e19132b636a2516156e1587d696d03468a55138f
Parent
38812f19
14 files changed +404 −88
client/src/play/alchemy.js +11 −3
@@ -11,6 +11,7 @@ import {
11 11 DYE_CAULDRON_SLOT_COUNT,
12 12 CAULDRON_EMPTY_FLAVOR
13 13 } from "/shared/definitions/alchemy.js";
14 import { FLOWER_MAX_STACK } from "/shared/definitions/dyes.js";
14 15 import { applyItemIcon } from "../render/potionIcon.js";
15 16
16 17 export function initAlchemy ({
@@ -343,8 +344,14 @@ export function initAlchemy ({
343 344 {
344 345 pickItemId = entry.itemId;
345 346 pickInstance = entry.instance;
346 pickQty.max = String(entry.quantity);
347 pickQty.value = String(Math.min(entry.quantity, Number(pickQty.value) || 1));
347 pickQty.max = String(pickMode === "dye"
348 ? Math.min(entry.quantity, FLOWER_MAX_STACK)
349 : entry.quantity);
350 pickQty.value = String(Math.min(
351 entry.quantity,
352 Number(pickQty.value) || 1,
353 pickMode === "dye" ? FLOWER_MAX_STACK : entry.quantity
354 ));
348 355 for (const child of pickList.children)
349 356 { child.classList.toggle("selected", child === btn); }
350 357 });
@@ -368,7 +375,8 @@ export function initAlchemy ({
368 375 {
369 376 if (pickSlotIndex == null || pickItemId == null)
370 377 { return; }
371 const quantity = Math.max(1, pickQty.value | 0);
378 const rawQty = Math.max(1, pickQty.value | 0);
379 const quantity = pickMode === "dye" ? Math.min(rawQty, FLOWER_MAX_STACK) : rawQty;
372 380 const entry = {
373 381 itemId: pickItemId,
374 382 quantity,
@@ -11,6 +11,7 @@ import {
11 DYE_CAULDRON_SLOT_COUNT,
11 DYE_CAULDRON_SLOT_COUNT,
12 CAULDRON_EMPTY_FLAVOR
12 CAULDRON_EMPTY_FLAVOR
13} from "/shared/definitions/alchemy.js";
13} from "/shared/definitions/alchemy.js";
14import { FLOWER_MAX_STACK } from "/shared/definitions/dyes.js";
14import { applyItemIcon } from "../render/potionIcon.js";
15import { applyItemIcon } from "../render/potionIcon.js";
15
16
16export function initAlchemy ({
17export function initAlchemy ({
@@ -343,8 +344,14 @@ export function initAlchemy ({
343 {
344 {
344 pickItemId = entry.itemId;
345 pickItemId = entry.itemId;
345 pickInstance = entry.instance;
346 pickInstance = entry.instance;
346 pickQty.max = String(entry.quantity);
347 pickQty.max = String(pickMode === "dye"
347 pickQty.value = String(Math.min(entry.quantity, Number(pickQty.value) || 1));
348 ? Math.min(entry.quantity, FLOWER_MAX_STACK)
349 : entry.quantity);
350 pickQty.value = String(Math.min(
351 entry.quantity,
352 Number(pickQty.value) || 1,
353 pickMode === "dye" ? FLOWER_MAX_STACK : entry.quantity
354 ));
348 for (const child of pickList.children)
355 for (const child of pickList.children)
349 { child.classList.toggle("selected", child === btn); }
356 { child.classList.toggle("selected", child === btn); }
350 });
357 });
@@ -368,7 +375,8 @@ export function initAlchemy ({
368 {
375 {
369 if (pickSlotIndex == null || pickItemId == null)
376 if (pickSlotIndex == null || pickItemId == null)
370 { return; }
377 { return; }
371 const quantity = Math.max(1, pickQty.value | 0);
378 const rawQty = Math.max(1, pickQty.value | 0);
379 const quantity = pickMode === "dye" ? Math.min(rawQty, FLOWER_MAX_STACK) : rawQty;
372 const entry = {
380 const entry = {
373 itemId: pickItemId,
381 itemId: pickItemId,
374 quantity,
382 quantity,
client/src/play/main.js +41 −28
@@ -1,7 +1,8 @@
1 import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
1 import { MessageType, GAIT, CHUNK_SIZE, STATIC_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2 2 import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
3 3 import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
4 4 import { OVERWORLD_ID } from "/shared/world/dimensions.js";
5 import { findPathToNearestGoal } from "/shared/navigation/bfs.js";
5 6 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
6 7 import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";
7 8 import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog } from "../render/sprites.js";
@@ -201,51 +202,63 @@ function approachAdjacentTile (tileX, tileY)
201 202 approachMove = null;
202 203 return true;
203 204 }
204 let bestWalkable = null;
205 let bestWalkableDist = Infinity;
206 let bestAny = null;
207 let bestAnyDist = Infinity;
208 for (let dy = -1; dy <= 1; dy++)
205 if (!local)
206 { return false; }
207
208 const radius = Math.max(1, STATIC_CHUNK_RADIUS | 0) * CHUNK_SIZE;
209 const path = findPathToNearestGoal(
210 local.tileX,
211 local.tileY,
212 (x, y) => chebyshev(x, y, tileX, tileY) === 1 && isClientApproachable(x, y),
213 (x, y) => isClientApproachable(x, y),
214 local.tileX - radius,
215 local.tileY - radius,
216 local.tileX + radius,
217 local.tileY + radius
218 );
219 let best = path.length ? path[path.length - 1] : null;
220 if (!best)
209 221 {
210 for (let dx = -1; dx <= 1; dx++)
222 // Fallback if BFS finds nothing (incomplete client map): nearest adjacent guess.
223 let bestAny = null;
224 let bestAnyDist = Infinity;
225 for (let dy = -1; dy <= 1; dy++)
211 226 {
212 if (dx === 0 && dy === 0)
213 { continue; }
214 const destX = tileX + dx;
215 const destY = tileY + dy;
216 const dist = local
217 ? chebyshev(local.tileX, local.tileY, destX, destY)
218 : 0;
219 if (dist < bestAnyDist)
227 for (let dx = -1; dx <= 1; dx++)
220 228 {
221 bestAnyDist = dist;
222 bestAny = { tileX: destX, tileY: destY };
223 }
224 if (isClientApproachable(destX, destY) && dist < bestWalkableDist)
225 {
226 bestWalkableDist = dist;
227 bestWalkable = { tileX: destX, tileY: destY };
229 if (dx === 0 && dy === 0)
230 { continue; }
231 const destX = tileX + dx;
232 const destY = tileY + dy;
233 const dist = chebyshev(local.tileX, local.tileY, destX, destY);
234 if (dist < bestAnyDist)
235 {
236 bestAnyDist = dist;
237 bestAny = { tileX: destX, tileY: destY };
238 }
228 239 }
229 240 }
241 best = bestAny ? { x: bestAny.tileX, y: bestAny.tileY } : null;
230 242 }
231 const best = bestWalkable ?? bestAny;
232 243 if (!best)
233 244 { return false; }
245 const destX = best.x ?? best.tileX;
246 const destY = best.y ?? best.tileY;
234 247 if (
235 248 approachMove
236 249 && approachMove.focusX === tileX
237 250 && approachMove.focusY === tileY
238 && approachMove.destX === best.tileX
239 && approachMove.destY === best.tileY
251 && approachMove.destX === destX
252 && approachMove.destY === destY
240 253 )
241 254 { return false; }
242 255 approachMove = {
243 256 focusX: tileX,
244 257 focusY: tileY,
245 destX: best.tileX,
246 destY: best.tileY
258 destX,
259 destY
247 260 };
248 socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY });
261 socket.send({ type: MessageType.moveTo, tileX: destX, tileY: destY });
249 262 return false;
250 263 }
251 264
@@ -1,7 +1,8 @@
1import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
1import { MessageType, GAIT, CHUNK_SIZE, STATIC_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
2import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
3import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
3import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
4import { OVERWORLD_ID } from "/shared/world/dimensions.js";
4import { OVERWORLD_ID } from "/shared/world/dimensions.js";
5import { findPathToNearestGoal } from "/shared/navigation/bfs.js";
5import { GameSocket, defaultSocketUrl } from "../net/socket.js";
6import { GameSocket, defaultSocketUrl } from "../net/socket.js";
6import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";
7import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";
7import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog } from "../render/sprites.js";
8import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog } from "../render/sprites.js";
@@ -201,51 +202,63 @@ function approachAdjacentTile (tileX, tileY)
201 approachMove = null;
202 approachMove = null;
202 return true;
203 return true;
203 }
204 }
204 let bestWalkable = null;
205 if (!local)
205 let bestWalkableDist = Infinity;
206 { return false; }
206 let bestAny = null;
207
207 let bestAnyDist = Infinity;
208 const radius = Math.max(1, STATIC_CHUNK_RADIUS | 0) * CHUNK_SIZE;
208 for (let dy = -1; dy <= 1; dy++)
209 const path = findPathToNearestGoal(
210 local.tileX,
211 local.tileY,
212 (x, y) => chebyshev(x, y, tileX, tileY) === 1 && isClientApproachable(x, y),
213 (x, y) => isClientApproachable(x, y),
214 local.tileX - radius,
215 local.tileY - radius,
216 local.tileX + radius,
217 local.tileY + radius
218 );
219 let best = path.length ? path[path.length - 1] : null;
220 if (!best)
209 {
221 {
210 for (let dx = -1; dx <= 1; dx++)
222 // Fallback if BFS finds nothing (incomplete client map): nearest adjacent guess.
223 let bestAny = null;
224 let bestAnyDist = Infinity;
225 for (let dy = -1; dy <= 1; dy++)
211 {
226 {
212 if (dx === 0 && dy === 0)
227 for (let dx = -1; dx <= 1; dx++)
213 { continue; }
214 const destX = tileX + dx;
215 const destY = tileY + dy;
216 const dist = local
217 ? chebyshev(local.tileX, local.tileY, destX, destY)
218 : 0;
219 if (dist < bestAnyDist)
220 {
228 {
221 bestAnyDist = dist;
229 if (dx === 0 && dy === 0)
222 bestAny = { tileX: destX, tileY: destY };
230 { continue; }
223 }
231 const destX = tileX + dx;
224 if (isClientApproachable(destX, destY) && dist < bestWalkableDist)
232 const destY = tileY + dy;
225 {
233 const dist = chebyshev(local.tileX, local.tileY, destX, destY);
226 bestWalkableDist = dist;
234 if (dist < bestAnyDist)
227 bestWalkable = { tileX: destX, tileY: destY };
235 {
236 bestAnyDist = dist;
237 bestAny = { tileX: destX, tileY: destY };
238 }
228 }
239 }
229 }
240 }
241 best = bestAny ? { x: bestAny.tileX, y: bestAny.tileY } : null;
230 }
242 }
231 const best = bestWalkable ?? bestAny;
232 if (!best)
243 if (!best)
233 { return false; }
244 { return false; }
245 const destX = best.x ?? best.tileX;
246 const destY = best.y ?? best.tileY;
234 if (
247 if (
235 approachMove
248 approachMove
236 && approachMove.focusX === tileX
249 && approachMove.focusX === tileX
237 && approachMove.focusY === tileY
250 && approachMove.focusY === tileY
238 && approachMove.destX === best.tileX
251 && approachMove.destX === destX
239 && approachMove.destY === best.tileY
252 && approachMove.destY === destY
240 )
253 )
241 { return false; }
254 { return false; }
242 approachMove = {
255 approachMove = {
243 focusX: tileX,
256 focusX: tileX,
244 focusY: tileY,
257 focusY: tileY,
245 destX: best.tileX,
258 destX,
246 destY: best.tileY
259 destY
247 };
260 };
248 socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY });
261 socket.send({ type: MessageType.moveTo, tileX: destX, tileY: destY });
249 return false;
262 return false;
250}
263}
251
264
server/src/alchemy/service.js +53 −5
@@ -6,6 +6,7 @@ import {
6 6 DYE_CAULDRON_SLOT_COUNT
7 7 } from "../../../shared/definitions/alchemy.js";
8 8 import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
9 import { SkillId } from "../../../shared/definitions/skills.js";
9 10 import {
10 11 evaluateAlchemyBottle,
11 12 potionItemInstance,
@@ -15,6 +16,7 @@ import {
15 16 } from "../../../shared/alchemy/recipes.js";
16 17 import {
17 18 DEFAULT_DYE_FILL,
19 FLOWER_MAX_STACK,
18 20 mixFlowersForDye
19 21 } from "../../../shared/definitions/dyes.js";
20 22 import { bagView } from "../items/bags.js";
@@ -27,6 +29,8 @@ import {
27 29 stackQuantity
28 30 } from "../../../shared/items/inventory.js";
29 31 import { attachOrigins, craftOrigin, CraftOriginVerb, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
32 import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
33 import { craftXpForConsumedInputs } from "../../../shared/definitions/gathering.js";
30 34 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
31 35 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
32 36 import { randomUUID } from "node:crypto";
@@ -343,7 +347,7 @@ function action (world, sessionId, command)
343 347
344 348 function bottle (world, sessionId, command)
345 349 {
346 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
350 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
347 351 requireNearCauldron(world, handle);
348 352 const session = requireSession(world, command.characterId);
349 353 if (!(session.pendingBrew?.length > 0) && !(session.steps?.length > 0))
@@ -425,8 +429,33 @@ function bottle (world, sessionId, command)
425 429 session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;
426 430 clearAlchemy(session);
427 431
432 const events = [];
433 if (evaluation.success && skills?.xp)
434 {
435 const xpInputs = (consumed ?? []).map((row) => ({
436 itemId: row.itemId,
437 quantity: row.quantity
438 }));
439 const amount = craftXpForConsumedInputs(xpInputs);
440 if (amount > 0)
441 {
442 const result = applySkillXp(skills, SkillId.alchemy, amount);
443 if (result.changed)
444 {
445 events.push({
446 type: "skills-updated",
447 entityId,
448 characterId: command.characterId,
449 skills: publicSkillsView(skills),
450 stored: storedSkillXp(skills),
451 levelUps: result.levelUp ? [result.levelUp] : []
452 });
453 }
454 }
455 }
456
428 457 return {
429 events: [],
458 events,
430 459 private: bagView(world.ecs, handle),
431 460 cauldron: true,
432 461 cauldronState: sessionView(session),
@@ -449,7 +478,7 @@ function bottle (world, sessionId, command)
449 478
450 479 function createDye (world, sessionId, command)
451 480 {
452 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
481 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
453 482 requireNearCauldron(world, handle);
454 483 requireSession(world, command.characterId);
455 484
@@ -524,8 +553,27 @@ function createDye (world, sessionId, command)
524 553 { throw userError("Not enough inventory space for dye."); }
525 554 inventory.slots = inserted.slots;
526 555
556 const events = [];
557 const skills = world.ecs.get(handle, Component.skills);
558 const flowerCount = rows.reduce((sum, row) => sum + (row.quantity | 0), 0);
559 if (skills?.xp && flowerCount > 0)
560 {
561 const result = applySkillXp(skills, SkillId.alchemy, flowerCount);
562 if (result.changed)
563 {
564 events.push({
565 type: "skills-updated",
566 entityId,
567 characterId: command.characterId,
568 skills: publicSkillsView(skills),
569 stored: storedSkillXp(skills),
570 levelUps: result.levelUp ? [result.levelUp] : []
571 });
572 }
573 }
574
527 575 return {
528 events: [],
576 events,
529 577 private: bagView(world.ecs, handle),
530 578 cauldron: true,
531 579 cauldronState: sessionView(requireSession(world, command.characterId)),
@@ -554,7 +602,7 @@ function normalizeFlowerRows (flowers)
554 602 for (const entry of flowers)
555 603 {
556 604 const itemId = entry?.itemId | 0;
557 const quantity = Math.max(0, entry?.quantity | 0);
605 const quantity = Math.min(FLOWER_MAX_STACK, Math.max(0, entry?.quantity | 0));
558 606 if (itemId !== ItemId.flower || quantity <= 0)
559 607 { continue; }
560 608 const instance = entry.instance ? structuredClone(entry.instance) : null;
@@ -6,6 +6,7 @@ import {
6 DYE_CAULDRON_SLOT_COUNT
6 DYE_CAULDRON_SLOT_COUNT
7} from "../../../shared/definitions/alchemy.js";
7} from "../../../shared/definitions/alchemy.js";
8import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
8import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
9import { SkillId } from "../../../shared/definitions/skills.js";
9import {
10import {
10 evaluateAlchemyBottle,
11 evaluateAlchemyBottle,
11 potionItemInstance,
12 potionItemInstance,
@@ -15,6 +16,7 @@ import {
15} from "../../../shared/alchemy/recipes.js";
16} from "../../../shared/alchemy/recipes.js";
16import {
17import {
17 DEFAULT_DYE_FILL,
18 DEFAULT_DYE_FILL,
19 FLOWER_MAX_STACK,
18 mixFlowersForDye
20 mixFlowersForDye
19} from "../../../shared/definitions/dyes.js";
21} from "../../../shared/definitions/dyes.js";
20import { bagView } from "../items/bags.js";
22import { bagView } from "../items/bags.js";
@@ -27,6 +29,8 @@ import {
27 stackQuantity
29 stackQuantity
28} from "../../../shared/items/inventory.js";
30} from "../../../shared/items/inventory.js";
29import { attachOrigins, craftOrigin, CraftOriginVerb, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
31import { attachOrigins, craftOrigin, CraftOriginVerb, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
32import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
33import { craftXpForConsumedInputs } from "../../../shared/definitions/gathering.js";
30import { tileToChunk, tileToLocal } from "../world/coordinates.js";
34import { tileToChunk, tileToLocal } from "../world/coordinates.js";
31import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
35import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
32import { randomUUID } from "node:crypto";
36import { randomUUID } from "node:crypto";
@@ -343,7 +347,7 @@ function action (world, sessionId, command)
343
347
344function bottle (world, sessionId, command)
348function bottle (world, sessionId, command)
345{
349{
346 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
350 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
347 requireNearCauldron(world, handle);
351 requireNearCauldron(world, handle);
348 const session = requireSession(world, command.characterId);
352 const session = requireSession(world, command.characterId);
349 if (!(session.pendingBrew?.length > 0) && !(session.steps?.length > 0))
353 if (!(session.pendingBrew?.length > 0) && !(session.steps?.length > 0))
@@ -425,8 +429,33 @@ function bottle (world, sessionId, command)
425 session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;
429 session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;
426 clearAlchemy(session);
430 clearAlchemy(session);
427
431
432 const events = [];
433 if (evaluation.success && skills?.xp)
434 {
435 const xpInputs = (consumed ?? []).map((row) => ({
436 itemId: row.itemId,
437 quantity: row.quantity
438 }));
439 const amount = craftXpForConsumedInputs(xpInputs);
440 if (amount > 0)
441 {
442 const result = applySkillXp(skills, SkillId.alchemy, amount);
443 if (result.changed)
444 {
445 events.push({
446 type: "skills-updated",
447 entityId,
448 characterId: command.characterId,
449 skills: publicSkillsView(skills),
450 stored: storedSkillXp(skills),
451 levelUps: result.levelUp ? [result.levelUp] : []
452 });
453 }
454 }
455 }
456
428 return {
457 return {
429 events: [],
458 events,
430 private: bagView(world.ecs, handle),
459 private: bagView(world.ecs, handle),
431 cauldron: true,
460 cauldron: true,
432 cauldronState: sessionView(session),
461 cauldronState: sessionView(session),
@@ -449,7 +478,7 @@ function bottle (world, sessionId, command)
449
478
450function createDye (world, sessionId, command)
479function createDye (world, sessionId, command)
451{
480{
452 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
481 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
453 requireNearCauldron(world, handle);
482 requireNearCauldron(world, handle);
454 requireSession(world, command.characterId);
483 requireSession(world, command.characterId);
455
484
@@ -524,8 +553,27 @@ function createDye (world, sessionId, command)
524 { throw userError("Not enough inventory space for dye."); }
553 { throw userError("Not enough inventory space for dye."); }
525 inventory.slots = inserted.slots;
554 inventory.slots = inserted.slots;
526
555
556 const events = [];
557 const skills = world.ecs.get(handle, Component.skills);
558 const flowerCount = rows.reduce((sum, row) => sum + (row.quantity | 0), 0);
559 if (skills?.xp && flowerCount > 0)
560 {
561 const result = applySkillXp(skills, SkillId.alchemy, flowerCount);
562 if (result.changed)
563 {
564 events.push({
565 type: "skills-updated",
566 entityId,
567 characterId: command.characterId,
568 skills: publicSkillsView(skills),
569 stored: storedSkillXp(skills),
570 levelUps: result.levelUp ? [result.levelUp] : []
571 });
572 }
573 }
574
527 return {
575 return {
528 events: [],
576 events,
529 private: bagView(world.ecs, handle),
577 private: bagView(world.ecs, handle),
530 cauldron: true,
578 cauldron: true,
531 cauldronState: sessionView(requireSession(world, command.characterId)),
579 cauldronState: sessionView(requireSession(world, command.characterId)),
@@ -554,7 +602,7 @@ function normalizeFlowerRows (flowers)
554 for (const entry of flowers)
602 for (const entry of flowers)
555 {
603 {
556 const itemId = entry?.itemId | 0;
604 const itemId = entry?.itemId | 0;
557 const quantity = Math.max(0, entry?.quantity | 0);
605 const quantity = Math.min(FLOWER_MAX_STACK, Math.max(0, entry?.quantity | 0));
558 if (itemId !== ItemId.flower || quantity <= 0)
606 if (itemId !== ItemId.flower || quantity <= 0)
559 { continue; }
607 { continue; }
560 const instance = entry.instance ? structuredClone(entry.instance) : null;
608 const instance = entry.instance ? structuredClone(entry.instance) : null;
server/src/combat/service.js +25 −44
@@ -31,6 +31,7 @@ import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
31 31 import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";
32 32 import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
33 33 import { chunkBoundsAround, findPath } from "../navigation/astar.js";
34 import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js";
34 35 import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
35 36 import { rayReaches } from "../../../shared/lighting/raycast.js";
36 37 import { tileToChunk } from "../world/coordinates.js";
@@ -727,7 +728,8 @@ function standInRangePathStale (world, entityId, path, goal, targetTileX, target
727 728 }
728 729
729 730 /**
730 * Path toward the nearest tile from which `targetTile` is in Chebyshev range with LOS.
731 * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS.
732 * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left).
731 733 * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile).
732 734 */
733 735 export function queueStandInRangeApproach (
@@ -758,39 +760,32 @@ export function queueStandInRangeApproach (
758 760 return;
759 761 }
760 762
761 let bestGoal = null;
762 let bestDist = Infinity;
763 for (let dy = -maxRange; dy <= maxRange; dy++)
764 {
765 for (let dx = -maxRange; dx <= maxRange; dx++)
766 {
767 const x = targetTileX + dx;
768 const y = targetTileY + dy;
769 const standOff = chebyshev(x, y, targetTileX, targetTileY);
770 if (standOff < minStandDist || standOff > maxRange)
771 { continue; }
772 if (!world.walkableFor(entityId, x, y))
773 { continue; }
774 if (!hasCombatLineOfSight(world, x, y, targetTileX, targetTileY))
775 { continue; }
776 const d = chebyshev(position.tileX, position.tileY, x, y);
777 if (d < bestDist)
778 {
779 bestDist = d;
780 bestGoal = { x, y };
781 }
782 }
783 }
784 if (!bestGoal)
763 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
764 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
765 const isGoal = (x, y) =>
785 766 {
786 path.tiles = [];
787 return;
788 }
789 if (bestGoal.x === position.tileX && bestGoal.y === position.tileY)
767 const standOff = chebyshev(x, y, targetTileX, targetTileY);
768 if (standOff < minStandDist || standOff > maxRange)
769 { return false; }
770 return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY);
771 };
772
773 const tiles = findPathToNearestGoal(
774 position.tileX,
775 position.tileY,
776 isGoal,
777 isWalkable,
778 bounds.minX,
779 bounds.minY,
780 bounds.maxX,
781 bounds.maxY
782 );
783 if (!tiles.length)
790 784 {
791 785 path.tiles = [];
792 786 return;
793 787 }
788 const bestGoal = tiles[tiles.length - 1];
794 789 if (path.tiles?.length && !standInRangePathStale(
795 790 world,
796 791 entityId,
@@ -802,21 +797,7 @@ export function queueStandInRangeApproach (
802 797 minStandDist
803 798 ))
804 799 { return; }
805 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
806 const preferVertical = !!world.ecs.get(handle, Component.character);
807 const tiles = findPath(
808 position.tileX,
809 position.tileY,
810 bestGoal.x,
811 bestGoal.y,
812 (x, y) => world.walkableFor(entityId, x, y),
813 bounds.minX,
814 bounds.minY,
815 bounds.maxX,
816 bounds.maxY,
817 { preferVertical }
818 );
819 path.tiles = tiles.length ? tiles : [];
800 path.tiles = tiles;
820 801 const movement = world.ecs.get(handle, Component.movement);
821 802 if (movement)
822 803 { movement.walkCarry = 0; }
@@ -31,6 +31,7 @@ import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
31import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";
31import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";
32import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
32import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
33import { chunkBoundsAround, findPath } from "../navigation/astar.js";
33import { chunkBoundsAround, findPath } from "../navigation/astar.js";
34import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js";
34import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
35import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
35import { rayReaches } from "../../../shared/lighting/raycast.js";
36import { rayReaches } from "../../../shared/lighting/raycast.js";
36import { tileToChunk } from "../world/coordinates.js";
37import { tileToChunk } from "../world/coordinates.js";
@@ -727,7 +728,8 @@ function standInRangePathStale (world, entityId, path, goal, targetTileX, target
727}
728}
728
729
729/**
730/**
730 * Path toward the nearest tile from which `targetTile` is in Chebyshev range with LOS.
731 * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS.
732 * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left).
731 * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile).
733 * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile).
732 */
734 */
733export function queueStandInRangeApproach (
735export function queueStandInRangeApproach (
@@ -758,39 +760,32 @@ export function queueStandInRangeApproach (
758 return;
760 return;
759 }
761 }
760
762
761 let bestGoal = null;
763 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
762 let bestDist = Infinity;
764 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
763 for (let dy = -maxRange; dy <= maxRange; dy++)
765 const isGoal = (x, y) =>
764 {
765 for (let dx = -maxRange; dx <= maxRange; dx++)
766 {
767 const x = targetTileX + dx;
768 const y = targetTileY + dy;
769 const standOff = chebyshev(x, y, targetTileX, targetTileY);
770 if (standOff < minStandDist || standOff > maxRange)
771 { continue; }
772 if (!world.walkableFor(entityId, x, y))
773 { continue; }
774 if (!hasCombatLineOfSight(world, x, y, targetTileX, targetTileY))
775 { continue; }
776 const d = chebyshev(position.tileX, position.tileY, x, y);
777 if (d < bestDist)
778 {
779 bestDist = d;
780 bestGoal = { x, y };
781 }
782 }
783 }
784 if (!bestGoal)
785 {
766 {
786 path.tiles = [];
767 const standOff = chebyshev(x, y, targetTileX, targetTileY);
787 return;
768 if (standOff < minStandDist || standOff > maxRange)
788 }
769 { return false; }
789 if (bestGoal.x === position.tileX && bestGoal.y === position.tileY)
770 return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY);
771 };
772
773 const tiles = findPathToNearestGoal(
774 position.tileX,
775 position.tileY,
776 isGoal,
777 isWalkable,
778 bounds.minX,
779 bounds.minY,
780 bounds.maxX,
781 bounds.maxY
782 );
783 if (!tiles.length)
790 {
784 {
791 path.tiles = [];
785 path.tiles = [];
792 return;
786 return;
793 }
787 }
788 const bestGoal = tiles[tiles.length - 1];
794 if (path.tiles?.length && !standInRangePathStale(
789 if (path.tiles?.length && !standInRangePathStale(
795 world,
790 world,
796 entityId,
791 entityId,
@@ -802,21 +797,7 @@ export function queueStandInRangeApproach (
802 minStandDist
797 minStandDist
803 ))
798 ))
804 { return; }
799 { return; }
805 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
800 path.tiles = tiles;
806 const preferVertical = !!world.ecs.get(handle, Component.character);
807 const tiles = findPath(
808 position.tileX,
809 position.tileY,
810 bestGoal.x,
811 bestGoal.y,
812 (x, y) => world.walkableFor(entityId, x, y),
813 bounds.minX,
814 bounds.minY,
815 bounds.maxX,
816 bounds.maxY,
817 { preferVertical }
818 );
819 path.tiles = tiles.length ? tiles : [];
820 const movement = world.ecs.get(handle, Component.movement);
801 const movement = world.ecs.get(handle, Component.movement);
821 if (movement)
802 if (movement)
822 { movement.walkCarry = 0; }
803 { movement.walkCarry = 0; }
server/src/crafting/service.js +3 −3
@@ -11,7 +11,7 @@ import {
11 11 hasRecipeInputs
12 12 } from "../../../shared/crafting/recipes.js";
13 13 import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
14 import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
14 import { craftDurationMs, craftXpForConsumedInputs } from "../../../shared/definitions/gathering.js";
15 15 import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";
16 16 import {
17 17 attachOrigins,
@@ -399,12 +399,12 @@ export function stepCrafting (world, now)
399 399
400 400 let skillsChanged = false;
401 401 const levelUps = [];
402 if (skills?.xp && recipe.xpMaterial && stationDef?.skillId)
402 if (skills?.xp && stationDef?.skillId)
403 403 {
404 404 const result = applySkillXp(
405 405 skills,
406 406 stationDef.skillId,
407 smeltingXpForMaterial(recipe.xpMaterial)
407 craftXpForConsumedInputs(recipe.inputs)
408 408 );
409 409 if (result.changed)
410 410 { skillsChanged = true; }
@@ -11,7 +11,7 @@ import {
11 hasRecipeInputs
11 hasRecipeInputs
12} from "../../../shared/crafting/recipes.js";
12} from "../../../shared/crafting/recipes.js";
13import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
13import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
14import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
14import { craftDurationMs, craftXpForConsumedInputs } from "../../../shared/definitions/gathering.js";
15import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";
15import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";
16import {
16import {
17 attachOrigins,
17 attachOrigins,
@@ -399,12 +399,12 @@ export function stepCrafting (world, now)
399
399
400 let skillsChanged = false;
400 let skillsChanged = false;
401 const levelUps = [];
401 const levelUps = [];
402 if (skills?.xp && recipe.xpMaterial && stationDef?.skillId)
402 if (skills?.xp && stationDef?.skillId)
403 {
403 {
404 const result = applySkillXp(
404 const result = applySkillXp(
405 skills,
405 skills,
406 stationDef.skillId,
406 stationDef.skillId,
407 smeltingXpForMaterial(recipe.xpMaterial)
407 craftXpForConsumedInputs(recipe.inputs)
408 );
408 );
409 if (result.changed)
409 if (result.changed)
410 { skillsChanged = true; }
410 { skillsChanged = true; }
server/src/simulation/simulation.js +6 −0
@@ -1190,6 +1190,12 @@ export class Simulation
1190 1190 const events = [];
1191 1191 for (const event of result?.events ?? [])
1192 1192 {
1193 if (event.type === "skills-updated")
1194 {
1195 this.#applySkillsUpdated(event);
1196 events.push(...this.#skillLevelUpEvents(event));
1197 continue;
1198 }
1193 1199 if (event.type === "spells-updated")
1194 1200 {
1195 1201 this.#applySpellsUpdated(event);
@@ -1190,6 +1190,12 @@ export class Simulation
1190 const events = [];
1190 const events = [];
1191 for (const event of result?.events ?? [])
1191 for (const event of result?.events ?? [])
1192 {
1192 {
1193 if (event.type === "skills-updated")
1194 {
1195 this.#applySkillsUpdated(event);
1196 events.push(...this.#skillLevelUpEvents(event));
1197 continue;
1198 }
1193 if (event.type === "spells-updated")
1199 if (event.type === "spells-updated")
1194 {
1200 {
1195 this.#applySpellsUpdated(event);
1201 this.#applySpellsUpdated(event);
server/tests/alchemy.test.js +51 −2
@@ -1,7 +1,8 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 3 import { BlockType } from "../../shared/definitions/tiles.js";
4 import { ItemId } from "../../shared/definitions/items.js";
4 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
5 import { flowerItemInstance } from "../../shared/definitions/dyes.js";
5 6 import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";
6 7 import {
7 8 evaluateAlchemyBottle,
@@ -11,7 +12,6 @@ import {
11 12 potionItemInstance
12 13 } from "../../shared/alchemy/recipes.js";
13 14 import { emptyEquipment, emptySlots, insertStack } from "../../shared/items/inventory.js";
14 import { itemDefinition } from "../../shared/definitions/items.js";
15 15 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
16 16 import { Component } from "../src/ecs/components.js";
17 17 import {
@@ -102,6 +102,7 @@ test("cauldron bottles lesser health tonic when steps and ratios match", () =>
102 102 });
103 103 const entityId = harness.simulation.spawnCharacter(1, character);
104 104 const cid = character.character_id;
105 const alchemyBefore = harness.stateDb.getSkills(cid).xp.alchemy ?? 0;
105 106
106 107 harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });
107 108 harness.simulation.step();
@@ -147,6 +148,9 @@ test("cauldron bottles lesser health tonic when steps and ratios match", () =>
147 148 const potion = bag.inventory.find((slot) => slot?.itemId === ItemId.potion);
148 149 assert.equal(potion.instance?.potionKey, "lesserHealthTonic");
149 150 assert.equal(potion.instance?.unstable, false);
151 const alchemyAfter = harness.stateDb.getSkills(cid).xp.alchemy ?? 0;
152 // thyme×2 (tier 2) + mint×2 (tier 1)
153 assert.equal(alchemyAfter - alchemyBefore, 6);
150 154
151 155 harness.simulation.enqueue(1, { type: "cauldron-save-recipe", characterId: cid });
152 156 harness.simulation.step();
@@ -314,3 +318,48 @@ test("drinking a lesser health tonic applies health regen", () =>
314 318 finally
315 319 { harness.close(); }
316 320 });
321
322 test("creating dye awards 1 alchemy XP per flower and caps a slot at 16", () =>
323 {
324 const harness = makeSimulation({ workerCount: 1 });
325 try
326 {
327 placeCauldron(harness.worldDb, 8, 8);
328 harness.simulation.reloadWorld();
329 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
330 const inventory = emptySlots();
331 const instance = flowerItemInstance("red");
332 const filled = insertStack(
333 inventory,
334 { itemId: ItemId.flower, quantity: 16, instance },
335 itemDefinition(ItemId.flower)
336 );
337 filled.slots[1] = { itemId: ItemId.glassBottle, quantity: 16 };
338 harness.stateDb.saveBag(character.character_id, {
339 inventory: filled.slots,
340 equipment: emptyEquipment(),
341 vault: [],
342 vaultReserved: []
343 });
344 const entityId = harness.simulation.spawnCharacter(1, character);
345 const cid = character.character_id;
346 const alchemyBefore = harness.stateDb.getSkills(cid).xp.alchemy ?? 0;
347
348 harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });
349 harness.simulation.step();
350 harness.simulation.enqueue(1, {
351 type: "cauldron-create-dye",
352 characterId: cid,
353 flowers: [{ itemId: ItemId.flower, quantity: 99, instance }]
354 });
355 const made = harness.simulation.step();
356 assert.equal(made.events.some((event) => event.type === "command-error"), false, JSON.stringify(made.events));
357 const alchemyAfter = harness.stateDb.getSkills(cid).xp.alchemy ?? 0;
358 assert.equal(alchemyAfter - alchemyBefore, 16);
359 const bag = harness.simulation.bagOf(entityId);
360 assert.equal(countItem(bag.inventory, ItemId.flower), 0);
361 assert.equal(countItem(bag.inventory, ItemId.dye), 16);
362 }
363 finally
364 { harness.close(); }
365 });
@@ -1,7 +1,8 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { BlockType } from "../../shared/definitions/tiles.js";
3import { BlockType } from "../../shared/definitions/tiles.js";
4import { ItemId } from "../../shared/definitions/items.js";
4import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
5import { flowerItemInstance } from "../../shared/definitions/dyes.js";
5import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";
6import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";
6import {
7import {
7 evaluateAlchemyBottle,
8 evaluateAlchemyBottle,
@@ -11,7 +12,6 @@ import {
11 potionItemInstance
12 potionItemInstance
12} from "../../shared/alchemy/recipes.js";
13} from "../../shared/alchemy/recipes.js";
13import { emptyEquipment, emptySlots, insertStack } from "../../shared/items/inventory.js";
14import { emptyEquipment, emptySlots, insertStack } from "../../shared/items/inventory.js";
14import { itemDefinition } from "../../shared/definitions/items.js";
15import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
15import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
16import { Component } from "../src/ecs/components.js";
16import { Component } from "../src/ecs/components.js";
17import {
17import {
@@ -102,6 +102,7 @@ test("cauldron bottles lesser health tonic when steps and ratios match", () =>
102 });
102 });
103 const entityId = harness.simulation.spawnCharacter(1, character);
103 const entityId = harness.simulation.spawnCharacter(1, character);
104 const cid = character.character_id;
104 const cid = character.character_id;
105 const alchemyBefore = harness.stateDb.getSkills(cid).xp.alchemy ?? 0;
105
106
106 harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });
107 harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });
107 harness.simulation.step();
108 harness.simulation.step();
@@ -147,6 +148,9 @@ test("cauldron bottles lesser health tonic when steps and ratios match", () =>
147 const potion = bag.inventory.find((slot) => slot?.itemId === ItemId.potion);
148 const potion = bag.inventory.find((slot) => slot?.itemId === ItemId.potion);
148 assert.equal(potion.instance?.potionKey, "lesserHealthTonic");
149 assert.equal(potion.instance?.potionKey, "lesserHealthTonic");
149 assert.equal(potion.instance?.unstable, false);
150 assert.equal(potion.instance?.unstable, false);
151 const alchemyAfter = harness.stateDb.getSkills(cid).xp.alchemy ?? 0;
152 // thyme×2 (tier 2) + mint×2 (tier 1)
153 assert.equal(alchemyAfter - alchemyBefore, 6);
150
154
151 harness.simulation.enqueue(1, { type: "cauldron-save-recipe", characterId: cid });
155 harness.simulation.enqueue(1, { type: "cauldron-save-recipe", characterId: cid });
152 harness.simulation.step();
156 harness.simulation.step();
@@ -314,3 +318,48 @@ test("drinking a lesser health tonic applies health regen", () =>
314 finally
318 finally
315 { harness.close(); }
319 { harness.close(); }
316});
320});
321
322test("creating dye awards 1 alchemy XP per flower and caps a slot at 16", () =>
323{
324 const harness = makeSimulation({ workerCount: 1 });
325 try
326 {
327 placeCauldron(harness.worldDb, 8, 8);
328 harness.simulation.reloadWorld();
329 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
330 const inventory = emptySlots();
331 const instance = flowerItemInstance("red");
332 const filled = insertStack(
333 inventory,
334 { itemId: ItemId.flower, quantity: 16, instance },
335 itemDefinition(ItemId.flower)
336 );
337 filled.slots[1] = { itemId: ItemId.glassBottle, quantity: 16 };
338 harness.stateDb.saveBag(character.character_id, {
339 inventory: filled.slots,
340 equipment: emptyEquipment(),
341 vault: [],
342 vaultReserved: []
343 });
344 const entityId = harness.simulation.spawnCharacter(1, character);
345 const cid = character.character_id;
346 const alchemyBefore = harness.stateDb.getSkills(cid).xp.alchemy ?? 0;
347
348 harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });
349 harness.simulation.step();
350 harness.simulation.enqueue(1, {
351 type: "cauldron-create-dye",
352 characterId: cid,
353 flowers: [{ itemId: ItemId.flower, quantity: 99, instance }]
354 });
355 const made = harness.simulation.step();
356 assert.equal(made.events.some((event) => event.type === "command-error"), false, JSON.stringify(made.events));
357 const alchemyAfter = harness.stateDb.getSkills(cid).xp.alchemy ?? 0;
358 assert.equal(alchemyAfter - alchemyBefore, 16);
359 const bag = harness.simulation.bagOf(entityId);
360 assert.equal(countItem(bag.inventory, ItemId.flower), 0);
361 assert.equal(countItem(bag.inventory, ItemId.dye), 16);
362 }
363 finally
364 { harness.close(); }
365});
server/tests/bfs-approach.test.js added +40 −0
@@ -0,0 +1,40 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { findPathToNearestGoal } from "../../shared/navigation/bfs.js";
4
5 test("BFS picks the nearest stand tile toward the target, not the top-left ring tile", () =>
6 {
7 // Open field. Player south of target — closest adjacent tile is directly north of player (south of target).
8 const playerX = 20;
9 const playerY = 30;
10 const targetX = 20;
11 const targetY = 20;
12 const path = findPathToNearestGoal(
13 playerX,
14 playerY,
15 (x, y) => Math.max(Math.abs(x - targetX), Math.abs(y - targetY)) === 1,
16 () => true,
17 0,
18 0,
19 40,
20 40
21 );
22 assert.ok(path.length);
23 const goal = path[path.length - 1];
24 assert.deepEqual(goal, { x: 20, y: 21 });
25 });
26
27 test("BFS returns empty when already at a goal", () =>
28 {
29 const path = findPathToNearestGoal(
30 5,
31 5,
32 (x, y) => x === 5 && y === 5,
33 () => true,
34 0,
35 0,
36 10,
37 10
38 );
39 assert.deepEqual(path, []);
40 });
@@ -0,0 +1,40 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { findPathToNearestGoal } from "../../shared/navigation/bfs.js";
4
5test("BFS picks the nearest stand tile toward the target, not the top-left ring tile", () =>
6{
7 // Open field. Player south of target — closest adjacent tile is directly north of player (south of target).
8 const playerX = 20;
9 const playerY = 30;
10 const targetX = 20;
11 const targetY = 20;
12 const path = findPathToNearestGoal(
13 playerX,
14 playerY,
15 (x, y) => Math.max(Math.abs(x - targetX), Math.abs(y - targetY)) === 1,
16 () => true,
17 0,
18 0,
19 40,
20 40
21 );
22 assert.ok(path.length);
23 const goal = path[path.length - 1];
24 assert.deepEqual(goal, { x: 20, y: 21 });
25});
26
27test("BFS returns empty when already at a goal", () =>
28{
29 const path = findPathToNearestGoal(
30 5,
31 5,
32 (x, y) => x === 5 && y === 5,
33 () => true,
34 0,
35 0,
36 10,
37 10
38 );
39 assert.deepEqual(path, []);
40});
server/tests/craft-xp.test.js added +53 −0
@@ -0,0 +1,53 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
4 import { MetalItemId } from "../../shared/definitions/metalItems.js";
5 import { CraftingItemId } from "../../shared/definitions/craftingItems.js";
6 import { recipeDefinition } from "../../shared/crafting/stationRecipes.js";
7 import {
8 itemCraftXpValue,
9 craftXpForConsumedInputs
10 } from "../../shared/definitions/gathering.js";
11 import { FLOWER_MAX_STACK } from "../../shared/definitions/dyes.js";
12
13 test("craft XP is tier rank per consumed item", () =>
14 {
15 assert.equal(itemCraftXpValue(CraftingItemId.bronzeBar), 1);
16 assert.equal(itemCraftXpValue(MetalItemId.ironBar), 2);
17 assert.equal(itemCraftXpValue(MetalItemId.steelBar), 3);
18 assert.equal(itemCraftXpValue(MetalItemId.coal), 3);
19 assert.equal(itemCraftXpValue(CraftingItemId.tinOre), 1);
20 assert.equal(itemCraftXpValue(CraftingItemId.copperOre), 1);
21 });
22
23 test("herb ingredients use numeric herb tier for craft XP", () =>
24 {
25 assert.equal(itemCraftXpValue(ItemId.mint), 1);
26 assert.equal(itemCraftXpValue(ItemId.aconite), 7);
27 });
28
29 test("two bars award twice the XP of one bar", () =>
30 {
31 const one = craftXpForConsumedInputs([{ itemId: MetalItemId.ironBar, quantity: 1 }]);
32 const two = craftXpForConsumedInputs([{ itemId: MetalItemId.ironBar, quantity: 2 }]);
33 assert.equal(one, 2);
34 assert.equal(two, 4);
35 });
36
37 test("bronze smelt XP is tin + copper ranks", () =>
38 {
39 const recipe = recipeDefinition("smelt-bronze");
40 assert.equal(craftXpForConsumedInputs(recipe.inputs), 2);
41 });
42
43 test("orichalcum smelt XP sums ore and three coal", () =>
44 {
45 const recipe = recipeDefinition("smelt-orichalcum");
46 assert.equal(craftXpForConsumedInputs(recipe.inputs), 6 + 3 * 3);
47 });
48
49 test("flowers stack to 16", () =>
50 {
51 assert.equal(itemDefinition(ItemId.flower).maxStackSize, FLOWER_MAX_STACK);
52 assert.equal(FLOWER_MAX_STACK, 16);
53 });
@@ -0,0 +1,53 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
4import { MetalItemId } from "../../shared/definitions/metalItems.js";
5import { CraftingItemId } from "../../shared/definitions/craftingItems.js";
6import { recipeDefinition } from "../../shared/crafting/stationRecipes.js";
7import {
8 itemCraftXpValue,
9 craftXpForConsumedInputs
10} from "../../shared/definitions/gathering.js";
11import { FLOWER_MAX_STACK } from "../../shared/definitions/dyes.js";
12
13test("craft XP is tier rank per consumed item", () =>
14{
15 assert.equal(itemCraftXpValue(CraftingItemId.bronzeBar), 1);
16 assert.equal(itemCraftXpValue(MetalItemId.ironBar), 2);
17 assert.equal(itemCraftXpValue(MetalItemId.steelBar), 3);
18 assert.equal(itemCraftXpValue(MetalItemId.coal), 3);
19 assert.equal(itemCraftXpValue(CraftingItemId.tinOre), 1);
20 assert.equal(itemCraftXpValue(CraftingItemId.copperOre), 1);
21});
22
23test("herb ingredients use numeric herb tier for craft XP", () =>
24{
25 assert.equal(itemCraftXpValue(ItemId.mint), 1);
26 assert.equal(itemCraftXpValue(ItemId.aconite), 7);
27});
28
29test("two bars award twice the XP of one bar", () =>
30{
31 const one = craftXpForConsumedInputs([{ itemId: MetalItemId.ironBar, quantity: 1 }]);
32 const two = craftXpForConsumedInputs([{ itemId: MetalItemId.ironBar, quantity: 2 }]);
33 assert.equal(one, 2);
34 assert.equal(two, 4);
35});
36
37test("bronze smelt XP is tin + copper ranks", () =>
38{
39 const recipe = recipeDefinition("smelt-bronze");
40 assert.equal(craftXpForConsumedInputs(recipe.inputs), 2);
41});
42
43test("orichalcum smelt XP sums ore and three coal", () =>
44{
45 const recipe = recipeDefinition("smelt-orichalcum");
46 assert.equal(craftXpForConsumedInputs(recipe.inputs), 6 + 3 * 3);
47});
48
49test("flowers stack to 16", () =>
50{
51 assert.equal(itemDefinition(ItemId.flower).maxStackSize, FLOWER_MAX_STACK);
52 assert.equal(FLOWER_MAX_STACK, 16);
53});
server/tests/crafting.test.js +1 −1
@@ -234,7 +234,7 @@ test("smelting bronze consumes tin and copper, grants bar and Smithing XP", () =
234 234 assert.equal(bar?.origins?.[0]?.origin?.verb, "Forged");
235 235 assert.match(bar?.origins?.[0]?.origin?.displayName ?? "", /^Ada/);
236 236 const smithingAfter = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
237 assert.ok(smithingAfter > smithingBefore);
237 assert.equal(smithingAfter - smithingBefore, 2);
238 238 }
239 239 finally
240 240 { harness.close(); }
@@ -234,7 +234,7 @@ test("smelting bronze consumes tin and copper, grants bar and Smithing XP", () =
234 assert.equal(bar?.origins?.[0]?.origin?.verb, "Forged");
234 assert.equal(bar?.origins?.[0]?.origin?.verb, "Forged");
235 assert.match(bar?.origins?.[0]?.origin?.displayName ?? "", /^Ada/);
235 assert.match(bar?.origins?.[0]?.origin?.displayName ?? "", /^Ada/);
236 const smithingAfter = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
236 const smithingAfter = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
237 assert.ok(smithingAfter > smithingBefore);
237 assert.equal(smithingAfter - smithingBefore, 2);
238 }
238 }
239 finally
239 finally
240 { harness.close(); }
240 { harness.close(); }
shared/definitions/dyes.js +4 −1
@@ -181,6 +181,9 @@ export function dyeColorKey (instance)
181 181 return colorKey(instance.color);
182 182 }
183 183
184 /** Flowers stack like potions; one cauldron dye slot cannot hold more than this. */
185 export const FLOWER_MAX_STACK = 16;
186
184 187 export const FLOWER_ITEM_DEFINITION = Object.freeze({
185 188 itemId: DyeItemId.flower,
186 189 key: "flower",
@@ -188,7 +191,7 @@ export const FLOWER_ITEM_DEFINITION = Object.freeze({
188 191 description: "A colourful flower. Crush into dye at a cauldron.",
189 192 seedValue: 2,
190 193 stackable: true,
191 maxStackSize: 99,
194 maxStackSize: FLOWER_MAX_STACK,
192 195 uniqueInstance: false,
193 196 category: ItemCategory.ingredient,
194 197 iconKey: "flower",
@@ -181,6 +181,9 @@ export function dyeColorKey (instance)
181 return colorKey(instance.color);
181 return colorKey(instance.color);
182}
182}
183
183
184/** Flowers stack like potions; one cauldron dye slot cannot hold more than this. */
185export const FLOWER_MAX_STACK = 16;
186
184export const FLOWER_ITEM_DEFINITION = Object.freeze({
187export const FLOWER_ITEM_DEFINITION = Object.freeze({
185 itemId: DyeItemId.flower,
188 itemId: DyeItemId.flower,
186 key: "flower",
189 key: "flower",
@@ -188,7 +191,7 @@ export const FLOWER_ITEM_DEFINITION = Object.freeze({
188 description: "A colourful flower. Crush into dye at a cauldron.",
191 description: "A colourful flower. Crush into dye at a cauldron.",
189 seedValue: 2,
192 seedValue: 2,
190 stackable: true,
193 stackable: true,
191 maxStackSize: 99,
194 maxStackSize: FLOWER_MAX_STACK,
192 uniqueInstance: false,
195 uniqueInstance: false,
193 category: ItemCategory.ingredient,
196 category: ItemCategory.ingredient,
194 iconKey: "flower",
197 iconKey: "flower",
shared/definitions/gathering.js +24 −0
@@ -107,6 +107,30 @@ export function smeltingXpForMaterial (materialId)
107 107 return Math.max(1, tierRank(materialId) * 5);
108 108 }
109 109
110 /** XP for one consumed craft ingredient: its material tier rank (untiered = 1). */
111 export function itemCraftXpValue (itemId)
112 {
113 const def = itemDefinition(itemId);
114 const rawTier = def?.tier ?? def?.equipment?.tier ?? null;
115 if (typeof rawTier === "number" && Number.isFinite(rawTier))
116 { return Math.max(1, Math.floor(rawTier)); }
117 return Math.max(1, tierRank(rawTier));
118 }
119
120 /** Sum of `itemCraftXpValue × quantity` over recipe inputs. */
121 export function craftXpForConsumedInputs (inputs)
122 {
123 let total = 0;
124 for (const input of inputs ?? [])
125 {
126 const quantity = Math.max(0, input?.quantity | 0);
127 if (!quantity)
128 { continue; }
129 total += itemCraftXpValue(input.itemId) * quantity;
130 }
131 return total;
132 }
133
110 134 /** Mine skill / tool gates use the associated bar's equip tier. */
111 135 export function gatherEquipTier (materialId)
112 136 {
@@ -107,6 +107,30 @@ export function smeltingXpForMaterial (materialId)
107 return Math.max(1, tierRank(materialId) * 5);
107 return Math.max(1, tierRank(materialId) * 5);
108}
108}
109
109
110/** XP for one consumed craft ingredient: its material tier rank (untiered = 1). */
111export function itemCraftXpValue (itemId)
112{
113 const def = itemDefinition(itemId);
114 const rawTier = def?.tier ?? def?.equipment?.tier ?? null;
115 if (typeof rawTier === "number" && Number.isFinite(rawTier))
116 { return Math.max(1, Math.floor(rawTier)); }
117 return Math.max(1, tierRank(rawTier));
118}
119
120/** Sum of `itemCraftXpValue × quantity` over recipe inputs. */
121export function craftXpForConsumedInputs (inputs)
122{
123 let total = 0;
124 for (const input of inputs ?? [])
125 {
126 const quantity = Math.max(0, input?.quantity | 0);
127 if (!quantity)
128 { continue; }
129 total += itemCraftXpValue(input.itemId) * quantity;
130 }
131 return total;
132}
133
110/** Mine skill / tool gates use the associated bar's equip tier. */
134/** Mine skill / tool gates use the associated bar's equip tier. */
111export function gatherEquipTier (materialId)
135export function gatherEquipTier (materialId)
112{
136{
shared/definitions/leatherItems.js +3 −1
@@ -4,6 +4,7 @@ import { equipImageName } from "./tileSprites.js";
4 4 import { CraftingItemId } from "./craftingItems.js";
5 5 import {
6 6 LeatherTier,
7 MaterialTier,
7 8 LEATHER_TIER_ORDER,
8 9 LEATHER_DISPLAY_NAME,
9 10 tierMinSkillLevel
@@ -111,7 +112,8 @@ export const LEATHER_ITEM_DEFINITIONS = Object.freeze({
111 112 uniqueInstance: false,
112 113 category: ItemCategory.intermediate,
113 114 iconKey: "metal",
114 defaultState: "stud"
115 defaultState: "stud",
116 tier: MaterialTier.steel
115 117 }),
116 118 [LeatherItemId.tanningBrew]: Object.freeze({
117 119 itemId: LeatherItemId.tanningBrew,
@@ -4,6 +4,7 @@ import { equipImageName } from "./tileSprites.js";
4import { CraftingItemId } from "./craftingItems.js";
4import { CraftingItemId } from "./craftingItems.js";
5import {
5import {
6 LeatherTier,
6 LeatherTier,
7 MaterialTier,
7 LEATHER_TIER_ORDER,
8 LEATHER_TIER_ORDER,
8 LEATHER_DISPLAY_NAME,
9 LEATHER_DISPLAY_NAME,
9 tierMinSkillLevel
10 tierMinSkillLevel
@@ -111,7 +112,8 @@ export const LEATHER_ITEM_DEFINITIONS = Object.freeze({
111 uniqueInstance: false,
112 uniqueInstance: false,
112 category: ItemCategory.intermediate,
113 category: ItemCategory.intermediate,
113 iconKey: "metal",
114 iconKey: "metal",
114 defaultState: "stud"
115 defaultState: "stud",
116 tier: MaterialTier.steel
115 }),
117 }),
116 [LeatherItemId.tanningBrew]: Object.freeze({
118 [LeatherItemId.tanningBrew]: Object.freeze({
117 itemId: LeatherItemId.tanningBrew,
119 itemId: LeatherItemId.tanningBrew,
shared/navigation/bfs.js added +89 −0
@@ -0,0 +1,89 @@
1 /**
2 * 4-connected BFS from the start tile to the nearest walkable goal.
3 * First goal reached is shortest path length (no top-left Chebyshev bias).
4 */
5
6 const CARDINALS = Object.freeze([
7 Object.freeze({ x: 0, y: -1 }),
8 Object.freeze({ x: 1, y: 0 }),
9 Object.freeze({ x: 0, y: 1 }),
10 Object.freeze({ x: -1, y: 0 })
11 ]);
12
13 /**
14 * @param {number} startX
15 * @param {number} startY
16 * @param {(x: number, y: number) => boolean} isGoal
17 * @param {(x: number, y: number) => boolean} isWalkable
18 * @param {number} minX
19 * @param {number} minY
20 * @param {number} maxX
21 * @param {number} maxY
22 * @returns {{ x: number, y: number }[]} path tiles after start (empty if already at goal or unreachable)
23 */
24 export function findPathToNearestGoal (startX, startY, isGoal, isWalkable, minX, minY, maxX, maxY)
25 {
26 if (!isWalkable(startX, startY))
27 { return []; }
28 if (isGoal(startX, startY))
29 { return []; }
30
31 const width = maxX - minX + 1;
32 const height = maxY - minY + 1;
33 if (width <= 0 || height <= 0)
34 { return []; }
35
36 const inBounds = (x, y) => x >= minX && y >= minY && x <= maxX && y <= maxY;
37 const index = (x, y) => (y - minY) * width + (x - minX);
38
39 const cameFrom = new Int32Array(width * height).fill(-1);
40 const visited = new Uint8Array(width * height);
41 const startIndex = index(startX, startY);
42 visited[startIndex] = 1;
43
44 const queue = [{ x: startX, y: startY }];
45 let head = 0;
46
47 while (head < queue.length)
48 {
49 const current = queue[head++];
50 for (const dir of CARDINALS)
51 {
52 const nx = current.x + dir.x;
53 const ny = current.y + dir.y;
54 if (!inBounds(nx, ny) || !isWalkable(nx, ny))
55 { continue; }
56 const neighborIndex = index(nx, ny);
57 if (visited[neighborIndex])
58 { continue; }
59 visited[neighborIndex] = 1;
60 cameFrom[neighborIndex] = index(current.x, current.y);
61 if (isGoal(nx, ny))
62 { return reconstruct(cameFrom, nx, ny, minX, minY, width); }
63 queue.push({ x: nx, y: ny });
64 }
65 }
66
67 return [];
68 }
69
70 function reconstruct (cameFrom, x, y, minX, minY, width)
71 {
72 const path = [];
73 let cx = x;
74 let cy = y;
75 while (true)
76 {
77 path.push({ x: cx, y: cy });
78 const idx = (cy - minY) * width + (cx - minX);
79 const prev = cameFrom[idx];
80 if (prev < 0)
81 { break; }
82 cx = minX + (prev % width);
83 cy = minY + Math.floor(prev / width);
84 }
85 path.reverse();
86 if (path.length > 0)
87 { path.shift(); }
88 return path;
89 }
@@ -0,0 +1,89 @@
1/**
2 * 4-connected BFS from the start tile to the nearest walkable goal.
3 * First goal reached is shortest path length (no top-left Chebyshev bias).
4 */
5
6const CARDINALS = Object.freeze([
7 Object.freeze({ x: 0, y: -1 }),
8 Object.freeze({ x: 1, y: 0 }),
9 Object.freeze({ x: 0, y: 1 }),
10 Object.freeze({ x: -1, y: 0 })
11]);
12
13/**
14 * @param {number} startX
15 * @param {number} startY
16 * @param {(x: number, y: number) => boolean} isGoal
17 * @param {(x: number, y: number) => boolean} isWalkable
18 * @param {number} minX
19 * @param {number} minY
20 * @param {number} maxX
21 * @param {number} maxY
22 * @returns {{ x: number, y: number }[]} path tiles after start (empty if already at goal or unreachable)
23 */
24export function findPathToNearestGoal (startX, startY, isGoal, isWalkable, minX, minY, maxX, maxY)
25{
26 if (!isWalkable(startX, startY))
27 { return []; }
28 if (isGoal(startX, startY))
29 { return []; }
30
31 const width = maxX - minX + 1;
32 const height = maxY - minY + 1;
33 if (width <= 0 || height <= 0)
34 { return []; }
35
36 const inBounds = (x, y) => x >= minX && y >= minY && x <= maxX && y <= maxY;
37 const index = (x, y) => (y - minY) * width + (x - minX);
38
39 const cameFrom = new Int32Array(width * height).fill(-1);
40 const visited = new Uint8Array(width * height);
41 const startIndex = index(startX, startY);
42 visited[startIndex] = 1;
43
44 const queue = [{ x: startX, y: startY }];
45 let head = 0;
46
47 while (head < queue.length)
48 {
49 const current = queue[head++];
50 for (const dir of CARDINALS)
51 {
52 const nx = current.x + dir.x;
53 const ny = current.y + dir.y;
54 if (!inBounds(nx, ny) || !isWalkable(nx, ny))
55 { continue; }
56 const neighborIndex = index(nx, ny);
57 if (visited[neighborIndex])
58 { continue; }
59 visited[neighborIndex] = 1;
60 cameFrom[neighborIndex] = index(current.x, current.y);
61 if (isGoal(nx, ny))
62 { return reconstruct(cameFrom, nx, ny, minX, minY, width); }
63 queue.push({ x: nx, y: ny });
64 }
65 }
66
67 return [];
68}
69
70function reconstruct (cameFrom, x, y, minX, minY, width)
71{
72 const path = [];
73 let cx = x;
74 let cy = y;
75 while (true)
76 {
77 path.push({ x: cx, y: cy });
78 const idx = (cy - minY) * width + (cx - minX);
79 const prev = cameFrom[idx];
80 if (prev < 0)
81 { break; }
82 cx = minX + (prev % width);
83 cy = minY + Math.floor(prev / width);
84 }
85 path.reverse();
86 if (path.length > 0)
87 { path.shift(); }
88 return path;
89}