BlueGit

timfa questward

Files

questward / server / src / bounty / service.js

service.js

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