diff --git a/packages/local-service/src/char/actions/action-table.ts b/packages/local-service/src/char/actions/action-table.ts index fe5d469..f780c2f 100644 --- a/packages/local-service/src/char/actions/action-table.ts +++ b/packages/local-service/src/char/actions/action-table.ts @@ -5,9 +5,10 @@ import type { ResearchRules } from '../../research/research-rules.ts'; import type { CharActionHandler } from '../char-action.ts'; import { acceptEula } from './agreement-actions.ts'; import { bulkTrainCrews, trainCrew } from './crew-actions.ts'; +import { buyUnlockAction } from './unlock-actions.ts'; import { buyAllModificationsAction, buyModificationAction, buySparesAction, buyWeaponsAction, enableModificationsAction } from './modification-actions.ts'; import { purchaseSkillPointsAction, specializeCrewAction, upgradeCrewAction } from './crew-skill-actions.ts'; -import { savePilotAppearanceAction, selectTitleAction, usersTerseInfoAction } from './player-card-actions.ts'; +import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts'; import { buyResourceAction } from './decor-actions.ts'; import { saveDecorLayoutsAction } from './decor-layout-actions.ts'; import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts'; @@ -40,6 +41,7 @@ export function actionTable(deps: ActionDependencies): ReadonlyMap{ nick:t pilotIcon:t pilotId:t title:t clanTag:t clanName:t background:t frame:t } + * request usersList=";", sent as a request header (char-action.ts headerParam) + * answer { nick:t pilotIcon:t pilotId:t title:t clanTag:t clanName:t background:t frame:t + * shcType:t showcase{...} } * or { failed:b=yes } for unknown users + * cln_save_profile_showcase (scripts user/profileShowcase.nut saveShowcase, charSendBlk): one + * showcase type and its choices, answered with the whole profile; cln_get_showcases (scripts + * user/profileShowcasesData.nut, charRequestBlk): every saved showcase (showcase-rules.ts). */ import type { BlkBlock, BlkParam } from '@wto/blk'; import type { AccountStore } from '../../accounts/account-store.ts'; import { chooseTitle, saveAppearance } from '../../player-card/player-card-rules.ts'; +import { currentShowcaseView, saveShowcase, showcasesAnswer } from '../../player-card/showcase-rules.ts'; +import type { ResearchRules } from '../../research/research-rules.ts'; import { appearance, chosenTitle } from '../../profile/profile-appearance.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { CharActionHandler } from '../char-action.ts'; @@ -31,9 +37,18 @@ export function savePilotAppearanceAction(profiles: PlayerProfiles, accounts: Ac }); } -export function usersTerseInfoAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { +export function saveShowcaseAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => (profile) => saveShowcase(profile, payload)); +} + +export function showcasesAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return (context) => withAccount(context, accounts, (account) => + ({ kind: 'data', blk: showcasesAnswer(profiles.profileOf(account.userId), rules.techTree) })); +} + +export function usersTerseInfoAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { return (context) => withAccount(context, accounts, () => { - const list = context.payload ? stringParam(context.payload, 'usersList') : undefined; + const list = (context.payload ? stringParam(context.payload, 'usersList') : undefined) ?? context.headerParam('usersList'); if (list === undefined) return { kind: 'error', code: 'BAD_PARAMS' }; const blocks = list.split(';').filter((uid) => uid !== '').map((uid): BlkBlock => { const account = accounts.byUserId(uid); @@ -44,7 +59,9 @@ export function usersTerseInfoAction(profiles: PlayerProfiles, accounts: Account ['nick', account.nick], ['pilotIcon', looks.pilotIcon ?? ''], ['title', chosenTitle(profile)], ['background', looks.background ?? ''], ['frame', looks.frame ?? ''], ]; - return { name: uid, params: fields.map(([name, value]): BlkParam => ({ name, value: { type: 'string', value } })), blocks: [] }; + const { type, showcase } = currentShowcaseView(profile, rules.techTree); + fields.push(['shcType', type]); + return { name: uid, params: fields.map(([name, value]): BlkParam => ({ name, value: { type: 'string', value } })), blocks: [showcase] }; }); return { kind: 'data', blk: { name: '', params: [], blocks } }; }); diff --git a/packages/local-service/src/char/actions/price-actions.ts b/packages/local-service/src/char/actions/price-actions.ts index 72f3b8c..97b3e19 100644 --- a/packages/local-service/src/char/actions/price-actions.ts +++ b/packages/local-service/src/char/actions/price-actions.ts @@ -9,6 +9,6 @@ import { priceTable } from '../../research/price-table.ts'; import type { ResearchRules } from '../../research/research-rules.ts'; export function priceEx(rules: ResearchRules): CharActionHandler { - const table = priceTable(rules.techTree, rules.equipment, rules.decor, rules.crew); + const table = priceTable(rules.techTree, rules.equipment, rules.decor, rules.crew, rules.unlocks); return () => ({ kind: 'data', blk: table }); } diff --git a/packages/local-service/src/char/actions/unlock-actions.ts b/packages/local-service/src/char/actions/unlock-actions.ts new file mode 100644 index 0000000..6cdc049 --- /dev/null +++ b/packages/local-service/src/char/actions/unlock-actions.ts @@ -0,0 +1,26 @@ +/** + * Buying unlocks. cln_buy_unlock is sent with charSendBlk (job type + * 13), so the answer is the whole profile. + * + * cln_buy_unlock (scripts unlocks/unlocksAction.nut buyUnlockImpl; ship flags from + * customization/decoratorAcquire.nut, icons from chooseImage.nut, awards, smokes...): + * name:t the unlock + * unitName:t the vehicle in the hangar (flags); not needed to buy + * wpCost:i goldCost:i + */ +import type { AccountStore } from '../../accounts/account-store.ts'; +import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import type { ResearchRules } from '../../research/research-rules.ts'; +import { buyUnlock } from '../../unlocks/unlock-purchase.ts'; +import type { CharActionHandler } from '../char-action.ts'; +import { intParam, stringParam } from './payload-params.ts'; +import { ruleAction } from './rule-answer.ts'; + +export function buyUnlockAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const name = stringParam(payload, 'name'); + if (name === undefined) return undefined; + const offered = { silverLions: intParam(payload, 'wpCost') ?? 0, goldenEagles: intParam(payload, 'goldCost') ?? 0 }; + return (profile) => buyUnlock(profile, rules.unlocks, name, offered); + }); +} diff --git a/packages/local-service/src/char/char-action.ts b/packages/local-service/src/char/char-action.ts index 5abe891..4ba4f9c 100644 --- a/packages/local-service/src/char/char-action.ts +++ b/packages/local-service/src/char/char-action.ts @@ -7,6 +7,13 @@ export interface CharActionContext { readonly userId: string | undefined; /** The request's BLK parameters, when the body carried a BLK. */ readonly payload: BlkBlock | undefined; + /** + * A request parameter sent as an HTTP header: char_request_blk_from_server (scripts + * charRequestBlk) sends the top-level parameters of its BLK that way and no body (lab round + * 22: cln_get_users_terse_info with a "usersList" header). Header names arrive lower-cased, + * so the lookup ignores case. + */ + readonly headerParam: (name: string) => string | undefined; } export type CharActionHandler = (context: CharActionContext) => CharAnswer; diff --git a/packages/local-service/src/char/char-service.ts b/packages/local-service/src/char/char-service.ts index 1d8d442..c482a3a 100644 --- a/packages/local-service/src/char/char-service.ts +++ b/packages/local-service/src/char/char-service.ts @@ -37,7 +37,7 @@ export class CharService implements Service { const payload = decodeRequestPayload(request.body); const handler = this.#actions.get(action); const answer: CharAnswer = handler - ? handler({ userId: header(request, 'uidhint'), payload: payload.blk }) + ? handler({ userId: header(request, 'uidhint'), payload: payload.blk, headerParam: (name) => header(request, name.toLowerCase()) }) : { kind: 'data', blk: emptyBlock() }; const response = toResponse(answer); return { diff --git a/packages/local-service/src/game-data/datasets/unlock-prices.ts b/packages/local-service/src/game-data/datasets/unlock-prices.ts new file mode 100644 index 0000000..b878321 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/unlock-prices.ts @@ -0,0 +1,32 @@ +/** + * Dataset: the unlocks that can be bought: ship flags, profile icons + * and frames, awards, some achievements. + * + * char.vromfs.bin config/unlocks.blk: unlockable{ id:t type:t cost:i costGold:i mode{...} ... }. + * Only unlocks with a positive cost or costGold are recorded. + */ +import type { BlkBlock } from '@wto/blk'; +import { numberField, stringField } from './blk-fields.ts'; +import type { Dataset } from './dataset.ts'; + +const UNLOCKS = 'config/unlocks.blk'; + +export interface UnlockPrice { + readonly id: string; + readonly silverLions: number; + readonly goldenEagles: number; +} + +export const unlockPrices: Dataset = { + id: 'unlock-prices', + version: 1, + extract: (source) => source.readBlk('char.vromfs.bin', UNLOCKS).blocks.flatMap(priceOf), +}; + +function priceOf(entry: BlkBlock): UnlockPrice[] { + const id = stringField(entry, 'id'); + const silverLions = Math.max(0, numberField(entry, 'cost') ?? 0); + const goldenEagles = Math.max(0, numberField(entry, 'costGold') ?? 0); + if (id === undefined || (silverLions === 0 && goldenEagles === 0)) return []; + return [{ id, silverLions, goldenEagles }]; +} diff --git a/packages/local-service/src/player-card/showcase-rules.ts b/packages/local-service/src/player-card/showcase-rules.ts new file mode 100644 index 0000000..743b887 --- /dev/null +++ b/packages/local-service/src/player-card/showcase-rules.ts @@ -0,0 +1,129 @@ +/** + * The profile showcase (implementation notes; scripts user/profileShowcase.nut and + * user/showcase/*.nut). + * + * cln_save_profile_showcase carries showcaseType:t and that type's choices under the names its + * getSaveData uses; the client reads them back (cln_get_showcases, the terse info's showcase + * block) under other names. Per type, request -> stored field: + * favorite_mode favoriteMode -> mode + * battle_hardened battleHardenedMode -> h_mode + * favorite_unit favoriteUnit, favoriteUnitDifficulty -> unit, difficulty + * unit_collector unitCollectorFavorites (repeated) -> units + * medalist medals (repeated) -> medals + * achievement_hunter achievements (repeated) -> achievements + * ace_of_spades acedUnitsFilter{ country_:t= ... }, kept as it is; the + * answer turns it into aced_units{ { :i= } } for the chosen + * pairs and aced_units_hidden for the rest, counting the vehicles a crew + * is an ace on (spec 2) + * atomic_ace, peacemaker, tank_footballer nothing + */ +import type { BlkBlock, BlkParam } from '@wto/blk'; +import { allCrews } from '../profile/profile-crews.ts'; +import { trainedPairs } from '../profile/profile-crew-skills.ts'; +import { currentShowcase, savedShowcases, writeShowcase } from '../profile/profile-showcase.ts'; +import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import type { TechTree } from '../research/tech-tree.ts'; +import type { VehicleType } from '../research/vehicle-types.ts'; + +const ACE_OF_SPADES = 'ace_of_spades'; +const ACED_FILTER = 'acedUnitsFilter'; +const ACE = 2; + +/** Request parameter -> stored field, per showcase type. */ +const STORED_FIELDS: Readonly>>> = { + favorite_mode: { favoriteMode: 'mode' }, + battle_hardened: { battleHardenedMode: 'h_mode' }, + favorite_unit: { favoriteUnit: 'unit', favoriteUnitDifficulty: 'difficulty' }, + unit_collector: { unitCollectorFavorites: 'units' }, + medalist: { medals: 'medals' }, + achievement_hunter: { achievements: 'achievements' }, + [ACE_OF_SPADES]: {}, + atomic_ace: {}, + peacemaker: {}, + tank_footballer: {}, +}; + +/** The client's unit type names (scripts unit/unitTypesList.nut). */ +const SHOWCASE_UNIT_TYPE: Partial> = { + Aircraft: 'aircraft', Tank: 'tank', Ship: 'ship', Helicopter: 'helicopter', Boat: 'boat', +}; + +export function saveShowcase(profile: BlkBlock, request: BlkBlock): RuleOutcome { + const typeParam = request.params.find((param) => param.name === 'showcaseType')?.value; + const type = typeParam?.type === 'string' ? typeParam.value : undefined; + const fields = type === undefined ? undefined : STORED_FIELDS[type]; + if (type === undefined || fields === undefined) return refused('BAD_PARAMS'); + const stored = request.params.flatMap((param): BlkParam[] => { + const field = fields[param.name]; + return field ? [{ name: field, value: param.value }] : []; + }); + writeShowcase(profile, type, stored); + if (type === ACE_OF_SPADES) { + const filter = request.blocks.find((block) => block.name === ACED_FILTER); + const saved = savedShowcases(profile).find((block) => block.name === ACE_OF_SPADES); + if (saved) saved.blocks = filter ? [{ ...filter, blocks: [] }] : []; + } + return ACCEPTED; +} + +/** The cln_get_showcases answer: current:t and one block per saved showcase type. */ +export function showcasesAnswer(profile: BlkBlock, techTree: TechTree): BlkBlock { + return { + name: '', + params: [{ name: 'current', value: { type: 'string', value: currentShowcase(profile) } }], + blocks: savedShowcases(profile).map((saved) => clientView(profile, techTree, saved)), + }; +} + +/** The current showcase for cln_get_users_terse_info: its type and its block named "showcase". */ +export function currentShowcaseView(profile: BlkBlock, techTree: TechTree): { type: string; showcase: BlkBlock } { + const type = currentShowcase(profile); + const saved = savedShowcases(profile).find((block) => block.name === type); + const view = saved ? clientView(profile, techTree, saved) : { name: type, params: [], blocks: [] }; + return { type, showcase: { ...view, name: 'showcase' } }; +} + +function clientView(profile: BlkBlock, techTree: TechTree, saved: BlkBlock): BlkBlock { + if (saved.name !== ACE_OF_SPADES) return { name: saved.name, params: saved.params, blocks: [] }; + const chosen = new Set((saved.blocks.find((block) => block.name === ACED_FILTER)?.params ?? []) + .flatMap((param) => param.value.type === 'string' ? [`${param.value.value}/${param.name.replace(/^country_/, '')}`] : [])); + const shown = new Map>(); + const hidden = new Map>(); + for (const [key, count] of acedVehicleCounts(profile, techTree)) { + const [type, country] = key.split('/') as [string, string]; + const target = chosen.has(key) ? shown : hidden; + let byCountry = target.get(type); + if (!byCountry) target.set(type, byCountry = new Map()); + byCountry.set(country, count); + } + return { name: saved.name, params: [], blocks: [countBlock('aced_units', shown), countBlock('aced_units_hidden', hidden)] }; +} + +/** "/" -> vehicles a crew is an ace on. */ +function acedVehicleCounts(profile: BlkBlock, techTree: TechTree): Map { + const aced = new Set(); + for (const crew of allCrews(profile)) { + for (const pair of trainedPairs(crew)) if (pair.spec >= ACE) aced.add(pair.vehicle); + } + const counts = new Map(); + for (const name of aced) { + const vehicle = techTree.vehicle(name); + const type = vehicle && SHOWCASE_UNIT_TYPE[vehicle.type]; + if (!vehicle || !type) continue; + const key = `${type}/${vehicle.country.replace(/^country_/, '')}`; + counts.set(key, (counts.get(key) ?? 0) + 1); + } + return counts; +} + +function countBlock(name: string, counts: Map>): BlkBlock { + return { + name, + params: [], + blocks: [...counts].map(([type, byCountry]) => ({ + name: type, + params: [...byCountry].map(([country, count]): BlkParam => ({ name: country, value: { type: 'int', value: count } })), + blocks: [], + })), + }; +} diff --git a/packages/local-service/src/profile/profile-crew-skills.ts b/packages/local-service/src/profile/profile-crew-skills.ts index 8623663..7f0448b 100644 --- a/packages/local-service/src/profile/profile-crew-skills.ts +++ b/packages/local-service/src/profile/profile-crew-skills.ts @@ -68,7 +68,8 @@ export function setSpecialization(crew: BlkBlock, vehicle: string, spec: number) } /** trained/spec pairs in order; a trained vehicle without a following spec has spec 0. */ -function trainedPairs(crew: BlkBlock): { vehicle: string; spec: number }[] { +/** The vehicles the crew is trained for, each with its specialization (0 none, 1 expert, 2 ace). */ +export function trainedPairs(crew: BlkBlock): { vehicle: string; spec: number }[] { const pairs: { vehicle: string; spec: number }[] = []; for (const param of findBlock(crew, VEHICLES)?.params ?? []) { if (param.name === TRAINED && param.value.type === 'string') pairs.push({ vehicle: param.value.value, spec: 0 }); diff --git a/packages/local-service/src/profile/profile-crews.ts b/packages/local-service/src/profile/profile-crews.ts index 581fd2d..a335296 100644 --- a/packages/local-service/src/profile/profile-crews.ts +++ b/packages/local-service/src/profile/profile-crews.ts @@ -24,6 +24,11 @@ export function crewOf(profile: BlkBlock, crewId: number): BlkBlock | undefined return profile.blocks.find((block) => block.name === CREWS)?.blocks.find((crew) => crew.name === `c${crewId}`); } +/** Every crew block, in profile order. */ +export function allCrews(profile: BlkBlock): readonly BlkBlock[] { + return (profile.blocks.find((block) => block.name === CREWS)?.blocks ?? []).filter((crew) => CREW_NAME.test(crew.name)); +} + export function crewCountOf(profile: BlkBlock, country: string): number { return (profile.blocks.find((block) => block.name === CREWS)?.blocks ?? []).filter((crew) => crewCountry(crew) === country).length; } diff --git a/packages/local-service/src/profile/profile-showcase.ts b/packages/local-service/src/profile/profile-showcase.ts new file mode 100644 index 0000000..2355908 --- /dev/null +++ b/packages/local-service/src/profile/profile-showcase.ts @@ -0,0 +1,33 @@ +/** + * The player's profile showcase, kept in the profile in the form the + * client reads it back from cln_get_showcases and cln_get_users_terse_info: + * + * showcase{ + * current:t="favorite_unit" + * favorite_unit{ unit:t="us_m22_locust" difficulty:t="arcade" } + * medalist{ medals:t="..." medals:t="..." } + * } + * + * This block is the local service's own record: the client's profile reader does not know it. + */ +import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; + +const SHOWCASE = 'showcase'; +const CURRENT = 'current'; + +export function currentShowcase(profile: BlkBlock): string { + const value = findParam(findBlock(profile, SHOWCASE) ?? { name: '', params: [], blocks: [] }, CURRENT)?.value; + return value?.type === 'string' ? value.value : ''; +} + +/** Every saved showcase, by type. */ +export function savedShowcases(profile: BlkBlock): readonly BlkBlock[] { + return findBlock(profile, SHOWCASE)?.blocks ?? []; +} + +/** Replace the fields of one showcase type and make it the current one. */ +export function writeShowcase(profile: BlkBlock, type: string, fields: readonly BlkParam[]): void { + const showcase = ensureBlock(profile, SHOWCASE); + setParam(showcase, CURRENT, { type: 'string', value: type }); + ensureBlock(showcase, type).params = [...fields]; +} diff --git a/packages/local-service/src/research/price-table.ts b/packages/local-service/src/research/price-table.ts index a406454..a37e966 100644 --- a/packages/local-service/src/research/price-table.ts +++ b/packages/local-service/src/research/price-table.ts @@ -22,6 +22,7 @@ * decals{ { ... } } * attachable{ { ... } } * skills{ { costGold:i } } skill point packs (0x916380) + * unlocks{ { cost:i costGold:i } } unlocks for sale (0x9170c0) * } * * Every entry is read as cost:i (silver lions), costGold:i (golden eagles), discount:i (percent @@ -29,18 +30,19 @@ * is the outright price of a modification before research progress (0xec0910). Anything the * lookup does not find costs 0 for the client, which then offers it at 0 (lab round 20). The * prices are config/wpcost.blk value and costGold (decorations: config/skins.blk, decals.blk, - * attachable.blk), the same the purchase rules charge. + * attachable.blk; unlocks: config/unlocks.blk), the same the purchase rules charge. */ import type { BlkBlock, BlkParam } from '@wto/blk'; import type { CrewSkillCatalogue } from '../crew/crew-skill-rules.ts'; import type { DecorShop } from '../decor/decor-purchase.ts'; import type { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts'; +import type { UnlockShop } from '../unlocks/unlock-purchase.ts'; import type { TechTree } from './tech-tree.ts'; /** The top-level block every client lookup falls back to (0x908e28). */ const COMMON_SECTION = 'Common'; -export function priceTable(techTree: TechTree, equipment: EquipmentCatalogue, decor: DecorShop, crew: CrewSkillCatalogue): BlkBlock { +export function priceTable(techTree: TechTree, equipment: EquipmentCatalogue, decor: DecorShop, crew: CrewSkillCatalogue, unlocks: UnlockShop): BlkBlock { const vehicles: BlkBlock[] = []; for (const vehicle of techTree.all()) { const entry: BlkBlock = { name: vehicle.name, params: priceParams(vehicle.silverLions, vehicle.goldenEagles), blocks: [] }; @@ -59,7 +61,7 @@ export function priceTable(techTree: TechTree, equipment: EquipmentCatalogue, de } if (entry.blocks.length || vehicle.silverLions > 0 || vehicle.goldenEagles > 0) vehicles.push(entry); } - const common: BlkBlock = { name: COMMON_SECTION, params: [], blocks: [{ name: 'aircrafts', params: [], blocks: vehicles }, ...decorSections(decor), skillPackSection(crew)] }; + const common: BlkBlock = { name: COMMON_SECTION, params: [], blocks: [{ name: 'aircrafts', params: [], blocks: vehicles }, ...decorSections(decor), skillPackSection(crew), unlockSection(unlocks)] }; return { name: '', params: [], blocks: [common] }; } @@ -92,3 +94,7 @@ function decorSections(decor: DecorShop): BlkBlock[] { function skillPackSection(crew: CrewSkillCatalogue): BlkBlock { return { name: 'skills', params: [], blocks: [...crew.packs()].map((pack) => ({ name: pack.name, params: priceParams(0, pack.goldenEagles), blocks: [] })) }; } + +function unlockSection(unlocks: UnlockShop): BlkBlock { + return { name: 'unlocks', params: [], blocks: [...unlocks.all()].map((price) => ({ name: price.id, params: priceParams(price.silverLions, price.goldenEagles), blocks: [] })) }; +} diff --git a/packages/local-service/src/research/research-rules.ts b/packages/local-service/src/research/research-rules.ts index 9c56591..0815686 100644 --- a/packages/local-service/src/research/research-rules.ts +++ b/packages/local-service/src/research/research-rules.ts @@ -13,6 +13,8 @@ import { vehicleEquipment } from '../game-data/datasets/vehicle-equipment.ts'; import { DecorShop } from '../decor/decor-purchase.ts'; import { vehicleUnlocks, type UnlockDefinition } from '../game-data/datasets/vehicle-unlocks.ts'; import { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts'; +import { unlockPrices } from '../game-data/datasets/unlock-prices.ts'; +import { UnlockShop } from '../unlocks/unlock-purchase.ts'; import { TechTree } from './tech-tree.ts'; export interface ResearchRules { @@ -27,6 +29,8 @@ export interface ResearchRules { readonly decor: DecorShop; /** Crew skills, skill point packs, training prices. */ readonly crew: CrewSkillCatalogue; + /** Unlocks for sale: ship flags, profile icons and frames, awards. */ + readonly unlocks: UnlockShop; } export function loadResearchRules(datasets: DatasetCache): ResearchRules { @@ -39,5 +43,6 @@ export function loadResearchRules(datasets: DatasetCache): ResearchRules { equipment: new EquipmentCatalogue(datasets.load(vehicleEquipment)), decor: new DecorShop(datasets.load(decorCatalogue)), crew: new CrewSkillCatalogue(datasets.load(crewSkillData)), + unlocks: new UnlockShop(datasets.load(unlockPrices)), }; } diff --git a/packages/local-service/src/unlocks/unlock-purchase.ts b/packages/local-service/src/unlocks/unlock-purchase.ts new file mode 100644 index 0000000..f9a42ca --- /dev/null +++ b/packages/local-service/src/unlocks/unlock-purchase.ts @@ -0,0 +1,37 @@ +/** + * Buying unlocks: ship flags, profile icons and frames, awards. The + * unlock must have a price (config/unlocks.blk cost, costGold), not be earned yet, and the + * offered price must match; it is then recorded as earned. + */ +import type { BlkBlock } from '@wto/blk'; +import type { UnlockPrice } from '../game-data/datasets/unlock-prices.ts'; +import { canAfford, pay, type Price } from '../profile/profile-currency.ts'; +import { addUnlock, earnedUnlocks } from '../profile/profile-unlocks.ts'; +import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; + +export class UnlockShop { + readonly #prices: ReadonlyMap; + + constructor(prices: readonly UnlockPrice[]) { + this.#prices = new Map(prices.map((price) => [price.id, price])); + } + + all(): Iterable { + return this.#prices.values(); + } + + price(id: string): UnlockPrice | undefined { + return this.#prices.get(id); + } +} + +export function buyUnlock(profile: BlkBlock, shop: UnlockShop, id: string, offered: Price): RuleOutcome { + const forSale = shop.price(id); + if (!forSale || earnedUnlocks(profile).has(id)) return refused('NOT_AVAILABLE'); + const price: Price = { silverLions: forSale.silverLions, goldenEagles: forSale.goldenEagles }; + if (price.silverLions !== offered.silverLions || price.goldenEagles !== offered.goldenEagles) return refused('PRICE_CHANGED'); + if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); + pay(profile, price); + addUnlock(profile, id); + return ACCEPTED; +}