// In-browser stand-in for the backend, used while MOCK_SERVER is on. It answers the same // WS intents with the same payload shapes, keeps its state in localStorage, finishes // build orders on timers and pushes `village:updated`, so the UI behaves as it will live. // Its rules are deliberately crude; nothing here is meant to survive into the backend. import { onUnmounted, ref } from 'vue' import type { AuthResult, AuthUser, BattleReport, BuildOption, BuildOrder, Building, BuildingType, Cost, GameError, MarchPlan, SimulatedBattle, MilitaryBuilding, Movement, MovementType, Offer, RallyInfo, Report, ReportPage, Resource, Resources, SupportGroup, SupportReport, TravelMode, UnitType, Units, VillageRef, VillageState, WorldSummary, } from '~/types/game' import type { MapVillage, MapView } from '~/types/map' import type { GameAuth, GameWs } from '~/utils/networking' import { BARBARIAN_STOCK, BASE_TRICKLE, BUILDERS, BUILDING_TYPES, CANCEL_WINDOW, CATALOG, DEFAULT_MODE, DEFAULT_PRIORITY, DEMOLISH_REFUND, DETECTION, MAX_SPACE, MILITIA_DEFENSE, SPACE_PER_HQ_LEVEL, MAX_LEVEL, START_RESOURCES, TRAVEL_MODES, UNITS, UNIT_TYPES, VILLAGER_UPKEEP, atLevel, } from './catalog' interface MockBuilding { id: number type: BuildingType level: number priority: number } interface MockOrder { id: number building_id: number | null type: BuildingType action: BuildOrder['action'] target_level: number cost: Cost seconds: number builder: number | null starts_at: number | null finishes_at: number | null } interface MockVillage { id: number world_id: number user_id: number name: string x: number y: number /** Base building space; the headquarters level adds to it. */ space_max: number resources: Resources resources_at: number buildings: MockBuilding[] orders: MockOrder[] /** Missing in states stored before recruiting existed. */ troops?: Partial> recruits?: MockRecruit[] militia?: number levy_until?: number | null /** Support standing here, by home village id; it eats here. */ support?: Record } interface MockMovement { id: number world_id: number /** Owner of the troops. */ user_id: number type: MovementType mode: TravelMode /** Village ids; negative for a made-up barbarian. */ origin_id: number target_id: number /** Fields between origin and target, for the way back. */ distance: number units: Units cargo: Cost | null sent_at: number arrives_at: number } type MockReport = Report & { world_id: number; user_id: number } /** Mock levy length; the backend's comes from the world config. */ const LEVY_SECONDS = 120 interface MockRecruit { id: number building_id: number unit: UnitType count: number done: number seconds_per_unit: number /** Per unit. */ cost: Cost starts_at: number finishes_at: number } interface MockState { seq: number token: string | null users: AuthUser[] villages: MockVillage[] /** Missing in states stored before the rally point existed. */ movements?: MockMovement[] reports?: MockReport[] } const STORAGE_KEY = 'vp.mock.v3' const LATENCY_MS = 60 const WORLDS = [ { id: 1, name: 'World 1', slug: 'w1', speed: 1 }, { id: 2, name: 'Dev world', slug: 'dev', speed: 100 }, ] const RESOURCES: Resource[] = ['wood', 'clay', 'iron', 'food'] function fail(code: string): never { throw { code, message: code } satisfies GameError } const delay = () => new Promise((resolve) => setTimeout(resolve, LATENCY_MS)) const iso = (ms: number) => new Date(ms).toISOString() const round = (n: number) => Math.round(n * 100) / 100 const mapCost = (cost: Cost, fn: (n: number) => number): Cost => ({ wood: fn(cost.wood), clay: fn(cost.clay), iron: fn(cost.iron), }) // State lives in localStorage and is re-read per request, so several tabs stay in step. function load(): MockState { try { const raw = localStorage.getItem(STORAGE_KEY) if (raw) return JSON.parse(raw) // v2 counted levels from 0: shift buildings and queued orders up by one. const old = localStorage.getItem('vp.mock.v2') if (old) { const state: MockState = JSON.parse(old) for (const v of state.villages) { v.buildings.forEach((b) => b.level++) v.orders.forEach((o) => o.target_level++) } return state } } catch { // fall through to a fresh state } return { seq: 1, token: null, users: [], villages: [] } } function save(state: MockState) { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)) } catch { // private mode: the mock just forgets on reload } } const nextId = (state: MockState) => state.seq++ // Village rules, crude stand-ins for app/Game/. const levelCost = (type: BuildingType, level: number) => mapCost(CATALOG[type].cost, (n) => atLevel(n, level)) const levelSeconds = (type: BuildingType, level: number) => atLevel(CATALOG[type].seconds, level) const requiredWorkers = (b: MockBuilding) => atLevel(CATALOG[b.type].workers, b.level) function foodBudget(v: MockVillage) { return v.buildings .filter((b) => b.type === 'farm') .reduce((sum, b) => sum + atLevel(CATALOG.farm.production!.per_hour, b.level), 0) } /** Known unit types with a positive count. */ const unitEntries = (units: Units) => Object.entries(units).filter(([unit, n]) => unit in UNITS && (n ?? 0) > 0) as [UnitType, number][] const counts = (units: Units): Units => Object.fromEntries(unitEntries(units)) const hasUnits = (units: Units) => unitEntries(units).length > 0 const unitSum = (units: Units, per: (unit: UnitType) => number) => unitEntries(units).reduce((sum, [u, n]) => sum + per(u) * n, 0) function addUnits(into: Units, units: Units) { for (const [u, n] of unitEntries(units)) into[u] = (into[u] ?? 0) + n return into } /** Food the troops, the support standing here and the units in training eat; it comes out of the villagers' share. */ function soldierUpkeep(v: MockVillage) { const home = unitSum(v.troops ?? {}, (u) => UNITS[u].upkeep) const support = Object.values(v.support ?? {}).reduce((sum, units) => sum + unitSum(units, (u) => UNITS[u].upkeep), 0) return home + support + (v.recruits ?? []).reduce((sum, o) => sum + UNITS[o.unit].upkeep * (o.count - o.done), 0) } function villagers(v: MockVillage) { return Math.max(0, Math.floor((foodBudget(v) - soldierUpkeep(v)) / VILLAGER_UPKEEP)) } /** Drafted villagers, never more than there are. */ const militia = (v: MockVillage) => Math.min(v.militia ?? 0, villagers(v)) /** Farms first, then by priority, then oldest first. */ function assignWorkers(v: MockVillage) { let free = villagers(v) - militia(v) const assigned = new Map() const order = [...v.buildings].sort( (a, b) => Number(b.type === 'farm') - Number(a.type === 'farm') || b.priority - a.priority || a.id - b.id, ) for (const b of order) { const n = Math.min(requiredWorkers(b), free) assigned.set(b.id, n) free -= n } return assigned } const staffing = (b: MockBuilding, assigned: Map) => { const required = requiredWorkers(b) return required === 0 ? 1 : (assigned.get(b.id) ?? 0) / required } /** Linear stand-in for the real staffing curve: empty buildings still make 10%. */ const outputFactor = (ratio: number) => 0.1 + 0.9 * ratio function production(b: MockBuilding, assigned: Map) { const prod = CATALOG[b.type].production if (!prod) return null return { resource: prod.resource, per_hour: atLevel(prod.per_hour, b.level) * outputFactor(staffing(b, assigned)) } } function rates(v: MockVillage): Resources { const assigned = assignWorkers(v) const r: Resources = { wood: BASE_TRICKLE, clay: BASE_TRICKLE, iron: BASE_TRICKLE, food: 0 } for (const b of v.buildings) { const p = production(b, assigned) if (p) r[p.resource] += p.per_hour } r.food -= villagers(v) * VILLAGER_UPKEEP + soldierUpkeep(v) return r } function storageCap(v: MockVillage) { return v.buildings .filter((b) => b.type === 'storage') .reduce((sum, b) => sum + atLevel(CATALOG.storage.capacity!, b.level), 0) } /** stored + rate × elapsed, written back into the village. */ function settle(v: MockVillage, at: number) { const r = rates(v) const cap = storageCap(v) const hours = (at - v.resources_at) / 3_600_000 for (const res of RESOURCES) { v.resources[res] = Math.min(cap, Math.max(0, v.resources[res] + r[res] * hours)) } v.resources_at = at } const canPay = (v: MockVillage, cost: Cost) => v.resources.wood >= cost.wood && v.resources.clay >= cost.clay && v.resources.iron >= cost.iron function pay(v: MockVillage, cost: Cost) { if (!canPay(v, cost)) fail('resources') v.resources.wood -= cost.wood v.resources.clay -= cost.clay v.resources.iron -= cost.iron } function refund(v: MockVillage, amount: Cost) { const cap = storageCap(v) v.resources.wood = Math.min(cap, v.resources.wood + amount.wood) v.resources.clay = Math.min(cap, v.resources.clay + amount.clay) v.resources.iron = Math.min(cap, v.resources.iron + amount.iron) } /** Building space taken by buildings and by queued new buildings. */ function spaceUsed(v: MockVillage) { return ( v.buildings.reduce((sum, b) => sum + CATALOG[b.type].space, 0) + v.orders.filter((o) => o.action === 'build').reduce((sum, o) => sum + CATALOG[o.type].space, 0) ) } const spaceMax = (v: MockVillage) => Math.min(v.space_max, MAX_SPACE) + SPACE_PER_HQ_LEVEL * Math.max(0, (v.buildings.find((b) => b.type === 'headquarters')?.level ?? 1) - 1) const spaceFits = (v: MockVillage, type: BuildingType) => spaceUsed(v) + CATALOG[type].space <= spaceMax(v) /** Level after everything already queued for this building; 0 if it is being removed. */ function queuedLevel(v: MockVillage, b: MockBuilding) { const last = v.orders.filter((o) => o.building_id === b.id).at(-1) return last ? last.target_level : b.level } const instances = (v: MockVillage, type: BuildingType) => v.buildings.filter((b) => b.type === type).length + v.orders.filter((o) => o.action === 'build' && o.type === type).length const isCore = (v: MockVillage, b: MockBuilding) => b.type === 'headquarters' || ((b.type === 'storage' || b.type === 'farm') && v.buildings.filter((o) => o.type === b.type).length === 1) function upgradeOffer(v: MockVillage, b: MockBuilding): Offer | null { const current = queuedLevel(v, b) if (current < 1 || current >= MAX_LEVEL) return null const target = current + 1 const cost = levelCost(b.type, target) return { target_level: target, cost, seconds: levelSeconds(b.type, target), blocked: null } } function demolishOffer(v: MockVillage, b: MockBuilding) { const current = queuedLevel(v, b) if (current < 1 || (current === 1 && isCore(v, b))) return null return { target_level: current - 1, refund: mapCost(levelCost(b.type, current), (n) => Math.floor(n * DEMOLISH_REFUND)), seconds: Math.ceil(levelSeconds(b.type, current) / 2), } } function buildOptions(v: MockVillage): BuildOption[] { return BUILDING_TYPES.map((type) => { const entry = CATALOG[type] const cost = levelCost(type, 1) const blocked = entry.max_per_village !== null && instances(v, type) >= entry.max_per_village ? 'max_per_village' : !spaceFits(v, type) ? 'no_space' : null return { type, space: entry.space, target_level: 1, cost, seconds: levelSeconds(type, 1), blocked, requires: [] } }) } // Build queue: a free builder takes the first waiting order whose building has no earlier order. function startWaiting(v: MockVillage, at: number) { const running = v.orders.filter((o) => o.builder !== null) const busy = new Set(running.map((o) => o.builder)) const blockedBuildings = new Set(running.map((o) => o.building_id).filter((id) => id !== null)) for (const o of v.orders) { if (o.builder !== null) continue if (o.building_id !== null) { if (blockedBuildings.has(o.building_id)) continue blockedBuildings.add(o.building_id) } const builder = Array.from({ length: BUILDERS }, (_, i) => i + 1).find((n) => !busy.has(n)) if (builder === undefined) break busy.add(builder) o.builder = builder o.starts_at = at o.finishes_at = at + o.seconds * 1000 } } function finish(state: MockState, v: MockVillage, o: MockOrder) { if (o.action === 'build') { v.buildings.push({ id: nextId(state), type: o.type, level: 1, priority: DEFAULT_PRIORITY }) return } const b = v.buildings.find((b) => b.id === o.building_id) if (!b) return if (o.action === 'demolish') { refund(v, mapCost(levelCost(b.type, b.level), (n) => Math.floor(n * DEMOLISH_REFUND))) } b.level = o.target_level if (b.level < 1) { v.buildings = v.buildings.filter((x) => x !== b) // Units still in training there go back to work, refunded. for (const r of (v.recruits ?? []).filter((r) => r.building_id === b.id)) { refund(v, mapCost(r.cost, (n) => n * (r.count - r.done))) } v.recruits = (v.recruits ?? []).filter((r) => r.building_id !== b.id) } } // Recruiting: each military building trains its own queue, one unit after another. const doneAt = (o: MockRecruit, at: number) => Math.min(o.count, Math.max(o.done, Math.floor((at - o.starts_at) / (o.seconds_per_unit * 1000)))) /** Move units trained by `at` into the village and drop finished orders. */ function settleRecruits(v: MockVillage, at: number) { v.troops ??= {} for (const o of v.recruits ?? []) { const done = doneAt(o, at) v.troops[o.unit] = (v.troops[o.unit] ?? 0) + done - o.done o.done = done } v.recruits = (v.recruits ?? []).filter((o) => o.done < o.count) } function missingRequirements(v: MockVillage, unit: UnitType) { return Object.entries(UNITS[unit].requires) .filter(([type, level]) => !v.buildings.some((b) => b.type === type && b.level >= (level ?? 0))) .map(([type, level]) => ({ type: type as BuildingType, level: level ?? 0 })) } const secondsPerUnit = (b: MockBuilding, unit: UnitType) => Math.max(1, Math.ceil(UNITS[unit].seconds / (1 + 0.05 * Math.max(0, b.level - 1)))) function military(v: MockVillage, at: number): MilitaryBuilding[] { const pop = villagers(v) - militia(v) return v.buildings .filter((b) => UNIT_TYPES.some((u) => UNITS[u].building === b.type)) .map((b) => ({ building_id: b.id, type: b.type, level: b.level, units: UNIT_TYPES.filter((u) => UNITS[u].building === b.type).map((unit) => { const { cost, upkeep } = UNITS[unit] const requires = missingRequirements(v, unit) const byResources = Math.min(...(['wood', 'clay', 'iron'] as const).map((r) => Math.floor(v.resources[r] / cost[r]))) return { unit, cost, seconds: secondsPerUnit(b, unit), upkeep, max: requires.length ? 0 : Math.max(0, Math.min(byResources, Math.floor(pop / upkeep))), blocked: requires.length ? ('requires' as const) : null, requires, } }), queue: (v.recruits ?? []) .filter((o) => o.building_id === b.id) .map((o) => ({ id: o.id, unit: o.unit, count: o.count, done: doneAt(o, at), seconds_per_unit: o.seconds_per_unit, starts_at: iso(o.starts_at), finishes_at: iso(o.finishes_at), })), })) } /** Process every order that finished before `now`, in order, then settle to `now`. */ function catchUp(state: MockState, v: MockVillage, now: number) { for (;;) { const due = v.orders .filter((o) => o.finishes_at !== null && o.finishes_at <= now) .sort((a, b) => a.finishes_at! - b.finishes_at! || a.id - b.id)[0] const levyEnds = v.levy_until != null && v.levy_until <= now ? v.levy_until : null if (levyEnds !== null && (!due || levyEnds <= due.finishes_at!)) { settle(v, levyEnds) v.militia = 0 v.levy_until = null continue } if (!due) break settle(v, due.finishes_at!) v.orders = v.orders.filter((o) => o !== due) settleRecruits(v, due.finishes_at!) finish(state, v, due) startWaiting(v, due.finishes_at!) } settleRecruits(v, now) settle(v, now) } function enqueue(state: MockState, v: MockVillage, order: Omit, now: number) { v.orders.push({ ...order, id: nextId(state), builder: null, starts_at: null, finishes_at: null }) startWaiting(v, now) } /** Only the warnings: the mock never makes soldiers desert. */ function starvation(v: MockVillage) { const rate = rates(v).food const empty = v.resources.food <= 0.001 return { food_empty_at: rate < 0 && !empty ? iso(v.resources_at + (v.resources.food / -rate) * 3_600_000) : null, since: rate < 0 && empty ? iso(v.resources_at) : null, desertion_at: null, } } function view(state: MockState, v: MockVillage, now: number): VillageState { const assigned = assignWorkers(v) const pop = villagers(v) return { id: v.id, world_id: v.world_id, name: v.name, x: v.x, y: v.y, continent: continentOf(v.x, v.y), points: points(v), space: { used: spaceUsed(v), max: spaceMax(v) }, resources: { ...v.resources }, resources_at: iso(v.resources_at), rates: rates(v), storage_cap: storageCap(v), population: { food_budget: foodBudget(v), upkeep: pop * VILLAGER_UPKEEP + soldierUpkeep(v), villagers: pop, workers: [...assigned.values()].reduce((a, b) => a + b, 0), soldiers: Object.values(v.troops ?? {}).reduce((a, b) => a + (b ?? 0), 0), training: (v.recruits ?? []).reduce((sum, o) => sum + o.count - o.done, 0), }, levy: { militia: militia(v), until: v.levy_until ? iso(v.levy_until) : null, seconds: LEVY_SECONDS }, starvation: starvation(v), troops: Object.fromEntries(Object.entries(v.troops ?? {}).filter(([, n]) => n)), military: military(v, now), movements: movements(state, v, now), support: support(state, v), rally: rallyInfo(v), unread_reports: (state.reports ?? []).filter((r) => r.user_id === v.user_id && r.world_id === v.world_id && !r.read).length, builders: BUILDERS, buildings: v.buildings.map( (b): Building => { const p = production(b, assigned) return { id: b.id, type: b.type, level: b.level, space: CATALOG[b.type].space, priority: b.priority, workers: { assigned: assigned.get(b.id) ?? 0, required: requiredWorkers(b) }, staffing: staffing(b, assigned), production: p ? { resource: p.resource, per_hour: round(p.per_hour) } : null, upgrade: upgradeOffer(v, b), demolish: demolishOffer(v, b), } }, ), queue: v.orders.map((o, i) => ({ id: o.id, building_id: o.building_id, type: o.type, action: o.action, target_level: o.target_level, space: CATALOG[o.type].space, cost: o.cost, position: i + 1, builder: o.builder, starts_at: o.starts_at === null ? null : iso(o.starts_at), finishes_at: o.finishes_at === null ? null : iso(o.finishes_at), })), buildable: buildOptions(v), server_time: iso(now), } } const continentOf = (x: number, y: number) => `K${Math.floor(y / 100)}${Math.floor(x / 100)}` /** Placeholder points: 5 per building level. */ const points = (v: MockVillage) => v.buildings.reduce((sum, b) => sum + 5 * b.level, 0) const MAP_SIZE = 1000 const BARBARIAN_NAME = 'Barbarian village' /** A barbarian made up from a hash of the field, near the map centre only; a player village on the field wins. */ function barbarianAt(x: number, y: number) { const r = (Math.imul(x * 73856093 ^ y * 19349663, 1274126177) >>> 0) / 4294967296 const near = Math.abs(x - 500) <= 25 && Math.abs(y - 500) <= 25 return near && r < 0.08 ? { id: -(y * MAP_SIZE + x), name: BARBARIAN_NAME, points: 20 + Math.floor(r * 1000) } : null } /** Mock map: the stored player villages plus barbarians made up from a hash of the field. */ function mapView(state: MockState, user: AuthUser, data: any): MapView { const size = MAP_SIZE const own = state.villages.find((v) => v.world_id === Number(data.world_id) && v.user_id === user.id) const cx = Number.isFinite(Number(data.x)) && data.x !== undefined ? Number(data.x) : (own?.x ?? 500) const cy = Number.isFinite(Number(data.y)) && data.y !== undefined ? Number(data.y) : (own?.y ?? 500) const w = Math.max(1, Math.min(41, Number(data.w) || 15)) const h = Math.max(1, Math.min(41, Number(data.h) || 15)) const x0 = Math.max(0, Math.min(size - w, cx - Math.floor(w / 2))) const y0 = Math.max(0, Math.min(size - h, cy - Math.floor(h / 2))) const villages: MapVillage[] = [] for (let y = y0; y < y0 + h; y++) { for (let x = x0; x < x0 + w; x++) { const player = state.villages.find((v) => v.world_id === Number(data.world_id) && v.x === x && v.y === y) if (player) { const owner = state.users.find((u) => u.id === player.user_id) villages.push({ id: player.id, x, y, name: player.name, points: points(player), continent: continentOf(x, y), player: { id: player.user_id, name: owner?.name ?? '?' }, own: player.user_id === user.id, }) continue } const barbarian = barbarianAt(x, y) if (barbarian) { villages.push({ ...barbarian, x, y, continent: continentOf(x, y), player: null, own: false }) } } } return { world_id: Number(data.world_id), size, center: { x: cx, y: cy }, x: x0, y: y0, w, h, villages } } // Rally point: marches, battles and reports, crude stand-ins for app/Engine/Rally.php. const REPORTS_PER_PAGE = 25 const LOOTED = ['wood', 'clay', 'iron'] as const function villageRef(state: MockState, id: number): VillageRef { if (id < 0) return { id, name: BARBARIAN_NAME, x: -id % MAP_SIZE, y: Math.floor(-id / MAP_SIZE), player: null } const v = state.villages.find((v) => v.id === id) if (!v) return { id, name: '?', x: 0, y: 0, player: null } const owner = state.users.find((u) => u.id === v.user_id) return { id: v.id, name: v.name, x: v.x, y: v.y, player: { id: v.user_id, name: owner?.name ?? '?' } } } /** The stored player village on a field, else a made-up barbarian, else null. */ function villageAt(state: MockState, worldId: number, x: number, y: number): VillageRef | null { const v = state.villages.find((v) => v.world_id === worldId && v.x === x && v.y === y) if (v) return villageRef(state, v.id) const barbarian = barbarianAt(x, y) return barbarian ? villageRef(state, barbarian.id) : null } const field = (n: unknown) => Math.trunc(Number(n) || 0) const fieldDistance = (a: { x: number; y: number }, b: { x: number; y: number }) => Math.hypot(a.x - b.x, a.y - b.y) const travelMode = (mode: unknown) => TRAVEL_MODES.find((m) => m.mode === mode) const hasRallyPoint = (v: MockVillage) => v.buildings.some((b) => b.type === 'rally_point') /** The slowest unit sets the pace. */ function travelSeconds(units: Units, distance: number, mode: TravelMode) { const slowest = Math.max(0, ...unitEntries(units).map(([u]) => UNITS[u].speed)) return Math.max(1, Math.round((slowest * distance) / (travelMode(mode)?.speed ?? 1))) } /** What the player picked: known unit types with a positive count. */ function pickUnits(raw: unknown): Units { const units: Units = {} for (const [unit, n] of Object.entries(raw && typeof raw === 'object' ? raw : {})) { const count = Math.floor(Number(n) || 0) if (unit in UNITS && count > 0) units[unit as UnitType] = count } return units } /** Catch a village up to `at`, never backwards. */ const advance = (state: MockState, v: MockVillage, at: number) => catchUp(state, v, Math.max(at, v.resources_at)) function march(state: MockState, m: Omit) { const movement: MockMovement = { ...m, id: nextId(state), arrives_at: m.sent_at + travelSeconds(m.units, m.distance, m.mode) * 1000 } ;(state.movements ??= []).push(movement) return movement } /** Survivors head home from the target with what they carry. */ function turnBack(state: MockState, m: MockMovement, units: Units, cargo: Cost | null, at: number) { march(state, { ...m, type: 'return', origin_id: m.target_id, target_id: m.origin_id, units, cargo, sent_at: at }) } /** The support of one home village standing in `host` goes home; settle the host first. */ function sendSupportHome(state: MockState, host: MockVillage, homeId: number, now: number) { const units = counts(host.support?.[homeId] ?? {}) if (!hasUnits(units)) fail('not_found') delete host.support![homeId] const home = state.villages.find((v) => v.id === homeId) // Its home is gone (mock.reset): the troops go with it. if (!home) return march(state, { world_id: host.world_id, user_id: home.user_id, type: 'return', mode: DEFAULT_MODE, origin_id: host.id, target_id: home.id, distance: fieldDistance(host, home), units, cargo: null, sent_at: now, }) } type ReportBody = { type: 'attack' | 'defense'; payload: BattleReport } | { type: 'support'; payload: SupportReport } function writeReport(state: MockState, userId: number, worldId: number, at: number, body: ReportBody) { ;(state.reports ??= []).push({ ...body, id: nextId(state), world_id: worldId, user_id: userId, happened_at: iso(at), read: false }) } /** Per unit: none of them. */ const noLosses = (units: Units) => Object.fromEntries(unitEntries(units).map(([u]) => [u, 0])) /** Barbarians have no troops: the attack always wins and loots the made-up stock. */ function raid(state: MockState, m: MockMovement, at: number) { const capacity = unitSum(m.units, (u) => UNITS[u].carry) const each = Math.floor(Math.min(capacity, 3 * BARBARIAN_STOCK) / 3) const loot: Cost = { wood: each, clay: each, iron: each } writeReport(state, m.user_id, m.world_id, at, { type: 'attack', payload: { won: true, luck: 0, morale: 100, night: false, attacker: { village: villageRef(state, m.origin_id), units: counts(m.units), lost: noLosses(m.units) }, defender: { village: villageRef(state, m.target_id), units: {}, lost: {} }, wall: null, building: null, loot, capacity, }, }) turnBack(state, m, m.units, each > 0 ? loot : null, at) } /** * Total attack against total defence (troops at home, support, militia). The winner loses * (loser / winner)^1.5 of every unit, the loser everything; survivors loot evenly up to their carry. */ function battle(state: MockState, m: MockMovement, d: MockVillage, at: number) { const drafted = militia(d) const defenders = addUnits({}, d.troops ?? {}) for (const units of Object.values(d.support ?? {})) addUnits(defenders, units) const attack = unitSum(m.units, (u) => UNITS[u].attack) const defense = unitSum(defenders, (u) => UNITS[u].defense) + drafted * MILITIA_DEFENSE const won = attack > defense const attackRatio = won ? (defense / attack) ** 1.5 : 1 const defenseRatio = won ? 1 : defense > 0 ? (attack / defense) ** 1.5 : 0 const dead = (units: Units, ratio: number): Record => Object.fromEntries(unitEntries(units).map(([u, n]) => [u, Math.min(n, Math.round(n * ratio))])) const left = (units: Units, lost: Record): Units => Object.fromEntries(unitEntries(units).map(([u, n]) => [u, n - (lost[u] ?? 0)]).filter(([, n]) => Number(n) > 0)) // Defenders fall in every group alike, support included. const defenseLost: Record = {} const troopsLost = dead(d.troops ?? {}, defenseRatio) addUnits(defenseLost, troopsLost) d.troops = left(d.troops ?? {}, troopsLost) const supporters = new Set() for (const [home, units] of Object.entries(d.support ?? {})) { const lost = dead(units, defenseRatio) addUnits(defenseLost, lost) const rest = left(units, lost) if (hasUnits(rest)) d.support![Number(home)] = rest else delete d.support![Number(home)] const owner = state.villages.find((v) => v.id === Number(home))?.user_id if (owner !== undefined && owner !== d.user_id) supporters.add(owner) } const militiaLost = Math.min(drafted, Math.round(drafted * defenseRatio)) if (militiaLost) { d.militia = drafted - militiaLost if (!d.militia) d.levy_until = null } const attackLost = dead(m.units, attackRatio) const survivors = left(m.units, attackLost) const capacity = won ? unitSum(survivors, (u) => UNITS[u].carry) : 0 const loot: Cost = { wood: 0, clay: 0, iron: 0 } for (const r of LOOTED) { loot[r] = Math.floor(Math.min(capacity / 3, d.resources[r])) d.resources[r] -= loot[r] } const wall = d.buildings.find((b) => b.type === 'wall') const report: BattleReport = { won, luck: 0, morale: 100, night: false, attacker: { village: villageRef(state, m.origin_id), units: counts(m.units), lost: attackLost }, defender: { village: villageRef(state, d.id), units: drafted ? { ...defenders, militia: drafted } : { ...defenders }, lost: drafted ? { ...defenseLost, militia: militiaLost } : defenseLost, }, wall: wall ? { before: wall.level, after: wall.level } : null, building: null, loot, capacity, } // An attacker with no survivors learns nothing about the defence. const seen: BattleReport = hasUnits(survivors) ? report : { ...report, defender: { village: report.defender.village, units: null, lost: null }, wall: null } writeReport(state, m.user_id, m.world_id, at, { type: 'attack', payload: seen }) writeReport(state, d.user_id, d.world_id, at, { type: 'defense', payload: report }) supporters.forEach((userId) => writeReport(state, userId, d.world_id, at, { type: 'defense', payload: report })) if (hasUnits(survivors)) turnBack(state, m, survivors, capacity > 0 ? loot : null, at) } /** A movement reaches its target, which was caught up to the arrival first. */ function arrive(state: MockState, m: MockMovement) { const at = m.arrives_at const target = m.target_id > 0 ? state.villages.find((v) => v.id === m.target_id) : undefined if (m.type === 'return') { // Its home is gone (mock.reset): the troops go with it. if (!target) return advance(state, target, at) addUnits((target.troops ??= {}), m.units) if (m.cargo) refund(target, m.cargo) return } if (m.type === 'attack' && m.target_id < 0) return raid(state, m, at) // The target is gone (mock.reset): the group just turns around. if (!target) return turnBack(state, m, m.units, null, at) advance(state, target, at) if (m.type === 'attack') return battle(state, m, target, at) target.support ??= {} target.support[m.origin_id] = addUnits({ ...target.support[m.origin_id] }, m.units) const report: SupportReport = { from: villageRef(state, m.origin_id), to: villageRef(state, target.id), units: counts(m.units) } writeReport(state, m.user_id, m.world_id, at, { type: 'support', payload: report }) if (target.user_id !== m.user_id) writeReport(state, target.user_id, m.world_id, at, { type: 'support', payload: report }) } /** Handle every movement that arrived by `now`, in arrival order; returns the villages involved. */ function processMovements(state: MockState, now: number) { const touched = new Set() for (;;) { const due = (state.movements ?? []) .filter((m) => m.arrives_at <= now) .sort((a, b) => a.arrives_at - b.arrives_at || a.id - b.id)[0] if (!due) break state.movements = state.movements!.filter((m) => m !== due) arrive(state, due) touched.add(due.origin_id).add(due.target_id) } return [...touched].filter((id) => id > 0) } /** Own groups leaving here or coming home here, and every group coming here; strangers' show no details. */ function movements(state: MockState, v: MockVillage, now: number): Movement[] { return (state.movements ?? []) .filter((m) => (m.type === 'return' ? m.target_id === v.id : m.origin_id === v.id || m.target_id === v.id)) .sort((a, b) => a.arrives_at - b.arrives_at || a.id - b.id) .map((m): Movement => { const direction: Movement['direction'] = m.type === 'return' ? 'home' : m.origin_id === v.id ? 'out' : 'in' const mine = m.user_id === v.user_id const cancelUntil = m.sent_at + CANCEL_WINDOW * 1000 return { id: m.id, type: m.type, direction, mode: mine ? m.mode : null, from: villageRef(state, m.origin_id), to: villageRef(state, m.target_id), units: mine ? counts(m.units) : null, cargo: mine ? m.cargo : null, sent_at: mine ? iso(m.sent_at) : null, arrives_at: iso(m.arrives_at), cancel_until: mine && direction === 'out' && cancelUntil > now ? iso(cancelUntil) : null, } }) } function support(state: MockState, v: MockVillage): VillageState['support'] { const group = (villageId: number, units: Units): SupportGroup => ({ village: villageRef(state, villageId), units: counts(units) }) return { here: Object.entries(v.support ?? {}) .filter(([, units]) => hasUnits(units)) .map(([home, units]) => group(Number(home), units)), away: state.villages .filter((host) => host.world_id === v.world_id && hasUnits(host.support?.[v.id] ?? {})) .map((host) => group(host.id, host.support![v.id]!)), } } function rallyInfo(v: MockVillage): RallyInfo { return { has_rally_point: hasRallyPoint(v), modes: TRAVEL_MODES.map((m) => ({ ...m })), default_mode: DEFAULT_MODE, detection: DETECTION + (v.buildings.find((b) => b.type === 'watchtower')?.level ?? 0), cancel_window: CANCEL_WINDOW, // The mock skips beginner protection. protected_until: null, } } const presentReport = (r: MockReport) => ({ id: r.id, type: r.type, happened_at: r.happened_at, read: r.read, payload: r.payload }) as Report /** The player's reports on a world, newest first. */ function reportPage(state: MockState, user: AuthUser, worldId: number, page = 1, type: string | null = null): ReportPage { const mine = (state.reports ?? []) .filter((r) => r.user_id === user.id && r.world_id === worldId) .sort((a, b) => Date.parse(b.happened_at) - Date.parse(a.happened_at) || b.id - a.id) const shown = type ? mine.filter((r) => r.type === type) : mine const pages = Math.max(1, Math.ceil(shown.length / REPORTS_PER_PAGE)) const current = Math.max(1, Math.min(pages, Math.floor(page) || 1)) return { reports: shown.slice((current - 1) * REPORTS_PER_PAGE, current * REPORTS_PER_PAGE).map(presentReport), page: current, pages, unread: mine.filter((r) => !r.read).length, } } function createVillage(state: MockState, user: AuthUser, worldId: number, now: number): MockVillage { const taken = new Set(state.villages.filter((v) => v.world_id === worldId).map((v) => `${v.x}|${v.y}`)) let x = 500 let y = 500 while (taken.has(`${x}|${y}`)) { x = 475 + Math.floor(Math.random() * 51) y = 475 + Math.floor(Math.random() * 51) } const v: MockVillage = { id: nextId(state), world_id: worldId, user_id: user.id, name: `${user.name}'s village`, x, y, space_max: MAX_SPACE, resources: { ...START_RESOURCES }, resources_at: now, buildings: [], orders: [], } for (const type of ['headquarters', 'storage', 'farm'] as const) { v.buildings.push({ id: nextId(state), type, level: 1, priority: DEFAULT_PRIORITY }) } return v } // WS intents. type Handler = (state: MockState, user: AuthUser, data: any, now: number) => unknown function ownVillage(state: MockState, user: AuthUser, id: unknown, now: number) { const v = state.villages.find((v) => v.id === Number(id) && v.user_id === user.id) if (!v) fail('not_found') catchUp(state, v, now) return v } function ownBuilding(v: MockVillage, id: unknown) { return v.buildings.find((b) => b.id === Number(id)) ?? fail('not_found') } const handlers: Record = { 'world.index': (state, user): WorldSummary[] => WORLDS.map((w) => ({ ...w, village_id: state.villages.find((v) => v.world_id === w.id && v.user_id === user.id)?.id ?? null, })), 'world.join': (state, user, data, now) => { const world = WORLDS.find((w) => w.id === Number(data.world_id)) ?? fail('not_found') let v = state.villages.find((v) => v.world_id === world.id && v.user_id === user.id) if (!v) { v = createVillage(state, user, world.id, now) state.villages.push(v) } return { village_id: v.id } }, 'village.show': (state, user, data, now) => view(state, ownVillage(state, user, data.village_id, now), now), 'map.view': (state, user, data) => mapView(state, user, data), 'village.build': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) const type = data.type as BuildingType const entry = CATALOG[type] ?? fail('not_found') if (entry.max_per_village !== null && instances(v, type) >= entry.max_per_village) fail('max_per_village') if (!spaceFits(v, type)) fail('no_space') const cost = levelCost(type, 1) pay(v, cost) enqueue(state, v, { building_id: null, type, action: 'build', target_level: 1, cost, seconds: levelSeconds(type, 1) }, now) return view(state, v, now) }, 'village.upgrade': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) const b = ownBuilding(v, data.building_id) const offer = upgradeOffer(v, b) ?? fail('max_level') pay(v, offer.cost) enqueue(state, v, { building_id: b.id, type: b.type, action: 'upgrade', target_level: offer.target_level, cost: offer.cost, seconds: offer.seconds }, now) return view(state, v, now) }, 'village.demolish': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) const b = ownBuilding(v, data.building_id) const offer = demolishOffer(v, b) ?? fail('core_building') enqueue(state, v, { building_id: b.id, type: b.type, action: 'demolish', target_level: offer.target_level, cost: { wood: 0, clay: 0, iron: 0 }, seconds: offer.seconds }, now) return view(state, v, now) }, // Cancelling also cancels later orders for the same building, since they build on it. 'village.cancel': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) const order = v.orders.find((o) => o.id === Number(data.order_id)) ?? fail('not_found') const index = v.orders.indexOf(order) const cancelled = v.orders.filter( (o, i) => o === order || (i > index && order.building_id !== null && o.building_id === order.building_id), ) v.orders = v.orders.filter((o) => !cancelled.includes(o)) cancelled.forEach((o) => refund(v, o.cost)) startWaiting(v, now) return view(state, v, now) }, 'village.staff': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) const b = ownBuilding(v, data.building_id) b.priority = Math.min(9, Math.max(0, Math.round(Number(data.priority) || 0))) return view(state, v, now) }, 'village.recruit': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) const b = ownBuilding(v, data.building_id) const unit = data.unit as UnitType const entry = UNITS[unit] if (!entry || entry.building !== b.type) fail('not_found') const count = Math.floor(Number(data.count) || 0) if (count < 1) fail('count') if (missingRequirements(v, unit).length) fail('requires') if (count * entry.upkeep > villagers(v) - militia(v)) fail('villagers') pay(v, mapCost(entry.cost, (n) => n * count)) const seconds = secondsPerUnit(b, unit) const last = (v.recruits ?? []).filter((o) => o.building_id === b.id).at(-1) const starts = last && last.finishes_at > now ? last.finishes_at : now v.recruits = [ ...(v.recruits ?? []), { id: nextId(state), building_id: b.id, unit, count, done: 0, seconds_per_unit: seconds, cost: entry.cost, starts_at: starts, finishes_at: starts + seconds * count * 1000 }, ] return view(state, v, now) }, // Refunds the untrained units; later orders at the same building move up. 'village.cancelRecruit': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) const order = (v.recruits ?? []).find((o) => o.id === Number(data.order_id)) ?? fail('not_found') refund(v, mapCost(order.cost, (n) => n * (order.count - order.done))) v.recruits = (v.recruits ?? []).filter((o) => o !== order) let from = now for (const o of v.recruits.filter((o) => o.building_id === order.building_id)) { if (o.id < order.id) { from = Math.max(now, o.finishes_at) continue } o.starts_at = from o.finishes_at = from + o.seconds_per_unit * o.count * 1000 from = o.finishes_at } return view(state, v, now) }, 'village.levy': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) const count = Math.floor(Number(data.count) || 0) if (v.militia) fail('levy_active') if (count < 1) fail('count') if (count > villagers(v)) fail('villagers') v.militia = count v.levy_until = now + LEVY_SECONDS * 1000 return view(state, v, now) }, 'village.endLevy': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) if (!v.militia) fail('not_found') v.militia = 0 v.levy_until = null return view(state, v, now) }, 'village.rename': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) const name = String(data.name ?? '').replace(/s+/g, ' ').trim() if (!name || name.length > 32) fail('name') v.name = name return view(state, v, now) }, 'rally.simulate': (_state, _user, data): SimulatedBattle => { // Crude stand-in for the backend's CombatResolver: totals against totals. const attack: Record = {} const defense: Record = {} for (const [u, n] of Object.entries(data.attack ?? {})) if (Number(n) > 0 && u in UNITS) attack[u] = Number(n) for (const [u, n] of Object.entries(data.defense ?? {})) if (Number(n) > 0 && (u in UNITS || u === 'militia')) defense[u] = Number(n) const a = Object.entries(attack).reduce((s, [u, n]) => s + n * UNITS[u as UnitType].attack, 0) const d = Object.entries(defense).reduce((s, [u, n]) => s + n * (u === 'militia' ? 5 : UNITS[u as UnitType].defense), 0) + 20 * Number(data.wall || 0) const won = a > d const ratio = won ? (d / a) ** 1.5 : a > 0 ? (a / d) ** 1.5 : 0 const dead = (units: Record, loss: number) => Object.fromEntries(Object.entries(units).map(([u, n]) => [u, Math.min(n, Math.round(n * loss))])) return { won, attacker: { units: attack, lost: dead(attack, won ? ratio : 1) }, defender: { units: defense, lost: dead(defense, won ? 1 : ratio) }, wall: Number(data.wall) > 0 ? { before: Number(data.wall), after: Number(data.wall) } : null, building: null, power: { attack: a, defense: d }, } }, 'rally.preview': (state, user, data, now): MarchPlan => { const v = ownVillage(state, user, data.village_id, now) const mode = travelMode(data.mode)?.mode ?? DEFAULT_MODE const units = pickUnits(data.units) const x = field(data.x) const y = field(data.y) const distance = fieldDistance(v, { x, y }) return { x, y, target: villageAt(state, v.world_id, x, y), mode, distance: round(distance), seconds: hasUnits(units) && distance > 0 ? travelSeconds(units, distance, mode) : null, } }, // The troops leave at once. The mock knows no catapult damage, so catapult_target is ignored. 'rally.send': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) const type = data.type as MovementType if (type !== 'attack' && type !== 'support') fail('not_found') if (!hasRallyPoint(v)) fail('no_rally_point') const mode = data.mode ? (travelMode(data.mode) ?? fail('not_found')).mode : DEFAULT_MODE const units = pickUnits(data.units) if (!hasUnits(units)) fail('count') if (unitEntries(units).some(([u, n]) => n > (v.troops?.[u] ?? 0))) fail('troops') const target = villageAt(state, v.world_id, field(data.x), field(data.y)) ?? fail('not_found') if (target.id === v.id) fail('same_village') if (type === 'attack' && target.player?.id === user.id) fail('own_village') if (type === 'support' && !target.player) fail('barbarian') v.troops ??= {} for (const [u, n] of unitEntries(units)) v.troops[u] = (v.troops[u] ?? 0) - n march(state, { world_id: v.world_id, user_id: user.id, type, mode, origin_id: v.id, target_id: target.id, distance: fieldDistance(v, target), units, cargo: null, sent_at: now, }) return view(state, v, now) }, // Within the window the group turns around where it is: home after as long as it was under way. 'rally.cancel': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) const m = (state.movements ?? []).find((m) => m.id === Number(data.movement_id) && m.origin_id === v.id && m.type !== 'return') ?? fail('not_found') if (now > m.sent_at + CANCEL_WINDOW * 1000 || m.arrives_at <= now) fail('too_late') const elapsed = now - m.sent_at m.type = 'return' m.origin_id = m.target_id m.target_id = v.id m.sent_at = now m.arrives_at = now + elapsed return view(state, v, now) }, // The host sends support standing here home. 'rally.sendHome': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) sendSupportHome(state, v, Number(data.home_village_id), now) return view(state, v, now) }, // This village calls its support at a host back. 'rally.withdraw': (state, user, data, now) => { const v = ownVillage(state, user, data.village_id, now) const host = state.villages.find((h) => h.id === Number(data.host_village_id) && h.id !== v.id) ?? fail('not_found') advance(state, host, now) sendSupportHome(state, host, v.id, now) return view(state, v, now) }, 'report.index': (state, user, data): ReportPage => reportPage(state, user, Number(data.world_id), Number(data.page) || 1, data.type || null), // Opening a report marks it read. 'report.show': (state, user, data): Report => { const report = (state.reports ?? []).find((r) => r.id === Number(data.id) && r.user_id === user.id) ?? fail('not_found') report.read = true return presentReport(report) }, 'report.delete': (state, user, data): ReportPage => { const worldId = Number(data.world_id) const ids = new Set((Array.isArray(data.ids) ? data.ids : []).map(Number)) state.reports = (state.reports ?? []).filter((r) => !(r.user_id === user.id && r.world_id === worldId && ids.has(r.id))) return reportPage(state, user, worldId) }, 'report.readAll': (state, user, data): ReportPage => { const worldId = Number(data.world_id) for (const r of state.reports ?? []) { if (r.user_id === user.id && r.world_id === worldId) r.read = true } return reportPage(state, user, worldId) }, // Also drops the player's marches and reports; others' support standing in the removed villages goes home. 'mock.reset': (state, user, _data, now) => { const gone = state.villages.filter((v) => v.user_id === user.id) const goneIds = new Set(gone.map((v) => v.id)) for (const host of gone) { for (const [home, units] of Object.entries(host.support ?? {})) { if (!goneIds.has(Number(home)) && hasUnits(units)) sendSupportHome(state, host, Number(home), now) } } state.villages = state.villages.filter((v) => !goneIds.has(v.id)) for (const v of state.villages) goneIds.forEach((id) => delete v.support?.[id]) state.movements = (state.movements ?? []).filter((m) => m.user_id !== user.id) state.reports = (state.reports ?? []).filter((r) => r.user_id !== user.id) return true }, } export function createMockServer(): { ws: GameWs; auth: GameAuth } { const bus = new EventTarget() const timers = new Map>() let marchTimer: ReturnType | undefined const emit = (event: string, data: unknown) => bus.dispatchEvent(new CustomEvent(event, { detail: { event, data, channel: 'websocket' } })) // Fire `village:updated` when a village's next order finishes or the next movement // arrives (for both ends), like the game:events worker. function schedule(state: MockState) { for (const v of state.villages) { clearTimeout(timers.get(v.id)) const next = Math.min( ...v.orders.map((o) => o.finishes_at ?? Infinity), ...(v.recruits ?? []).map((o) => o.finishes_at), v.levy_until ?? Infinity, ) if (next === Infinity) continue timers.set( v.id, setTimeout(() => { const fresh = load() const now = Date.now() const touched = processMovements(fresh, now) const village = fresh.villages.find((x) => x.id === v.id) if (village) catchUp(fresh, village, now) save(fresh) schedule(fresh) new Set([...touched, ...(village ? [v.id] : [])]).forEach((id) => emit('village:updated', { village_id: id })) }, Math.max(0, next - Date.now()) + 20), ) } clearTimeout(marchTimer) const arrival = Math.min(...(state.movements ?? []).map((m) => m.arrives_at)) if (arrival === Infinity) return marchTimer = setTimeout(() => { const fresh = load() const touched = processMovements(fresh, Date.now()) save(fresh) schedule(fresh) touched.forEach((id) => emit('village:updated', { village_id: id })) }, Math.max(0, arrival - Date.now()) + 20) } function currentUser(state: MockState) { return state.users.find((u) => state.token === `mock-${u.id}`) ?? fail('unauthenticated') } function signIn(state: MockState, user: AuthUser): AuthResult { state.token = `mock-${user.id}` save(state) return { token: state.token, user } } function addUser(state: MockState, name: string, email: string) { const user = { id: nextId(state), name, email } state.users.push(user) return user } function listen(event: string, _channel: string | null | undefined, callback: (data: any) => void) { const handler = (e: Event) => callback((e as CustomEvent).detail.data) bus.addEventListener(event, handler) return () => bus.removeEventListener(event, handler) } const ws: GameWs = { is_setup: ref(true), is_opened: ref(true), resetConnection() {}, listen, listenWhileMounted(event, channel, callback) { const off = listen(event, channel, callback) onUnmounted(off) return off }, async send(event: string, data: object = {}): Promise { await delay() const handler = handlers[event] ?? fail('not_found') const state = load() const now = Date.now() // Arrivals first, for every village, so the handler sees the world as of now. processMovements(state, now) const result = handler(state, currentUser(state), data, now) save(state) schedule(state) return structuredClone(result) as T }, } const auth: GameAuth = { token: () => load().token, async login(email, password) { await delay() if (!email || !password) fail('invalid_credentials') const state = load() const user = state.users.find((u) => u.email.toLowerCase() === email.toLowerCase()) ?? addUser(state, email.split('@')[0] || email, email) return signIn(state, user) }, async register(name, email, password) { await delay() if (!name || !email || !password) fail('invalid_credentials') const state = load() if (state.users.some((u) => u.email.toLowerCase() === email.toLowerCase())) fail('email_taken') return signIn(state, addUser(state, name, email)) }, logout() { const state = load() state.token = null save(state) }, } return { ws, auth } }