BlueGit

timfa questward

Files

questward / server / src / bounty / service.js

service.js

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