BlueGit

timfa questward

Files

questward / server / src / shop / service.js

service.js

service.js 5.7 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { bagView } from "../items/bags.js";
3import { itemDefinition } from "../../../shared/definitions/items.js";
4import { ItemOriginKind, attachOrigins } from "../../../shared/items/origin.js";
5import {
6 countCoinsInSlots,
7 insertStack,
8 takeCoinsFromSlots
9} from "../../../shared/items/inventory.js";
10import { canSellInNpcShop, shopUnitPrice } from "../../../shared/shop/pricing.js";
11import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
12import { chebyshev } from "../combat/service.js";
13
14function userError (message)
15{
16 const error = new Error(message);
17 error.userFacing = true;
18 return error;
19}
20
21function lastSaleFor (world, itemId)
22{
23 return world.itemLastSales?.get(itemId) ?? null;
24}
25
26function shopStockView (world, shop, now)
27{
28 const lerpDurationMs = world.settings?.shopPriceLerpDurationMs
29 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
30 const stock = [];
31 for (const itemId of shop.stock ?? [])
32 {
33 if (!canSellInNpcShop(itemId))
34 { continue; }
35 const def = itemDefinition(itemId);
36 if (!def)
37 { continue; }
38 stock.push({
39 itemId,
40 displayName: def.displayName,
41 unitPrice: shopUnitPrice(itemId, {
42 lastSale: lastSaleFor(world, itemId),
43 now,
44 lerpDurationMs,
45 hiddenDiscount: shop.hiddenDiscount ?? 1
46 })
47 });
48 }
49 return stock;
50}
51
52export function openShop (world, sessionId, characterId, npcEntityId, now = Date.now())
53{
54 const entityId = world.characterEntities.get(characterId);
55 if (entityId == null)
56 { throw userError("Character is not in the world."); }
57 const handle = world.ecs.handleOf(entityId);
58 const identity = world.ecs.get(handle, Component.networkIdentity);
59 if (!identity || identity.sessionId !== sessionId)
60 { throw userError("Character is not in the world."); }
61 if (world.ecs.has(handle, Component.dead))
62 { throw userError("You are dead."); }
63
64 const npcHandle = world.ecs.handleOf(npcEntityId);
65 if (npcHandle == null)
66 { throw userError("Target is not here."); }
67 const shop = world.ecs.get(npcHandle, Component.shop);
68 if (!shop?.stock?.length)
69 { throw userError("They are not selling anything."); }
70
71 const playerPos = world.ecs.get(handle, Component.position);
72 const npcPos = world.ecs.get(npcHandle, Component.position);
73 if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1)
74 { throw userError("You need to stand next to them."); }
75
76 const appearance = world.ecs.get(npcHandle, Component.appearance);
77 const displayName = shop.displayName
78 || [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")
79 || "Shopkeeper";
80
81 return {
82 events: [{
83 type: "shop-open",
84 sessionId,
85 characterId,
86 npcEntityId,
87 displayName,
88 stock: shopStockView(world, shop, now)
89 }]
90 };
91}
92
93export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now())
94{
95 const entityId = world.characterEntities.get(characterId);
96 if (entityId == null)
97 { throw userError("Character is not in the world."); }
98 const handle = world.ecs.handleOf(entityId);
99 const identity = world.ecs.get(handle, Component.networkIdentity);
100 if (!identity || identity.sessionId !== sessionId)
101 { throw userError("Character is not in the world."); }
102 if (world.ecs.has(handle, Component.dead))
103 { throw userError("You are dead."); }
104
105 const npcHandle = world.ecs.handleOf(npcEntityId);
106 if (npcHandle == null)
107 { throw userError("Target is not here."); }
108 const shop = world.ecs.get(npcHandle, Component.shop);
109 if (!shop?.stock?.includes(itemId | 0))
110 { throw userError("They do not sell that."); }
111 if (!canSellInNpcShop(itemId))
112 { throw userError("That item cannot be sold here."); }
113
114 const playerPos = world.ecs.get(handle, Component.position);
115 const npcPos = world.ecs.get(npcHandle, Component.position);
116 if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1)
117 { throw userError("You need to stand next to them."); }
118
119 const qty = Math.max(1, Math.min(99, quantity | 0 || 1));
120 const def = itemDefinition(itemId);
121 if (!def)
122 { throw userError("Unknown item."); }
123
124 const lerpDurationMs = world.settings?.shopPriceLerpDurationMs
125 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
126 const unitPrice = shopUnitPrice(itemId, {
127 lastSale: lastSaleFor(world, itemId),
128 now,
129 lerpDurationMs,
130 hiddenDiscount: shop.hiddenDiscount ?? 1
131 });
132 const total = unitPrice * qty;
133 const inventory = world.ecs.get(handle, Component.inventory);
134 if (!inventory)
135 { throw userError("No inventory."); }
136 if (countCoinsInSlots(inventory.slots) < total)
137 { throw userError("You cannot afford that."); }
138
139 const paid = takeCoinsFromSlots(inventory.slots, total);
140 if (!paid.ok)
141 { throw userError("You cannot afford that."); }
142
143 const appearance = world.ecs.get(npcHandle, Component.appearance);
144 const displayName = shop.displayName
145 || [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")
146 || "Shopkeeper";
147 const stack = attachOrigins({
148 itemId,
149 quantity: qty,
150 origins: [{
151 origin: { kind: ItemOriginKind.shop, displayName },
152 quantity: qty
153 }]
154 });
155 const added = insertStack(paid.slots, stack, def);
156 if (!added.ok || added.remainder > 0)
157 { throw userError("Not enough bag space."); }
158
159 inventory.slots = added.slots;
160 return {
161 events: [{
162 type: "shop-open",
163 sessionId,
164 characterId,
165 npcEntityId,
166 displayName,
167 stock: shopStockView(world, shop, now)
168 }],
169 private: bagView(world.ecs, handle)
170 };
171}
172
173export function handleShopCommand (world, sessionId, command, now)
174{
175 switch (command.type)
176 {
177 case "buy-from-shop":
178 return buyFromShop(
179 world,
180 sessionId,
181 command.characterId,
182 command.npcEntityId | 0,
183 command.itemId | 0,
184 command.quantity | 0 || 1,
185 now
186 );
187 default:
188 return null;
189 }
190}