import { formatQuantity } from "../../../shared/definitions/items.js"; import { bountyPayoutLetterBody, formatBountyCopper, bountyPayoffFromCoins, BOUNTY_PAYOFF_COINS_PER_POINT, bountyNextDecayAt } from "../../../shared/bounty/pricing.js"; import { BOUNTY_OFFICE_AUTHOR } from "../../../shared/courier/systemLetters.js"; import { layersFromBag } from "../../../shared/appearance/layers.js"; import { hairFromCharacterRow } from "../../../shared/appearance/hair.js"; import { addCoinsToSlots, normalizeVault, takeCoinsFromSlots } from "../../../shared/items/inventory.js"; import { isAdjacentTile } from "../../../shared/navigation/adjacency.js"; import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js"; function userError (message) { const error = new Error(message); error.userFacing = true; return error; } /** * Bounty office: place/raise bounties (near office), settle PvP kills into killer vault + letter. */ export class BountyService { constructor (stateDb, simulation, courier) { this.stateDb = stateDb; this.simulation = simulation; this.courier = courier; } handleCommand (sessionId, command) { switch (command.type) { case "open-bounty": return this.open(sessionId, command.characterId); case "raise-bounty": return this.placeOrRaise( sessionId, command.characterId, command.firstName, command.lastName, command.amountCopper ); case "pay-bounty": return this.payOff(sessionId, command.characterId, command.amountCopper); case "get-character-bounty": return this.lookup( sessionId, command.characterId, command.targetCharacterId, command.firstName, command.lastName ); case "close-bounty": return { events: [{ type: "bounty-closed", sessionId, characterId: command.characterId }] }; default: return null; } } open (sessionId, characterId) { this.#requireNearOffice(characterId); return { events: [{ type: "bounty-snapshot", sessionId, characterId, ...this.#myBountyPayload(characterId) }] }; } /** * Lookup target by characterId or first+last name. Adjacency not required (inspect UI). */ lookup (sessionId, requesterCharacterId, targetCharacterId, firstName, lastName) { let row = null; if (targetCharacterId) { row = this.stateDb.getCharacter(targetCharacterId | 0); } else { const first = String(firstName ?? "").trim(); const last = String(lastName ?? "").trim(); if (!first || !last) { throw userError("Enter a first and last name."); } row = this.stateDb.getCharacterByName(first, last); } if (!row) { throw userError("No adventurer by that name."); } const amountCopper = this.stateDb.getCharacterBounty(row.character_id, this.#now()); const bag = this.#loadBagQuiet(row.character_id); return { events: [{ type: "character-bounty", sessionId, characterId: requesterCharacterId, target: { characterId: row.character_id, firstName: row.first_name, lastName: row.last_name, sex: row.sex, layers: layersFromBag(row.sex, bag, hairFromCharacterRow(row)), amountCopper, amountLabel: formatBountyCopper(amountCopper) } }] }; } placeOrRaise (sessionId, placerCharacterId, firstName, lastName, amountCopper) { this.#requireNearOffice(placerCharacterId); const first = String(firstName ?? "").trim(); const last = String(lastName ?? "").trim(); if (!first || !last) { throw userError("Enter a first and last name."); } const copper = Math.floor(Number(amountCopper) || 0); if (!Number.isFinite(copper) || copper <= 0) { throw userError("Enter a positive coin amount."); } const target = this.stateDb.getCharacterByName(first, last); if (!target) { throw userError("No adventurer by that name."); } const targetId = target.character_id | 0; if (targetId === (placerCharacterId | 0)) { throw userError("You cannot place a bounty on yourself."); } const previous = this.stateDb.getCharacterBounty(targetId, this.#now()); const bag = this.#loadBag(placerCharacterId); const paid = takeCoinsFromSlots(bag.inventory ?? [], copper); if (!paid.ok) { throw userError(`Need ${formatQuantity(copper)} in your inventory.`); } bag.inventory = paid.slots; this.#persistBag(placerCharacterId, bag); const nextAmount = this.stateDb.addCharacterBounty(targetId, copper, this.#now()); this.simulation.refreshCharacterSkull?.(targetId, { force: true }); this.simulation.pendingPrivate.push({ type: "toast", characterId: targetId, message: previous > 0 ? `Someone raised the bounty on your head to ${formatBountyCopper(nextAmount)}.` : `A bounty of ${formatBountyCopper(nextAmount)} has been placed on your head.` }); return { events: [{ type: "bounty-snapshot", sessionId, characterId: placerCharacterId, ...this.#myBountyPayload(placerCharacterId), raised: { characterId: targetId, firstName: target.first_name, lastName: target.last_name, amountCopper: nextAmount, amountLabel: formatBountyCopper(nextAmount), addedCopper: copper, message: previous > 0 ? `Raised bounty on ${target.first_name} ${target.last_name} to ${formatBountyCopper(nextAmount)}.` : `Placed a ${formatBountyCopper(nextAmount)} bounty on ${target.first_name} ${target.last_name}.` } }] }; } /** * Pay inventory coins to reduce your own bounty (10 coins → 1 bounty cleared). */ payOff (sessionId, characterId, amountCopper) { this.#requireNearOffice(characterId); const offered = Math.floor(Number(amountCopper) || 0); if (!Number.isFinite(offered) || offered <= 0) { throw userError("Enter a positive coin amount."); } const current = this.stateDb.getCharacterBounty(characterId, this.#now()); if (current <= 0) { throw userError("There is no bounty on your head."); } const { reduce, costCopper } = bountyPayoffFromCoins(offered, current); if (reduce <= 0) { throw userError( `Need at least ${formatQuantity(BOUNTY_PAYOFF_COINS_PER_POINT)} to clear 1 bounty coin.` ); } const bag = this.#loadBag(characterId); const paid = takeCoinsFromSlots(bag.inventory ?? [], costCopper); if (!paid.ok) { throw userError(`Need ${formatQuantity(costCopper)} in your inventory.`); } bag.inventory = paid.slots; this.#persistBag(characterId, bag); const nextAmount = this.stateDb.reduceCharacterBounty(characterId, reduce, this.#now()); this.simulation.refreshCharacterSkull?.(characterId, { force: true }); return { events: [{ type: "bounty-snapshot", sessionId, characterId, ...this.#myBountyPayload(characterId), paidOff: { spentCopper: costCopper, clearedCopper: reduce, amountCopper: nextAmount, amountLabel: formatBountyCopper(nextAmount), message: nextAmount > 0 ? `Paid ${formatQuantity(costCopper)} to clear ${formatBountyCopper(reduce)}. Remaining: ${formatBountyCopper(nextAmount)}.` : `Paid ${formatQuantity(costCopper)} — your bounty is cleared.` } }] }; } /** * Called when a player dies. Non-friend PvP killer collects full bounty into vault + office letter. * Friend / same-account / mob kills leave the bounty untouched. * @returns {{ paidCopper: number, victimName: string } | null} */ settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY, deathDimensionId = null) { const attackerId = attackerEntityId | 0; if (!attackerId) { return null; } const attackerRec = this.simulation.directory.get(attackerId); const killerCharacterId = Number(attackerRec?.characterId) || 0; if (!killerCharacterId || killerCharacterId === (victimCharacterId | 0)) { return null; } if (this.stateDb.areFriends(victimCharacterId, killerCharacterId)) { return null; } const paidCopper = this.stateDb.takeCharacterBounty(victimCharacterId, this.#now()); if (paidCopper <= 0) { return null; } const bag = this.#loadBag(killerCharacterId); const vault = normalizeVault( bag.vaultReserved != null ? { slots: bag.vault, reserved: bag.vaultReserved } : bag.vault ); const added = addCoinsToSlots(vault.slots, paidCopper, { growable: true }); bag.vault = added.slots; bag.vaultReserved = vault.reserved; this.#persistBag(killerCharacterId, bag); const victim = this.stateDb.getCharacter(victimCharacterId); const killer = this.stateDb.getCharacter(killerCharacterId); const victimName = victim ? `${victim.first_name} ${victim.last_name}`.trim() : "someone"; const killerName = killer ? `${killer.first_name} ${killer.last_name}`.trim() : "Adventurer"; this.#dispatchPayoutLetter({ killerCharacterId, killerName, victimName, paidCopper, deathTileX, deathTileY, deathDimensionId }); this.simulation.pendingPrivate.push({ type: "toast", characterId: killerCharacterId, message: `Bounty collected: ${formatBountyCopper(paidCopper)} for defeating ${victimName} (sent to vault).` }); this.simulation.refreshCharacterSkull?.(victimCharacterId, { force: true }); return { paidCopper, victimName }; } #now () { return typeof this.simulation?.now === "number" ? this.simulation.now : Date.now(); } #myBountyPayload (characterId) { const now = this.#now(); const amountCopper = this.stateDb.getCharacterBounty(characterId, now); return { myAmountCopper: amountCopper, myAmountLabel: formatBountyCopper(amountCopper), nextDecayAt: bountyNextDecayAt(now), payoffCoinsPerPoint: BOUNTY_PAYOFF_COINS_PER_POINT, message: amountCopper > 0 ? `Bounty on your head: ${formatBountyCopper(amountCopper)}.` : "No bounty on your head." }; } #dispatchPayoutLetter ({ killerCharacterId, killerName, victimName, paidCopper, deathTileX, deathTileY, deathDimensionId = null }) { const office = this.courier?.nearestBountyOffice?.(deathTileX | 0, deathTileY | 0, deathDimensionId) ?? { tileX: deathTileX | 0, tileY: deathTileY | 0, dimensionId: deathDimensionId }; const body = bountyPayoutLetterBody({ killerName, victimName, amountCopper: paidCopper }); try { this.courier.enqueueSystemLetter({ characterId: killerCharacterId, originTileX: office.tileX, originTileY: office.tileY, originDimensionId: office.dimensionId, authorDisplayName: BOUNTY_OFFICE_AUTHOR, body }); } catch { /* Coins already vaulted; letter is best-effort if no bank exists. */ } } #requireNearOffice (characterId) { const entityId = this.simulation.characterEntities.get(characterId); const position = entityId ? this.simulation.positionOf(entityId) : null; if (!position) { throw userError("Enter the world before using a Bounty Office."); } const tiles = this.courier?.bountyOfficeTiles ?? []; if (!tiles.length) { throw userError("No Bounty Office exists in this world yet."); } const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); const near = tiles.some((tile) => normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) === dim && isAdjacentTile(position.tileX, position.tileY, tile.tileX, tile.tileY)); if (!near) { throw userError("Stand next to a Bounty Office."); } return position; } #loadBagQuiet (characterId) { const onlineId = this.simulation.characterEntities.get(characterId); return onlineId ? this.simulation.bagOf(onlineId) : this.stateDb.getBag(characterId); } #loadBag (characterId) { const bag = this.#loadBagQuiet(characterId); if (!bag) { throw userError("No bag."); } return bag; } #persistBag (characterId, bag) { this.stateDb.saveBag(characterId, bag); const onlineId = this.simulation.characterEntities.get(characterId); if (onlineId) { this.simulation.applyBag(onlineId, bag); this.simulation.pushInventory(characterId, bag); } } }