feat(profile): add unlock purchases and showcases

Load unlock prices from unlocks.blk and expose them in Common/unlocks.
Support purchasing unlocks and saving showcases, and count qualified
crews for the ace showcase.

Read charRequestBlk action parameters from HTTP headers and apply this
to cln_get_users_terse_info.
This commit is contained in:
N0VAN0M4LY committed 2026-11-25 02:49:13 +08:00
1 parent 1e7dc2447f
commit f463f3e325
14 files changed
+315 -13

No files matched your search

@@ -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<string, CharA
['cln_buy_modification', buyModificationAction(deps.profiles, deps.accounts, deps.research)],
['cln_buy_all_modification', buyAllModificationsAction(deps.profiles, deps.accounts, deps.research)],
['cln_buy_spare_aircrafts', buySparesAction(deps.profiles, deps.accounts, deps.research)],
['cln_buy_unlock', buyUnlockAction(deps.profiles, deps.accounts, deps.research)],
['cln_buy_weapon', buyWeaponsAction(deps.profiles, deps.accounts, deps.research)],
['cln_enable_modifications', enableModificationsAction(deps.profiles, deps.accounts)],
['cln_upgrade_crew', upgradeCrewAction(deps.profiles, deps.accounts, deps.research)],
@@ -47,7 +49,9 @@ export function actionTable(deps: ActionDependencies): ReadonlyMap<string, CharA
['cln_specialize_crew', specializeCrewAction(deps.profiles, deps.accounts, deps.research)],
['cln_select_title', selectTitleAction(deps.profiles, deps.accounts)],
['cln_save_pilot_appearance', savePilotAppearanceAction(deps.profiles, deps.accounts)],
['cln_get_users_terse_info', usersTerseInfoAction(deps.profiles, deps.accounts)],
['cln_get_users_terse_info', usersTerseInfoAction(deps.profiles, deps.accounts, deps.research)],
['cln_save_profile_showcase', saveShowcaseAction(deps.profiles, deps.accounts)],
['cln_get_showcases', showcasesAction(deps.profiles, deps.accounts, deps.research)],
['cln_buy_resource', buyResourceAction(deps.profiles, deps.accounts, deps.research)],
['cln_save_decals', saveDecorLayoutsAction(deps.profiles, deps.accounts, 'decals')],
['cln_save_attachables', saveDecorLayoutsAction(deps.profiles, deps.accounts, 'attachables')],
@@ -2,13 +2,19 @@
* Player card actions. cln_select_title and cln_save_pilot_appearance
* are sent with char_send_blk (job type 13) and answer the whole profile; cln_get_users_terse_info
* (scripts user/usersInfoManager.nut, charRequestBlk) answers one block per requested user:
* request usersList:t="<uid>;<uid>"
* answer <uid>{ nick:t pilotIcon:t pilotId:t title:t clanTag:t clanName:t background:t frame:t }
* request usersList="<uid>;<uid>", sent as a request header (char-action.ts headerParam)
* answer <uid>{ nick:t pilotIcon:t pilotId:t title:t clanTag:t clanName:t background:t frame:t
* shcType:t showcase{...} }
* or <uid>{ 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 } };
});
@@ -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 });
}
@@ -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);
});
}
@@ -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;
@@ -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 {
@@ -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<readonly UnlockPrice[]> = {
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 }];
}
@@ -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_<c>:t=<unit type> ... }, kept as it is; the
* answer turns it into aced_units{ <type>{ <c>:i=<count> } } 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<Record<string, Readonly<Record<string, string>>>> = {
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<Record<VehicleType, string>> = {
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<string, Map<string, number>>();
const hidden = new Map<string, Map<string, number>>();
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)] };
}
/** "<unit type>/<country without the country_ prefix>" -> vehicles a crew is an ace on. */
function acedVehicleCounts(profile: BlkBlock, techTree: TechTree): Map<string, number> {
const aced = new Set<string>();
for (const crew of allCrews(profile)) {
for (const pair of trainedPairs(crew)) if (pair.spec >= ACE) aced.add(pair.vehicle);
}
const counts = new Map<string, number>();
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<string, Map<string, number>>): 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: [],
})),
};
}
@@ -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 });
@@ -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;
}
@@ -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];
}
@@ -22,6 +22,7 @@
* decals{ <decal>{ ... } }
* attachable{ <attachable>{ ... } }
* skills{ <pack>{ costGold:i } } skill point packs (0x916380)
* unlocks{ <unlock>{ 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: [] })) };
}
@@ -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)),
};
}
@@ -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<string, UnlockPrice>;
constructor(prices: readonly UnlockPrice[]) {
this.#prices = new Map(prices.map((price) => [price.id, price]));
}
all(): Iterable<UnlockPrice> {
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;
}