diff --git a/app/components/market/Amounts.vue b/app/components/market/Amounts.vue new file mode 100644 index 0000000..fc45541 --- /dev/null +++ b/app/components/market/Amounts.vue @@ -0,0 +1,53 @@ + + + + diff --git a/app/components/market/Cargo.vue b/app/components/market/Cargo.vue new file mode 100644 index 0000000..2e3c6e7 --- /dev/null +++ b/app/components/market/Cargo.vue @@ -0,0 +1,14 @@ + + + + diff --git a/app/components/market/Interval.vue b/app/components/market/Interval.vue new file mode 100644 index 0000000..7b01ab9 --- /dev/null +++ b/app/components/market/Interval.vue @@ -0,0 +1,34 @@ + + + + diff --git a/app/components/market/MyOffers.vue b/app/components/market/MyOffers.vue new file mode 100644 index 0000000..f92a463 --- /dev/null +++ b/app/components/market/MyOffers.vue @@ -0,0 +1,126 @@ + + + + diff --git a/app/components/market/Routes.vue b/app/components/market/Routes.vue new file mode 100644 index 0000000..ab3f2e4 --- /dev/null +++ b/app/components/market/Routes.vue @@ -0,0 +1,151 @@ + + + + diff --git a/app/components/market/Send.vue b/app/components/market/Send.vue new file mode 100644 index 0000000..1fea004 --- /dev/null +++ b/app/components/market/Send.vue @@ -0,0 +1,54 @@ + + + + diff --git a/app/components/market/Target.vue b/app/components/market/Target.vue new file mode 100644 index 0000000..9a75c9f --- /dev/null +++ b/app/components/market/Target.vue @@ -0,0 +1,69 @@ + + + + diff --git a/app/components/market/Trades.vue b/app/components/market/Trades.vue new file mode 100644 index 0000000..88c7a2a --- /dev/null +++ b/app/components/market/Trades.vue @@ -0,0 +1,71 @@ + + + + diff --git a/app/components/market/WorldOffers.vue b/app/components/market/WorldOffers.vue new file mode 100644 index 0000000..5cf824e --- /dev/null +++ b/app/components/market/WorldOffers.vue @@ -0,0 +1,135 @@ + + + + diff --git a/app/components/village/Market.vue b/app/components/village/Market.vue new file mode 100644 index 0000000..ec2a2ef --- /dev/null +++ b/app/components/village/Market.vue @@ -0,0 +1,97 @@ + + + + diff --git a/app/composables/useMarket.ts b/app/composables/useMarket.ts new file mode 100644 index 0000000..29b482c --- /dev/null +++ b/app/composables/useMarket.ts @@ -0,0 +1,178 @@ +import type { Cost, GameError, MarketOffers, MarketState, TradePlan, TradeResource, TradeSide, VillageUpdated } from '~/types/game' +import { toRaw } from 'vue' +import type { VillageContext } from './useVillage' + +/** + * The market of the village in `v`: the last `market.show` snapshot and the market's + * intents. Every mutation answers with `market.show`; the village is refreshed after it + * for the stock. Sending, posting and accepting offers and creating routes commit + * resources, so they lock their forms (`busy`); cancelling, pausing, editing and deleting + * show their result at once and confirm in the background. Call it from a component's + * setup(): it listens for `village:updated` while mounted. + */ +export function useMarket(v: VillageContext) { + const state = ref(null) + const busy = ref(false) + const error = ref(null) + const generic = useErrorText() + const { t, te } = useI18n() + /** Refusals in the market's words first (`market.errors.`), then the game's. */ + const errorText = (e: unknown) => { + const code = (e as Partial | null)?.code + return code && te(`market.errors.${code}`) ? t(`market.errors.${code}`) : generic(e) + } + const villageId = computed(() => v.village.value?.id ?? null) + + /** Server time of the snapshot shown: an older answer never replaces it. */ + let shownAt = 0 + let blocking = 0 + + function apply(s: MarketState) { + const at = Date.parse(s.server_time) + if (at < shownAt) return + shownAt = at + state.value = s + } + + async function run(event: string, data: object = {}, opts: { block?: boolean; optimistic?: (s: MarketState) => void } = {}) { + const id = villageId.value + if (id === null) return false + const block = opts.block ?? !opts.optimistic + if (block) busy.value = ++blocking > 0 + error.value = null + if (opts.optimistic && state.value) { + const copy = JSON.parse(JSON.stringify(toRaw(state.value))) as MarketState + opts.optimistic(copy) + state.value = copy + } + try { + apply(await ws.send(event, { village_id: id, ...data })) + v.refresh() + return true + } catch (e) { + if (opts.optimistic) load() + error.value = errorText(e) + return false + } finally { + if (block) busy.value = --blocking > 0 + } + } + + // Reloads run quietly, one at a time; a call while one runs asks for one more after it. + let loading: Promise | null = null + let again = false + async function load(): Promise { + const id = villageId.value + if (id === null) return + if (loading) { + again = true + return loading + } + loading = (async () => { + try { + apply(await ws.send('market.show', { village_id: id })) + } catch (e) { + error.value = errorText(e) + } + })() + try { + await loading + } finally { + loading = null + if (again) { + again = false + load() + } + } + } + + watch( + villageId, + () => { + state.value = null + shownAt = 0 + load() + }, + { immediate: true }, + ) + + // Reload once when the next trade arrives or the next route runs. + const nextDue = computed(() => { + const s = state.value + if (!s) return null + const times = [...s.trades.map((t) => Date.parse(t.arrives_at)), ...s.routes.filter((r) => !r.paused).map((r) => Date.parse(r.next_at))] + return times.length ? Math.min(...times) : null + }) + watch( + () => nextDue.value !== null && v.now.value >= nextDue.value, + (due) => { + if (due) load() + }, + ) + + ws.listenWhileMounted('village:updated', null, (data) => { + if (data.village_id === villageId.value) load() + }) + + return { + state, + busy, + error, + load, + /** Who lives on the field and how long merchants walk; the refusal's text when the server says no. */ + preview: async (x: number, y: number): Promise<{ plan: TradePlan | null; refusal: string | null }> => { + try { + return { plan: await ws.send('market.preview', { village_id: villageId.value, x, y }), refusal: null } + } catch (e) { + return { plan: null, refusal: errorText(e) } + } + }, + send: (x: number, y: number, cargo: Cost) => run('market.send', { x, y, ...cargo }), + /** The world's open offers, nearest first; null after a refusal (shown in `error`). */ + offers: async (give: TradeResource | null, want: TradeResource | null): Promise => { + try { + return await ws.send('market.offers', { village_id: villageId.value, ...(give ? { give } : {}), ...(want ? { want } : {}) }) + } catch (e) { + error.value = errorText(e) + return null + } + }, + offer: (give: TradeSide, want: TradeSide, count: number) => run('market.offer', { give, want, count }), + cancelOffer: (offerId: number) => + run('market.cancelOffer', { offer_id: offerId }, { + optimistic: (s) => { + const o = s.offers.find((x) => x.id === offerId) + if (!o) return + s.offers = s.offers.filter((x) => x !== o) + if (s.market) { + s.market.free += o.count * o.merchants + s.market.busy -= o.count * o.merchants + } + }, + }), + accept: (offerId: number, count: number) => run('market.accept', { offer_id: offerId, count }), + routeCreate: (x: number, y: number, resources: Cost, every: number) => run('market.routeCreate', { x, y, ...resources, every }), + routeUpdate: (routeId: number, change: Partial & { every?: number; paused?: boolean }) => + run('market.routeUpdate', { route_id: routeId, ...change }, { + optimistic: (s) => { + const r = s.routes.find((x) => x.id === routeId) + if (!r) return + for (const res of ['wood', 'clay', 'iron'] as const) if (change[res] !== undefined) r.resources[res] = change[res] + if (change.every !== undefined) r.every = change.every + // Pausing by hand or resuming clears the reason the route paused itself. + if (change.paused !== undefined) { + r.paused = change.paused + r.paused_reason = null + } + }, + }), + routeDelete: (routeId: number) => + run('market.routeDelete', { route_id: routeId }, { + optimistic: (s) => { + s.routes = s.routes.filter((x) => x.id !== routeId) + }, + }), + } +} + +export type MarketContext = ReturnType diff --git a/app/pages/village/[id]/building/[bid].vue b/app/pages/village/[id]/building/[bid].vue index 902537f..f4eeeed 100644 --- a/app/pages/village/[id]/building/[bid].vue +++ b/app/pages/village/[id]/building/[bid].vue @@ -29,8 +29,11 @@ watch(building, (b) => { + + ) => string + +/** A route's interval in real time: "2 h 30 min", "45 min", "1 d 2 h". */ +export function formatInterval(seconds: number, t: Translate) { + const m = Math.round(Math.max(0, seconds) / 60) + const days = Math.floor(m / 1440) + const hours = Math.floor((m % 1440) / 60) + const minutes = m % 60 + if (days) return t('market.interval.dh', { d: days, h: hours }) + if (hours && minutes) return t('market.interval.hm', { h: hours, m: minutes }) + if (hours) return t('market.interval.h', { h: hours }) + return t('market.interval.m', { m: minutes }) +} + +/** The resources of a cargo with an amount above zero, in wood, clay, iron order. */ +export const cargoRows = (cargo: Cost | null | undefined) => (['wood', 'clay', 'iron'] as const).filter((r) => (cargo?.[r] ?? 0) > 0).map((r) => [r, cargo![r]] as const)