BlueGit

timfa questward

Files

questward / server / src / bounty / service.js

service.js

service.js 9.6 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
21import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
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, hairFromCharacterRow(row)),
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.refreshCharacterSkull?.(targetId, { force: true });
144 this.simulation.pendingPrivate.push({
145 type: "toast",
146 characterId: targetId,
147 message: previous > 0
148 ? `Someone raised the bounty on your head to ${formatBountyCopper(nextAmount)}.`
149 : `A bounty of ${formatBountyCopper(nextAmount)} has been placed on your head.`
150 });
151
152 return {
153 events: [{
154 type: "bounty-snapshot",
155 sessionId,
156 characterId: placerCharacterId,
157 ...this.#myBountyPayload(placerCharacterId),
158 raised: {
159 characterId: targetId,
160 firstName: target.first_name,
161 lastName: target.last_name,
162 amountCopper: nextAmount,
163 amountLabel: formatBountyCopper(nextAmount),
164 addedCopper: copper,
165 message: previous > 0
166 ? `Raised bounty on ${target.first_name} ${target.last_name} to ${formatBountyCopper(nextAmount)}.`
167 : `Placed a ${formatBountyCopper(nextAmount)} bounty on ${target.first_name} ${target.last_name}.`
168 }
169 }]
170 };
171 }
172
173 /**
174 * Called when a player dies. Non-friend PvP killer collects full bounty into vault + office letter.
175 * Friend / same-account / mob kills leave the bounty untouched.
176 * @returns {{ paidCopper: number, victimName: string } | null}
177 */
178 settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY)
179 {
180 const attackerId = attackerEntityId | 0;
181 if (!attackerId)
182 { return null; }
183 const attackerRec = this.simulation.directory.get(attackerId);
184 const killerCharacterId = Number(attackerRec?.characterId) || 0;
185 if (!killerCharacterId || killerCharacterId === (victimCharacterId | 0))
186 { return null; }
187
188 if (this.stateDb.areFriends(victimCharacterId, killerCharacterId))
189 { return null; }
190
191 const paidCopper = this.stateDb.takeCharacterBounty(victimCharacterId);
192 if (paidCopper <= 0)
193 { return null; }
194
195 const bag = this.#loadBag(killerCharacterId);
196 const vault = normalizeVault(
197 bag.vaultReserved != null
198 ? { slots: bag.vault, reserved: bag.vaultReserved }
199 : bag.vault
200 );
201 const added = addCoinsToSlots(vault.slots, paidCopper, { growable: true });
202 bag.vault = added.slots;
203 bag.vaultReserved = vault.reserved;
204 this.#persistBag(killerCharacterId, bag);
205
206 const victim = this.stateDb.getCharacter(victimCharacterId);
207 const killer = this.stateDb.getCharacter(killerCharacterId);
208 const victimName = victim
209 ? `${victim.first_name} ${victim.last_name}`.trim()
210 : "someone";
211 const killerName = killer
212 ? `${killer.first_name} ${killer.last_name}`.trim()
213 : "Adventurer";
214
215 this.#dispatchPayoutLetter({
216 killerCharacterId,
217 killerName,
218 victimName,
219 paidCopper,
220 deathTileX,
221 deathTileY
222 });
223
224 this.simulation.pendingPrivate.push({
225 type: "toast",
226 characterId: killerCharacterId,
227 message: `Bounty collected: ${formatBountyCopper(paidCopper)} for defeating ${victimName} (sent to vault).`
228 });
229
230 this.simulation.refreshCharacterSkull?.(victimCharacterId, { force: true });
231
232 return { paidCopper, victimName };
233 }
234
235 #myBountyPayload (characterId)
236 {
237 const amountCopper = this.stateDb.getCharacterBounty(characterId);
238 return {
239 myAmountCopper: amountCopper,
240 myAmountLabel: formatBountyCopper(amountCopper),
241 message: amountCopper > 0
242 ? `Bounty on your head: ${formatBountyCopper(amountCopper)}.`
243 : "No bounty on your head."
244 };
245 }
246
247 #dispatchPayoutLetter ({ killerCharacterId, killerName, victimName, paidCopper, deathTileX, deathTileY })
248 {
249 const office = this.courier?.nearestBountyOffice?.(deathTileX | 0, deathTileY | 0)
250 ?? { tileX: deathTileX | 0, tileY: deathTileY | 0 };
251 const body = bountyPayoutLetterBody({
252 killerName,
253 victimName,
254 amountCopper: paidCopper
255 }).replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
256 const stack = attachOrigins({
257 itemId: ItemId.letter,
258 quantity: 1,
259 origins: [{ origin: writtenOrigin(BOUNTY_OFFICE_AUTHOR), quantity: 1 }],
260 instance: {
261 kind: "letter",
262 letterId: randomUUID(),
263 authorCharacterId: 0,
264 authorDisplayName: BOUNTY_OFFICE_AUTHOR,
265 body,
266 opened: false,
267 writtenAt: Date.now()
268 }
269 });
270 try
271 {
272 this.courier.dispatchSystemLetter({
273 characterId: killerCharacterId,
274 originTileX: office.tileX,
275 originTileY: office.tileY,
276 stack
277 });
278 }
279 catch
280 {
281 /* Coins already vaulted; letter is best-effort if no bank exists. */
282 }
283 }
284
285 #requireNearOffice (characterId)
286 {
287 const entityId = this.simulation.characterEntities.get(characterId);
288 const position = entityId ? this.simulation.positionOf(entityId) : null;
289 if (!position)
290 { throw userError("Enter the world before using a Bounty Office."); }
291 const tiles = this.courier?.bountyOfficeTiles ?? [];
292 if (!tiles.length)
293 { throw userError("No Bounty Office exists in this world yet."); }
294 const near = tiles.some((tile) =>
295 isAdjacentTile(position.tileX, position.tileY, tile.tileX, tile.tileY));
296 if (!near)
297 { throw userError("Stand next to a Bounty Office."); }
298 return position;
299 }
300
301 #loadBagQuiet (characterId)
302 {
303 const onlineId = this.simulation.characterEntities.get(characterId);
304 return onlineId
305 ? this.simulation.bagOf(onlineId)
306 : this.stateDb.getBag(characterId);
307 }
308
309 #loadBag (characterId)
310 {
311 const bag = this.#loadBagQuiet(characterId);
312 if (!bag)
313 { throw userError("No bag."); }
314 return bag;
315 }
316
317 #persistBag (characterId, bag)
318 {
319 this.stateDb.saveBag(characterId, bag);
320 const onlineId = this.simulation.characterEntities.get(characterId);
321 if (onlineId)
322 {
323 this.simulation.applyBag(onlineId, bag);
324 this.simulation.pushInventory(characterId, bag);
325 }
326 }
327}