/** * Using universal spares on a vehicle (cln_apply_spare_item: uid:t unit:t useItemsCount:i; * scripts items/itemsClasses/itemUniversalSpare.nut activateOnUnit). * * The vehicle must be owned and fit the item's conditions as the scripts check them * (itemModBase.nut initConditions, itemUniversalSpare.nut canActivateOnUnit): one of its * countries, its rank range, one of its unit types. Each piece used adds numSpares spares to * hangar//spareAircraftsCount, which stays within MAX_SPARE_AMOUNT like bought spares. */ import type { BlkBlock } from '@wto/blk'; import { ownsVehicle } from '../profile/profile-hangar.ts'; import { ownedItem, removeItem, setItemCount } from '../profile/profile-items.ts'; import { setSpareCount, spareCount } from '../profile/profile-vehicle-state.ts'; import { MAX_SPARE_AMOUNT } from '../modifications/spare-purchase.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; import type { TechTree, TreeVehicle } from '../research/tech-tree.ts'; import type { VehicleType } from '../research/vehicle-types.ts'; import type { SpareConditions } from '../game-data/datasets/item-catalogue.ts'; import type { ItemCatalogue } from './item-catalogue.ts'; /** The scripts' unitType.lowerName (scripts unit/unitTypesList.nut). */ const UNIT_TYPE_NAME: Partial> = { Aircraft: 'aircraft', Tank: 'tank', Ship: 'ship', Helicopter: 'helicopter', Boat: 'boat', }; export function applyUniversalSpares(profile: BlkBlock, catalogue: ItemCatalogue, techTree: TechTree, uid: string, vehicleName: string, pieces: number): RuleOutcome { const owned = ownedItem(profile, uid); const conditions = owned && catalogue.item(owned.id)?.spare; const vehicle = techTree.vehicle(vehicleName); if (!owned || !conditions || !vehicle || owned.type !== 'universalSpare') return refused('BAD_PARAMS'); if (pieces < 1 || pieces > owned.count) return refused('BAD_PARAMS'); if (!ownsVehicle(profile, vehicle.name) || !fits(vehicle, conditions)) return refused('NOT_AVAILABLE'); const spares = spareCount(profile, vehicle.name) + conditions.spares * pieces; if (spares > MAX_SPARE_AMOUNT) return refused('NOT_AVAILABLE'); setSpareCount(profile, vehicle.name, spares); if (owned.count === pieces) removeItem(profile, uid); else setItemCount(profile, uid, owned.count - pieces); return ACCEPTED; } function fits(vehicle: TreeVehicle, conditions: SpareConditions): boolean { if (conditions.countries.length && !conditions.countries.includes(vehicle.country)) return false; if (conditions.minRank !== undefined && vehicle.rank < conditions.minRank) return false; if (conditions.maxRank !== undefined && vehicle.rank > conditions.maxRank) return false; const typeName = UNIT_TYPE_NAME[vehicle.type]; return !conditions.unitTypes.length || (typeName !== undefined && conditions.unitTypes.includes(typeName)); }