From af78f0510638c34f6d565b578b16bd98b656e130 Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Sat, 31 Oct 2026 11:07:33 +0100 Subject: [PATCH] feat: the market stands in the village: stalls under faded awnings, a cart and crates (hut, then counting house with an open hall and the pillory, then a stone guild hall), its tag shows free merchants; trade reports in the list, filter and detail; the mock answers the market contract with made-up traders Co-Authored-By: Claude Opus 5.5 (1M context) --- app/components/game/MenuBar.vue | 2 +- app/components/icon/Building.vue | 6 + app/components/icon/Ui.vue | 11 + app/components/report/Trade.vue | 34 ++ app/diorama/models.ts | 150 ++++++++ app/mock/catalog.ts | 1 + app/mock/market.ts | 517 ++++++++++++++++++++++++++ app/mock/server.ts | 56 ++- app/pages/reports/[worldId]/[id].vue | 3 +- app/pages/reports/[worldId]/index.vue | 6 +- app/types/game.ts | 130 ++++++- app/utils/buildingTags.ts | 11 + app/utils/demoVillage.ts | 2 +- app/utils/military.ts | 6 +- app/utils/palette.ts | 1 + i18n/locales/en.ts | 1 + i18n/messageloader.ts | 3 +- i18n/pages/market.ts | 158 ++++++++ 18 files changed, 1079 insertions(+), 19 deletions(-) create mode 100644 app/components/report/Trade.vue create mode 100644 app/mock/market.ts create mode 100644 i18n/pages/market.ts diff --git a/app/components/game/MenuBar.vue b/app/components/game/MenuBar.vue index e00030b..c50d6c1 100644 --- a/app/components/game/MenuBar.vue +++ b/app/components/game/MenuBar.vue @@ -52,7 +52,7 @@ const entries = computed(() => { icon: 'report', active: route.path.startsWith('/reports/'), count: unread.value, - sub: (['all', 'attack', 'defense', 'support'] as const).map((kind) => ({ + sub: (['all', 'attack', 'defense', 'support', 'trade'] as const).map((kind) => ({ label: t(`reports.kinds.${kind}`), to: kind === 'all' ? `/reports/${c.worldId}` : { path: `/reports/${c.worldId}`, query: { type: kind } }, })), diff --git a/app/components/icon/Building.vue b/app/components/icon/Building.vue index 9e35a3a..16bcd7e 100644 --- a/app/components/icon/Building.vue +++ b/app/components/icon/Building.vue @@ -82,6 +82,12 @@ defineProps<{ type: BuildingType }>() + + + + + + diff --git a/app/components/icon/Ui.vue b/app/components/icon/Ui.vue index 0b01215..5409893 100644 --- a/app/components/icon/Ui.vue +++ b/app/components/icon/Ui.vue @@ -7,6 +7,8 @@ export type UiIconName = | 'minus' | 'plus' | 'pin' + | 'cart' + | 'repeat' | 'users' | 'globe' | 'logout' @@ -81,6 +83,15 @@ defineProps<{ name: UiIconName }>() + + + + + + + + + diff --git a/app/components/report/Trade.vue b/app/components/report/Trade.vue new file mode 100644 index 0000000..6deb678 --- /dev/null +++ b/app/components/report/Trade.vue @@ -0,0 +1,34 @@ + + + + diff --git a/app/diorama/models.ts b/app/diorama/models.ts index ca1b9b3..b2c2019 100644 --- a/app/diorama/models.ts +++ b/app/diorama/models.ts @@ -681,6 +681,92 @@ function herbs(x: number, y: number, w: number, d: number): Face[] { return field(x, y, w, d, C.leaf, 4) } +/** + * A market stall along x, open towards +y: a counter with goods heaped on it, posts higher + * at the back, and a striped awning sloping down to the front with a valance at its edge. + */ +function stall(x: number, y: number, s: number, stripes: [string, string], goods: string[]): Face[] { + const w = s * 0.56 + const d = s * 0.34 + const y0 = y - d / 2 + const y1 = y + d / 2 + const hb = s * 0.6 + const hf = s * 0.5 + const faces: Face[] = [ + ...post(x - w / 2, y0, hb, s * 0.022), + ...post(x + w / 2, y0, hb, s * 0.022), + ...post(x - w / 2, y1, hf, s * 0.022), + ...post(x + w / 2, y1, hf, s * 0.022), + ...box(x, y + d * 0.15, w * 0.9, d * 0.5, 0, s * 0.2, C.wood, C.plank), + ] + goods.forEach((color, i) => { + const gx = x - w * 0.28 + (i * w * 0.56) / Math.max(1, goods.length - 1) + faces.push(...pyramid(ngon(gx, y + d * 0.15, s * 0.065, 6, i), s * 0.2, s * 0.075, color)) + }) + const x0 = x - w / 2 - s * 0.03 + const span = w + s * 0.06 + const ya = y0 - s * 0.02 + const yb = y1 + s * 0.04 + const zb = hf - s * 0.02 + for (let i = 0; i < 4; i++) { + const xa = x0 + (i * span) / 4 + const xb = x0 + ((i + 1) * span) / 4 + faces.push(plane([[xa, ya, hb], [xb, ya, hb], [xb, yb, zb], [xa, yb, zb]], stripes[i % 2]!)) + } + faces.push(plane([[x0, yb, zb], [x0 + span, yb, zb], [x0 + span, yb, zb - s * 0.06], [x0, yb, zb - s * 0.06]], stripes[0])) + return faces +} + +/** A stall at (x, y), open towards +y or turned to open towards +x. */ +function stallAt(x: number, y: number, s: number, opens: 'x' | 'y', stripes: [string, string], goods: string[]): Face[] { + return opens === 'y' ? stall(x, y, s, stripes, goods) : shift(turn(stall(0, 0, s, stripes, goods), 3), x, y) +} + +/** A two-wheeled cart facing +x before `quarters` turns: a railed bed, shafts down at the front, its load on the bed. */ +function cart(x: number, y: number, k: number, quarters = 0, load: Face[] = []): Face[] { + const bed = k * 0.5 + const shaft = (side: number) => + slab( + rect(k * 0.8, side * k * 0.32, k * 0.08, k * 0.08).map(([px, py]): V3 => [px, py, bed]), + rect(k * 1.9, side * k * 0.32, k * 0.08, k * 0.08).map(([px, py]): V3 => [px, py, k * 0.04]), + C.woodDark, + ) + const faces: Face[] = [ + ...wheel(-k * 0.1, -k * 0.62, k * 0.45, 'y'), + ...box(0, 0, k * 1.6, k * 1.0, bed, k * 0.1, C.plank, C.wood), + ...box(0, -k * 0.47, k * 1.6, k * 0.06, bed + k * 0.1, k * 0.2, C.wood), + ...box(-k * 0.77, 0, k * 0.06, k * 0.88, bed + k * 0.1, k * 0.2, C.wood), + ...box(0, k * 0.47, k * 1.6, k * 0.06, bed + k * 0.1, k * 0.2, C.wood), + ...shaft(-1), + ...shaft(1), + ...shift(load, 0, 0, bed + k * 0.1), + ...wheel(-k * 0.1, k * 0.62, k * 0.45, 'y'), + ] + return shift(turn(faces, quarters), x, y) +} + +/** The pillory on the market square: a post on a stone step with the board for neck and hands. */ +function pillory(x: number, y: number, s: number): Face[] { + return [ + ...box(x, y, s * 0.28, s * 0.28, 0, s * 0.06, C.stoneDark, C.stone), + ...post(x, y, s * 0.66, s * 0.03), + ...box(x, y, s * 0.06, s * 0.36, s * 0.4, s * 0.08, C.woodDark), + ] +} + +/** An open hall: posts under a gable roof along x over [x0, x1] × [y0, y1], a long counter beneath. */ +function hall(x0: number, x1: number, y0: number, y1: number, h: number, rise: number, s: number, roof: string, goods: string[]): Face[] { + const o = s * 0.05 + const cx = (x0 + x1) / 2 + const cy = (y0 + y1) / 2 + return [ + ...[x0, cx, x1].flatMap((x) => [...post(x, y0, h, s * 0.035), ...post(x, y1, h, s * 0.035)]), + ...box(cx, cy + (y1 - y0) * 0.1, (x1 - x0) * 0.8, (y1 - y0) * 0.35, 0, s * 0.2, C.wood, C.plank), + ...goods.flatMap((color, i) => pyramid(ngon(x0 + ((x1 - x0) * (i + 1)) / (goods.length + 1), cy + (y1 - y0) * 0.1, s * 0.07, 6, i), s * 0.2, s * 0.08, color)), + ...gable(x0 - o, y0 - o, x1 + o, y1 + o, h, rise, 'x', roof, C.wood), + ] +} + /** The village banner on a tall pole, flying from its top. */ function flag(x: number, y: number, h: number, size: number): Face[] { return [...post(x, y, h, size * 0.03), plane([[x, y, h], [x - size * 0.1, y + size * 0.85, h - size * 0.08], [x, y, h - size * 0.4]], C.banner)] @@ -1243,6 +1329,70 @@ const models: Record Model> = { } }, + // The market square, trodden to mud: stalls under faded striped awnings, a cart with + // its load, crates and barrels. A merchant's hut first; then a counting house with an + // open hall, a horse at the cart and the pillory; then a stone guild hall on a paved + // square with three stalls. + market(s, t) { + const faded = mix(C.banner, C.canvas, 0.45) + const moss = mix(C.leaf, C.canvas, 0.35) + const square = (r: number, seed: number, ground = mix(C.soil, C.furrow, 0.35)): Face[] => [ + blot(0, s * 0.05, r, 11, seed, 0.5, ground), + blot(s * 0.3, s * 0.5, s * 0.16, 7, seed + 1, 0.6, mix(C.water, C.soil, 0.35)), + blot(-s * 0.1, s * 0.05, s * 0.13, 6, seed + 2, 0.55, mix(C.hay, C.soil, 0.45)), + ] + const sacks = (k: number) => [...sack(-k * 0.35, -k * 0.18, k * 2.4), ...sack(k * 0.05, k * 0.2, k * 2.4), ...sack(k * 0.4, -k * 0.12, k * 2.2)] + const crates = (k: number) => [...crate(-k * 0.35, 0, 0, k * 0.45), ...crate(k * 0.2, -k * 0.1, 0, k * 0.42), ...crate(-k * 0.3, 0, k * 0.45, k * 0.38)] + const stack = (x: number, y: number): Face[] => [...crate(x, y, 0, s * 0.15), ...crate(x, y, s * 0.15, s * 0.12), ...crate(x - s * 0.17, y + s * 0.04, 0, s * 0.13)] + if (t === 1) { + return { + faces: [ + ...square(s * 1.05, 41), + ...house(-s * 0.5, -s * 0.55, s * 0.7, s * 0.55, s * 0.4, s * 0.32, C.wood, C.thatch, 'y'), + ...stallAt(s * 0.4, -s * 0.5, s, 'y', [C.canvas, faded], [C.wheat, C.leaf, C.clay]), + ...stallAt(-s * 0.6, s * 0.35, s, 'x', [C.canvasDark, moss], [C.ore, C.wheat]), + ...cart(s * 0.3, s * 0.38, s * 0.26, 1, sacks(s * 0.26)), + ...stack(s * 0.88, -s * 0.05), + ...barrel(s * 0.85, s * 0.25, s), + ...person(s * 0.45, -s * 0.18, s, C.cloth), + ], + height: s * 0.85, + } + } + if (t === 2) { + return { + faces: [ + ...square(s * 1.12, 42), + ...house(-s * 0.6, -s * 0.55, s * 0.62, s * 0.7, s * 0.5, s * 0.36, C.plank, C.shingle, 'y'), + ...hall(-s * 0.15, s * 0.85, -s * 0.92, -s * 0.38, s * 0.48, s * 0.3, s, C.thatch, [C.wheat, C.clay, C.ore, C.leaf]), + ...stallAt(-s * 0.55, s * 0.4, s, 'x', [C.canvas, faded], [C.wheat, C.clay, C.leaf]), + ...pillory(s * 0.1, s * 0.02, s), + ...cart(s * 0.12, s * 0.62, s * 0.26, 0, crates(s * 0.26)), + ...horse(s * 0.6, s * 0.62, s * 0.1, 0, C.bay), + ...stack(s * 0.9, -s * 0.12), + ...barrel(s * 0.62, -s * 0.15, s), + ], + height: s * 1.0, + } + } + return { + faces: [ + ...square(s * 1.15, 43, mix(C.stoneDark, C.soil, 0.4)), + blot(-s * 0.2, s * 0.3, s * 0.45, 9, 47, 0.55, mix(C.soil, C.furrow, 0.35)), + ...house(-s * 0.4, -s * 0.55, s * 1.15, s * 0.7, s * 0.62, s * 0.42, C.stone, C.slate, 'x'), + ...stallAt(-s * 0.65, s * 0.35, s, 'y', [C.canvas, faded], [C.wheat, C.clay, C.leaf]), + ...stallAt(-s * 0.05, s * 0.4, s, 'y', [C.canvasDark, moss], [C.ore, C.wheat]), + ...stallAt(s * 0.75, -s * 0.15, s, 'x', [C.canvas, faded], [C.leaf, C.clay, C.wheat]), + ...pillory(s * 0.85, s * 0.35, s), + ...cart(s * 0.22, s * 0.75, s * 0.24, 0, sacks(s * 0.24)), + ...horse(s * 0.66, s * 0.75, s * 0.09, 0, C.grey), + ...stack(s * 0.5, -s * 0.85), + ...barrel(s * 0.75, -s * 0.8, s), + ], + height: s * 1.3, + } + }, + // The academy (Adelshof): a stone manor with towers. academy(s, t) { const tower = (x: number, y: number, h: number): Face[] => [ diff --git a/app/mock/catalog.ts b/app/mock/catalog.ts index 1d06a44..3cab277 100644 --- a/app/mock/catalog.ts +++ b/app/mock/catalog.ts @@ -42,6 +42,7 @@ export const CATALOG: Record = { stable: { space: 6, max_per_village: null, cost: { wood: 270, clay: 240, iron: 260 }, seconds: 40, workers: 3, production: null }, workshop: { space: 6, max_per_village: null, cost: { wood: 300, clay: 240, iron: 260 }, seconds: 50, workers: 4, production: null }, hospital: { space: 4, max_per_village: null, cost: { wood: 160, clay: 200, iron: 120 }, seconds: 30, workers: 2, production: null }, + market: { space: 4, max_per_village: 1, cost: { wood: 100, clay: 100, iron: 100 }, seconds: 20, workers: 2, production: null }, academy: { space: 9, max_per_village: 1, cost: { wood: 1500, clay: 2500, iron: 1000 }, seconds: 60, workers: 5, production: null }, } diff --git a/app/mock/market.ts b/app/mock/market.ts new file mode 100644 index 0000000..43b2f67 --- /dev/null +++ b/app/mock/market.ts @@ -0,0 +1,517 @@ +// 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) + }, + } +} diff --git a/app/mock/server.ts b/app/mock/server.ts index f593aea..a665e3c 100644 --- a/app/mock/server.ts +++ b/app/mock/server.ts @@ -68,6 +68,8 @@ import { VILLAGER_UPKEEP, atLevel, } from './catalog' +import type { TradeReport } from '~/types/game' +import { dropMarket, type MarketHost, marketEffects, marketHandlers, type MockMarket, nextMarketDue, processMarket, traderAt, traderRef, villageMarket } from './market' interface MockBuilding { id: number @@ -96,7 +98,7 @@ interface MockWounded { heals_at: number } -interface MockVillage { +export interface MockVillage { id: number world_id: number user_id: number @@ -159,7 +161,7 @@ interface MockRecruit { finishes_at: number } -interface MockState { +export interface MockState { seq: number token: string | null users: AuthUser[] @@ -175,6 +177,8 @@ interface MockState { coins?: Record /** 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; at: string }[] }[] + /** Trades under way, open offers and trade routes (market.ts). */ + market?: MockMarket } const STORAGE_KEY = 'vp.mock.v4' @@ -650,6 +654,7 @@ function view(state: MockState, v: MockVillage, now: number): VillageState { starvation: starvation(v), troops: Object.fromEntries(Object.entries(v.troops ?? {}).filter(([, n]) => n)), hospital: hospital(v), + market: villageMarket(state, v), military: military(v, now), movements: movements(state, v, now), support: support(state, v), @@ -688,9 +693,13 @@ function view(state: MockState, v: MockVillage, now: number): VillageState { production: p ? { resource: p.resource, per_hour: round(p.per_hour) } : null, upgrade: upgradeOffer(v, b), demolish: demolishOffer(v, b), - // Placeholder: production and training speed only; the backend lists every effect. - effects: p ? [{ key: 'production', value: round(p.per_hour), resource: p.resource }] : trains(b) ? [recruitSpeed(v, b, b.level)] : [], - next_effects: !p && trains(b) && b.level < MAX_LEVEL ? [recruitSpeed(v, b, b.level + 1)] : null, + // Placeholder: production, training speed and merchants only; the backend lists every effect. + effects: p + ? [{ key: 'production', value: round(p.per_hour), resource: p.resource }] + : trains(b) ? [recruitSpeed(v, b, b.level)] : b.type === 'market' ? marketEffects(b.level).effects : [], + next_effects: !p && trains(b) && b.level < MAX_LEVEL + ? [recruitSpeed(v, b, b.level + 1)] + : b.type === 'market' ? marketEffects(b.level).next_effects : null, instance_share: instanceShare(v, b), } }, @@ -741,7 +750,7 @@ 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 + const near = Math.abs(x) <= 25 && Math.abs(y) <= 25 && !traderAt(x, y) 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 } @@ -779,6 +788,12 @@ function mapView(state: MockState, user: AuthUser, data: any): MapView { }) continue } + // The market's made-up traders: other players' villages. + const trader = traderAt(x, y) + if (trader) { + villages.push({ id: trader.id, x, y, name: trader.name, points: 640, continent: continentOf(x, y), player: { ...trader.player!, tribe: null }, own: false, crown: false, relation: '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' }) @@ -827,6 +842,8 @@ const REPORTS_PER_PAGE = 25 const LOOTED = ['wood', 'clay', 'iron'] as const function villageRef(state: MockState, id: number): VillageRef { + const trader = traderRef(id) + if (trader) return { ...trader } 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 } @@ -838,6 +855,8 @@ function villageRef(state: MockState, id: number): VillageRef { 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 trader = traderAt(x, y) + if (trader) return { ...trader } const barbarian = barbarianAt(x, y) return barbarian ? villageRef(state, barbarian.id) : null } @@ -911,7 +930,7 @@ function sendSupportHome(state: MockState, host: MockVillage, homeId: number, no }) } -type ReportBody = { type: 'attack' | 'defense'; payload: BattleReport } | { type: 'support'; payload: SupportReport } +type ReportBody = { type: 'attack' | 'defense'; payload: BattleReport } | { type: 'support'; payload: SupportReport } | { type: 'trade'; payload: TradeReport } 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 }) @@ -1214,7 +1233,7 @@ function createVillage(state: MockState, user: AuthUser, worldId: number, now: n 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}`)) { + while (taken.has(`${x}|${y}`) || traderAt(x, y)) { x = -25 + Math.floor(Math.random() * 51) y = -25 + Math.floor(Math.random() * 51) } @@ -1294,7 +1313,12 @@ function ownBuilding(v: MockVillage, id: unknown) { return v.buildings.find((b) => b.id === Number(id)) ?? fail('not_found') } +/** What the market (market.ts) uses of the rest of the mock. */ +const marketHost: MarketHost = { ownVillage, villageRef, villageAt, advance, refund, pay, nextId, writeReport } + const handlers: Record = { + ...marketHandlers(marketHost), + 'world.index': (state, user): WorldSummary[] => WORLDS.map((w) => ({ ...w, @@ -1716,6 +1740,7 @@ const handlers: Record = { 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) + dropMarket(state, goneIds) return true }, } @@ -1724,6 +1749,7 @@ export function createMockServer(): { ws: GameWs; auth: GameAuth } { const bus = new EventTarget() const timers = new Map>() let marchTimer: ReturnType | undefined + let marketTimer: ReturnType | undefined const emit = (event: string, data: unknown) => bus.dispatchEvent(new CustomEvent(event, { detail: { event, data, channel: 'websocket' } })) @@ -1754,6 +1780,19 @@ export function createMockServer(): { ws: GameWs; auth: GameAuth } { ) } + // Merchants arriving or coming home, routes running, traders taking own offers. + clearTimeout(marketTimer) + const market = nextMarketDue(state) + if (market !== Infinity) { + marketTimer = setTimeout(() => { + const fresh = load() + const touched = processMarket(fresh, marketHost, Date.now()) + save(fresh) + schedule(fresh) + touched.forEach((id) => emit('village:updated', { village_id: id })) + }, Math.max(0, market - Date.now()) + 20) + } + clearTimeout(marchTimer) const arrival = Math.min(...(state.movements ?? []).map((m) => m.arrives_at)) if (arrival === Infinity) return @@ -1805,6 +1844,7 @@ export function createMockServer(): { ws: GameWs; auth: GameAuth } { const now = Date.now() // Arrivals first, for every village, so the handler sees the world as of now. processMovements(state, now) + processMarket(state, marketHost, now) const result = handler(state, currentUser(state), data, now) save(state) schedule(state) diff --git a/app/pages/reports/[worldId]/[id].vue b/app/pages/reports/[worldId]/[id].vue index d5e5dec..6ae8f42 100644 --- a/app/pages/reports/[worldId]/[id].vue +++ b/app/pages/reports/[worldId]/[id].vue @@ -21,7 +21,7 @@ const subject = computed(() => { const r = report.value return r ? reportSubject(r, t) : '' }) -const fight = computed(() => (report.value && report.value.type !== 'support' ? report.value.payload : null)) +const fight = computed(() => (report.value && (report.value.type === 'attack' || report.value.type === 'defense') ? report.value.payload : null)) const battle = computed(() => (fight.value && !('scattered' in fight.value) ? fight.value : null)) const scattered = computed(() => (fight.value && 'scattered' in fight.value ? fight.value : null)) @@ -42,6 +42,7 @@ const scattered = computed(() => (fight.value && 'scattered' in fight.value ? fi

{{ $t('reports.support.arrived', { to: villageLabel(report.payload.to) }) }}

+

{{ $t('common.loading') }}

diff --git a/app/pages/reports/[worldId]/index.vue b/app/pages/reports/[worldId]/index.vue index 594c42f..7edbfd4 100644 --- a/app/pages/reports/[worldId]/index.vue +++ b/app/pages/reports/[worldId]/index.vue @@ -11,7 +11,7 @@ const { t } = useI18n() const clock = useNow() // The kind of reports comes from the URL, so the menu's dropdown and the side menu link here. -const KINDS = ['attack', 'defense', 'support'] as const +const KINDS = ['attack', 'defense', 'support', 'trade'] as const watch( () => route.query.type, (q) => { @@ -39,7 +39,7 @@ function toggleAll() { const subject = (r: Report) => reportSubject(r, t) -const DOT = { won: 'bg-moss-600', losses: 'bg-gold-500', lost: 'bg-blood-700', info: 'bg-iron-400' } +const DOT = { won: 'bg-moss-600', losses: 'bg-gold-500', lost: 'bg-blood-700', info: 'bg-iron-400', trade: 'bg-wood-600' } @@ -67,7 +67,7 @@ const DOT = { won: 'bg-moss-600', losses: 'bg-gold-500', lost: 'bg-blood-700', i - + {{ subject(r) }} ({{ $t('reports.unread') }}) diff --git a/app/types/game.ts b/app/types/game.ts index 95d3018..b147a70 100644 --- a/app/types/game.ts +++ b/app/types/game.ts @@ -21,6 +21,7 @@ export type BuildingType = | 'workshop' | 'academy' | 'hospital' + | 'market' export type UnitType = | 'spear' @@ -189,6 +190,8 @@ export interface VillageState { /** Own units standing in the village. */ troops: Partial> hospital: Hospital + /** The market's merchants; null without a market. */ + market: VillageMarket | null /** One entry per building that trains units, in building order. */ military: MilitaryBuilding[] /** Own groups leaving from or coming home to this village, and spotted groups coming here; by arrival. */ @@ -279,7 +282,7 @@ export interface MarchPlan { seconds: number | null } -export type ReportType = 'attack' | 'defense' | 'support' +export type ReportType = 'attack' | 'defense' | 'support' | 'trade' export interface BattleSide { village: VillageRef @@ -368,6 +371,7 @@ export interface ScatteredRaid { export type Report = | (ReportBase & { type: 'attack' | 'defense'; payload: BattleReport | ScatteredRaid }) | (ReportBase & { type: 'support'; payload: SupportReport }) + | (ReportBase & { type: 'trade'; payload: TradeReport }) export type TribeRole = 'leader' | 'council' | 'member' export type Pact = 'ally' | 'nap' @@ -568,7 +572,7 @@ export interface Building { /** One line of what a building does: production at full staffing (per hour), percentages as whole numbers. */ export interface BuildingEffect { - key: 'production' | 'capacity' | 'hides' | 'beds' | 'detection' | 'wall_defense' | 'wall_bonus' | 'build_speed' | 'builders' | 'space' | 'recruit_speed' + key: 'production' | 'capacity' | 'hides' | 'beds' | 'detection' | 'wall_defense' | 'wall_bonus' | 'build_speed' | 'builders' | 'space' | 'recruit_speed' | 'merchants' value: number resource?: Resource } @@ -693,3 +697,125 @@ export interface Conquest { /** Fields a nobleman marches at most; 0 for no limit. */ max_distance: number } + +// The market: merchants carry wood, clay and iron (never food) to other villages, for +// offers on the world's market and on repeating trade routes. + +/** What merchants carry. */ +export type TradeResource = Exclude + +/** The village payload's market: merchants in all, free ones, and what one carries. */ +export interface VillageMarket { + building_id: number + level: number + merchants: number + free: number + carry: number +} + +/** A resource and an amount: one side of an offer. */ +export interface TradeSide { + resource: TradeResource + amount: number +} + +/** + * Merchants under way. out: this village's merchants on the way there; back: on their way + * home; in: anyone's merchants coming here with cargo. Cargo is null on the way back. + */ +export interface Trade { + id: number + kind: 'out' | 'back' | 'in' + from: VillageRef + to: VillageRef + cargo: Cost | null + merchants: number + sent_at: string + arrives_at: string + route_id: number | null + /** Part of an accepted offer. */ + offer: boolean +} + +/** One of this village's open offers, its resources and merchants reserved; `merchants` per unit of `count`. */ +export interface OwnOffer { + id: number + give: TradeSide + want: TradeSide + count: number + merchants: number + created_at: string +} + +/** + * A repeating trade route: every `every` real seconds it sends what the stock and the free + * merchants allow, up to the amounts. It pauses itself when the target changes owner. + */ +export interface TradeRoute { + id: number + to: VillageRef + resources: Cost + every: number + next_at: string + paused: boolean + paused_reason: null | 'owner_changed' + last_sent_at: string | null + last_cargo: Cost | null +} + +/** `market.show`, and the reply to every mutating `market.*` intent. */ +export interface MarketState { + server_time: string + market: { + building_id: number + level: number + merchants: number + free: number + busy: number + carry: number + minutes_per_field: number + resources: TradeResource[] + /** An offer may want at most this many times what it gives, and give at most this many times what it wants. */ + max_ratio: number + /** Route intervals in real seconds, and how many routes the market runs at most. */ + route: { min_every: number; max_every: number; max_routes: number } + } | null + trades: Trade[] + /** This village's own open offers. */ + offers: OwnOffer[] + routes: TradeRoute[] +} + +/** `market.preview`: who lives on the field and how long merchants walk there. */ +export interface TradePlan { + target: VillageRef + distance: number + seconds: number + arrives_at: string +} + +/** An open offer on the world, as `market.offers` lists it, nearest first. */ +export interface WorldOffer { + id: number + village: VillageRef + give: TradeSide + want: TradeSide + count: number + distance: number + seconds: number + own: boolean +} + +/** `market.offers`. */ +export interface MarketOffers { + server_time: string + offers: WorldOffer[] +} + +/** Report `trade`: a delivery arrived; `offer` when it was part of an accepted offer. */ +export interface TradeReport { + from: VillageRef + to: VillageRef + cargo: Cost + offer: boolean +} diff --git a/app/utils/buildingTags.ts b/app/utils/buildingTags.ts index c399361..02ead7c 100644 --- a/app/utils/buildingTags.ts +++ b/app/utils/buildingTags.ts @@ -151,6 +151,17 @@ export function buildingTag( } } + case 'market': { + if (!village.market) return null + const { free, merchants } = village.market + return { + icon: { kind: 'ui', name: 'cart' }, + text: t('village.tags.merchants', { free, merchants }), + tone: free <= 0 ? 'warn' : 'plain', + title: t('village.tags.merchants_title', { free, merchants }), + } + } + case 'watchtower': return { icon: { kind: 'ui', name: 'eye' }, text: t('village.tags.fields', { fields: effect('detection') }), tone: 'plain', title: t('village.tags.detection', { fields: effect('detection') }) } diff --git a/app/utils/demoVillage.ts b/app/utils/demoVillage.ts index b501790..03d2b4f 100644 --- a/app/utils/demoVillage.ts +++ b/app/utils/demoVillage.ts @@ -11,7 +11,7 @@ const SPACE: Partial> = { export function demoVillage(): VillageState { const levels: [BuildingType, number][] = [ ['headquarters', 14], ['storage', 11], ['storage', 7], ['farm', 10], ['farm', 6], ['timber_camp', 9], ['timber_camp', 7], - ['clay_pit', 8], ['clay_pit', 6], ['iron_mine', 8], ['hiding_place', 3], ['wall', 9], ['rally_point', 1], ['barracks', 7], ['stable', 4], ['workshop', 2], ['hospital', 6], + ['clay_pit', 8], ['clay_pit', 6], ['iron_mine', 8], ['hiding_place', 3], ['wall', 9], ['rally_point', 1], ['barracks', 7], ['stable', 4], ['workshop', 2], ['hospital', 6], ['market', 8], ] const buildings = levels.map(([type, level], i): Building => ({ id: i + 1, type, level, space: SPACE[type] ?? 4, priority: 5, diff --git a/app/utils/military.ts b/app/utils/military.ts index 440dac9..fdcfd2d 100644 --- a/app/utils/military.ts +++ b/app/utils/military.ts @@ -35,10 +35,11 @@ const lost = (side: BattleSide) => Object.values(side.lost ?? {}).reduce((a, b) /** * The dot colour of a report, as in Die Stämme: green for a win without losses, yellow - * for a win with losses, red for a loss, blue for support. + * for a win with losses, red for a loss, blue for support; brown for a trade. */ -export function reportTone(r: Report): 'won' | 'losses' | 'lost' | 'info' { +export function reportTone(r: Report): 'won' | 'losses' | 'lost' | 'info' | 'trade' { if (r.type === 'support') return 'info' + if (r.type === 'trade') return 'trade' const p = r.payload if ('scattered' in p) return 'won' const ownSide = r.type === 'attack' ? p.attacker : p.defender @@ -50,6 +51,7 @@ export function reportTone(r: Report): 'won' | 'losses' | 'lost' | 'info' { /** A report's subject line: who attacked or supported whom, raiders by name. */ export function reportSubject(r: Report, t: (key: string, values?: Record) => string) { if (r.type === 'support') return t('reports.title_support', { from: villageLabel(r.payload.from), to: villageLabel(r.payload.to) }) + if (r.type === 'trade') return t(r.payload.offer ? 'reports.title_trade_offer' : 'reports.title_trade', { from: villageLabel(r.payload.from), to: villageLabel(r.payload.to) }) const p = r.payload if ('scattered' in p) return t('reports.title_scattered', { from: villageLabel(p.attacker.village) }) return t(p.raid ? 'reports.title_raid' : 'reports.title_attack', { from: villageLabel(p.attacker.village), to: villageLabel(p.defender.village) }) diff --git a/app/utils/palette.ts b/app/utils/palette.ts index 1bc778a..2cb1a4e 100644 --- a/app/utils/palette.ts +++ b/app/utils/palette.ts @@ -17,6 +17,7 @@ export const BUILDING_COLORS: Record ({ diff --git a/i18n/locales/en.ts b/i18n/locales/en.ts index 8f715de..464024d 100644 --- a/i18n/locales/en.ts +++ b/i18n/locales/en.ts @@ -52,6 +52,7 @@ export default { workshop: 'Workshop', academy: 'Academy', hospital: 'Hospital', + market: 'Market', }, units: { spear: 'Spear fighter', diff --git a/i18n/messageloader.ts b/i18n/messageloader.ts index 2e471fe..50a2341 100644 --- a/i18n/messageloader.ts +++ b/i18n/messageloader.ts @@ -7,6 +7,7 @@ import chat from './pages/chat' import landing from './pages/landing' import legal from './pages/legal' import map from './pages/map' +import market from './pages/market' import quests from './pages/quests' import ranking from './pages/ranking' import tribe from './pages/tribe' @@ -16,6 +17,6 @@ import worlds from './pages/worlds' // Explicit imports instead of import.meta.glob: @nuxtjs/i18n also loads this file in the // Nitro build, where glob imports don't exist. Add new page files here, in path order. -export default mergeMessages({ en }, [account, auth, chat, landing, legal, map, quests, ranking, reports, tribe, village, worlds], { packages: [networking] }) as { +export default mergeMessages({ en }, [account, auth, chat, landing, legal, map, market, quests, ranking, reports, tribe, village, worlds], { packages: [networking] }) as { en: Record } diff --git a/i18n/pages/market.ts b/i18n/pages/market.ts new file mode 100644 index 0000000..24d408e --- /dev/null +++ b/i18n/pages/market.ts @@ -0,0 +1,158 @@ +import type { TranslationFile } from '@blax-software/i18n' + +// The market and everything it adds elsewhere: its building text and tag in `village`, its +// report in `reports`. mergeMessages merges these into the other page files' namespaces. +export default { + en: { + village: { + building_about: { + market: "Merchants carry wood, clay and iron to other villages: send them out, trade on the world's market, or set up routes that deliver again and again. Every level adds merchants.", + }, + effects: { + merchants: 'Merchants', + }, + tags: { + merchants: '{free}/{merchants}', + merchants_title: '{free} of {merchants} merchants free', + }, + }, + reports: { + kinds: { trade: 'Trade' }, + tone: { trade: 'Trade' }, + title_trade: '{from} delivers to {to}', + title_trade_offer: '{from} trades with {to}', + trade: { + arrived: 'The merchants have delivered to {to}.', + arrived_offer: 'The merchants have delivered to {to}, as agreed in an offer.', + from: 'From', + to: 'To', + cargo: 'Delivered', + }, + }, + market: { + no_market: 'This village has no market.', + merchants_free: 'Merchants {free}/{merchants}', + merchants_title: 'Free merchants of all; each carries {carry}', + merchants_needed: 'Merchants needed: {needed} of {merchants} free', + merchants_per_run: 'Merchants per run: {needed} of {merchants}', + target: 'Target', + target_placeholder: 'x|y', + village: 'Village', + distance: 'Distance', + fields: '{fields} fields', + duration: 'Way', + arrival: 'Arrival', + amount_of: 'Amount of {resource}', + tabs: { + send: 'Send', + offers: 'Offers', + mine: 'My offers', + routes: 'Routes', + trades: 'Under way', + }, + send: { + title: 'Send resources', + submit: 'Send', + }, + offers: { + title: 'Offers on the world', + refresh: 'Refresh', + gives: 'Gives', + wants: 'Wants', + any: 'Any', + none: 'No open offers.', + count: 'Times', + take: 'Accept', + own: 'Yours', + count_of: 'How often to accept the offer of {village}', + accept: 'Accept', + hint: 'Accepting sends your merchants with what the offer wants; the other side’s merchants bring what it gives.', + }, + mine: { + create: 'New offer', + give: 'I give', + give_amount: 'Amount given', + want: 'I want', + want_amount: 'Amount wanted', + count: 'Times', + count_hint: 'one trade each', + ratio: 'You ask {ratio} for each 1 you give; at most {max} times as much either way.', + reserved: 'Held back while the offer is open: {amount} {resource}', + submit: 'Post offer', + open: 'Open offers', + merchants: 'Merchants', + posted: 'Posted', + cancel: 'Cancel', + none: 'No open offers. Resources and merchants of an offer are held back until it is taken or cancelled.', + }, + routes: { + title: 'Trade routes', + used: '{used}/{max}', + route: 'Route', + next: 'Next run', + every: 'Every', + every_n: 'every {every}', + hours: 'Hours', + minutes: 'Minutes', + h: 'h', + min: 'min', + range: 'Between {min} and {max}, in real time.', + paused: 'Paused', + reason: { owner_changed: 'The village changed hands.' }, + last: 'Last run {when}:', + never: 'Not run yet', + nothing_sent: 'nothing sent: no stock or no free merchants', + pause: 'Pause', + resume: 'Resume', + edit: 'Edit', + delete: 'Delete', + save: 'Save', + cancel: 'Cancel', + none: 'No routes yet.', + hint: 'A route first runs one interval after it is made. On every run it sends what the stock and the free merchants allow, up to its amounts. It pauses itself when the target changes hands.', + create: 'New route', + full: 'All {max} routes are in use. A higher market runs more.', + submit: 'Create route', + }, + interval: { + dh: '{d} d {h} h', + hm: '{h} h {m} min', + h: '{h} h', + m: '{m} min', + }, + trades: { + title: 'Merchants under way', + merchants: '{busy}/{merchants} out', + incoming: 'Coming here', + own: 'Own merchants', + from: 'From {from}', + back_from: 'Home from {from}', + to: 'To {to}', + by: 'by {player}', + merchants_n: 'merchants: {count}', + route: 'Route', + offer: 'Offer', + trade: 'Trade', + arrives_in: 'Arrives in', + none_incoming: 'No deliveries on the way here.', + none_own: 'All merchants are at home.', + }, + errors: { + no_market: 'Build a market first.', + not_found: 'Not found: no village on that field, or the offer or route is gone.', + same_village: 'Pick another village than this one.', + barbarian: 'Barbarian villages don’t trade.', + nothing: 'Pick an amount.', + resources: 'Not enough resources.', + merchants: 'Not enough free merchants.', + same_resource: 'Give and want different resources.', + ratio: 'That ratio is beyond the market’s limit.', + amount: 'Amounts are whole numbers above 0.', + count: 'Not that many times.', + own_offer: 'That is your own offer.', + every: 'That interval is outside what the market allows.', + max_routes: 'All routes are in use.', + }, + }, + }, +} satisfies TranslationFile