BlueGit

timfa questward

Files

questward / server / src / bounty / service.js

service.js

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