BlueGit

timfa questward

Files

questward / server / src / bounty / service.js

service.js

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