From 9e66209ffdd4f7e75c953d64c6a4397930c87d44 Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Wed, 28 Oct 2026 17:57:43 +0100 Subject: [PATCH] feat: in-browser mock server for the M1 village intents Co-Authored-By: Claude Opus 5.5 --- app/mock/catalog.ts | 41 +++ app/mock/server.ts | 623 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 664 insertions(+) create mode 100644 app/mock/catalog.ts create mode 100644 app/mock/server.ts diff --git a/app/mock/catalog.ts b/app/mock/catalog.ts new file mode 100644 index 0000000..b30fea7 --- /dev/null +++ b/app/mock/catalog.ts @@ -0,0 +1,41 @@ +import type { BuildingType, Cost, Resource, Resources } from '~/types/game' + +// Placeholder numbers so the PoC has something to show. They scale linearly with the +// level on purpose: the real values and formulas belong to the backend +// (config/game/buildings.php and app/Game/), not to the client. + +export interface CatalogEntry { + footprint: [number, number] + max_per_village: number | null + /** Level 0 values. Level n costs, takes, needs and produces (n + 1) times as much. */ + cost: Cost + seconds: number + workers: number + production: { resource: Resource; per_hour: number } | null + capacity?: number +} + +export const MAX_LEVEL = 30 +export const BUILDERS = 2 +export const BASE_TRICKLE = 5 +export const VILLAGER_UPKEEP = 1 +export const DEMOLISH_REFUND = 0.5 +export const DEFAULT_PRIORITY = 5 +export const GRID = { w: 10, h: 5 } +export const START_RESOURCES: Resources = { wood: 500, clay: 500, iron: 500, food: 100 } + +export const CATALOG: Record = { + headquarters: { footprint: [3, 3], max_per_village: 1, cost: { wood: 90, clay: 80, iron: 70 }, seconds: 20, workers: 2, production: null }, + storage: { footprint: [2, 2], max_per_village: null, cost: { wood: 60, clay: 50, iron: 40 }, seconds: 15, workers: 1, production: null, capacity: 1000 }, + farm: { footprint: [2, 2], max_per_village: null, cost: { wood: 45, clay: 40, iron: 30 }, seconds: 15, workers: 2, production: { resource: 'food', per_hour: 20 } }, + timber_camp: { footprint: [2, 2], max_per_village: null, cost: { wood: 50, clay: 60, iron: 40 }, seconds: 12, workers: 2, production: { resource: 'wood', per_hour: 30 } }, + clay_pit: { footprint: [2, 2], max_per_village: null, cost: { wood: 65, clay: 50, iron: 40 }, seconds: 12, workers: 2, production: { resource: 'clay', per_hour: 30 } }, + iron_mine: { footprint: [2, 2], max_per_village: null, cost: { wood: 75, clay: 65, iron: 70 }, seconds: 14, workers: 2, production: { resource: 'iron', per_hour: 30 } }, + hiding_place: { footprint: [1, 1], max_per_village: null, cost: { wood: 50, clay: 60, iron: 50 }, seconds: 10, workers: 0, production: null }, + wall: { footprint: [0, 0], max_per_village: 1, cost: { wood: 50, clay: 100, iron: 20 }, seconds: 20, workers: 1, production: null }, + rally_point: { footprint: [1, 1], max_per_village: 1, cost: { wood: 10, clay: 40, iron: 30 }, seconds: 10, workers: 0, production: null }, +} + +export const BUILDING_TYPES = Object.keys(CATALOG) as BuildingType[] + +export const atLevel = (base: number, level: number) => base * (level + 1) diff --git a/app/mock/server.ts b/app/mock/server.ts new file mode 100644 index 0000000..2ac9459 --- /dev/null +++ b/app/mock/server.ts @@ -0,0 +1,623 @@ +// 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, + BuildOption, + BuildOrder, + Building, + BuildingType, + Cost, + GameError, + Offer, + Resource, + Resources, + VillageState, + WorldSummary, +} from '~/types/game' +import type { GameAuth, GameWs } from '~/utils/networking' +import { + BASE_TRICKLE, + BUILDERS, + BUILDING_TYPES, + CATALOG, + DEFAULT_PRIORITY, + DEMOLISH_REFUND, + GRID, + MAX_LEVEL, + START_RESOURCES, + VILLAGER_UPKEEP, + atLevel, +} from './catalog' + +interface MockBuilding { + id: number + type: BuildingType + level: number + x: number + y: number + priority: number +} + +interface MockOrder { + id: number + building_id: number | null + type: BuildingType + action: BuildOrder['action'] + target_level: number + x: number + y: 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 + grid: { w: number; h: number } + resources: Resources + resources_at: number + buildings: MockBuilding[] + orders: MockOrder[] +} + +interface MockState { + seq: number + token: string | null + users: AuthUser[] + villages: MockVillage[] +} + +const STORAGE_KEY = 'vp.mock.v1' +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) + } 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) +} + +function villagers(v: MockVillage) { + return Math.floor(foodBudget(v) / VILLAGER_UPKEEP) +} + +/** Farms first, then by priority, then oldest first. */ +function assignWorkers(v: MockVillage) { + let free = villagers(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 + 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) +} + +/** Cells taken by buildings and by queued new buildings. */ +function occupied(v: MockVillage) { + const cells = new Set() + const mark = (type: BuildingType, x: number, y: number) => { + const [w, h] = CATALOG[type].footprint + for (let dy = 0; dy < h; dy++) for (let dx = 0; dx < w; dx++) cells.add(`${x + dx},${y + dy}`) + } + v.buildings.forEach((b) => mark(b.type, b.x, b.y)) + v.orders.filter((o) => o.action === 'build').forEach((o) => mark(o.type, o.x, o.y)) + return cells +} + +function fits(v: MockVillage, type: BuildingType, x: number, y: number) { + const [w, h] = CATALOG[type].footprint + if (w === 0 || h === 0) return true + if (x < 0 || y < 0 || x + w > v.grid.w || y + h > v.grid.h) return false + const cells = occupied(v) + for (let dy = 0; dy < h; dy++) for (let dx = 0; dx < w; dx++) if (cells.has(`${x + dx},${y + dy}`)) return false + return true +} + +function freeSlot(v: MockVillage, type: BuildingType) { + for (let y = 0; y < v.grid.h; y++) for (let x = 0; x < v.grid.w; x++) if (fits(v, type, x, y)) return { x, y } + return null +} + +/** Level after everything already queued for this building; -1 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 < 0 || 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 < 0 || (current === 0 && 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, 0) + const blocked = + entry.max_per_village !== null && instances(v, type) >= entry.max_per_village + ? 'max_per_village' + : freeSlot(v, type) === null + ? 'no_space' + : null + return { type, footprint: entry.footprint, target_level: 0, cost, seconds: levelSeconds(type, 0), blocked } + }) +} + +// 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: 0, x: o.x, y: o.y, 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 < 0) v.buildings = v.buildings.filter((x) => x !== b) +} + +/** 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] + if (!due) break + settle(v, due.finishes_at!) + v.orders = v.orders.filter((o) => o !== due) + finish(state, v, due) + startWaiting(v, due.finishes_at!) + } + 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) +} + +function view(v: MockVillage, now: number): VillageState { + const assigned = assignWorkers(v) + const pop = villagers(v) + return { + id: v.id, + name: v.name, + x: v.x, + y: v.y, + grid: { ...v.grid }, + 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, + villagers: pop, + workers: [...assigned.values()].reduce((a, b) => a + b, 0), + soldiers: 0, + }, + builders: BUILDERS, + buildings: v.buildings.map( + (b): Building => { + const p = production(b, assigned) + return { + id: b.id, + type: b.type, + level: b.level, + x: b.x, + y: b.y, + footprint: CATALOG[b.type].footprint, + 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, + x: o.x, + y: o.y, + footprint: CATALOG[o.type].footprint, + 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), + } +} + +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, + grid: { ...GRID }, + resources: { ...START_RESOURCES }, + resources_at: now, + buildings: [], + orders: [], + } + for (const type of ['headquarters', 'storage', 'farm'] as const) { + const at = freeSlot(v, type)! + v.buildings.push({ id: nextId(state), type, level: 0, x: at.x, y: at.y, 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(ownVillage(state, user, data.village_id, now), now), + + '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') + const at = + typeof data.x === 'number' && typeof data.y === 'number' + ? fits(v, type, data.x, data.y) + ? { x: data.x, y: data.y } + : fail('no_space') + : (freeSlot(v, type) ?? fail('no_space')) + const cost = levelCost(type, 0) + pay(v, cost) + enqueue(state, v, { building_id: null, type, action: 'build', target_level: 0, x: at.x, y: at.y, cost, seconds: levelSeconds(type, 0) }, now) + return view(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, x: b.x, y: b.y, cost: offer.cost, seconds: offer.seconds }, now) + return view(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, x: b.x, y: b.y, cost: { wood: 0, clay: 0, iron: 0 }, seconds: offer.seconds }, now) + return view(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(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(v, now) + }, + + 'mock.reset': (state, user) => { + state.villages = state.villages.filter((v) => v.user_id !== user.id) + return true + }, +} + +export function createMockServer(): { ws: GameWs; auth: GameAuth } { + const bus = new EventTarget() + const timers = new Map>() + + 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, 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)) + if (next === Infinity) continue + timers.set( + v.id, + setTimeout(() => { + const fresh = load() + const village = fresh.villages.find((x) => x.id === v.id) + if (!village) return + catchUp(fresh, village, Date.now()) + save(fresh) + schedule(fresh) + emit('village:updated', { village_id: v.id }) + }, Math.max(0, next - 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() + 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 } +}