BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

bags.js 15.6 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { ItemId, itemDefinition, itemSpriteName, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";
4import {
5 emptyEquipment,
6 emptySlots,
7 insertStack,
8 publicEquipment,
9 publicSlots,
10 takeFromSlot
11} from "../../../shared/items/inventory.js";
12import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
13import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
14import { randomUUID } from "node:crypto";
15
16export function publicGroundItem (item)
17{
18 const def = itemDefinition(item.stack?.itemId);
19 return {
20 groundItemId: item.groundItemId,
21 tileX: item.tileX,
22 tileY: item.tileY,
23 itemId: item.stack.itemId,
24 quantity: item.stack.quantity,
25 displayName: def?.displayName ?? "Item",
26 sprite: itemSpriteName(item.stack.itemId, item.stack.instance),
27 expiresAt: item.expiresAt
28 };
29}
30
31export function bagView (ecs, handle)
32{
33 return {
34 inventory: publicSlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots()),
35 equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()),
36 currency: ecs.get(handle, Component.currency)?.amount ?? 0,
37 vault: publicSlots(ecs.get(handle, Component.vault)?.slots ?? emptySlots()),
38 vaultCurrency: ecs.get(handle, Component.vault)?.currency ?? 0
39 };
40}
41
42export function applyBagView (ecs, handle, bag)
43{
44 const inventory = ensureInventory(ecs, handle);
45 inventory.slots = publicSlots(bag.inventory ?? emptySlots());
46 const equipment = ensureEquipment(ecs, handle);
47 const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment());
48 equipment.slots = nextEquip.slots;
49 let currency = ecs.get(handle, Component.currency);
50 if (!currency)
51 { currency = ecs.add(handle, Component.currency, { amount: 0 }); }
52 currency.amount = bag.currency | 0;
53 const vault = ensureVault(ecs, handle);
54 vault.slots = publicSlots(bag.vault ?? emptySlots());
55 vault.currency = bag.vaultCurrency | 0;
56 return bagView(ecs, handle);
57}
58
59export function handleItemCommand (world, sessionId, command, now)
60{
61 switch (command.type)
62 {
63 case "drop-item":
64 return dropItem(world, sessionId, command, now);
65 case "pickup-item":
66 return pickupItem(world, sessionId, command);
67 case "equip-item":
68 return equipItem(world, sessionId, command);
69 case "unequip-item":
70 return unequipItem(world, sessionId, command);
71 case "open-bank":
72 return openBank(world, sessionId, command);
73 case "bank-deposit":
74 return bankMove(world, sessionId, command, "inventory", "vault");
75 case "bank-withdraw":
76 return bankMove(world, sessionId, command, "vault", "inventory");
77 case "bank-deposit-money":
78 return bankMoney(world, sessionId, command, "currency", "vault");
79 case "bank-withdraw-money":
80 return bankMoney(world, sessionId, command, "vault", "currency");
81 case "claim-inheritance":
82 return claimInheritance(world, sessionId, command);
83 case "write-letter":
84 return writeLetter(world, sessionId, command);
85 case "edit-letter":
86 return editLetter(world, sessionId, command);
87 case "open-letter":
88 return openLetter(world, sessionId, command);
89 default:
90 return null;
91 }
92}
93
94export function expireGroundItems (world, now)
95{
96 const events = [];
97 for (const item of [...world.groundItems.values()])
98 {
99 if (item.expiresAt > now)
100 { continue; }
101 removeGroundItem(world, item.groundItemId);
102 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
103 }
104 return events;
105}
106
107export function groundItemsInChunk (world, chunkX, chunkY)
108{
109 return [...world.groundItems.values()]
110 .filter((item) => tileToChunk(item.tileX) === chunkX && tileToChunk(item.tileY) === chunkY)
111 .map(publicGroundItem);
112}
113
114export function groundItemsInRegion (world, regionX, regionY, tileToRegion)
115{
116 return [...world.groundItems.values()].filter((item) =>
117 tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY
118 );
119}
120
121export function addGroundItem (world, item)
122{
123 world.groundItems.set(item.groundItemId, item);
124 const key = tileKey(item.tileX, item.tileY);
125 if (!world.groundByTile.has(key))
126 { world.groundByTile.set(key, new Set()); }
127 world.groundByTile.get(key).add(item.groundItemId);
128}
129
130export function removeGroundItem (world, groundItemId)
131{
132 const item = world.groundItems.get(groundItemId);
133 if (!item)
134 { return null; }
135 world.groundItems.delete(groundItemId);
136 const key = tileKey(item.tileX, item.tileY);
137 world.groundByTile.get(key)?.delete(groundItemId);
138 return item;
139}
140
141export function replaceGroundItems (world, items)
142{
143 world.groundItems.clear();
144 world.groundByTile.clear();
145 for (const item of items ?? [])
146 { addGroundItem(world, item); }
147}
148
149export function setGroundItemsForRegion (world, regionX, regionY, items, tileToRegion)
150{
151 for (const item of [...world.groundItems.values()])
152 {
153 if (tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY)
154 { removeGroundItem(world, item.groundItemId); }
155 }
156 for (const item of items ?? [])
157 { addGroundItem(world, item); }
158}
159
160function dropItem (world, sessionId, command, now)
161{
162 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
163 const inventory = ensureInventory(world.ecs, handle);
164 const taken = takeFromSlot(inventory.slots, command.slotIndex, command.quantity ?? null);
165 if (!taken.ok)
166 { throw userError("That inventory slot is empty."); }
167 inventory.slots = taken.slots;
168 const position = world.ecs.get(handle, Component.position);
169 const item = {
170 groundItemId: command.groundItemId,
171 tileX: position.tileX,
172 tileY: position.tileY,
173 stack: taken.taken,
174 droppedAt: now,
175 expiresAt: now + (world.settings.groundItemDespawnDurationMs ?? 600_000),
176 source: "player-drop",
177 droppedByCharacterId: command.characterId
178 };
179 addGroundItem(world, item);
180 return {
181 events: [{ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, droppedByCharacterId: item.droppedByCharacterId, expiresAt: item.expiresAt }],
182 private: bagView(world.ecs, handle)
183 };
184}
185
186function pickupItem (world, sessionId, command)
187{
188 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
189 const item = world.groundItems.get(command.groundItemId);
190 if (!item)
191 { throw userError("That item is no longer on the ground."); }
192 const position = world.ecs.get(handle, Component.position);
193 if (position.tileX !== item.tileX || position.tileY !== item.tileY)
194 { throw userError("Stand on the item to pick it up."); }
195 const def = itemDefinition(item.stack.itemId);
196 if (!def)
197 { throw userError("Unknown item."); }
198 const inventory = ensureInventory(world.ecs, handle);
199 const inserted = insertStack(inventory.slots, item.stack, def);
200 if (!inserted.ok)
201 { throw userError("Your inventory cannot hold that."); }
202 inventory.slots = inserted.slots;
203 removeGroundItem(world, item.groundItemId);
204 return {
205 events: [{ type: "ground-item-despawn", ...publicGroundItem(item) }],
206 private: bagView(world.ecs, handle)
207 };
208}
209
210function equipItem (world, sessionId, command)
211{
212 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
213 const inventory = ensureInventory(world.ecs, handle);
214 const equipment = ensureEquipment(world.ecs, handle);
215 const taken = takeFromSlot(inventory.slots, command.slotIndex, 1);
216 if (!taken.ok)
217 { throw userError("That inventory slot is empty."); }
218 const def = itemDefinition(taken.taken.itemId);
219 const slot = def?.equipment?.slot;
220 if (!slot)
221 {
222 inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
223 throw userError("That item cannot be equipped.");
224 }
225 const previous = equipment.slots[slot];
226 if (previous)
227 {
228 const back = insertStack(taken.slots, previous, itemDefinition(previous.itemId));
229 if (!back.ok)
230 {
231 inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
232 throw userError("No inventory space to unequip the current item.");
233 }
234 inventory.slots = back.slots;
235 }
236 else
237 { inventory.slots = taken.slots; }
238 equipment.slots[slot] = { ...taken.taken, quantity: 1 };
239 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
240}
241
242function unequipItem (world, sessionId, command)
243{
244 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
245 const inventory = ensureInventory(world.ecs, handle);
246 const equipment = ensureEquipment(world.ecs, handle);
247 const worn = equipment.slots[command.equipSlot];
248 if (!worn)
249 { throw userError("Nothing is equipped there."); }
250 const def = itemDefinition(worn.itemId);
251 const inserted = insertStack(inventory.slots, worn, def);
252 if (!inserted.ok)
253 { throw userError("Your inventory cannot hold that."); }
254 inventory.slots = inserted.slots;
255 equipment.slots[command.equipSlot] = null;
256 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
257}
258
259function openBank (world, sessionId, command)
260{
261 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
262 const position = world.ecs.get(handle, Component.position);
263 if (!nearBank(world, position.tileX, position.tileY))
264 { throw userError("Stand next to a bank."); }
265 return { events: [], private: bagView(world.ecs, handle), bank: true };
266}
267
268function bankMove (world, sessionId, command, fromKey, toKey)
269{
270 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
271 requireBank(world, handle);
272 const inventory = ensureInventory(world.ecs, handle);
273 const vault = ensureVault(world.ecs, handle);
274 const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots;
275 const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null);
276 if (!taken.ok)
277 { throw userError("That slot is empty."); }
278 const def = itemDefinition(taken.taken.itemId);
279 const dest = toKey === "vault" ? vault : inventory;
280 const inserted = insertStack(dest.slots, taken.taken, def);
281 if (!inserted.ok)
282 { throw userError("Not enough space."); }
283 if (fromKey === "vault")
284 { vault.slots = taken.slots; }
285 else
286 { inventory.slots = taken.slots; }
287 dest.slots = inserted.slots;
288 return { events: [], private: bagView(world.ecs, handle), bank: true };
289}
290
291function bankMoney (world, sessionId, command, fromKey, toKey)
292{
293 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
294 requireBank(world, handle);
295 const amount = Math.max(0, command.amount | 0);
296 if (!amount)
297 { throw userError("Enter an amount."); }
298 const currency = world.ecs.get(handle, Component.currency) ?? world.ecs.add(handle, Component.currency, { amount: 0 });
299 const vault = ensureVault(world.ecs, handle);
300 const from = fromKey === "vault" ? vault : currency;
301 const to = toKey === "vault" ? vault : currency;
302 const fromAmount = fromKey === "vault" ? vault.currency : currency.amount;
303 if (fromAmount < amount)
304 { throw userError("Not enough coins."); }
305 if (fromKey === "vault")
306 { vault.currency -= amount; }
307 else
308 { currency.amount -= amount; }
309 if (toKey === "vault")
310 { vault.currency += amount; }
311 else
312 { currency.amount += amount; }
313 return { events: [], private: bagView(world.ecs, handle), bank: true };
314}
315
316function claimInheritance (world, sessionId, command)
317{
318 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
319 requireBank(world, handle);
320 const vault = ensureVault(world.ecs, handle);
321 const remainder = [];
322 for (const stack of command.stacks ?? [])
323 {
324 const def = itemDefinition(stack.itemId);
325 if (!def)
326 {
327 remainder.push(stack);
328 continue;
329 }
330 const inserted = insertStack(vault.slots, stack, def);
331 if (inserted.ok)
332 { vault.slots = inserted.slots; }
333 else
334 { remainder.push(stack); }
335 }
336 vault.currency += command.currency | 0;
337 return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };
338}
339
340function writeLetter (world, sessionId, command)
341{
342 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
343 const inventory = ensureInventory(world.ecs, handle);
344 const slotIndex = command.slotIndex | 0;
345 const slot = inventory.slots[slotIndex];
346 if (!slot || slot.itemId !== ItemId.paper)
347 { throw userError("Select blank paper."); }
348 const body = normalizeLetterBody(command.body);
349 const appearance = world.ecs.get(handle, Component.appearance);
350 const authorDisplayName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim();
351 const letterStack = {
352 itemId: ItemId.letter,
353 quantity: 1,
354 origin: null,
355 instance: {
356 kind: "letter",
357 letterId: randomUUID(),
358 authorCharacterId: command.characterId,
359 authorDisplayName,
360 body,
361 opened: true,
362 writtenAt: Date.now()
363 }
364 };
365 if (slot.quantity <= 1)
366 {
367 inventory.slots[slotIndex] = letterStack;
368 return { events: [], private: bagView(world.ecs, handle) };
369 }
370 const free = inventory.slots.findIndex((entry) => !entry);
371 if (free < 0)
372 { throw userError("Need a free inventory slot for the letter."); }
373 slot.quantity -= 1;
374 inventory.slots[free] = letterStack;
375 return { events: [], private: bagView(world.ecs, handle) };
376}
377
378function editLetter (world, sessionId, command)
379{
380 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
381 const inventory = ensureInventory(world.ecs, handle);
382 const slotIndex = command.slotIndex | 0;
383 const slot = inventory.slots[slotIndex];
384 if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter")
385 { throw userError("That is not a letter."); }
386 if (slot.instance.authorCharacterId !== command.characterId)
387 { throw userError("Only the signer can edit this letter."); }
388 const appearance = world.ecs.get(handle, Component.appearance);
389 const authorDisplayName = `${appearance?.firstName ?? slot.instance.authorDisplayName} ${appearance?.lastName ?? ""}`.trim()
390 || slot.instance.authorDisplayName;
391 slot.instance = {
392 ...slot.instance,
393 authorDisplayName,
394 body: normalizeLetterBody(command.body),
395 writtenAt: Date.now()
396 };
397 return { events: [], private: bagView(world.ecs, handle) };
398}
399
400function openLetter (world, sessionId, command)
401{
402 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
403 const inventory = ensureInventory(world.ecs, handle);
404 const slotIndex = command.slotIndex | 0;
405 const slot = inventory.slots[slotIndex];
406 if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter")
407 { throw userError("That is not a letter."); }
408 if (slot.instance.opened !== false)
409 { return { events: [], private: bagView(world.ecs, handle) }; }
410 slot.instance = { ...slot.instance, opened: true };
411 return { events: [], private: bagView(world.ecs, handle) };
412}
413
414function normalizeLetterBody (raw)
415{
416 const body = String(raw ?? "").replace(/\r\n/g, "\n").trimEnd();
417 if (body.length > LETTER_MAX_BODY_CHARS)
418 { throw userError(`Letters can be at most ${LETTER_MAX_BODY_CHARS} characters.`); }
419 return body;
420}
421
422function requireBank (world, handle)
423{
424 const position = world.ecs.get(handle, Component.position);
425 if (!nearBank(world, position.tileX, position.tileY))
426 { throw userError("Stand next to a bank."); }
427}
428
429function nearBank (world, tileX, tileY)
430{
431 for (let dy = -1; dy <= 1; dy++)
432 {
433 for (let dx = -1; dx <= 1; dx++)
434 {
435 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
436 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
437 if (data.blocks[index]?.typeId === BlockType.bank)
438 { return true; }
439 }
440 }
441 return false;
442}
443
444function ensureInventory (ecs, handle)
445{
446 return ecs.get(handle, Component.inventory) ?? ecs.add(handle, Component.inventory, { slots: emptySlots() });
447}
448
449function ensureEquipment (ecs, handle)
450{
451 return ecs.get(handle, Component.equipment) ?? ecs.add(handle, Component.equipment, emptyEquipment());
452}
453
454function ensureVault (ecs, handle)
455{
456 return ecs.get(handle, Component.vault) ?? ecs.add(handle, Component.vault, { slots: emptySlots(), currency: 0 });
457}
458
459function userError (message)
460{
461 const error = new Error(message);
462 error.userFacing = true;
463 return error;
464}