BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

bags.js 12.3 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { itemDefinition, itemSpriteName } 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";
14
15export function publicGroundItem (item)
16{
17 const def = itemDefinition(item.stack?.itemId);
18 return {
19 groundItemId: item.groundItemId,
20 tileX: item.tileX,
21 tileY: item.tileY,
22 itemId: item.stack.itemId,
23 quantity: item.stack.quantity,
24 displayName: def?.displayName ?? "Item",
25 sprite: itemSpriteName(item.stack.itemId),
26 expiresAt: item.expiresAt
27 };
28}
29
30export function bagView (ecs, handle)
31{
32 return {
33 inventory: publicSlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots()),
34 equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()),
35 currency: ecs.get(handle, Component.currency)?.amount ?? 0,
36 vault: publicSlots(ecs.get(handle, Component.vault)?.slots ?? emptySlots()),
37 vaultCurrency: ecs.get(handle, Component.vault)?.currency ?? 0
38 };
39}
40
41export function applyBagView (ecs, handle, bag)
42{
43 const inventory = ensureInventory(ecs, handle);
44 inventory.slots = publicSlots(bag.inventory ?? emptySlots());
45 const equipment = ensureEquipment(ecs, handle);
46 const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment());
47 equipment.slots = nextEquip.slots;
48 let currency = ecs.get(handle, Component.currency);
49 if (!currency)
50 { currency = ecs.add(handle, Component.currency, { amount: 0 }); }
51 currency.amount = bag.currency | 0;
52 const vault = ensureVault(ecs, handle);
53 vault.slots = publicSlots(bag.vault ?? emptySlots());
54 vault.currency = bag.vaultCurrency | 0;
55 return bagView(ecs, handle);
56}
57
58export function handleItemCommand (world, sessionId, command, now)
59{
60 switch (command.type)
61 {
62 case "drop-item":
63 return dropItem(world, sessionId, command, now);
64 case "pickup-item":
65 return pickupItem(world, sessionId, command);
66 case "equip-item":
67 return equipItem(world, sessionId, command);
68 case "unequip-item":
69 return unequipItem(world, sessionId, command);
70 case "open-bank":
71 return openBank(world, sessionId, command);
72 case "bank-deposit":
73 return bankMove(world, sessionId, command, "inventory", "vault");
74 case "bank-withdraw":
75 return bankMove(world, sessionId, command, "vault", "inventory");
76 case "bank-deposit-money":
77 return bankMoney(world, sessionId, command, "currency", "vault");
78 case "bank-withdraw-money":
79 return bankMoney(world, sessionId, command, "vault", "currency");
80 case "claim-inheritance":
81 return claimInheritance(world, sessionId, command);
82 default:
83 return null;
84 }
85}
86
87export function expireGroundItems (world, now)
88{
89 const events = [];
90 for (const item of [...world.groundItems.values()])
91 {
92 if (item.expiresAt > now)
93 { continue; }
94 removeGroundItem(world, item.groundItemId);
95 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
96 }
97 return events;
98}
99
100export function groundItemsInChunk (world, chunkX, chunkY)
101{
102 return [...world.groundItems.values()]
103 .filter((item) => tileToChunk(item.tileX) === chunkX && tileToChunk(item.tileY) === chunkY)
104 .map(publicGroundItem);
105}
106
107export function groundItemsInRegion (world, regionX, regionY, tileToRegion)
108{
109 return [...world.groundItems.values()].filter((item) =>
110 tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY
111 );
112}
113
114export function addGroundItem (world, item)
115{
116 world.groundItems.set(item.groundItemId, item);
117 const key = tileKey(item.tileX, item.tileY);
118 if (!world.groundByTile.has(key))
119 { world.groundByTile.set(key, new Set()); }
120 world.groundByTile.get(key).add(item.groundItemId);
121}
122
123export function removeGroundItem (world, groundItemId)
124{
125 const item = world.groundItems.get(groundItemId);
126 if (!item)
127 { return null; }
128 world.groundItems.delete(groundItemId);
129 const key = tileKey(item.tileX, item.tileY);
130 world.groundByTile.get(key)?.delete(groundItemId);
131 return item;
132}
133
134export function replaceGroundItems (world, items)
135{
136 world.groundItems.clear();
137 world.groundByTile.clear();
138 for (const item of items ?? [])
139 { addGroundItem(world, item); }
140}
141
142export function setGroundItemsForRegion (world, regionX, regionY, items, tileToRegion)
143{
144 for (const item of [...world.groundItems.values()])
145 {
146 if (tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY)
147 { removeGroundItem(world, item.groundItemId); }
148 }
149 for (const item of items ?? [])
150 { addGroundItem(world, item); }
151}
152
153function dropItem (world, sessionId, command, now)
154{
155 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
156 const inventory = ensureInventory(world.ecs, handle);
157 const taken = takeFromSlot(inventory.slots, command.slotIndex, command.quantity ?? null);
158 if (!taken.ok)
159 { throw userError("That inventory slot is empty."); }
160 inventory.slots = taken.slots;
161 const position = world.ecs.get(handle, Component.position);
162 const item = {
163 groundItemId: command.groundItemId,
164 tileX: position.tileX,
165 tileY: position.tileY,
166 stack: taken.taken,
167 droppedAt: now,
168 expiresAt: now + (world.settings.groundItemDespawnDurationMs ?? 600_000),
169 source: "player-drop",
170 droppedByCharacterId: command.characterId
171 };
172 addGroundItem(world, item);
173 return {
174 events: [{ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, droppedByCharacterId: item.droppedByCharacterId, expiresAt: item.expiresAt }],
175 private: bagView(world.ecs, handle)
176 };
177}
178
179function pickupItem (world, sessionId, command)
180{
181 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
182 const item = world.groundItems.get(command.groundItemId);
183 if (!item)
184 { throw userError("That item is no longer on the ground."); }
185 const position = world.ecs.get(handle, Component.position);
186 if (position.tileX !== item.tileX || position.tileY !== item.tileY)
187 { throw userError("Stand on the item to pick it up."); }
188 const def = itemDefinition(item.stack.itemId);
189 if (!def)
190 { throw userError("Unknown item."); }
191 const inventory = ensureInventory(world.ecs, handle);
192 const inserted = insertStack(inventory.slots, item.stack, def);
193 if (!inserted.ok)
194 { throw userError("Your inventory cannot hold that."); }
195 inventory.slots = inserted.slots;
196 removeGroundItem(world, item.groundItemId);
197 return {
198 events: [{ type: "ground-item-despawn", ...publicGroundItem(item) }],
199 private: bagView(world.ecs, handle)
200 };
201}
202
203function equipItem (world, sessionId, command)
204{
205 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
206 const inventory = ensureInventory(world.ecs, handle);
207 const equipment = ensureEquipment(world.ecs, handle);
208 const taken = takeFromSlot(inventory.slots, command.slotIndex, 1);
209 if (!taken.ok)
210 { throw userError("That inventory slot is empty."); }
211 const def = itemDefinition(taken.taken.itemId);
212 const slot = def?.equipment?.slot;
213 if (!slot)
214 {
215 inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
216 throw userError("That item cannot be equipped.");
217 }
218 const previous = equipment.slots[slot];
219 if (previous)
220 {
221 const back = insertStack(taken.slots, previous, itemDefinition(previous.itemId));
222 if (!back.ok)
223 {
224 inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
225 throw userError("No inventory space to unequip the current item.");
226 }
227 inventory.slots = back.slots;
228 }
229 else
230 { inventory.slots = taken.slots; }
231 equipment.slots[slot] = { ...taken.taken, quantity: 1 };
232 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
233}
234
235function unequipItem (world, sessionId, command)
236{
237 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
238 const inventory = ensureInventory(world.ecs, handle);
239 const equipment = ensureEquipment(world.ecs, handle);
240 const worn = equipment.slots[command.equipSlot];
241 if (!worn)
242 { throw userError("Nothing is equipped there."); }
243 const def = itemDefinition(worn.itemId);
244 const inserted = insertStack(inventory.slots, worn, def);
245 if (!inserted.ok)
246 { throw userError("Your inventory cannot hold that."); }
247 inventory.slots = inserted.slots;
248 equipment.slots[command.equipSlot] = null;
249 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
250}
251
252function openBank (world, sessionId, command)
253{
254 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
255 const position = world.ecs.get(handle, Component.position);
256 if (!nearBank(world, position.tileX, position.tileY))
257 { throw userError("Stand next to a bank."); }
258 return { events: [], private: bagView(world.ecs, handle), bank: true };
259}
260
261function bankMove (world, sessionId, command, fromKey, toKey)
262{
263 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
264 requireBank(world, handle);
265 const inventory = ensureInventory(world.ecs, handle);
266 const vault = ensureVault(world.ecs, handle);
267 const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots;
268 const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null);
269 if (!taken.ok)
270 { throw userError("That slot is empty."); }
271 const def = itemDefinition(taken.taken.itemId);
272 const dest = toKey === "vault" ? vault : inventory;
273 const inserted = insertStack(dest.slots, taken.taken, def);
274 if (!inserted.ok)
275 { throw userError("Not enough space."); }
276 if (fromKey === "vault")
277 { vault.slots = taken.slots; }
278 else
279 { inventory.slots = taken.slots; }
280 dest.slots = inserted.slots;
281 return { events: [], private: bagView(world.ecs, handle), bank: true };
282}
283
284function bankMoney (world, sessionId, command, fromKey, toKey)
285{
286 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
287 requireBank(world, handle);
288 const amount = Math.max(0, command.amount | 0);
289 if (!amount)
290 { throw userError("Enter an amount."); }
291 const currency = world.ecs.get(handle, Component.currency) ?? world.ecs.add(handle, Component.currency, { amount: 0 });
292 const vault = ensureVault(world.ecs, handle);
293 const from = fromKey === "vault" ? vault : currency;
294 const to = toKey === "vault" ? vault : currency;
295 const fromAmount = fromKey === "vault" ? vault.currency : currency.amount;
296 if (fromAmount < amount)
297 { throw userError("Not enough coins."); }
298 if (fromKey === "vault")
299 { vault.currency -= amount; }
300 else
301 { currency.amount -= amount; }
302 if (toKey === "vault")
303 { vault.currency += amount; }
304 else
305 { currency.amount += amount; }
306 return { events: [], private: bagView(world.ecs, handle), bank: true };
307}
308
309function claimInheritance (world, sessionId, command)
310{
311 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
312 requireBank(world, handle);
313 const vault = ensureVault(world.ecs, handle);
314 const remainder = [];
315 for (const stack of command.stacks ?? [])
316 {
317 const def = itemDefinition(stack.itemId);
318 if (!def)
319 {
320 remainder.push(stack);
321 continue;
322 }
323 const inserted = insertStack(vault.slots, stack, def);
324 if (inserted.ok)
325 { vault.slots = inserted.slots; }
326 else
327 { remainder.push(stack); }
328 }
329 vault.currency += command.currency | 0;
330 return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };
331}
332
333function requireBank (world, handle)
334{
335 const position = world.ecs.get(handle, Component.position);
336 if (!nearBank(world, position.tileX, position.tileY))
337 { throw userError("Stand next to a bank."); }
338}
339
340function nearBank (world, tileX, tileY)
341{
342 for (let dy = -1; dy <= 1; dy++)
343 {
344 for (let dx = -1; dx <= 1; dx++)
345 {
346 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
347 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
348 if (data.blocks[index]?.typeId === BlockType.bank)
349 { return true; }
350 }
351 }
352 return false;
353}
354
355function ensureInventory (ecs, handle)
356{
357 return ecs.get(handle, Component.inventory) ?? ecs.add(handle, Component.inventory, { slots: emptySlots() });
358}
359
360function ensureEquipment (ecs, handle)
361{
362 return ecs.get(handle, Component.equipment) ?? ecs.add(handle, Component.equipment, emptyEquipment());
363}
364
365function ensureVault (ecs, handle)
366{
367 return ecs.get(handle, Component.vault) ?? ecs.add(handle, Component.vault, { slots: emptySlots(), currency: 0 });
368}
369
370function userError (message)
371{
372 const error = new Error(message);
373 error.userFacing = true;
374 return error;
375}