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

1752 lines
69 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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 {
TribePage,
RankingPage,
RankingRow,
Specialisation,
AuthResult,
QuestBookState,
QuestClaimed,
QuestGoal,
QuestLine,
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 { MapMovement, 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
}
/** The wounded of one battle; the mock's battles wound nobody, so only seeded state has them. */
interface MockWounded {
id: number
units: Partial<Record<UnitType, number>>
heals_at: number
}
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<Record<UnitType, number>>
wounded?: MockWounded[]
recruits?: MockRecruit[]
militia?: number
levy_until?: number | null
/** Support standing here, by home village id; it eats here. */
support?: Record<number, Units>
/** When the next mock raid gathers against this village. */
next_raid_at?: number
}
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
/** Raiders (user_id 0) gather until they march. */
marches_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[]
/** Claimed quests per `user:world`. */
quests?: Record<string, string[]>
/** Chat messages; the mock has no other players, so only the player's own talk. */
chat?: { id: number; world_id: number; channel: string; user_id: number; body: string; at: number }[]
/** Tribes, each led by the one user who founded it: the mock has no other players. */
tribes?: { id: number; world_id: number; user_id: number; name: string; tag: string; description: string | null; events: { type: string; payload: Record<string, any>; at: string }[] }[]
}
const STORAGE_KEY = 'vp.mock.v4'
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)
// v3 put the centre at 500|500; v4 puts it at 0|0.
const v3 = localStorage.getItem('vp.mock.v3')
if (v3) {
const state: MockState = JSON.parse(v3)
for (const v of state.villages) {
v.x -= 500
v.y -= 500
}
return state
}
// 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<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 + 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)
}
// Tribes in the mock: one player, so one member, no invites and no diplomacy partners.
const mockTribe = (state: MockState, userId: number, worldId: number) => (state.tribes ?? []).find((t) => t.user_id === userId && t.world_id === worldId) ?? null
const tribeRef = (t: { id: number; name: string; tag: string }) => ({ id: t.id, name: t.name, tag: t.tag })
function tribePage(state: MockState, userId: number, worldId: number): TribePage {
const t = mockTribe(state, userId, worldId)
const user = state.users.find((u) => u.id === userId)
return {
tribe: t
? {
...tribeRef(t),
description: t.description,
role: 'leader',
player_id: userId,
members: [{ player: { id: userId, name: user?.name ?? '?' }, role: 'leader', points: 0, villages: state.villages.filter((v) => v.user_id === userId && v.world_id === worldId).length }],
invites: [],
relations: [],
events: t.events,
}
: null,
invites: [],
max_members: 25,
notice_seconds: 86400,
}
}
/** Village roles as the backend defines them (world.village.specialisation); the mock grants no bonus. */
const ROLES: Specialisation['roles'] = [
{ role: 'resources', buildings: ['timber_camp', 'clay_pit', 'iron_mine'], bonuses: { production: 0.2 } },
{ role: 'military', buildings: ['barracks', 'stable', 'workshop', 'academy'], bonuses: { recruit_speed: 0.2, defense: 0.1 } },
]
function specialisation(v: MockVillage): Specialisation {
const space: Specialisation['space'] = { resources: 0, military: 0 }
for (const b of v.buildings) {
const r = ROLES.find((r) => r.buildings.includes(b.type))
if (r) space[r.role] += CATALOG[b.type].space
}
const total = space.resources + space.military
const role = ROLES.find((r) => total > 0 && space[r.role] >= 16 && space[r.role] / total >= 0.7)?.role ?? null
return { role, space, share: 0.7, min_space: 16, roles: ROLES }
}
/** 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<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)
}
/** 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) },
specialisation: specialisation(v),
tribe: { tribe: mockTribe(state, v.user_id, v.world_id) ? { ...tribeRef(mockTribe(state, v.user_id, v.world_id)!), role: 'leader' } : null, invites: 0 },
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)),
hospital: hospital(v),
military: military(v, now),
movements: movements(state, v, now),
support: support(state, v),
rally: rallyInfo(v),
loyalty: 100,
conquest: { coins: 0, slots: 0, used: 0, next_slot_coins: 1, coin_cost: { wood: 28000, clay: 30000, iron: 25000 }, max_distance: 100 },
villages: state.villages
.filter((o) => o.user_id === v.user_id && o.world_id === v.world_id)
.map((o) => ({ id: o.id, name: o.name, x: o.x, y: o.y, points: points(o) })),
quests: { claimable: questBook(state, v).lines.filter((l) => l.quest?.complete).length, rewards: 0 },
// The mock's crowns stand from the start, all barbarian.
season: {
crowns_at: iso(now - 86_400_000),
count: CROWN_SPOTS.length,
needed: 3,
hold_seconds: 7 * 86400,
crowns: CROWN_SPOTS.map(([x, y], i) => ({ id: -900 - i, name: 'Crown fort', x, y, player: null })),
holder: null,
ends_at: null,
ended_at: null,
winner: null,
},
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),
// Placeholder: production only; the backend lists every effect.
effects: p ? [{ key: 'production', value: round(p.per_hour), resource: p.resource }] : [],
next_effects: null,
}
},
),
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 - MAP_MIN) / 100)}${Math.floor((x - MAP_MIN) / 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
/** The world starts at 0|0: coordinates run from -500 to 499. */
const MAP_MIN = -MAP_SIZE / 2
const BARBARIAN_NAME = 'Barbarian village'
/** A barbarian made up from a hash of the field, around 0|0 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) <= 25 && Math.abs(y) <= 25
return near && r < 0.08 ? { id: -((y - MAP_MIN) * MAP_SIZE + (x - MAP_MIN) + 1), name: BARBARIAN_NAME, points: 20 + Math.floor(r * 1000) } : null
}
/** The season's crown forts, barbarian in the mock, on the backend's ring round 0|0. */
const CROWN_SPOTS: [number, number][] = [[0, -10], [10, -3], [6, 8], [-6, 8], [-10, -3]]
const crownAt = (x: number, y: number) => CROWN_SPOTS.findIndex(([cx, cy]) => cx === x && cy === y)
/** 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 ?? 0)
const cy = Number.isFinite(Number(data.y)) && data.y !== undefined ? Number(data.y) : (own?.y ?? 0)
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(MAP_MIN, Math.min(MAP_MIN + size - w, cx - Math.floor(w / 2)))
const y0 = Math.max(MAP_MIN, Math.min(MAP_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 ?? '?', tribe: ((t) => (t ? { id: t.id, tag: t.tag } : null))(mockTribe(state, player.user_id, player.world_id)) },
own: player.user_id === user.id,
crown: false,
relation: player.user_id === user.id ? 'own' : 'none',
})
continue
}
const crown = crownAt(x, y)
if (crown >= 0) {
villages.push({ id: -900 - crown, x, y, name: 'Crown fort', points: 3000, continent: continentOf(x, y), player: null, own: false, crown: true, relation: 'barbarian' })
continue
}
const barbarian = barbarianAt(x, y)
if (barbarian) {
villages.push({ ...barbarian, x, y, continent: continentOf(x, y), player: null, own: false, crown: false, relation: 'barbarian' })
}
}
}
return { world_id: Number(data.world_id), size, min: MAP_MIN, center: { x: cx, y: cy }, x: x0, y: y0, w, h, villages, movements: mapMovements(state, user) }
}
/** The player's own groups and raids on their villages, sized like the backend's tiers. */
function mapMovements(state: MockState, user: AuthUser): MapMovement[] {
const now = Date.now()
const mine = new Set(state.villages.filter((v) => v.user_id === user.id).map((v) => v.id))
const tier = (units: Units): MapMovement['size'] => {
const n = unitSum(units, () => 1)
return n < 50 ? 'tiny' : n < 250 ? 'small' : n < 1000 ? 'medium' : n < 5000 ? 'large' : 'huge'
}
const end = (id: number) => {
const r = villageRef(state, id)
return { id: r.id, name: r.name, x: r.x, y: r.y }
}
return (state.movements ?? [])
.filter((m) => m.arrives_at > now && (m.user_id === user.id || (m.user_id === RAIDERS && mine.has(m.target_id))))
.map((m) => ({
id: m.id,
type: m.type,
own: m.user_id === user.id,
raid: m.user_id === RAIDERS,
from: end(m.origin_id),
to: end(m.target_id),
sent_at: iso(m.sent_at),
arrives_at: iso(m.arrives_at),
size: tier(m.units),
units: m.user_id === user.id ? counts(m.units) : null,
}))
}
// 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 - 1) % MAP_SIZE) + MAP_MIN, y: Math.floor((-id - 1) / MAP_SIZE) + MAP_MIN, 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)
/** Beds as the backend's level 1 times the level, per hospital; wounded still lying there. */
function hospital(v: MockVillage) {
const wounded = (v.wounded ?? []).filter((w) => w.heals_at > Date.now())
return {
beds: v.buildings.filter((b) => b.type === 'hospital').reduce((n, b) => n + 20 * b.level, 0),
occupied: wounded.reduce((n, w) => n + Object.values(w.units).reduce((a, c) => a + (c ?? 0), 0), 0),
share: 0.5,
heal_seconds: 14400,
wounded: wounded.map((w) => ({ id: w.id, units: w.units, heals_at: iso(w.heals_at) })),
}
}
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<MockMovement, 'id' | 'arrives_at'>) {
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<string, number> =>
Object.fromEntries(unitEntries(units).map(([u, n]) => [u, Math.min(n, Math.round(n * ratio))]))
const left = (units: Units, lost: Record<string, number>): 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<string, number> = {}
const troopsLost = dead(d.troops ?? {}, defenseRatio)
addUnits(defenseLost, troopsLost)
d.troops = left(d.troops ?? {}, troopsLost)
const supporters = new Set<number>()
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')
// A beaten band of raiders leaves half its attack in resources.
const raided = m.user_id === RAIDERS
const each = raided && !won ? Math.floor(attack / 6) : 0
const bounty: Cost | null = raided && !won ? { wood: each, clay: each, iron: each } : null
if (bounty) refund(d, bounty)
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,
raid: raided,
bounty,
}
// 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)
}
/** Raiders have no player. */
const RAIDERS = 0
/**
* Every few minutes the nearest made-up barbarian sends a small band at the village; it
* gathers two minutes before it marches. A crude stand-in for app/Engine/Raiders.php.
*/
function planRaid(state: MockState, v: MockVillage, now: number) {
if ((v.next_raid_at ?? 0) > now || (state.movements ?? []).some((m) => m.user_id === RAIDERS && m.target_id === v.id)) return
let camp: { id: number; x: number; y: number } | null = null
for (let r = 1; r <= 8 && !camp; r++) {
for (let dy = -r; dy <= r && !camp; dy++) {
for (let dx = -r; dx <= r && !camp; dx++) {
const b = Math.max(Math.abs(dx), Math.abs(dy)) === r ? barbarianAt(v.x + dx, v.y + dy) : null
if (b) camp = { id: b.id, x: v.x + dx, y: v.y + dy }
}
}
}
if (!camp) return
const marches = now + 120_000
const m = march(state, {
world_id: v.world_id,
user_id: RAIDERS,
type: 'attack',
mode: DEFAULT_MODE,
origin_id: camp.id,
target_id: v.id,
distance: fieldDistance(camp, v),
units: { spear: 6, sword: 2 },
cargo: null,
sent_at: marches,
})
m.marches_at = marches
v.next_raid_at = m.arrives_at + 600_000
}
/** 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<number>()
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,
raid: m.user_id === RAIDERS,
marches_at: m.marches_at && m.marches_at > now ? iso(m.marches_at) : 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 = 0
let y = 0
while (taken.has(`${x}|${y}`)) {
x = -25 + Math.floor(Math.random() * 51)
y = -25 + 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.
// A short copy of the quest lines with building goals only; the backend has the real book.
const MOCK_QUESTS: Record<QuestLine['line'], Record<string, { goals: [BuildingType, number][]; reward: Cost }>> = {
construction: {
hq_2: { goals: [['headquarters', 2]], reward: { wood: 120, clay: 120, iron: 100 } },
storage_farm_2: { goals: [['storage', 2], ['farm', 2]], reward: { wood: 150, clay: 150, iron: 150 } },
resource_camps: { goals: [['timber_camp', 1], ['clay_pit', 1], ['iron_mine', 1]], reward: { wood: 200, clay: 200, iron: 150 } },
},
army: {
barracks: { goals: [['barracks', 1]], reward: { wood: 250, clay: 220, iron: 120 } },
rally_point: { goals: [['rally_point', 1]], reward: { wood: 100, clay: 100, iron: 100 } },
},
village: {
hiding_place: { goals: [['hiding_place', 1]], reward: { wood: 120, clay: 120, iron: 120 } },
},
}
function questBook(state: MockState, v: MockVillage): QuestBookState {
const claimed = state.quests?.[`${v.user_id}:${v.world_id}`] ?? []
const levels = new Map<string, number>()
for (const own of state.villages.filter((o) => o.user_id === v.user_id && o.world_id === v.world_id)) {
for (const b of own.buildings) levels.set(b.type, Math.max(levels.get(b.type) ?? 0, b.level))
}
const lines = (Object.keys(MOCK_QUESTS) as QuestLine['line'][]).map((line): QuestLine => {
const quests = MOCK_QUESTS[line]
const key = Object.keys(quests).find((k) => !claimed.includes(k))
const goals = key
? quests[key]!.goals.map(([type, need]): QuestGoal => {
const have = levels.get(type) ?? 0
return { kind: 'building', subject: type, have: Math.min(have, need), need, met: have >= need, hint: type }
})
: []
return {
line,
done: Object.keys(quests).filter((k) => claimed.includes(k)).length,
total: Object.keys(quests).length,
quest: key ? { key, goals, reward: quests[key]!.reward, complete: goals.every((g) => g.met) } : null,
quests: Object.keys(quests).map((k) => ({ key: k, claimed: claimed.includes(k) })),
}
})
return { lines, rewards: [], upcoming: [], share: 0.2 }
}
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,
fallen: false,
started_at: iso(Date.now() - 3 * 86_400_000),
players: state.villages.filter((v) => v.world_id === w.id).length,
villages: state.villages.filter((v) => v.world_id === w.id).length,
tribes: (state.tribes ?? []).filter((t) => t.world_id === w.id).length,
crowns_at: iso(Date.now() - 86_400_000),
holder: null,
ends_at: null,
ended_at: null,
winner: null,
})),
// Rough numbers: the backend's config is the truth.
'world.settings': (_state, _user, data) => {
const w = WORLDS.find((w) => w.id === Number(data.world_id)) ?? fail('not_found')
const s = (seconds: number) => Math.round(seconds / w.speed)
return {
id: w.id,
name: w.name,
settings: {
pace: { speed: w.speed, unit_speed: 1, protection: s(3 * 86400), inactive: 14 * 86400 },
village: { space: 40, space_per_hq_level: 5, builders: 2, map_size: 1000 },
combat: { morale: true, luck: 25, night: null, noble_distance: 100, loyalty_drop: [20, 35], loyalty_regen: w.speed },
raids: { every: [s(18 * 3600), s(30 * 3600)], warning: s(3 * 3600), range: 15 },
tribes: { max_members: 25, notice: s(86400) },
season: { crowns: 5, needed: 3, crowns_after: s(30 * 86400), hold: s(7 * 86400) },
},
}
},
'account.show': (state, user) => ({
name: user.name,
email: user.email,
since: iso(Date.now()),
worlds: WORLDS.filter((w) => state.villages.some((v) => v.world_id === w.id && v.user_id === user.id)).map((w) => ({
world: { id: w.id, name: w.name },
villages: state.villages.filter((v) => v.world_id === w.id && v.user_id === user.id).length,
points: 0,
tribe: null,
})),
}),
'account.password': (state, user, data) => {
if (String(data.password ?? '').length < 8) fail('password_short')
return handlers['account.show']!(state, user, data, Date.now())
},
'account.delete': () => ({ deleted: true }),
'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) => {
const v = ownVillage(state, user, data.village_id, now)
planRaid(state, v, now)
return view(state, v, 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<string, number> = {}
const defense: Record<string, number> = {}
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<string, number>, 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)
},
// The mock takes the payment but keeps no coins; the backend has the real slots.
'village.mint': (state, user, data, now) => {
const v = ownVillage(state, user, data.village_id, now)
if (!v.buildings.some((b) => b.type === 'academy')) fail('requires')
const n = Math.max(1, Number(data.count) || 1)
pay(v, { wood: 28000 * n, clay: 30000 * n, iron: 25000 * n })
return view(state, v, now)
},
'quest.index': (state, user, data, now): QuestBookState => questBook(state, ownVillage(state, user, data.village_id, now)),
'quest.claim': (state, user, data, now): QuestClaimed => {
const v = ownVillage(state, user, data.village_id, now)
const line = questBook(state, v).lines.find((l) => l.quest?.key === data.quest)
if (!line?.quest?.complete) fail('quest_open')
const key = `${v.user_id}:${v.world_id}`
state.quests = { ...state.quests, [key]: [...(state.quests?.[key] ?? []), line.quest.key] }
refund(v, line.quest.reward as Cost)
return { book: questBook(state, v), village: view(state, v, now) }
},
// The mock pays no level rewards.
'quest.collect': (state, user, data, now): QuestClaimed => {
const v = ownVillage(state, user, data.village_id, now)
return { book: questBook(state, v), village: view(state, v, now) }
},
'chat.channels': (state, user, data) => [
{ channel: 'world', with: null, unread: 0 },
...(mockTribe(state, user.id, Number(data.world_id)) ? [{ channel: 'tribe', with: null, unread: 0 }] : []),
],
'chat.history': (state, user, data) => ({
channel: String(data.channel),
messages: (state.chat ?? [])
.filter((m) => m.world_id === Number(data.world_id) && m.channel === String(data.channel))
.map((m) => ({ id: m.id, player: { id: m.user_id, name: user.name }, body: m.body, at: iso(m.at) })),
more: false,
}),
'chat.read': (_state, _user, data) => ({ channel: String(data.channel), unread: 0 }),
'chat.open': () => fail('no_player'),
'chat.send': (state, user, data) => {
const body = String(data.body ?? '').trim()
if (!body || body.length > 500) fail('chat_length')
const m = { id: nextId(state), world_id: Number(data.world_id), channel: String(data.channel), user_id: user.id, body, at: Date.now() }
;(state.chat ??= []).push(m)
return { id: m.id, player: { id: user.id, name: user.name }, body, at: iso(m.at) }
},
'tribe.show': (state, user, data) => tribePage(state, user.id, Number(data.world_id)),
'tribe.list': (state, user, data) =>
(state.tribes ?? [])
.filter((t) => t.world_id === Number(data.world_id))
.map((t) => ({ ...tribeRef(t), members: 1, points: 0, relation: t.user_id === user.id ? ('tribe' as const) : ('none' as const) })),
'tribe.found': (state, user, data) => {
const worldId = Number(data.world_id)
if (mockTribe(state, user.id, worldId)) fail('in_tribe')
const name = String(data.name ?? '').trim()
const tag = String(data.tag ?? '').trim()
if (name.length < 3 || name.length > 32 || tag.length < 2 || tag.length > 6) fail('tribe_name')
if ((state.tribes ?? []).some((t) => t.world_id === worldId && (t.name === name || t.tag === tag))) fail('tribe_taken')
;(state.tribes ??= []).push({ id: nextId(state), world_id: worldId, user_id: user.id, name, tag, description: null, events: [{ type: 'founded', payload: { player: user.name }, at: iso(Date.now()) }] })
return tribePage(state, user.id, worldId)
},
'tribe.describe': (state, user, data) => {
const tribe = mockTribe(state, user.id, Number(data.world_id)) ?? fail('no_tribe')
tribe.description = String(data.description ?? '').trim() || null
return tribePage(state, user.id, Number(data.world_id))
},
'tribe.leave': (state, user, data) => {
state.tribes = (state.tribes ?? []).filter((t) => !(t.user_id === user.id && t.world_id === Number(data.world_id)))
return tribePage(state, user.id, Number(data.world_id))
},
'tribe.disband': (state, user, data) => {
state.tribes = (state.tribes ?? []).filter((t) => !(t.user_id === user.id && t.world_id === Number(data.world_id)))
return tribePage(state, user.id, Number(data.world_id))
},
// Only the player's own villages exist in the mock, so the ranking is short.
'ranking.index': (state, user, data): RankingPage => {
const kind = (['players', 'villages', 'attack', 'defense'] as const).find((k) => k === data.kind) ?? 'players'
const mine = state.villages.filter((v) => v.user_id === user.id && v.world_id === Number(data.world_id))
const player = { id: user.id, name: user.name }
const points = (v: MockVillage) => v.buildings.reduce((sum, b) => sum + b.level * 5, 0)
const rows: RankingRow[] =
kind === 'players' && mine.length
? [{ rank: 1, player: { ...player, tribe: null }, value: mine.reduce((sum, v) => sum + points(v), 0), villages: mine.length, own: true }]
: kind === 'villages'
? mine.map((v, i) => ({ rank: i + 1, player: { ...player, tribe: null }, village: { id: v.id, name: v.name, x: v.x, y: v.y }, value: points(v), own: true }))
: []
return { kind, page: 1, pages: 1, rows, own: rows.length ? { rank: 1, page: 1 } : null }
},
'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<number, ReturnType<typeof setTimeout>>()
let marchTimer: ReturnType<typeof setTimeout> | 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<T = any>(event: string, data: object = {}): Promise<T> {
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, terms) {
await delay()
if (!name || !email || !password) fail('invalid_credentials')
if (!terms) fail('terms_required')
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 }
}