import type { BuildingType, BuildOrder, Cost, GameError, MarchPlan, MovementType, Resource, Resources, TravelMode, Units, UnitType, VillageState, VillageUpdated } from '~/types/game' import { toRaw, type InjectionKey } from 'vue' const RESOURCES: Resource[] = ['wood', 'clay', 'iron', 'food'] /** * One village: the last server snapshot, resources projected to now, and the intents. * Call it from a page's setup(), since it listens for pushes while that page is mounted. */ export function useVillage(villageId: number) { const village = ref(null) const error = ref(null) const busy = ref(false) const errorText = useErrorText() const unreadReports = useUnreadReports() // Projections and countdowns run on the server's clock. const { now, sync } = useServerClock() const { forget } = useCurrentWorld() /** Server time of the snapshot shown: an answer that left the server earlier is older and never replaces it. */ let shownAt = 0 /** Changes in flight that lock their forms (sending troops, recruiting); quick actions never do. */ let blocking = 0 function apply(state: VillageState) { const at = Date.parse(state.server_time) if (at < shownAt) return shownAt = at sync(state.server_time) village.value = state unreadReports.value = state.unread_reports } /** * Send an intent and show the answer. A quick action passes `optimistic`: its result shows * at once on a copy of the village, the server's answer replaces it, and a refusal puts * the village back. Only intents with `block` lock the controls while they run. */ async function run(event: string, data: object = {}, opts: { block?: boolean; optimistic?: (v: VillageState) => void } = {}) { const block = opts.block ?? !opts.optimistic if (block) busy.value = ++blocking > 0 error.value = null const before = village.value if (opts.optimistic && before) { const copy = JSON.parse(JSON.stringify(toRaw(before))) as VillageState opts.optimistic(copy) village.value = copy } try { apply(await ws.send(event, { village_id: villageId, ...data })) return true } catch (e) { // The village is gone (the world was reset): forget it and pick a world again. if (event === 'village.show' && (e as Partial)?.code === 'not_found') { forget(villageId) await navigateTo('/worlds') return false } if (opts.optimistic) refresh() error.value = errorText(e) return false } finally { if (block) busy.value = --blocking > 0 } } // Refreshes run quietly in the background, one at a time; a call while one runs asks for one more after it. let refreshing: Promise | null = null let again = false async function refresh(): Promise { if (refreshing) { again = true return refreshing } refreshing = run('village.show', {}, { block: false }) try { return await refreshing } finally { refreshing = null if (again) { again = false refresh() } } } // What quick actions look like before the server answers. let placeholder = 0 const pay = (v: VillageState, cost: Cost, sign = -1) => { for (const r of ['wood', 'clay', 'iron'] as const) v.resources[r] = Math.min(v.storage_cap, Math.max(0, v.resources[r] + sign * cost[r])) } const queueOrder = (v: VillageState, order: Omit) => v.queue.push({ ...order, id: --placeholder, position: v.queue.length + 1, builder: null, starts_at: null, finishes_at: null }) /** The queue holds back (or, with sign 1, frees) the villagers an order needs, as the server counts them. */ const hold = (v: VillageState, villagers: number, sign = -1) => { v.population.idle = Math.max(0, v.population.idle + sign * villagers) v.population.reserved = Math.max(0, v.population.reserved - sign * villagers) } /** stored + rate × elapsed, kept between 0 and the storage cap. */ const resources = computed(() => { const v = village.value if (!v) return null const hours = (now.value - Date.parse(v.resources_at)) / 3_600_000 const project = (r: Resource) => Math.min(v.storage_cap, Math.max(0, v.resources[r] + v.rates[r] * hours)) return Object.fromEntries(RESOURCES.map((r) => [r, project(r)])) as Resources }) const canAfford = (cost: Cost) => !!resources.value && resources.value.wood >= cost.wood && resources.value.clay >= cost.clay && resources.value.iron >= cost.iron /** Whole seconds until a server timestamp, never below zero. */ const secondsUntil = (iso: string) => Math.max(0, Math.ceil((Date.parse(iso) - now.value) / 1000)) // Refetch once when the next build order, unit in training or group under way is due, // so new buildings, trained troops and arrivals show up without waiting for a push. const nextDue = computed(() => { const v = village.value if (!v) return null const times = [ ...v.queue.flatMap((o) => (o.finishes_at ? [Date.parse(o.finishes_at)] : [])), ...[v.levy.until, v.starvation.food_empty_at, v.starvation.desertion_at].flatMap((at) => (at ? [Date.parse(at)] : [])), ...v.movements.map((m) => Date.parse(m.arrives_at)), ...v.military.flatMap((m) => m.queue.filter((o) => o.done < o.count).map((o) => Date.parse(o.starts_at) + (o.done + 1) * o.seconds_per_unit * 1000), ), ] return times.length ? Math.min(...times) : null }) watch( () => nextDue.value !== null && now.value >= nextDue.value, (due) => { if (due) refresh() }, ) ws.listenWhileMounted('village:updated', null, (data) => { if (data.village_id === villageId) refresh() }) return { village, resources, /** Milliseconds on the server clock, ticking. */ now, error, busy, canAfford, secondsUntil, refresh, build: (type: BuildingType) => run('village.build', { type }, { optimistic: (v) => { const o = v.buildable.find((b) => b.type === type) if (!o) return pay(v, o.cost) queueOrder(v, { building_id: null, type, action: 'build', target_level: 1, space: o.space, cost: o.cost, villagers: o.villagers }) v.space.used += o.space hold(v, o.villagers) }, }), upgrade: (buildingId: number) => run('village.upgrade', { building_id: buildingId }, { optimistic: (v) => { const b = v.buildings.find((x) => x.id === buildingId) if (!b?.upgrade) return pay(v, b.upgrade.cost) queueOrder(v, { building_id: b.id, type: b.type, action: 'upgrade', target_level: b.upgrade.target_level, space: b.space, cost: b.upgrade.cost, villagers: b.upgrade.villagers }) hold(v, b.upgrade.villagers) }, }), demolish: (buildingId: number) => run('village.demolish', { building_id: buildingId }, { optimistic: (v) => { const b = v.buildings.find((x) => x.id === buildingId) if (!b?.demolish) return queueOrder(v, { building_id: b.id, type: b.type, action: 'demolish', target_level: b.demolish.target_level, space: b.space, cost: { wood: 0, clay: 0, iron: 0 }, villagers: 0 }) }, }), cancel: (orderId: number) => run('village.cancel', { order_id: orderId }, { optimistic: (v) => { const o = v.queue.find((x) => x.id === orderId) if (!o) return v.queue = v.queue.filter((x) => x !== o) pay(v, o.cost, 1) if (o.action === 'build') v.space.used -= o.space hold(v, o.villagers ?? 0, 1) }, }), setPriority: (buildingId: number, priority: number) => run('village.staff', { building_id: buildingId, priority }, { optimistic: (v) => { const b = v.buildings.find((x) => x.id === buildingId) if (b) b.priority = priority }, }), /** One order per unit type, sent one after another; stops at the first refusal. */ recruit: async (buildingId: number, orders: { unit: UnitType; count: number }[]) => { for (const o of orders) { await run('village.recruit', { building_id: buildingId, unit: o.unit, count: o.count }) if (error.value) return false } return true }, cancelRecruit: (orderId: number) => run('village.cancelRecruit', { order_id: orderId }), levy: (count: number) => run('village.levy', { count }), endLevy: () => run('village.endLevy'), /** Target, distance and travel time for the send form; null when the server refuses. */ preview: async (x: number, y: number, units: Units, mode: TravelMode) => { try { return await ws.send('rally.preview', { village_id: villageId, x, y, units, mode }) } catch { return null } }, send: (type: Exclude, x: number, y: number, units: Units, mode: TravelMode, catapultTarget: BuildingType | null) => run('rally.send', { type, x, y, units, mode, catapult_target: catapultTarget }), cancelMovement: (movementId: number) => run('rally.cancel', { movement_id: movementId }), sendHome: (homeVillageId: number) => run('rally.sendHome', { home_village_id: homeVillageId }), withdraw: (hostVillageId: number) => run('rally.withdraw', { host_village_id: hostVillageId }), rename: (name: string) => run('village.rename', { name }), mint: (count: number) => run('village.mint', { count }), } } export type VillageContext = ReturnType const VILLAGE: InjectionKey = Symbol('village') /** The village page shares its one useVillage() with every screen in it. */ export function provideVillage(context: VillageContext) { provide(VILLAGE, context) } export function useVillageContext(): VillageContext { const context = inject(VILLAGE) if (!context) throw new Error('useVillageContext() needs the village page around it.') return context } /** The village of the bar on top, where a page may also stand without one (the map). */ export function useVillageContextOrNull(): VillageContext | null { return inject(VILLAGE, null) }