BlueGit

timfa questward

Files

questward / shared / trade / space.js

space.js

space.js 2.2 KiB Download Raw
1import {
2 cloneStack,
3 insertStack,
4 stackQuantity,
5 takeFromSlot,
6 INVENTORY_SLOTS
7} from "../items/inventory.js";
8import { itemDefinition } from "../definitions/items.js";
9
10/**
11 * How many additional empty bag slots a player would need after giving
12 * `giveLines` and receiving `receiveStacks`. 0 = swap fits.
13 *
14 * @param {Array} inventorySlots
15 * @param {Array<{ bagSlotIndex: number, quantity: number }>} giveLines
16 * @param {Array} receiveStacks stacks the partner is offering (item payloads)
17 */
18export function inventorySlotsShortAfterTrade (inventorySlots, giveLines, receiveStacks)
19{
20 let next = (inventorySlots ?? []).map((slot) => cloneStack(slot));
21 while (next.length < INVENTORY_SLOTS)
22 { next.push(null); }
23
24 const gives = [...(giveLines ?? [])]
25 .map((line) => ({
26 bagSlotIndex: line.bagSlotIndex | 0,
27 quantity: Math.max(1, line.quantity | 0 || 1)
28 }))
29 .sort((a, b) => b.bagSlotIndex - a.bagSlotIndex);
30
31 for (const line of gives)
32 {
33 const taken = takeFromSlot(next, line.bagSlotIndex, line.quantity);
34 if (!taken.ok)
35 { return INVENTORY_SLOTS; }
36 next = taken.slots;
37 }
38
39 for (const stack of receiveStacks ?? [])
40 {
41 if (!stack)
42 { continue; }
43 const def = itemDefinition(stack.itemId);
44 if (!def)
45 { return INVENTORY_SLOTS; }
46 const inserted = insertStack(next, cloneStack(stack), def);
47 if (!inserted.ok || (inserted.remainder | 0) > 0)
48 {
49 const empty = next.filter((slot) => !slot).length;
50 const needApprox = Math.max(1, Math.ceil(
51 stackQuantity(stack.quantity) / Math.max(1, def.maxStackSize | 0 || 1)
52 ));
53 return Math.max(1, needApprox - empty);
54 }
55 next = inserted.slots;
56 }
57 return 0;
58}
59
60/** Snapshot offer lines as transferable stacks from a bag (or null if invalid). */
61export function resolveOfferStacks (inventorySlots, offerLines)
62{
63 const stacks = [];
64 for (const line of offerLines ?? [])
65 {
66 const slot = inventorySlots?.[line.bagSlotIndex | 0];
67 const qty = Math.max(1, line.quantity | 0 || 1);
68 if (!slot || stackQuantity(slot.quantity) < qty)
69 { return null; }
70 stacks.push({
71 itemId: slot.itemId,
72 quantity: qty,
73 instance: slot.instance ? structuredClone(slot.instance) : null,
74 origins: slot.origins ? structuredClone(slot.origins) : undefined
75 });
76 }
77 return stacks;
78}