// The mock's market: merchants, deliveries, offers and trade routes, a crude stand-in for // the backend's market. Its numbers are placeholders; the backend is the source of truth. // A few made-up traders of other players live round 0|0, so the world's market has offers // and sends can go somewhere; they take a unit of the player's own offers now and then. import type { AuthUser, Cost, GameError, MarketOffers, MarketState, Trade, TradePlan, TradeReport, TradeResource, TradeRoute, TradeSide, VillageMarket, VillageRef, WorldOffer, } from '~/types/game' import type { MockState, MockVillage } from './server' /** What one merchant carries. */ const CARRY = 1000 /** Merchants walk fast in the mock, so deliveries arrive while you watch: 6 s per field. */ const MINUTES_PER_FIELD = 0.1 const MAX_RATIO = 3 const ROUTE_MIN_EVERY = 600 const ROUTE_MAX_EVERY = 86_400 /** A trader takes one unit of an own offer this long after it was posted, then again and again. */ const TAKE_AFTER_MS = 90_000 const TAKE_EVERY_MS = 150_000 const RESOURCES: TradeResource[] = ['wood', 'clay', 'iron'] export const merchantsAt = (level: number) => 2 * Math.max(1, level) const maxRoutes = (level: number) => 2 + Math.floor(level / 5) /** Merchants carrying one load: the backend's ceil(amount / carry). */ const merchantsFor = (amount: number) => Math.ceil(amount / CARRY) const sum = (c: Cost) => c.wood + c.clay + c.iron const none = (): Cost => ({ wood: 0, clay: 0, iron: 0 }) const one = (side: TradeSide, times = 1): Cost => ({ ...none(), [side.resource]: side.amount * times }) /** Merchants under way: a delivery with its cargo, or the way home. */ export interface MockTrade { id: number world_id: number /** Village whose merchants these are. */ owner_id: number kind: 'deliver' | 'return' from_id: number to_id: number cargo: Cost | null merchants: number sent_at: number arrives_at: number route_id: number | null offer: boolean } export interface MockOffer { id: number world_id: number village_id: number give: TradeSide want: TradeSide count: number /** Per unit of count. */ merchants: number created_at: number /** Own offers only: when a trader takes the next unit. */ next_take_at?: number } export interface MockRoute { id: number world_id: number village_id: number to_id: number resources: Cost every: number next_at: number paused: boolean paused_reason: null | 'owner_changed' last_sent_at: number | null last_cargo: Cost | null } export interface MockMarket { trades: MockTrade[] offers: MockOffer[] routes: MockRoute[] } /** What the market needs from the rest of the mock server. */ export interface MarketHost { ownVillage: (state: MockState, user: AuthUser, id: unknown, now: number) => MockVillage villageRef: (state: MockState, id: number) => VillageRef villageAt: (state: MockState, worldId: number, x: number, y: number) => VillageRef | null /** Catch a village up to `at`, never backwards. */ advance: (state: MockState, v: MockVillage, at: number) => void /** Add to the stock, up to the storage cap. */ refund: (v: MockVillage, amount: Cost) => void /** Take from the stock; fails with `resources`. */ pay: (v: MockVillage, cost: Cost) => void nextId: (state: MockState) => number writeReport: (state: MockState, userId: number, worldId: number, at: number, body: { type: 'trade'; payload: TradeReport }) => void } function fail(code: string): never { throw { code, message: code } satisfies GameError } const iso = (ms: number) => new Date(ms).toISOString() const amount = (n: unknown) => Math.max(0, Math.floor(Number(n) || 0)) const distance = (a: { x: number; y: number }, b: { x: number; y: number }) => Math.hypot(a.x - b.x, a.y - b.y) const tripSeconds = (fields: number) => Math.max(1, Math.round(fields * MINUTES_PER_FIELD * 60)) // The made-up traders: other players' villages round 0|0, below the barbarians' ids. const TRADERS: VillageRef[] = [ { id: -2_000_001, name: 'Eichenau', x: 7, y: -14, player: { id: -101, name: 'Hagen' } }, { id: -2_000_002, name: 'Rabenfeld', x: -13, y: 5, player: { id: -102, name: 'Brunhild' } }, { id: -2_000_003, name: 'Moorbach', x: 16, y: 12, player: { id: -103, name: 'Wendel' } }, { id: -2_000_004, name: 'Steinach', x: -18, y: -16, player: { id: -104, name: 'Gerlind' } }, { id: -2_000_005, name: 'Aschental', x: 21, y: -4, player: { id: -105, name: 'Ortwin' } }, ] export const traderRef = (id: number) => TRADERS.find((t) => t.id === id) ?? null export const traderAt = (x: number, y: number) => TRADERS.find((t) => t.x === x && t.y === y) ?? null const data = (state: MockState): MockMarket => (state.market ??= { trades: [], offers: [], routes: [] }) const marketOf = (v: MockVillage) => v.buildings.find((b) => b.type === 'market') ?? null const ownerOf = (state: MockState, villageId: number) => state.villages.find((v) => v.id === villageId) /** Merchants out with trades, home-bound included, and held back for open offers. */ function busy(state: MockState, v: MockVillage) { const m = data(state) return ( m.trades.filter((t) => t.owner_id === v.id).reduce((n, t) => n + t.merchants, 0) + m.offers.filter((o) => o.village_id === v.id).reduce((n, o) => n + o.count * o.merchants, 0) ) } function freeMerchants(state: MockState, v: MockVillage) { const b = marketOf(v) return b ? Math.max(0, merchantsAt(b.level) - busy(state, v)) : 0 } /** The village payload's market. */ export function villageMarket(state: MockState, v: MockVillage): VillageMarket | null { const b = marketOf(v) if (!b) return null return { building_id: b.id, level: b.level, merchants: merchantsAt(b.level), free: freeMerchants(state, v), carry: CARRY } } /** The market's effects for the building list: merchants now and one level up. */ export const marketEffects = (level: number) => ({ effects: [{ key: 'merchants' as const, value: merchantsAt(level) }], next_effects: [{ key: 'merchants' as const, value: merchantsAt(level + 1) }], }) function view(state: MockState, host: MarketHost, v: MockVillage, now: number): MarketState { const b = marketOf(v) const m = data(state) const ref = (id: number) => host.villageRef(state, id) const trades = m.trades .filter((t) => t.owner_id === v.id || (t.kind === 'deliver' && t.to_id === v.id)) .sort((a, b) => a.arrives_at - b.arrives_at || a.id - b.id) .map( (t): Trade => ({ id: t.id, kind: t.owner_id === v.id ? (t.kind === 'deliver' ? 'out' : 'back') : 'in', from: ref(t.from_id), to: ref(t.to_id), cargo: t.kind === 'deliver' ? t.cargo : null, merchants: t.merchants, sent_at: iso(t.sent_at), arrives_at: iso(t.arrives_at), route_id: t.route_id, offer: t.offer, }), ) return { server_time: iso(now), market: b ? { building_id: b.id, level: b.level, merchants: merchantsAt(b.level), free: freeMerchants(state, v), busy: busy(state, v), carry: CARRY, minutes_per_field: MINUTES_PER_FIELD, resources: [...RESOURCES], max_ratio: MAX_RATIO, route: { min_every: ROUTE_MIN_EVERY, max_every: ROUTE_MAX_EVERY, max_routes: maxRoutes(b.level) }, } : null, trades, offers: m.offers .filter((o) => o.village_id === v.id) .map((o) => ({ id: o.id, give: o.give, want: o.want, count: o.count, merchants: o.merchants, created_at: iso(o.created_at) })), routes: m.routes .filter((r) => r.village_id === v.id) .map( (r): TradeRoute => ({ id: r.id, to: ref(r.to_id), resources: r.resources, every: r.every, next_at: iso(r.next_at), paused: r.paused, paused_reason: r.paused_reason, last_sent_at: r.last_sent_at === null ? null : iso(r.last_sent_at), last_cargo: r.last_cargo, }), ), } } /** The village on a field for a delivery: not this one, not barbarian. */ function target(state: MockState, host: MarketHost, v: MockVillage, x: unknown, y: unknown) { const ref = host.villageAt(state, v.world_id, Math.trunc(Number(x) || 0), Math.trunc(Number(y) || 0)) ?? fail('not_found') if (ref.id === v.id) fail('same_village') if (!ref.player) fail('barbarian') return ref } function deliver(state: MockState, host: MarketHost, t: Omit, fields: number) { const trade: MockTrade = { ...t, id: host.nextId(state), kind: 'deliver', arrives_at: t.sent_at + tripSeconds(fields) * 1000 } data(state).trades.push(trade) return trade } /** Pick up to the amounts from the cargo picked, as far as the stock and `merchants` carry. */ function load(v: MockVillage, wanted: Cost, merchants: number): Cost { const cargo = Object.fromEntries(RESOURCES.map((r) => [r, Math.min(wanted[r], Math.floor(v.resources[r]))])) as Cost const room = merchants * CARRY const total = sum(cargo) if (total <= room) return cargo const k = room / total return Object.fromEntries(RESOURCES.map((r) => [r, Math.floor(cargo[r] * k)])) as Cost } function runRoute(state: MockState, host: MarketHost, r: MockRoute, at: number) { r.next_at = at + r.every * 1000 const v = state.villages.find((x) => x.id === r.village_id) if (!v || !marketOf(v)) return const to = host.villageRef(state, r.to_id) // The target was taken or vanished: the route stops until the player looks at it. if (!to.player || (r.to_id > 0 && !ownerOf(state, r.to_id))) { r.paused = true r.paused_reason = 'owner_changed' return } host.advance(state, v, at) const cargo = load(v, r.resources, freeMerchants(state, v)) // Like the backend, a run that sends nothing still counts as the last run, with an empty cargo. r.last_sent_at = at r.last_cargo = cargo if (sum(cargo) <= 0) return host.pay(v, cargo) deliver(state, host, { world_id: v.world_id, owner_id: v.id, from_id: v.id, to_id: r.to_id, cargo, merchants: merchantsFor(sum(cargo)), sent_at: at, route_id: r.id, offer: false }, distance(v, to)) } /** Merchants arrive: cargo into the stock and a report, then the way home. */ function arrive(state: MockState, host: MarketHost, t: MockTrade, touched: Set) { const m = data(state) m.trades = m.trades.filter((x) => x !== t) touched.add(t.owner_id) if (t.kind === 'return') return const to = ownerOf(state, t.to_id) if (to && t.cargo) { host.advance(state, to, t.arrives_at) host.refund(to, t.cargo) touched.add(to.id) } const report: TradeReport = { from: host.villageRef(state, t.from_id), to: host.villageRef(state, t.to_id), cargo: t.cargo ?? none(), offer: t.offer } const users = new Set([ownerOf(state, t.from_id)?.user_id, to?.user_id].filter((u): u is number => u !== undefined)) users.forEach((userId) => host.writeReport(state, userId, t.world_id, t.arrives_at, { type: 'trade', payload: report })) // Merchants of a real village walk home; the traders' are of no interest. if (ownerOf(state, t.owner_id)) { m.trades.push({ ...t, id: host.nextId(state), kind: 'return', from_id: t.to_id, to_id: t.owner_id, cargo: null, sent_at: t.arrives_at, arrives_at: t.arrives_at + (t.arrives_at - t.sent_at) }) } } /** A trader takes one unit of an own offer: both sides' merchants set out. */ function take(state: MockState, host: MarketHost, o: MockOffer, at: number, touched: Set) { const v = ownerOf(state, o.village_id) const m = data(state) if (!v) { m.offers = m.offers.filter((x) => x !== o) return } const trader = [...TRADERS].sort((a, b) => distance(v, a) - distance(v, b))[o.id % 3]! const fields = distance(v, trader) deliver(state, host, { world_id: v.world_id, owner_id: v.id, from_id: v.id, to_id: trader.id, cargo: one(o.give), merchants: o.merchants, sent_at: at, route_id: null, offer: true }, fields) deliver(state, host, { world_id: v.world_id, owner_id: trader.id, from_id: trader.id, to_id: v.id, cargo: one(o.want), merchants: merchantsFor(o.want.amount), sent_at: at, route_id: null, offer: true }, fields) o.count -= 1 o.next_take_at = at + TAKE_EVERY_MS if (o.count <= 0) m.offers = m.offers.filter((x) => x !== o) touched.add(v.id) } /** When the next trade arrives, route runs or trader takes an offer. */ export function nextMarketDue(state: MockState) { const m = data(state) return Math.min( ...m.trades.map((t) => t.arrives_at), ...m.routes.filter((r) => !r.paused).map((r) => r.next_at), ...m.offers.flatMap((o) => (o.next_take_at === undefined ? [] : [o.next_take_at])), ) } /** Everything due by `now`, oldest first; returns the villages touched. */ export function processMarket(state: MockState, host: MarketHost, now: number): number[] { const touched = new Set() const m = data(state) for (;;) { const trade = [...m.trades].sort((a, b) => a.arrives_at - b.arrives_at || a.id - b.id)[0] const route = m.routes.filter((r) => !r.paused).sort((a, b) => a.next_at - b.next_at || a.id - b.id)[0] const offer = m.offers.filter((o) => o.next_take_at !== undefined).sort((a, b) => a.next_take_at! - b.next_take_at!)[0] const at = Math.min(trade?.arrives_at ?? Infinity, route?.next_at ?? Infinity, offer?.next_take_at ?? Infinity) if (at > now) break if (trade && trade.arrives_at === at) arrive(state, host, trade, touched) else if (route && route.next_at === at) { runRoute(state, host, route, at) touched.add(route.village_id) } else if (offer) take(state, host, offer, at, touched) } return [...touched].filter((id) => id > 0) } /** The traders keep a handful of offers on every world. */ function stock(state: MockState, host: MarketHost, worldId: number, now: number) { const m = data(state) const traders = new Set(TRADERS.map((t) => t.id)) let open = m.offers.filter((o) => o.world_id === worldId && traders.has(o.village_id)).length for (; open < 6; open++) { const n = m.offers.length + open const trader = TRADERS[n % TRADERS.length]! const give = RESOURCES[n % 3]! const want = RESOURCES[(n + 1 + (n % 2)) % 3]! const giveAmount = 200 * (1 + ((open * 3 + 1) % 5)) const wantAmount = Math.max(100, Math.round((giveAmount * (0.7 + 0.15 * (open % 4))) / 50) * 50) m.offers.push({ id: host.nextId(state), world_id: worldId, village_id: trader.id, give: { resource: give, amount: giveAmount }, want: { resource: want, amount: wantAmount }, count: 1 + (open % 4), merchants: merchantsFor(giveAmount), created_at: now - open * 600_000, }) } } /** One side of an offer; an untraded resource (food) is not found, like on the backend. */ const side = (raw: any): TradeSide => ({ resource: RESOURCES.find((r) => r === raw?.resource) ?? fail('not_found'), amount: amount(raw?.amount) }) function withMarket(v: MockVillage) { return marketOf(v) ?? fail('no_market') } /** Drop the market data of villages that are gone (mock.reset). */ export function dropMarket(state: MockState, gone: Set) { const m = data(state) m.trades = m.trades.filter((t) => !gone.has(t.owner_id)) m.offers = m.offers.filter((o) => !gone.has(o.village_id)) m.routes = m.routes.filter((r) => !gone.has(r.village_id)) } type Handler = (state: MockState, user: AuthUser, data: any, now: number) => unknown export function marketHandlers(host: MarketHost): Record { const show = (state: MockState, v: MockVillage, now: number) => view(state, host, v, now) return { 'market.show': (state, user, d, now) => show(state, host.ownVillage(state, user, d.village_id, now), now), 'market.preview': (state, user, d, now): TradePlan => { const v = host.ownVillage(state, user, d.village_id, now) const to = target(state, host, v, d.x, d.y) const seconds = tripSeconds(distance(v, to)) return { target: to, distance: Math.round(distance(v, to) * 100) / 100, seconds, arrives_at: iso(now + seconds * 1000) } }, 'market.send': (state, user, d, now) => { const v = host.ownVillage(state, user, d.village_id, now) withMarket(v) const to = target(state, host, v, d.x, d.y) const cargo: Cost = { wood: amount(d.wood), clay: amount(d.clay), iron: amount(d.iron) } if (sum(cargo) <= 0) fail('nothing') if (RESOURCES.some((r) => cargo[r] > v.resources[r])) fail('resources') const merchants = merchantsFor(sum(cargo)) if (merchants > freeMerchants(state, v)) fail('merchants') host.pay(v, cargo) deliver(state, host, { world_id: v.world_id, owner_id: v.id, from_id: v.id, to_id: to.id, cargo, merchants, sent_at: now, route_id: null, offer: false }, distance(v, to)) return show(state, v, now) }, 'market.offers': (state, user, d, now): MarketOffers => { const v = host.ownVillage(state, user, d.village_id, now) stock(state, host, v.world_id, now) const own = new Set(state.villages.filter((x) => x.user_id === user.id).map((x) => x.id)) const offers = data(state) .offers.filter((o) => o.world_id === v.world_id && (!d.give || o.give.resource === d.give) && (!d.want || o.want.resource === d.want)) .map((o): WorldOffer => { const village = host.villageRef(state, o.village_id) const fields = distance(v, village) return { id: o.id, village, give: o.give, want: o.want, count: o.count, distance: Math.round(fields * 100) / 100, seconds: tripSeconds(fields), own: own.has(o.village_id) } }) .sort((a, b) => a.distance - b.distance || a.id - b.id) return { server_time: iso(now), offers } }, 'market.offer': (state, user, d, now) => { const v = host.ownVillage(state, user, d.village_id, now) withMarket(v) // The backend's order: no_market, not_found, same_resource, amount, count, ratio, resources, merchants. const give = side(d.give) const want = side(d.want) if (give.resource === want.resource) fail('same_resource') if (give.amount < 1 || want.amount < 1) fail('amount') const count = amount(d.count) if (count < 1) fail('count') if (want.amount > give.amount * MAX_RATIO || give.amount > want.amount * MAX_RATIO) fail('ratio') if (give.amount * count > v.resources[give.resource]) fail('resources') const merchants = merchantsFor(give.amount) if (merchants * count > freeMerchants(state, v)) fail('merchants') host.pay(v, one(give, count)) data(state).offers.push({ id: host.nextId(state), world_id: v.world_id, village_id: v.id, give, want, count, merchants, created_at: now, next_take_at: now + TAKE_AFTER_MS }) return show(state, v, now) }, 'market.cancelOffer': (state, user, d, now) => { const v = host.ownVillage(state, user, d.village_id, now) const m = data(state) const o = m.offers.find((x) => x.id === Number(d.offer_id) && x.village_id === v.id) ?? fail('not_found') host.refund(v, one(o.give, o.count)) m.offers = m.offers.filter((x) => x !== o) return show(state, v, now) }, 'market.accept': (state, user, d, now) => { const v = host.ownVillage(state, user, d.village_id, now) withMarket(v) const m = data(state) const o = m.offers.find((x) => x.id === Number(d.offer_id) && x.world_id === v.world_id) ?? fail('not_found') if (state.villages.some((x) => x.id === o.village_id && x.user_id === user.id)) fail('own_offer') const count = amount(d.count) if (count < 1 || count > o.count) fail('count') if (o.want.amount * count > v.resources[o.want.resource]) fail('resources') const merchants = merchantsFor(o.want.amount) * count if (merchants > freeMerchants(state, v)) fail('merchants') host.pay(v, one(o.want, count)) const other = host.villageRef(state, o.village_id) const fields = distance(v, other) deliver(state, host, { world_id: v.world_id, owner_id: v.id, from_id: v.id, to_id: other.id, cargo: one(o.want, count), merchants, sent_at: now, route_id: null, offer: true }, fields) deliver(state, host, { world_id: v.world_id, owner_id: other.id, from_id: other.id, to_id: v.id, cargo: one(o.give, count), merchants: o.merchants * count, sent_at: now, route_id: null, offer: true }, fields) o.count -= count if (o.count <= 0) m.offers = m.offers.filter((x) => x !== o) return show(state, v, now) }, // A new route first runs `every` seconds after it was made, like the backend's. 'market.routeCreate': (state, user, d, now) => { const v = host.ownVillage(state, user, d.village_id, now) const b = withMarket(v) const to = target(state, host, v, d.x, d.y) const resources: Cost = { wood: amount(d.wood), clay: amount(d.clay), iron: amount(d.iron) } if (sum(resources) <= 0) fail('nothing') const every = amount(d.every) if (every < ROUTE_MIN_EVERY || every > ROUTE_MAX_EVERY) fail('every') const m = data(state) if (m.routes.filter((r) => r.village_id === v.id).length >= maxRoutes(b.level)) fail('max_routes') const route: MockRoute = { id: host.nextId(state), world_id: v.world_id, village_id: v.id, to_id: to.id, resources, every, next_at: now + every * 1000, paused: false, paused_reason: null, last_sent_at: null, last_cargo: null } m.routes.push(route) return show(state, v, now) }, 'market.routeUpdate': (state, user, d, now) => { const v = host.ownVillage(state, user, d.village_id, now) const r = data(state).routes.find((x) => x.id === Number(d.route_id) && x.village_id === v.id) ?? fail('not_found') const resources = { ...r.resources } for (const res of RESOURCES) if (d[res] !== undefined) resources[res] = amount(d[res]) if (sum(resources) <= 0) fail('nothing') let every = r.every if (d.every !== undefined) { every = amount(d.every) if (every < ROUTE_MIN_EVERY || every > ROUTE_MAX_EVERY) fail('every') } // Resuming takes the target's owner as it is now; a target turned barbarian is refused. const resuming = d.paused !== undefined && !d.paused && r.paused if (resuming && !host.villageRef(state, r.to_id).player) fail('barbarian') r.resources = resources if (d.paused !== undefined) { r.paused = !!d.paused r.paused_reason = null } // A new interval on an active route, or resuming, starts the clock again from now. if ((every !== r.every || resuming) && !r.paused) r.next_at = now + every * 1000 r.every = every return show(state, v, now) }, 'market.routeDelete': (state, user, d, now) => { const v = host.ownVillage(state, user, d.village_id, now) const m = data(state) const r = m.routes.find((x) => x.id === Number(d.route_id) && x.village_id === v.id) ?? fail('not_found') m.routes = m.routes.filter((x) => x !== r) return show(state, v, now) }, } }