feat: the market's page: send resources to a field with the server's preview and (max) fills, the world's offers with filters and Accept, own offers with the ratio limit and merchants held back, trade routes with pause, edit and delete, and merchants under way with countdowns
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
af78f05106
commit
8ae8e75163
|
|
@ -0,0 +1,53 @@
|
|||
<script setup lang="ts">
|
||||
import type { Cost, Resources, TradeResource } from '~/types/game'
|
||||
|
||||
const props = defineProps<{
|
||||
id: string
|
||||
resources: TradeResource[]
|
||||
carry: number
|
||||
/** Merchants to count against: free ones for a send, all of them for a route. */
|
||||
merchants: number
|
||||
/** The projected stock: fill buttons take what it and the merchants allow. None on routes. */
|
||||
stock?: Resources | null
|
||||
}>()
|
||||
/** Amounts per resource; empty fields count as 0. */
|
||||
const amounts = defineModel<Partial<Cost>>({ required: true })
|
||||
|
||||
const amount = (r: TradeResource) => Math.max(0, Math.floor(Number(amounts.value[r]) || 0))
|
||||
const total = computed(() => props.resources.reduce((n, r) => n + amount(r), 0))
|
||||
/** Merchants that many resources take, one load of `carry` each. */
|
||||
const needed = computed(() => Math.ceil(total.value / props.carry))
|
||||
|
||||
/** The most of a resource the stock holds and the merchants carry next to the other amounts. */
|
||||
function most(r: TradeResource) {
|
||||
if (!props.stock) return 0
|
||||
const room = props.merchants * props.carry - (total.value - amount(r))
|
||||
return Math.max(0, Math.min(Math.floor(props.stock[r]), room))
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- One amount field per resource, a "(max)" fill button by stock and merchants, and the merchants it takes. -->
|
||||
<template>
|
||||
<div class="space-y-1.5">
|
||||
<div class="flex flex-wrap gap-x-5 gap-y-1.5">
|
||||
<div v-for="r in resources" :key="r" class="flex items-center gap-1.5">
|
||||
<IconResource :resource="r" class="size-5" :title="$t(`resources.${r}`)" />
|
||||
<input
|
||||
:id="`${id}-${r}`"
|
||||
v-model.number="amounts[r]"
|
||||
type="number"
|
||||
min="0"
|
||||
step="100"
|
||||
inputmode="numeric"
|
||||
class="input w-20 px-1.5 py-0.5 text-right tabular-nums"
|
||||
:aria-label="$t('market.amount_of', { resource: $t(`resources.${r}`) })"
|
||||
/>
|
||||
<button v-if="stock" type="button" class="btn-fill" :disabled="!most(r)" @click="amounts[r] = most(r)">({{ most(r) }})</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-sm" :class="needed > merchants ? 'text-blood-700' : 'text-ink-700'">
|
||||
<IconUi name="cart" class="mr-1 inline size-4 align-[-3px]" />
|
||||
{{ $t(stock ? 'market.merchants_needed' : 'market.merchants_per_run', { needed, merchants }) }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
<script setup lang="ts">
|
||||
import type { Cost } from '~/types/game'
|
||||
|
||||
defineProps<{ cargo: Cost | null }>()
|
||||
</script>
|
||||
|
||||
<!-- What merchants carry: an icon and amount per resource, nothing for none. -->
|
||||
<template>
|
||||
<span class="inline-flex flex-wrap items-center gap-x-2 gap-y-0.5 tabular-nums">
|
||||
<span v-for="[r, amount] in cargoRows(cargo)" :key="r" class="inline-flex items-center gap-0.5 whitespace-nowrap" :title="$t(`resources.${r}`)">
|
||||
<IconResource :resource="r" class="size-3.5" />{{ amount }}
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
<script setup lang="ts">
|
||||
const props = defineProps<{ id: string; min: number; max: number }>()
|
||||
/** Seconds of real time. */
|
||||
const every = defineModel<number>({ required: true })
|
||||
const { t } = useI18n()
|
||||
|
||||
const hours = ref(Math.floor(every.value / 3600))
|
||||
const minutes = ref(Math.round((every.value % 3600) / 60))
|
||||
watch([hours, minutes], () => {
|
||||
every.value = Math.max(0, Math.floor(Number(hours.value) || 0)) * 3600 + Math.max(0, Math.floor(Number(minutes.value) || 0)) * 60
|
||||
})
|
||||
watch(every, (s) => {
|
||||
if (s === Math.floor(Number(hours.value) || 0) * 3600 + Math.floor(Number(minutes.value) || 0) * 60) return
|
||||
hours.value = Math.floor(s / 3600)
|
||||
minutes.value = Math.round((s % 3600) / 60)
|
||||
})
|
||||
const outside = computed(() => every.value < props.min || every.value > props.max)
|
||||
</script>
|
||||
|
||||
<!-- A route's interval in real hours and minutes, with the range the market allows. -->
|
||||
<template>
|
||||
<div class="space-y-0.5 text-sm">
|
||||
<div class="flex flex-wrap items-center gap-1.5">
|
||||
<label :for="`${id}-h`" class="label mb-0 w-24">{{ $t('market.routes.every') }}</label>
|
||||
<input :id="`${id}-h`" v-model.number="hours" type="number" min="0" inputmode="numeric" class="input w-14 px-1.5 py-0.5 text-right tabular-nums" :aria-label="$t('market.routes.hours')" />
|
||||
<span>{{ $t('market.routes.h') }}</span>
|
||||
<input v-model.number="minutes" type="number" min="0" max="59" step="5" inputmode="numeric" class="input w-14 px-1.5 py-0.5 text-right tabular-nums" :aria-label="$t('market.routes.minutes')" />
|
||||
<span>{{ $t('market.routes.min') }}</span>
|
||||
</div>
|
||||
<p class="text-xs" :class="outside ? 'text-blood-700' : 'text-ink-500'">
|
||||
{{ $t('market.routes.range', { min: formatInterval(min, t), max: formatInterval(max, t) }) }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,126 @@
|
|||
<script setup lang="ts">
|
||||
import type { MarketState, OwnOffer, Resources, TradeResource } from '~/types/game'
|
||||
import type { MarketContext } from '~/composables/useMarket'
|
||||
|
||||
const props = defineProps<{
|
||||
market: NonNullable<MarketState['market']>
|
||||
offers: OwnOffer[]
|
||||
stock: Resources
|
||||
now: number
|
||||
busy: boolean
|
||||
offer: MarketContext['offer']
|
||||
cancel: MarketContext['cancelOffer']
|
||||
}>()
|
||||
const { t } = useI18n()
|
||||
|
||||
const give = ref<TradeResource>(props.market.resources[0] ?? 'wood')
|
||||
const want = ref<TradeResource>(props.market.resources[1] ?? 'clay')
|
||||
const giveAmount = ref<number | ''>(1000)
|
||||
const wantAmount = ref<number | ''>(1000)
|
||||
const count = ref<number | ''>(1)
|
||||
|
||||
const n = (v: number | '') => Math.max(0, Math.floor(Number(v) || 0))
|
||||
const merchants = computed(() => Math.ceil(n(giveAmount.value) / props.market.carry) * n(count.value))
|
||||
const reserved = computed(() => n(giveAmount.value) * n(count.value))
|
||||
/** Wanted per given, as the ratio line shows it. */
|
||||
const ratio = computed(() => (n(giveAmount.value) ? n(wantAmount.value) / n(giveAmount.value) : 0))
|
||||
const outOfRatio = computed(() => {
|
||||
const g = n(giveAmount.value)
|
||||
const w = n(wantAmount.value)
|
||||
return !!g && !!w && (w > g * props.market.max_ratio || g > w * props.market.max_ratio)
|
||||
})
|
||||
const problem = computed(() => {
|
||||
if (give.value === want.value) return t('market.errors.same_resource')
|
||||
if (outOfRatio.value) return t('market.errors.ratio')
|
||||
if (reserved.value > Math.floor(props.stock[give.value])) return t('market.errors.resources')
|
||||
if (merchants.value > props.market.free) return t('market.errors.merchants')
|
||||
return null
|
||||
})
|
||||
const canPost = computed(() => !props.busy && n(giveAmount.value) > 0 && n(wantAmount.value) > 0 && n(count.value) > 0 && !problem.value)
|
||||
|
||||
async function submit() {
|
||||
if (!canPost.value) return
|
||||
if (await props.offer({ resource: give.value, amount: n(giveAmount.value) }, { resource: want.value, amount: n(wantAmount.value) }, n(count.value))) count.value = 1
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Own offers: post one (what to give, what for, how often; resources and merchants are held for it) and the open ones with Cancel. -->
|
||||
<template>
|
||||
<div class="grid gap-3 @4xl:grid-cols-[minmax(0,22rem)_minmax(0,1fr)]">
|
||||
<section class="panel self-start">
|
||||
<div class="panel-head">
|
||||
<h2 class="panel-title">{{ $t('market.mine.create') }}</h2>
|
||||
</div>
|
||||
<form class="panel-body space-y-2.5 text-sm" @submit.prevent="submit">
|
||||
<div class="grid grid-cols-[5.5rem_auto_1fr] items-center gap-x-2 gap-y-1.5">
|
||||
<label for="offer-give" class="font-semibold text-ink-700">{{ $t('market.mine.give') }}</label>
|
||||
<select id="offer-give" v-model="give" class="input w-auto py-0.5">
|
||||
<option v-for="r in market.resources" :key="r" :value="r">{{ $t(`resources.${r}`) }}</option>
|
||||
</select>
|
||||
<input v-model.number="giveAmount" type="number" min="1" step="100" inputmode="numeric" class="input w-24 px-1.5 py-0.5 text-right tabular-nums" :aria-label="$t('market.mine.give_amount')" />
|
||||
|
||||
<label for="offer-want" class="font-semibold text-ink-700">{{ $t('market.mine.want') }}</label>
|
||||
<select id="offer-want" v-model="want" class="input w-auto py-0.5">
|
||||
<option v-for="r in market.resources" :key="r" :value="r">{{ $t(`resources.${r}`) }}</option>
|
||||
</select>
|
||||
<input v-model.number="wantAmount" type="number" min="1" step="100" inputmode="numeric" class="input w-24 px-1.5 py-0.5 text-right tabular-nums" :aria-label="$t('market.mine.want_amount')" />
|
||||
|
||||
<label for="offer-count" class="font-semibold text-ink-700">{{ $t('market.mine.count') }}</label>
|
||||
<input id="offer-count" v-model.number="count" type="number" min="1" inputmode="numeric" class="input w-16 px-1.5 py-0.5 text-right tabular-nums" />
|
||||
<span class="text-xs text-ink-500">{{ $t('market.mine.count_hint') }}</span>
|
||||
</div>
|
||||
|
||||
<ul class="space-y-0.5 text-ink-700">
|
||||
<li :class="outOfRatio ? 'text-blood-700' : ''">
|
||||
{{ $t('market.mine.ratio', { ratio: ratio.toFixed(2), max: market.max_ratio }) }}
|
||||
</li>
|
||||
<li :class="merchants > market.free ? 'text-blood-700' : ''">
|
||||
<IconUi name="cart" class="mr-1 inline size-4 align-[-3px]" />{{ $t('market.merchants_needed', { needed: merchants, merchants: market.free }) }}
|
||||
</li>
|
||||
<li :class="reserved > Math.floor(stock[give]) ? 'text-blood-700' : ''">
|
||||
{{ $t('market.mine.reserved', { amount: reserved, resource: $t(`resources.${give}`) }) }}
|
||||
</li>
|
||||
</ul>
|
||||
<p v-if="problem && n(giveAmount) && n(wantAmount)" class="text-blood-700">{{ problem }}</p>
|
||||
<button type="submit" class="btn btn-primary" :disabled="!canPost">{{ $t('market.mine.submit') }}</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="panel self-start">
|
||||
<div class="panel-head">
|
||||
<h2 class="panel-title">{{ $t('market.mine.open') }}</h2>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<table v-if="offers.length" class="grid-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ $t('market.offers.gives') }}</th>
|
||||
<th>{{ $t('market.offers.wants') }}</th>
|
||||
<th class="text-right">{{ $t('market.offers.count') }}</th>
|
||||
<th class="hidden text-right @lg:table-cell">{{ $t('market.mine.merchants') }}</th>
|
||||
<th class="hidden @xl:table-cell">{{ $t('market.mine.posted') }}</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="o in offers" :key="o.id">
|
||||
<td class="whitespace-nowrap tabular-nums">
|
||||
<span class="inline-flex items-center gap-1"><IconResource :resource="o.give.resource" class="size-4" :title="$t(`resources.${o.give.resource}`)" />{{ o.give.amount }}</span>
|
||||
</td>
|
||||
<td class="whitespace-nowrap tabular-nums">
|
||||
<span class="inline-flex items-center gap-1"><IconResource :resource="o.want.resource" class="size-4" :title="$t(`resources.${o.want.resource}`)" />{{ o.want.amount }}</span>
|
||||
</td>
|
||||
<td class="text-right tabular-nums">{{ o.count }}</td>
|
||||
<td class="hidden text-right tabular-nums @lg:table-cell">{{ o.count * o.merchants }}</td>
|
||||
<td class="hidden whitespace-nowrap text-ink-700 tabular-nums @xl:table-cell">{{ formatArrival(Date.parse(o.created_at), now, t) }}</td>
|
||||
<td class="text-right">
|
||||
<button type="button" class="btn btn-outline px-2 py-0.5 text-xs" @click="cancel(o.id)">{{ $t('market.mine.cancel') }}</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p v-else class="text-sm text-ink-500">{{ $t('market.mine.none') }}</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,151 @@
|
|||
<script setup lang="ts">
|
||||
import type { Cost, MarketState, TradePlan, TradeRoute } from '~/types/game'
|
||||
import type { MarketContext } from '~/composables/useMarket'
|
||||
|
||||
const props = defineProps<{
|
||||
market: NonNullable<MarketState['market']>
|
||||
routes: TradeRoute[]
|
||||
worldId: number
|
||||
now: number
|
||||
busy: boolean
|
||||
secondsUntil: (iso: string) => number
|
||||
preview: MarketContext['preview']
|
||||
create: MarketContext['routeCreate']
|
||||
update: MarketContext['routeUpdate']
|
||||
remove: MarketContext['routeDelete']
|
||||
}>()
|
||||
const { t } = useI18n()
|
||||
|
||||
const limits = computed(() => props.market.route)
|
||||
const clampEvery = (s: number) => Math.min(limits.value.max_every, Math.max(limits.value.min_every, s))
|
||||
const n = (v: unknown) => Math.max(0, Math.floor(Number(v) || 0))
|
||||
const cost = (a: Partial<Cost>): Cost => ({ wood: n(a.wood), clay: n(a.clay), iron: n(a.iron) })
|
||||
const sum = (c: Cost) => c.wood + c.clay + c.iron
|
||||
const inRange = (s: number) => s >= limits.value.min_every && s <= limits.value.max_every
|
||||
|
||||
// A new route: target, amounts per run, interval.
|
||||
const target = ref('')
|
||||
const plan = ref<TradePlan | null>(null)
|
||||
const amounts = ref<Partial<Cost>>({})
|
||||
const every = ref(clampEvery(3600))
|
||||
const full = computed(() => props.routes.length >= limits.value.max_routes)
|
||||
const canCreate = computed(() => !props.busy && !full.value && !!plan.value && sum(cost(amounts.value)) > 0 && inRange(every.value))
|
||||
|
||||
async function submit() {
|
||||
const c = parseCoords(target.value)
|
||||
if (!c || !canCreate.value) return
|
||||
if (await props.create(c.x, c.y, cost(amounts.value), every.value)) {
|
||||
target.value = ''
|
||||
amounts.value = {}
|
||||
}
|
||||
}
|
||||
|
||||
// One route at a time is edited in its own row.
|
||||
const editing = ref<number | null>(null)
|
||||
const editAmounts = ref<Partial<Cost>>({})
|
||||
const editEvery = ref(3600)
|
||||
function edit(r: TradeRoute) {
|
||||
editing.value = r.id
|
||||
editAmounts.value = { ...r.resources }
|
||||
editEvery.value = r.every
|
||||
}
|
||||
async function save(r: TradeRoute) {
|
||||
const resources = cost(editAmounts.value)
|
||||
if (!sum(resources) || !inRange(editEvery.value)) return
|
||||
editing.value = null
|
||||
await props.update(r.id, { ...resources, every: editEvery.value })
|
||||
}
|
||||
|
||||
const mapLink = (r: TradeRoute) => ({ path: `/map/${props.worldId}`, query: { x: r.to.x, y: r.to.y } })
|
||||
</script>
|
||||
|
||||
<!-- Trade routes: each one's target, what it sends and how often, the next run and the last delivery; pause, edit, delete; and a new one. -->
|
||||
<template>
|
||||
<div class="grid gap-3 @4xl:grid-cols-[minmax(0,1fr)_minmax(0,22rem)]">
|
||||
<section class="panel self-start">
|
||||
<div class="panel-head">
|
||||
<h2 class="panel-title">{{ $t('market.routes.title') }}</h2>
|
||||
<span class="badge badge-plain tabular-nums">{{ $t('market.routes.used', { used: routes.length, max: limits.max_routes }) }}</span>
|
||||
</div>
|
||||
<div class="panel-body space-y-2">
|
||||
<table v-if="routes.length" class="grid-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ $t('market.routes.route') }}</th>
|
||||
<th>{{ $t('market.routes.next') }}</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-for="r in routes" :key="r.id">
|
||||
<tr :class="r.paused ? 'bg-parchment-100 text-ink-500' : ''">
|
||||
<td class="py-1">
|
||||
<NuxtLink :to="mapLink(r)" class="font-semibold text-ink-900 hover:underline">{{ villageLabel(r.to) }}</NuxtLink>
|
||||
<span class="text-xs text-ink-500"> {{ r.to.player?.name }}</span>
|
||||
<span class="mt-0.5 flex flex-wrap items-center gap-x-2 text-xs text-ink-700">
|
||||
<MarketCargo :cargo="r.resources" />
|
||||
<span class="inline-flex items-center gap-0.5 whitespace-nowrap"><IconUi name="repeat" class="size-3.5" />{{ $t('market.routes.every_n', { every: formatInterval(r.every, t) }) }}</span>
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-1 text-sm">
|
||||
<span v-if="r.paused" class="badge badge-gold">{{ $t('market.routes.paused') }}</span>
|
||||
<span v-else class="font-semibold whitespace-nowrap tabular-nums">{{ formatDuration(secondsUntil(r.next_at)) }}</span>
|
||||
<span v-if="r.paused_reason" class="block text-xs text-blood-700">{{ $t(`market.routes.reason.${r.paused_reason}`) }}</span>
|
||||
<span class="mt-0.5 block text-xs text-ink-500">
|
||||
<template v-if="r.last_sent_at">
|
||||
{{ $t('market.routes.last', { when: formatArrival(Date.parse(r.last_sent_at), now, t) }) }}
|
||||
<MarketCargo v-if="r.last_cargo && sum(r.last_cargo)" :cargo="r.last_cargo" />
|
||||
<span v-else class="text-blood-700">{{ $t('market.routes.nothing_sent') }}</span>
|
||||
</template>
|
||||
<template v-else>{{ $t('market.routes.never') }}</template>
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-1 text-right">
|
||||
<span class="inline-flex flex-wrap justify-end gap-1">
|
||||
<button type="button" class="btn btn-outline px-1.5 py-0.5 text-xs" @click="update(r.id, { paused: !r.paused })">
|
||||
{{ r.paused ? $t('market.routes.resume') : $t('market.routes.pause') }}
|
||||
</button>
|
||||
<button type="button" class="btn btn-outline px-1.5 py-0.5 text-xs" :aria-expanded="editing === r.id" @click="editing === r.id ? (editing = null) : edit(r)">
|
||||
{{ $t('market.routes.edit') }}
|
||||
</button>
|
||||
<button type="button" class="btn btn-outline px-1.5 py-0.5 text-xs text-blood-700" @click="remove(r.id)">{{ $t('market.routes.delete') }}</button>
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="editing === r.id">
|
||||
<td colspan="3" class="bg-parchment-100 py-2">
|
||||
<form class="space-y-2" @submit.prevent="save(r)">
|
||||
<MarketAmounts :id="`route-${r.id}`" v-model="editAmounts" :resources="market.resources" :carry="market.carry" :merchants="market.merchants" />
|
||||
<MarketInterval :id="`route-${r.id}-every`" v-model="editEvery" :min="limits.min_every" :max="limits.max_every" />
|
||||
<div class="flex gap-1.5">
|
||||
<button type="submit" class="btn btn-primary" :disabled="!sum(cost(editAmounts)) || !inRange(editEvery)">{{ $t('market.routes.save') }}</button>
|
||||
<button type="button" class="btn btn-outline" @click="editing = null">{{ $t('market.routes.cancel') }}</button>
|
||||
</div>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
<p v-else class="text-sm text-ink-500">{{ $t('market.routes.none') }}</p>
|
||||
<p class="text-xs text-ink-500">{{ $t('market.routes.hint') }}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel self-start">
|
||||
<div class="panel-head">
|
||||
<h2 class="panel-title">{{ $t('market.routes.create') }}</h2>
|
||||
</div>
|
||||
<form class="panel-body space-y-3" @submit.prevent="submit">
|
||||
<p v-if="full" class="text-sm text-blood-700">{{ $t('market.routes.full', { max: limits.max_routes }) }}</p>
|
||||
<MarketTarget id="route-target" v-model="target" v-model:plan="plan" :now="now" :preview="preview" />
|
||||
<MarketAmounts id="route-new" v-model="amounts" :resources="market.resources" :carry="market.carry" :merchants="market.merchants" />
|
||||
<MarketInterval id="route-every" v-model="every" :min="limits.min_every" :max="limits.max_every" />
|
||||
<button type="submit" class="btn btn-primary" :disabled="!canCreate">
|
||||
<IconUi name="repeat" class="size-4" />
|
||||
{{ $t('market.routes.submit') }}
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
<script setup lang="ts">
|
||||
import type { Cost, MarketState, Resources, TradePlan } from '~/types/game'
|
||||
import type { MarketContext } from '~/composables/useMarket'
|
||||
|
||||
const props = defineProps<{
|
||||
market: NonNullable<MarketState['market']>
|
||||
stock: Resources
|
||||
now: number
|
||||
busy: boolean
|
||||
/** Field to aim at, e.g. from the map. */
|
||||
initialTarget: { x: number; y: number } | null
|
||||
preview: MarketContext['preview']
|
||||
send: MarketContext['send']
|
||||
}>()
|
||||
|
||||
const target = ref(props.initialTarget ? `${props.initialTarget.x}|${props.initialTarget.y}` : '')
|
||||
const plan = ref<TradePlan | null>(null)
|
||||
const amounts = ref<Partial<Cost>>({})
|
||||
|
||||
const cargo = computed<Cost>(() => ({
|
||||
wood: Math.max(0, Math.floor(Number(amounts.value.wood) || 0)),
|
||||
clay: Math.max(0, Math.floor(Number(amounts.value.clay) || 0)),
|
||||
iron: Math.max(0, Math.floor(Number(amounts.value.iron) || 0)),
|
||||
}))
|
||||
const total = computed(() => cargo.value.wood + cargo.value.clay + cargo.value.iron)
|
||||
const fits = computed(
|
||||
() => Math.ceil(total.value / props.market.carry) <= props.market.free && props.market.resources.every((r) => cargo.value[r] <= Math.floor(props.stock[r])),
|
||||
)
|
||||
const coords = computed(() => parseCoords(target.value))
|
||||
const canSend = computed(() => !props.busy && !!plan.value && total.value > 0 && fits.value)
|
||||
|
||||
async function submit() {
|
||||
const c = coords.value
|
||||
if (!c || !canSend.value) return
|
||||
if (await props.send(c.x, c.y, cargo.value)) amounts.value = {}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Send resources: the target field with what the server says about it, an amount per resource, the merchants it takes, Send. -->
|
||||
<template>
|
||||
<section class="panel">
|
||||
<div class="panel-head">
|
||||
<h2 class="panel-title">{{ $t('market.send.title') }}</h2>
|
||||
</div>
|
||||
<form class="panel-body space-y-3" @submit.prevent="submit">
|
||||
<MarketTarget id="market-send-target" v-model="target" v-model:plan="plan" :now="now" :preview="preview" />
|
||||
<MarketAmounts id="market-send" v-model="amounts" :resources="market.resources" :carry="market.carry" :merchants="market.free" :stock="stock" />
|
||||
<button type="submit" class="btn btn-primary" :disabled="!canSend">
|
||||
<IconUi name="cart" class="size-4" />
|
||||
{{ $t('market.send.submit') }}
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
<script setup lang="ts">
|
||||
import type { TradePlan } from '~/types/game'
|
||||
|
||||
const props = defineProps<{
|
||||
id: string
|
||||
now: number
|
||||
preview: (x: number, y: number) => Promise<{ plan: TradePlan | null; refusal: string | null }>
|
||||
}>()
|
||||
/** The field as typed, "x|y". */
|
||||
const target = defineModel<string>({ required: true })
|
||||
/** What the server says about the field: the village there and the walk. */
|
||||
const plan = defineModel<TradePlan | null>('plan', { default: null })
|
||||
const { t } = useI18n()
|
||||
|
||||
const coords = computed(() => parseCoords(target.value))
|
||||
const refusal = ref<string | null>(null)
|
||||
|
||||
// Asked again a moment after each change; answers for a field that changed meanwhile are dropped.
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
watch(
|
||||
coords,
|
||||
(c) => {
|
||||
clearTimeout(timer)
|
||||
plan.value = null
|
||||
refusal.value = null
|
||||
if (!c) return
|
||||
timer = setTimeout(async () => {
|
||||
const result = await props.preview(c.x, c.y)
|
||||
if (coords.value?.x !== c.x || coords.value?.y !== c.y) return
|
||||
plan.value = result.plan
|
||||
refusal.value = result.refusal
|
||||
}, 250)
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
onBeforeUnmount(() => clearTimeout(timer))
|
||||
</script>
|
||||
|
||||
<!-- The target field, typed like the rally point's, and what the server says about it: the village, the distance and the walk. -->
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<div class="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<label :for="id" class="label mb-0 w-24">{{ $t('market.target') }}</label>
|
||||
<input
|
||||
:id="id"
|
||||
v-model="target"
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
autocomplete="off"
|
||||
:placeholder="$t('market.target_placeholder')"
|
||||
class="input w-32 tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
<dl v-if="plan" class="grid grid-cols-[auto_1fr] gap-x-4 gap-y-0.5 border border-parchment-300 bg-parchment-50 px-2 py-1.5 text-sm">
|
||||
<dt class="text-ink-500">{{ $t('market.village') }}</dt>
|
||||
<dd class="min-w-0 font-semibold">
|
||||
{{ villageLabel(plan.target) }}
|
||||
<span class="font-normal text-ink-500">{{ plan.target.player?.name }}</span>
|
||||
</dd>
|
||||
<dt class="text-ink-500">{{ $t('market.distance') }}</dt>
|
||||
<dd class="tabular-nums">{{ $t('market.fields', { fields: plan.distance.toFixed(1) }) }}</dd>
|
||||
<dt class="text-ink-500">{{ $t('market.duration') }}</dt>
|
||||
<dd class="tabular-nums">{{ formatDuration(plan.seconds) }}</dd>
|
||||
<dt class="text-ink-500">{{ $t('market.arrival') }}</dt>
|
||||
<dd class="tabular-nums">{{ formatArrival(now + plan.seconds * 1000, now, t) }}</dd>
|
||||
</dl>
|
||||
<p v-else-if="refusal" class="text-sm text-blood-700">{{ refusal }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
<script setup lang="ts">
|
||||
import type { MarketState, Trade, VillageRef } from '~/types/game'
|
||||
|
||||
const props = defineProps<{
|
||||
market: NonNullable<MarketState['market']>
|
||||
trades: Trade[]
|
||||
worldId: number
|
||||
now: number
|
||||
secondsUntil: (iso: string) => number
|
||||
}>()
|
||||
const { t } = useI18n()
|
||||
|
||||
const incoming = computed(() => props.trades.filter((x) => x.kind === 'in'))
|
||||
const own = computed(() => props.trades.filter((x) => x.kind !== 'in'))
|
||||
|
||||
function title(x: Trade) {
|
||||
if (x.kind === 'in') return t('market.trades.from', { from: villageLabel(x.from) })
|
||||
if (x.kind === 'back') return t('market.trades.back_from', { from: villageLabel(x.from) })
|
||||
return t('market.trades.to', { to: villageLabel(x.to) })
|
||||
}
|
||||
/** The other end, for the map link. */
|
||||
const other = (x: Trade): VillageRef => (x.kind === 'out' ? x.to : x.from)
|
||||
</script>
|
||||
|
||||
<!-- Merchants under way, like the rally point's movements: deliveries coming here first, then this village's merchants out and home. -->
|
||||
<template>
|
||||
<section class="panel">
|
||||
<div class="panel-head">
|
||||
<h2 class="panel-title">{{ $t('market.trades.title') }}</h2>
|
||||
<span class="badge badge-plain tabular-nums">{{ $t('market.trades.merchants', { busy: market.busy, merchants: market.merchants }) }}</span>
|
||||
</div>
|
||||
<div class="panel-body space-y-4">
|
||||
<div v-for="list in [{ key: 'incoming', rows: incoming }, { key: 'own', rows: own }]" :key="list.key">
|
||||
<h3 class="mb-1 text-xs font-semibold tracking-wide text-ink-500 uppercase">{{ $t(`market.trades.${list.key}`) }}</h3>
|
||||
<table v-if="list.rows.length" class="w-full text-sm">
|
||||
<thead class="sr-only">
|
||||
<tr>
|
||||
<th>{{ $t('market.trades.trade') }}</th>
|
||||
<th class="hidden @md:table-cell">{{ $t('market.arrival') }}</th>
|
||||
<th>{{ $t('market.trades.arrives_in') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-parchment-300">
|
||||
<tr v-for="x in list.rows" :key="x.id">
|
||||
<td class="py-1.5 pr-2">
|
||||
<div class="flex items-start gap-2">
|
||||
<IconUi :name="x.kind === 'back' ? 'return' : 'cart'" class="mt-0.5 size-4 shrink-0" />
|
||||
<div class="min-w-0">
|
||||
<NuxtLink :to="{ path: `/map/${worldId}`, query: { x: other(x).x, y: other(x).y } }" class="font-semibold hover:underline">{{ title(x) }}</NuxtLink>
|
||||
<span v-if="x.kind === 'in' && x.from.player" class="text-ink-500"> {{ $t('market.trades.by', { player: x.from.player.name }) }}</span>
|
||||
<div class="mt-0.5 flex flex-wrap items-center gap-x-2.5 gap-y-0.5 text-xs text-ink-700">
|
||||
<MarketCargo v-if="x.cargo" :cargo="x.cargo" />
|
||||
<span v-if="x.kind !== 'in'" class="inline-flex items-center gap-0.5 whitespace-nowrap tabular-nums">
|
||||
<IconUi name="cart" class="size-3.5" />{{ $t('market.trades.merchants_n', { count: x.merchants }) }}
|
||||
</span>
|
||||
<span v-if="x.route_id !== null" class="badge badge-plain">{{ $t('market.trades.route') }}</span>
|
||||
<span v-if="x.offer" class="badge badge-plain">{{ $t('market.trades.offer') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="hidden py-1.5 pr-2 whitespace-nowrap text-ink-700 tabular-nums @md:table-cell">{{ formatArrival(Date.parse(x.arrives_at), now, t) }}</td>
|
||||
<td class="py-1.5 text-right font-semibold whitespace-nowrap tabular-nums">{{ formatDuration(secondsUntil(x.arrives_at)) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p v-else class="text-sm text-ink-500">{{ $t(`market.trades.none_${list.key}`) }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,135 @@
|
|||
<script setup lang="ts">
|
||||
import type { MarketOffers, MarketState, Resources, TradeResource, WorldOffer } from '~/types/game'
|
||||
import type { MarketContext } from '~/composables/useMarket'
|
||||
|
||||
const props = defineProps<{
|
||||
market: NonNullable<MarketState['market']>
|
||||
stock: Resources
|
||||
worldId: number
|
||||
busy: boolean
|
||||
offers: MarketContext['offers']
|
||||
accept: MarketContext['accept']
|
||||
}>()
|
||||
const { t } = useI18n()
|
||||
|
||||
const give = ref<TradeResource | null>(null)
|
||||
const want = ref<TradeResource | null>(null)
|
||||
const list = ref<MarketOffers | null>(null)
|
||||
const loading = ref(false)
|
||||
/** The count typed per offer; 1 until changed. */
|
||||
const counts = reactive<Record<number, number>>({})
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
const filters = [give.value, want.value]
|
||||
const result = await props.offers(give.value, want.value)
|
||||
// Drop answers for filters that changed meanwhile.
|
||||
if (filters[0] === give.value && filters[1] === want.value) list.value = result
|
||||
loading.value = false
|
||||
}
|
||||
watch([give, want], load, { immediate: true })
|
||||
|
||||
const count = (o: WorldOffer) => Math.max(1, Math.min(o.count, Math.floor(Number(counts[o.id]) || 1)))
|
||||
/** Why an offer can't be taken that many times right now, or null. */
|
||||
function blocked(o: WorldOffer) {
|
||||
const n = count(o)
|
||||
if (o.want.amount * n > Math.floor(props.stock[o.want.resource])) return t('market.errors.resources')
|
||||
if (Math.ceil(o.want.amount / props.market.carry) * n > props.market.free) return t('market.errors.merchants')
|
||||
return null
|
||||
}
|
||||
|
||||
async function take(o: WorldOffer) {
|
||||
if (props.busy || blocked(o)) return
|
||||
if (await props.accept(o.id, count(o))) {
|
||||
delete counts[o.id]
|
||||
load()
|
||||
}
|
||||
}
|
||||
|
||||
const mapLink = (o: WorldOffer) => ({ path: `/map/${props.worldId}`, query: { x: o.village.x, y: o.village.y } })
|
||||
</script>
|
||||
|
||||
<!-- The world's open offers, nearest first: what each gives and wants, how often, how far; take one or several. -->
|
||||
<template>
|
||||
<section class="panel">
|
||||
<div class="panel-head">
|
||||
<h2 class="panel-title">{{ $t('market.offers.title') }}</h2>
|
||||
<button type="button" class="btn btn-outline px-2 py-0.5 text-xs" :disabled="loading" @click="load">{{ $t('market.offers.refresh') }}</button>
|
||||
</div>
|
||||
<div class="panel-body space-y-2">
|
||||
<div class="flex flex-wrap items-center gap-x-4 gap-y-1.5 text-sm">
|
||||
<label class="flex items-center gap-1.5">
|
||||
<span class="font-semibold text-ink-700">{{ $t('market.offers.gives') }}</span>
|
||||
<select v-model="give" class="input w-auto py-0.5">
|
||||
<option :value="null">{{ $t('market.offers.any') }}</option>
|
||||
<option v-for="r in market.resources" :key="r" :value="r">{{ $t(`resources.${r}`) }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="flex items-center gap-1.5">
|
||||
<span class="font-semibold text-ink-700">{{ $t('market.offers.wants') }}</span>
|
||||
<select v-model="want" class="input w-auto py-0.5">
|
||||
<option :value="null">{{ $t('market.offers.any') }}</option>
|
||||
<option v-for="r in market.resources" :key="r" :value="r">{{ $t(`resources.${r}`) }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p v-if="!list" class="text-sm text-ink-500">{{ $t('common.loading') }}</p>
|
||||
<p v-else-if="!list.offers.length" class="text-sm text-ink-500">{{ $t('market.offers.none') }}</p>
|
||||
<table v-else class="grid-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ $t('market.offers.gives') }}</th>
|
||||
<th>{{ $t('market.offers.wants') }}</th>
|
||||
<th class="hidden text-right @lg:table-cell">{{ $t('market.offers.count') }}</th>
|
||||
<th>{{ $t('market.village') }}</th>
|
||||
<th class="hidden text-right @xl:table-cell">{{ $t('market.duration') }}</th>
|
||||
<th class="text-right">{{ $t('market.offers.take') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="o in list.offers" :key="o.id" :class="o.own ? 'bg-parchment-100' : ''">
|
||||
<td class="whitespace-nowrap tabular-nums">
|
||||
<span class="inline-flex items-center gap-1"><IconResource :resource="o.give.resource" class="size-4" :title="$t(`resources.${o.give.resource}`)" />{{ o.give.amount }}</span>
|
||||
</td>
|
||||
<td class="whitespace-nowrap tabular-nums">
|
||||
<span class="inline-flex items-center gap-1"><IconResource :resource="o.want.resource" class="size-4" :title="$t(`resources.${o.want.resource}`)" />{{ o.want.amount }}</span>
|
||||
<span class="ml-1 text-xs text-ink-500 @lg:hidden">×{{ o.count }}</span>
|
||||
</td>
|
||||
<td class="hidden text-right tabular-nums @lg:table-cell">{{ o.count }}</td>
|
||||
<td class="min-w-0">
|
||||
<NuxtLink :to="mapLink(o)" class="font-semibold hover:underline">{{ villageLabel(o.village) }}</NuxtLink>
|
||||
<span class="block text-xs text-ink-500">
|
||||
{{ o.village.player?.name }}
|
||||
<span class="tabular-nums @xl:hidden">· {{ formatDuration(o.seconds) }}</span>
|
||||
</span>
|
||||
</td>
|
||||
<td class="hidden text-right whitespace-nowrap tabular-nums @xl:table-cell">
|
||||
{{ formatDuration(o.seconds) }}
|
||||
<span class="block text-xs text-ink-500">{{ $t('market.fields', { fields: o.distance.toFixed(1) }) }}</span>
|
||||
</td>
|
||||
<td class="text-right">
|
||||
<span v-if="o.own" class="badge badge-plain">{{ $t('market.offers.own') }}</span>
|
||||
<span v-else class="inline-flex items-center justify-end gap-1">
|
||||
<input
|
||||
v-model.number="counts[o.id]"
|
||||
type="number"
|
||||
min="1"
|
||||
:max="o.count"
|
||||
inputmode="numeric"
|
||||
placeholder="1"
|
||||
class="input w-11 px-1 py-0.5 text-right tabular-nums"
|
||||
:aria-label="$t('market.offers.count_of', { village: villageLabel(o.village) })"
|
||||
/>
|
||||
<button type="button" class="btn btn-primary px-2 py-0.5" :disabled="busy || !!blocked(o)" :title="blocked(o) ?? undefined" @click="take(o)">
|
||||
{{ $t('market.offers.accept') }}
|
||||
</button>
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="text-xs text-ink-500">{{ $t('market.offers.hint') }}</p>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
<script setup lang="ts">
|
||||
import type { UiIconName } from '~/components/icon/Ui.vue'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const v = useVillageContext()
|
||||
const m = useMarket(v)
|
||||
const { t } = useI18n()
|
||||
const village = computed(() => v.village.value!)
|
||||
const state = computed(() => m.state.value)
|
||||
|
||||
// The market's parts are tabs, like the rally point's: send, the world's offers, own
|
||||
// offers, trade routes, merchants under way.
|
||||
type Tab = 'send' | 'offers' | 'mine' | 'routes' | 'trades'
|
||||
const OTHERS: Tab[] = ['offers', 'mine', 'routes', 'trades']
|
||||
const tab = computed<Tab>({
|
||||
get: () => (OTHERS.includes(route.query.tab as Tab) ? (route.query.tab as Tab) : 'send'),
|
||||
set: (value) => router.replace({ query: { ...route.query, tab: value === 'send' ? undefined : value } }),
|
||||
})
|
||||
const tabs = computed(() => {
|
||||
const s = state.value
|
||||
return [
|
||||
{ key: 'send' as const, label: t('market.tabs.send'), icon: 'cart' as UiIconName },
|
||||
{ key: 'offers' as const, label: t('market.tabs.offers'), icon: 'globe' as UiIconName },
|
||||
{ key: 'mine' as const, label: t('market.tabs.mine'), icon: 'edit' as UiIconName, count: s?.offers.length },
|
||||
{ key: 'routes' as const, label: t('market.tabs.routes'), icon: 'repeat' as UiIconName, count: s?.routes.length },
|
||||
{ key: 'trades' as const, label: t('market.tabs.trades'), icon: 'clock' as UiIconName, count: s?.trades.length },
|
||||
]
|
||||
})
|
||||
|
||||
/** `?x=&y=` from the map fills in the send form's target. */
|
||||
const initialTarget = computed(() => (route.query.x && route.query.y ? { x: Number(route.query.x), y: Number(route.query.y) } : null))
|
||||
</script>
|
||||
|
||||
<!-- The market's work: send resources, the world's offers, own offers, trade routes, merchants under way. -->
|
||||
<template>
|
||||
<div class="space-y-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<UiSubTabs v-model="tab" :tabs="tabs" />
|
||||
<span v-if="state?.market" class="inline-flex items-center gap-1 text-sm whitespace-nowrap text-ink-700 tabular-nums" :title="$t('market.merchants_title', { carry: state.market.carry })">
|
||||
<IconUi name="cart" class="size-4" />
|
||||
{{ $t('market.merchants_free', { free: state.market.free, merchants: state.market.merchants }) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p v-if="m.error.value" class="alert" role="alert">{{ m.error.value }}</p>
|
||||
|
||||
<p v-if="!state" class="text-sm text-ink-500">{{ $t('common.loading') }}</p>
|
||||
<p v-else-if="!state.market" class="text-sm text-ink-500">{{ $t('market.no_market') }}</p>
|
||||
<template v-else>
|
||||
<MarketSend
|
||||
v-if="tab === 'send'"
|
||||
:key="`${route.query.x}|${route.query.y}`"
|
||||
:market="state.market"
|
||||
:stock="v.resources.value!"
|
||||
:now="v.now.value"
|
||||
:busy="m.busy.value"
|
||||
:initial-target="initialTarget"
|
||||
:preview="m.preview"
|
||||
:send="m.send"
|
||||
/>
|
||||
<MarketWorldOffers
|
||||
v-else-if="tab === 'offers'"
|
||||
:market="state.market"
|
||||
:stock="v.resources.value!"
|
||||
:world-id="village.world_id"
|
||||
:busy="m.busy.value"
|
||||
:offers="m.offers"
|
||||
:accept="m.accept"
|
||||
/>
|
||||
<MarketMyOffers
|
||||
v-else-if="tab === 'mine'"
|
||||
:market="state.market"
|
||||
:offers="state.offers"
|
||||
:stock="v.resources.value!"
|
||||
:now="v.now.value"
|
||||
:busy="m.busy.value"
|
||||
:offer="m.offer"
|
||||
:cancel="m.cancelOffer"
|
||||
/>
|
||||
<MarketRoutes
|
||||
v-else-if="tab === 'routes'"
|
||||
:market="state.market"
|
||||
:routes="state.routes"
|
||||
:world-id="village.world_id"
|
||||
:now="v.now.value"
|
||||
:busy="m.busy.value"
|
||||
:seconds-until="v.secondsUntil"
|
||||
:preview="m.preview"
|
||||
:create="m.routeCreate"
|
||||
:update="m.routeUpdate"
|
||||
:remove="m.routeDelete"
|
||||
/>
|
||||
<MarketTrades v-else :market="state.market" :trades="state.trades" :world-id="village.world_id" :now="v.now.value" :seconds-until="v.secondsUntil" />
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -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<MarketState | null>(null)
|
||||
const busy = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const generic = useErrorText()
|
||||
const { t, te } = useI18n()
|
||||
/** Refusals in the market's words first (`market.errors.<code>`), then the game's. */
|
||||
const errorText = (e: unknown) => {
|
||||
const code = (e as Partial<GameError> | 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<MarketState>(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<void> | null = null
|
||||
let again = false
|
||||
async function load(): Promise<void> {
|
||||
const id = villageId.value
|
||||
if (id === null) return
|
||||
if (loading) {
|
||||
again = true
|
||||
return loading
|
||||
}
|
||||
loading = (async () => {
|
||||
try {
|
||||
apply(await ws.send<MarketState>('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<VillageUpdated>('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<TradePlan>('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<MarketOffers | null> => {
|
||||
try {
|
||||
return await ws.send<MarketOffers>('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<Cost> & { 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<typeof useMarket>
|
||||
|
|
@ -29,8 +29,11 @@ watch(building, (b) => {
|
|||
</template>
|
||||
<!-- The wounded lie in all hospitals together. -->
|
||||
<VillageHospitalPanel v-if="building.type === 'hospital'" :hospital="village.hospital" :seconds-until="v.secondsUntil" />
|
||||
<!-- The market trades: its tabs instead of the list, since a village has one market. -->
|
||||
<VillageMarket v-if="building.type === 'market'" />
|
||||
<!-- Every building of this type, and one more: the headquarters list for just this type. -->
|
||||
<VillageBuildForm
|
||||
v-else
|
||||
:options="village.buildable.filter((o) => o.type === building!.type)"
|
||||
:buildings="village.buildings.filter((b) => b.type === building!.type)"
|
||||
:space="village.space"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,18 @@
|
|||
import type { Cost } from '~/types/game'
|
||||
|
||||
type Translate = (key: string, values?: Record<string, unknown>) => 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)
|
||||
Loading…
Reference in New Issue