game-village-politics-frontend/app/mock/server.ts

652 lines
22 KiB
TypeScript
Raw Normal View History

// 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 { MapVillage, MapView } from '~/types/map'
import type { GameAuth, GameWs } from '~/utils/networking'
import {
BASE_TRICKLE,
BUILDERS,
BUILDING_TYPES,
CATALOG,
DEFAULT_PRIORITY,
DEMOLISH_REFUND,
MAX_SPACE,
MAX_LEVEL,
START_RESOURCES,
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
space_max: 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.v2'
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<number, number>()
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<number, number>) => {
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<number, number>) {
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)
}
/** 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 spaceFits = (v: MockVillage, type: BuildingType) => spaceUsed(v) + CATALOG[type].space <= v.space_max
/** 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'
: !spaceFits(v, type)
? 'no_space'
: null
return { type, space: entry.space, target_level: 0, cost, seconds: levelSeconds(type, 0), 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: 0, 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<MockOrder, 'id' | 'builder' | 'starts_at' | 'finishes_at'>, 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,
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: v.space_max },
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,
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, counting level 0. */
const points = (v: MockVillage) => v.buildings.reduce((sum, b) => sum + 5 * (b.level + 1), 0)
/** 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 = 1000
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 r = (Math.imul(x * 73856093 ^ y * 19349663, 1274126177) >>> 0) / 4294967296
const near = Math.abs(x - 500) <= 25 && Math.abs(y - 500) <= 25
if (near && r < 0.08) {
villages.push({
id: -(y * size + x),
x,
y,
name: 'Barbarian village',
points: 20 + Math.floor(r * 1000),
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 }
}
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: 0, 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<string, Handler> = {
'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),
'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, 0)
pay(v, cost)
enqueue(state, v, { building_id: null, type, action: 'build', target_level: 0, 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, 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, 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<number, ReturnType<typeof setTimeout>>()
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<T = any>(event: string, data: object = {}): Promise<T> {
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 }
}