BlueGit

timfa questward

Files

questward / server / src / fishing / service.js

service.js

service.js 16.2 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import {
3 BlockType,
4 GroundType,
5 isLiquidWaterGround,
6 normalizeGround
7} from "../../../shared/definitions/tiles.js";
8import {
9 FISH_SPECIES,
10 fishTierRankFromItemId,
11 fishingDifficulty,
12 fishingExhaustDurationMs,
13 baitItemIdForCloth,
14 BaitItemId,
15 normalizeFishingSpotConfig,
16 fishingPoleItemIdForWood,
17 woodTierFromFishingRodItemId
18} from "../../../shared/definitions/fishItems.js";
19import { resolveFishingTool } from "../../../shared/definitions/gathering.js";
20import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
21import {
22 ClothTier,
23 tierRank,
24 clothTierForWood
25} from "../../../shared/definitions/materialTiers.js";
26import { yarnItemId } from "../../../shared/definitions/clothItems.js";
27import { itemDefinition } from "../../../shared/definitions/items.js";
28import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
29import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
30import { rollSkill } from "../../../shared/combat/rolls.js";
31import {
32 insertStack,
33 stackQuantity,
34 takeMatchingFromSlots,
35 takeFromSlot
36} from "../../../shared/items/inventory.js";
37import { attachOrigins, gatherOrigin, GatherOriginVerb } from "../../../shared/items/origin.js";
38import { addGroundItem, publicGroundItem, bagView } from "../items/bags.js";
39import { chebyshev } from "../combat/service.js";
40import { tileToChunk, tileToLocal } from "../world/coordinates.js";
41import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
42import { tileShoveEvent } from "../simulation/tileInteract.js";
43import { seasonIdAt } from "../../../shared/world/season.js";
44
45const FISH_ATTEMPT_MS = 3000;
46const FISH_SHOVE_MS = 1000;
47const MAX_FISH_ATTEMPTS = 3;
48/** Chance the fishing line snaps after a fully failed rod session. */
49const LINE_BREAK_CHANCE = 0.05;
50
51function userError (message)
52{
53 const error = new Error(message);
54 error.userFacing = true;
55 return error;
56}
57
58function tileKey (tileX, tileY)
59{
60 return `${tileX},${tileY}`;
61}
62
63function characterDisplayName (world, handle)
64{
65 const appearance = world.ecs.get(handle, Component.appearance);
66 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
67 return name || "someone";
68}
69
70function ensureFishSessions (world)
71{
72 if (!world.fishSessions)
73 { world.fishSessions = new Map(); }
74 return world.fishSessions;
75}
76
77function ensureFishSpotRespawns (world)
78{
79 if (!world.fishingSpotRespawns)
80 { world.fishingSpotRespawns = new Map(); }
81 return world.fishingSpotRespawns;
82}
83
84function clearFishSession (world, characterId)
85{
86 ensureFishSessions(world).delete(characterId);
87}
88
89function blockAt (world, tileX, tileY)
90{
91 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
92 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
93 return data.blocks[index] ?? null;
94}
95
96function groundAt (world, tileX, tileY)
97{
98 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
99 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
100 return normalizeGround(data.grounds[index]).typeId;
101}
102
103function setBlockState (world, tileX, tileY, state)
104{
105 const chunkX = tileToChunk(tileX);
106 const chunkY = tileToChunk(tileY);
107 const localX = tileToLocal(tileX);
108 const localY = tileToLocal(tileY);
109 const data = world.chunkData(chunkX, chunkY);
110 const index = localY * CHUNK_SIZE + localX;
111 const existing = data.blocks[index];
112 if (!existing)
113 { return null; }
114 const block = { ...existing, state };
115 data.blocks[index] = block;
116 return {
117 type: "chunk-delta",
118 chunkX,
119 chunkY,
120 tileX,
121 tileY,
122 localX,
123 localY,
124 block
125 };
126}
127
128function spotFishItemIds (block)
129{
130 return normalizeFishingSpotConfig(block?.config).fishes;
131}
132
133function maxFishTierInList (fishItemIds)
134{
135 let max = 0;
136 for (const itemId of fishItemIds)
137 { max = Math.max(max, fishTierRankFromItemId(itemId)); }
138 return max;
139}
140
141function eligibleFishItemIds (fishItemIds, baitTierRank)
142{
143 return fishItemIds.filter((itemId) => fishTierRankFromItemId(itemId) <= baitTierRank);
144}
145
146function findBestBaitSlot (slots, maxRank)
147{
148 let best = null;
149 for (let i = 0; i < (slots?.length ?? 0); i++)
150 {
151 const slot = slots[i];
152 if (!slot || stackQuantity(slot.quantity) <= 0)
153 { continue; }
154 const def = itemDefinition(slot.itemId);
155 if (!def?.bait || !def.tier)
156 { continue; }
157 const rank = tierRank(def.tier);
158 if (rank < 1 || rank > maxRank)
159 { continue; }
160 if (!best || rank > best.rank)
161 { best = { slotIndex: i, itemId: slot.itemId, rank, tier: def.tier }; }
162 }
163 return best;
164}
165
166function toolTierRank (tool)
167{
168 const tier = tool?.def?.equipment?.tier ?? tool?.tier;
169 return tierRank(tier);
170}
171
172/**
173 * Start fishing at a fishing-spot block tile.
174 */
175export function startFish (world, sessionId, characterId, tileX, tileY, now = Date.now())
176{
177 const entityId = world.characterEntities.get(characterId);
178 if (entityId == null)
179 { throw userError("Character is not in the world."); }
180 const handle = world.ecs.handleOf(entityId);
181 const identity = world.ecs.get(handle, Component.networkIdentity);
182 if (!identity || identity.sessionId !== sessionId)
183 { throw userError("Character is not in the world."); }
184 if (world.ecs.has(handle, Component.dead))
185 { throw userError("You are dead."); }
186
187 const position = world.ecs.get(handle, Component.position);
188 if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
189 { throw userError("You need to stand next to the fishing spot."); }
190
191 const block = blockAt(world, tileX, tileY);
192 if (!block || block.typeId !== BlockType.fishingSpot)
193 { throw userError("There is no fishing spot there."); }
194 if (block.state === "exhausted" || ensureFishSpotRespawns(world).has(tileKey(tileX, tileY)))
195 { throw userError("The fish have scattered. Wait for them to return."); }
196
197 const ground = groundAt(world, tileX, tileY);
198 const season = seasonIdAt(now);
199 if (ground !== GroundType.water && ground !== GroundType.deepWater)
200 { throw userError("Fishing spots must be on water."); }
201 if (!isLiquidWaterGround(ground, season))
202 { throw userError("The water is frozen solid."); }
203
204 const fishList = spotFishItemIds(block);
205 if (!fishList.length)
206 { throw userError("No fish swim here."); }
207
208 const inventory = world.ecs.get(handle, Component.inventory);
209 const equipment = world.ecs.get(handle, Component.equipment);
210 const skills = world.ecs.get(handle, Component.skills);
211 const resolved = resolveFishingTool({
212 inventorySlots: inventory?.slots,
213 equipmentSlots: equipment?.slots,
214 skills
215 });
216 if (!resolved.ok)
217 { throw userError(resolved.reason); }
218
219 const isNet = resolved.kind === EquipmentKind.fishingNet;
220 const rodRank = isNet ? 1 : toolTierRank(resolved.tool);
221 const maxInSpot = maxFishTierInList(fishList);
222 const usefulMax = Math.min(rodRank, maxInSpot);
223
224 let baitRank = 1;
225 let baitItemId = null;
226 let baitConsumedRank = 0;
227
228 if (isNet)
229 {
230 baitRank = 1;
231 baitConsumedRank = 0;
232 }
233 else
234 {
235 const bait = findBestBaitSlot(inventory?.slots, usefulMax);
236 if (!bait)
237 { throw userError("You need suitable bait for this spot."); }
238 baitRank = bait.rank;
239 baitItemId = bait.itemId;
240 baitConsumedRank = bait.rank;
241 }
242
243 const eligible = eligibleFishItemIds(fishList, baitRank);
244 if (!eligible.length)
245 { throw userError("No fish here match your bait."); }
246
247 if (!isNet)
248 {
249 const taken = takeMatchingFromSlots(inventory.slots, {
250 itemId: baitItemId,
251 quantity: 1,
252 compact: false
253 });
254 if (!taken.ok)
255 { throw userError("You need suitable bait for this spot."); }
256 inventory.slots = taken.slots;
257 }
258
259 clearFishSession(world, characterId);
260 if (world.ecs.has(handle, Component.gather))
261 { world.ecs.remove(handle, Component.gather); }
262 const path = world.ecs.get(handle, Component.path);
263 if (path)
264 { path.tiles = []; }
265
266 ensureFishSessions(world).set(characterId, {
267 sessionId,
268 tileX,
269 tileY,
270 toolItemId: resolved.tool.def.itemId,
271 isNet,
272 baitRank,
273 baitConsumedRank,
274 baitItemId,
275 eligible,
276 difficulty: fishingDifficulty(baitRank),
277 attemptsLeft: MAX_FISH_ATTEMPTS,
278 attemptStartedAt: now,
279 nextShoveAt: now,
280 attemptEndsAt: now + FISH_ATTEMPT_MS
281 });
282
283 return {
284 events: [],
285 private: isNet ? null : bagView(world.ecs, handle)
286 };
287}
288
289export function handleFishingCommand (world, sessionId, command, now = Date.now())
290{
291 if (command.type === "start-fish")
292 {
293 return startFish(
294 world,
295 sessionId,
296 command.characterId,
297 command.tileX | 0,
298 command.tileY | 0,
299 now
300 );
301 }
302 if (command.type === "cancel-fish")
303 {
304 clearFishSession(world, command.characterId);
305 return { events: [] };
306 }
307 return null;
308}
309
310function completeCatch (world, handle, entityId, characterId, session, events, privates, now)
311{
312 const eligible = session.eligible ?? [];
313 if (!eligible.length)
314 {
315 events.push({
316 type: "command-error",
317 sessionId: session.sessionId,
318 message: "The fish got away."
319 });
320 clearFishSession(world, characterId);
321 return;
322 }
323 const rng = world.rng ?? Math.random;
324 const pick = eligible[Math.floor(rng() * eligible.length) % eligible.length];
325 const fishRank = fishTierRankFromItemId(pick);
326 const inventory = world.ecs.get(handle, Component.inventory);
327 const def = itemDefinition(pick);
328 const origin = gatherOrigin(GatherOriginVerb.caught, characterDisplayName(world, handle));
329 const stack = attachOrigins({
330 itemId: pick,
331 quantity: 1,
332 origins: [{ origin, quantity: 1 }]
333 });
334 const inserted = insertStack(inventory.slots, stack, def);
335 if (!inserted.ok || inserted.remainder > 0)
336 {
337 events.push({
338 type: "command-error",
339 sessionId: session.sessionId,
340 message: "Your inventory is full."
341 });
342 clearFishSession(world, characterId);
343 return;
344 }
345 inventory.slots = inserted.slots;
346
347 const xpAmount = (session.baitConsumedRank | 0) + fishRank;
348 const skills = world.ecs.get(handle, Component.skills);
349 let skillsChanged = false;
350 const levelUps = [];
351 if (skills?.xp && xpAmount > 0)
352 {
353 const result = applySkillXp(skills, SkillId.fishing, xpAmount);
354 if (result.changed)
355 { skillsChanged = true; }
356 if (result.levelUp)
357 { levelUps.push(result.levelUp); }
358 }
359 if (skillsChanged)
360 {
361 events.push({
362 type: "skills-updated",
363 entityId,
364 characterId,
365 skills: publicSkillsView(skills),
366 stored: storedSkillXp(skills),
367 levelUps
368 });
369 }
370
371 const exhausted = setBlockState(world, session.tileX, session.tileY, "exhausted");
372 if (exhausted)
373 { events.push(exhausted); }
374 ensureFishSpotRespawns(world).set(tileKey(session.tileX, session.tileY), {
375 tileX: session.tileX,
376 tileY: session.tileY,
377 respawnsAt: now + fishingExhaustDurationMs(fishRank)
378 });
379
380 privates.push({ characterId, bag: bagView(world.ecs, handle) });
381 events.push({
382 type: "item-bubble",
383 entityId,
384 itemId: pick,
385 quantity: 1
386 });
387 clearFishSession(world, characterId);
388}
389
390export function stepFishing (world, now)
391{
392 const events = [];
393 const privates = [];
394 events.push(...stepFishingSpotRespawns(world, now).events);
395
396 const sessions = ensureFishSessions(world);
397 for (const [characterId, session] of [...sessions.entries()])
398 {
399 const entityId = world.characterEntities.get(characterId);
400 if (entityId == null)
401 {
402 clearFishSession(world, characterId);
403 continue;
404 }
405 const handle = world.ecs.handleOf(entityId);
406 if (world.ecs.has(handle, Component.dead))
407 {
408 clearFishSession(world, characterId);
409 continue;
410 }
411 const position = world.ecs.get(handle, Component.position);
412 if (chebyshev(position.tileX, position.tileY, session.tileX, session.tileY) > 1)
413 {
414 clearFishSession(world, characterId);
415 continue;
416 }
417
418 if (now >= session.nextShoveAt && now < session.attemptEndsAt)
419 {
420 session.nextShoveAt = now + FISH_SHOVE_MS;
421 events.push(tileShoveEvent(
422 entityId,
423 position.tileX,
424 position.tileY,
425 session.tileX,
426 session.tileY
427 ));
428 // Also emit gather-swing so tool overlay shows.
429 events.push({
430 type: "gather-swing",
431 attackerId: entityId,
432 tileX: session.tileX,
433 tileY: session.tileY,
434 fromTileX: position.tileX,
435 fromTileY: position.tileY,
436 toolItemId: session.toolItemId,
437 swipe: false
438 });
439 }
440
441 if (now < session.attemptEndsAt)
442 { continue; }
443
444 const skills = world.ecs.get(handle, Component.skills);
445 const level = skillLevel(skills, SkillId.fishing);
446 const roll = rollSkill(level, world.rng ?? Math.random);
447 session.attemptsLeft -= 1;
448
449 if (roll >= session.difficulty)
450 {
451 completeCatch(world, handle, entityId, characterId, session, events, privates, now);
452 continue;
453 }
454
455 if (session.attemptsLeft <= 0)
456 {
457 events.push({
458 type: "command-error",
459 sessionId: session.sessionId,
460 message: "The fish got away."
461 });
462 maybeBreakFishingLine(world, handle, entityId, characterId, session, events, privates, now);
463 clearFishSession(world, characterId);
464 continue;
465 }
466
467 session.attemptStartedAt = now;
468 session.nextShoveAt = now;
469 session.attemptEndsAt = now + FISH_ATTEMPT_MS;
470 }
471
472 return { events, privates };
473}
474
475function spawnGroundStack (world, tileX, tileY, itemId, now, events, source = "fishing-line-break")
476{
477 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
478 const stack = attachOrigins({
479 itemId,
480 quantity: 1,
481 origins: []
482 });
483 const item = {
484 groundItemId,
485 tileX,
486 tileY,
487 stack,
488 droppedAt: now,
489 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
490 source
491 };
492 addGroundItem(world, item);
493 events.push({
494 type: "ground-item-appear",
495 ...publicGroundItem(item),
496 stack: item.stack,
497 droppedAt: item.droppedAt,
498 source: item.source,
499 expiresAt: item.expiresAt
500 });
501}
502
503/**
504 * After a fully failed rod session: 5% chance the line snaps → rod becomes pole + 1 yarn.
505 */
506function maybeBreakFishingLine (world, handle, entityId, characterId, session, events, privates, now)
507{
508 if (session.isNet)
509 { return; }
510 const rng = world.rng ?? Math.random;
511 if (rng() >= LINE_BREAK_CHANCE)
512 { return; }
513
514 const rodItemId = session.toolItemId | 0;
515 const rodDef = itemDefinition(rodItemId);
516 const woodTier = woodTierFromFishingRodItemId(rodItemId) ?? rodDef?.tier;
517 const poleItemId = rodDef?.poleItemId ?? fishingPoleItemIdForWood(woodTier);
518 const clothTier = rodDef?.clothTier ?? clothTierForWood(woodTier);
519 const yarnId = yarnItemId(clothTier);
520 if (!poleItemId || !yarnId)
521 { return; }
522
523 const inventory = world.ecs.get(handle, Component.inventory);
524 const equipment = world.ecs.get(handle, Component.equipment);
525 let removed = false;
526 let appearanceChanged = false;
527
528 if (inventory?.slots)
529 {
530 const idx = inventory.slots.findIndex((s) => s?.itemId === rodItemId);
531 if (idx >= 0)
532 {
533 const taken = takeFromSlot(inventory.slots, idx, 1);
534 if (taken.ok)
535 {
536 inventory.slots = taken.slots;
537 removed = true;
538 }
539 }
540 }
541 if (!removed && equipment?.slots?.weapon?.itemId === rodItemId)
542 {
543 equipment.slots.weapon = null;
544 removed = true;
545 appearanceChanged = true;
546 }
547 if (!removed)
548 { return; }
549
550 const position = world.ecs.get(handle, Component.position);
551 const poleDef = itemDefinition(poleItemId);
552 const yarnDef = itemDefinition(yarnId);
553 let slots = inventory.slots;
554
555 const poleIns = insertStack(slots, attachOrigins({ itemId: poleItemId, quantity: 1, origins: [] }), poleDef);
556 if (poleIns.ok && poleIns.remainder === 0)
557 { slots = poleIns.slots; }
558 else
559 { spawnGroundStack(world, position.tileX, position.tileY, poleItemId, now, events); }
560
561 const yarnIns = insertStack(slots, attachOrigins({ itemId: yarnId, quantity: 1, origins: [] }), yarnDef);
562 if (yarnIns.ok && yarnIns.remainder === 0)
563 { slots = yarnIns.slots; }
564 else
565 { spawnGroundStack(world, position.tileX, position.tileY, yarnId, now, events); }
566
567 inventory.slots = slots;
568
569 events.push({
570 type: "command-error",
571 sessionId: session.sessionId,
572 message: "Your fishing line broke!"
573 });
574 privates.push({
575 characterId,
576 bag: bagView(world.ecs, handle),
577 ...(appearanceChanged ? { appearanceChanged: true } : {})
578 });
579}
580
581export function stepFishingSpotRespawns (world, now)
582{
583 const respawns = world.fishingSpotRespawns;
584 if (!respawns?.size)
585 { return { events: [] }; }
586 const events = [];
587 for (const [key, entry] of [...respawns.entries()])
588 {
589 if (now < entry.respawnsAt)
590 { continue; }
591 respawns.delete(key);
592 const block = blockAt(world, entry.tileX, entry.tileY);
593 if (!block || block.typeId !== BlockType.fishingSpot)
594 { continue; }
595 const delta = setBlockState(world, entry.tileX, entry.tileY, "fishing-spot");
596 if (delta)
597 { events.push(delta); }
598 }
599 return { events };
600}
601
602export { ClothTier, BaitItemId, baitItemIdForCloth, FISH_SPECIES };