BlueGit

timfa questward

Files

questward / server / src / bounty / service.js

service.js

service.js 9.1 KiB Download Raw
1import { randomUUID } from "node:crypto";
2import { ItemId, LETTER_MAX_BODY_CHARS, formatQuantity } from "../../../shared/definitions/items.js";
3import { bountyPayoutLetterBody, formatBountyCopper } from "../../../shared/bounty/pricing.js";
4import { layersFromBag } from "../../../shared/appearance/layers.js";
5import {
6 addCoinsToSlots,
7 normalizeVault,
8 takeCoinsFromSlots
9} from "../../../shared/items/inventory.js";
10
11function userError (message)
12{
13 const error = new Error(message);
14 error.userFacing = true;
15 return error;
16}
17
18function chebyshev (ax, ay, bx, by)
19{
20 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
21}
22
23/**
24 * Bounty office: place/raise bounties (near office), settle PvP kills into killer vault + letter.
25 */
26export class BountyService
27{
28 constructor (stateDb, simulation, courier)
29 {
30 this.stateDb = stateDb;
31 this.simulation = simulation;
32 this.courier = courier;
33 }
34
35 handleCommand (sessionId, command)
36 {
37 switch (command.type)
38 {
39 case "open-bounty":
40 return this.open(sessionId, command.characterId);
41 case "raise-bounty":
42 return this.placeOrRaise(
43 sessionId,
44 command.characterId,
45 command.firstName,
46 command.lastName,
47 command.amountCopper
48 );
49 case "get-character-bounty":
50 return this.lookup(
51 sessionId,
52 command.characterId,
53 command.targetCharacterId,
54 command.firstName,
55 command.lastName
56 );
57 case "close-bounty":
58 return { events: [{ type: "bounty-closed", sessionId, characterId: command.characterId }] };
59 default:
60 return null;
61 }
62 }
63
64 open (sessionId, characterId)
65 {
66 this.#requireNearOffice(characterId);
67 return {
68 events: [{
69 type: "bounty-snapshot",
70 sessionId,
71 characterId,
72 ...this.#myBountyPayload(characterId)
73 }]
74 };
75 }
76
77 /**
78 * Lookup target by characterId or first+last name. Adjacency not required (inspect UI).
79 */
80 lookup (sessionId, requesterCharacterId, targetCharacterId, firstName, lastName)
81 {
82 let row = null;
83 if (targetCharacterId)
84 { row = this.stateDb.getCharacter(targetCharacterId | 0); }
85 else
86 {
87 const first = String(firstName ?? "").trim();
88 const last = String(lastName ?? "").trim();
89 if (!first || !last)
90 { throw userError("Enter a first and last name."); }
91 row = this.stateDb.getCharacterByName(first, last);
92 }
93 if (!row)
94 { throw userError("No adventurer by that name."); }
95
96 const amountCopper = this.stateDb.getCharacterBounty(row.character_id);
97 const bag = this.#loadBagQuiet(row.character_id);
98 return {
99 events: [{
100 type: "character-bounty",
101 sessionId,
102 characterId: requesterCharacterId,
103 target: {
104 characterId: row.character_id,
105 firstName: row.first_name,
106 lastName: row.last_name,
107 sex: row.sex,
108 layers: layersFromBag(row.sex, bag),
109 amountCopper,
110 amountLabel: formatBountyCopper(amountCopper)
111 }
112 }]
113 };
114 }
115
116 placeOrRaise (sessionId, placerCharacterId, firstName, lastName, amountCopper)
117 {
118 this.#requireNearOffice(placerCharacterId);
119 const first = String(firstName ?? "").trim();
120 const last = String(lastName ?? "").trim();
121 if (!first || !last)
122 { throw userError("Enter a first and last name."); }
123 const copper = Math.floor(Number(amountCopper) || 0);
124 if (!Number.isFinite(copper) || copper <= 0)
125 { throw userError("Enter a positive coin amount."); }
126
127 const target = this.stateDb.getCharacterByName(first, last);
128 if (!target)
129 { throw userError("No adventurer by that name."); }
130 const targetId = target.character_id | 0;
131 if (targetId === (placerCharacterId | 0))
132 { throw userError("You cannot place a bounty on yourself."); }
133
134 const previous = this.stateDb.getCharacterBounty(targetId);
135 const bag = this.#loadBag(placerCharacterId);
136 const paid = takeCoinsFromSlots(bag.inventory ?? [], copper);
137 if (!paid.ok)
138 { throw userError(`Need ${formatQuantity(copper)} in your inventory.`); }
139 bag.inventory = paid.slots;
140 this.#persistBag(placerCharacterId, bag);
141
142 const nextAmount = this.stateDb.addCharacterBounty(targetId, copper);
143 this.simulation.pendingPrivate.push({
144 type: "toast",
145 characterId: targetId,
146 message: previous > 0
147 ? `Someone raised the bounty on your head to ${formatBountyCopper(nextAmount)}.`
148 : `A bounty of ${formatBountyCopper(nextAmount)} has been placed on your head.`
149 });
150
151 return {
152 events: [{
153 type: "bounty-snapshot",
154 sessionId,
155 characterId: placerCharacterId,
156 ...this.#myBountyPayload(placerCharacterId),
157 raised: {
158 characterId: targetId,
159 firstName: target.first_name,
160 lastName: target.last_name,
161 amountCopper: nextAmount,
162 amountLabel: formatBountyCopper(nextAmount),
163 addedCopper: copper,
164 message: previous > 0
165 ? `Raised bounty on ${target.first_name} ${target.last_name} to ${formatBountyCopper(nextAmount)}.`
166 : `Placed a ${formatBountyCopper(nextAmount)} bounty on ${target.first_name} ${target.last_name}.`
167 }
168 }]
169 };
170 }
171
172 /**
173 * Called when a player dies. PvP killer collects full bounty into vault + office letter.
174 * @returns {{ paidCopper: number, victimName: string } | null}
175 */
176 settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY)
177 {
178 const attackerId = attackerEntityId | 0;
179 if (!attackerId)
180 { return null; }
181 const attackerRec = this.simulation.directory.get(attackerId);
182 const killerCharacterId = attackerRec?.characterId | 0;
183 if (!killerCharacterId || killerCharacterId === (victimCharacterId | 0))
184 { return null; }
185
186 const paidCopper = this.stateDb.takeCharacterBounty(victimCharacterId);
187 if (paidCopper <= 0)
188 { return null; }
189
190 const bag = this.#loadBag(killerCharacterId);
191 const vault = normalizeVault(
192 bag.vaultReserved != null
193 ? { slots: bag.vault, reserved: bag.vaultReserved }
194 : bag.vault
195 );
196 const added = addCoinsToSlots(vault.slots, paidCopper, { growable: true });
197 bag.vault = added.slots;
198 bag.vaultReserved = vault.reserved;
199 this.#persistBag(killerCharacterId, bag);
200
201 const victim = this.stateDb.getCharacter(victimCharacterId);
202 const killer = this.stateDb.getCharacter(killerCharacterId);
203 const victimName = victim
204 ? `${victim.first_name} ${victim.last_name}`.trim()
205 : "someone";
206 const killerName = killer
207 ? `${killer.first_name} ${killer.last_name}`.trim()
208 : "Adventurer";
209
210 this.#dispatchPayoutLetter({
211 killerCharacterId,
212 killerName,
213 victimName,
214 paidCopper,
215 deathTileX,
216 deathTileY
217 });
218
219 this.simulation.pendingPrivate.push({
220 type: "toast",
221 characterId: killerCharacterId,
222 message: `Bounty collected: ${formatBountyCopper(paidCopper)} for defeating ${victimName} (sent to vault).`
223 });
224
225 return { paidCopper, victimName };
226 }
227
228 #myBountyPayload (characterId)
229 {
230 const amountCopper = this.stateDb.getCharacterBounty(characterId);
231 return {
232 myAmountCopper: amountCopper,
233 myAmountLabel: formatBountyCopper(amountCopper),
234 message: amountCopper > 0
235 ? `Bounty on your head: ${formatBountyCopper(amountCopper)}.`
236 : "No bounty on your head."
237 };
238 }
239
240 #dispatchPayoutLetter ({ killerCharacterId, killerName, victimName, paidCopper, deathTileX, deathTileY })
241 {
242 const office = this.courier?.nearestBountyOffice?.(deathTileX | 0, deathTileY | 0)
243 ?? { tileX: deathTileX | 0, tileY: deathTileY | 0 };
244 const body = bountyPayoutLetterBody({
245 killerName,
246 victimName,
247 amountCopper: paidCopper
248 }).replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
249 const stack = {
250 itemId: ItemId.letter,
251 quantity: 1,
252 instance: {
253 kind: "letter",
254 letterId: randomUUID(),
255 authorCharacterId: 0,
256 authorDisplayName: "Bounty Office",
257 body,
258 opened: false,
259 writtenAt: Date.now()
260 }
261 };
262 try
263 {
264 this.courier.dispatchHeldCargo({
265 senderCharacterId: killerCharacterId,
266 originTileX: office.tileX,
267 originTileY: office.tileY,
268 destination: { kind: "bank" },
269 cargo: { kind: "item", stack },
270 vaultCharacterId: killerCharacterId
271 });
272 }
273 catch
274 {
275 /* Coins already vaulted; letter is best-effort if no bank exists. */
276 }
277 }
278
279 #requireNearOffice (characterId)
280 {
281 const entityId = this.simulation.characterEntities.get(characterId);
282 const position = entityId ? this.simulation.positionOf(entityId) : null;
283 if (!position)
284 { throw userError("Enter the world before using a Bounty Office."); }
285 const tiles = this.courier?.bountyOfficeTiles ?? [];
286 if (!tiles.length)
287 { throw userError("No Bounty Office exists in this world yet."); }
288 const near = tiles.some((tile) =>
289 chebyshev(position.tileX, position.tileY, tile.tileX, tile.tileY) <= 1);
290 if (!near)
291 { throw userError("Stand next to a Bounty Office."); }
292 return position;
293 }
294
295 #loadBagQuiet (characterId)
296 {
297 const onlineId = this.simulation.characterEntities.get(characterId);
298 return onlineId
299 ? this.simulation.bagOf(onlineId)
300 : this.stateDb.getBag(characterId);
301 }
302
303 #loadBag (characterId)
304 {
305 const bag = this.#loadBagQuiet(characterId);
306 if (!bag)
307 { throw userError("No bag."); }
308 return bag;
309 }
310
311 #persistBag (characterId, bag)
312 {
313 this.stateDb.saveBag(characterId, bag);
314 const onlineId = this.simulation.characterEntities.get(characterId);
315 if (onlineId)
316 {
317 this.simulation.applyBag(onlineId, bag);
318 this.simulation.pushInventory(characterId, bag);
319 }
320 }
321}