BlueGit

timfa questward

Files

questward / server / src / bounty / service.js

service.js

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