game-village-politics-frontend/app/pages/map/[worldId].vue

437 lines
18 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

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

<script setup lang="ts">
import type { DockItem } from '~/components/ui/Dock.vue'
import type { VillageUpdated } from '~/types/game'
import type { MapMovement, MapRelationKind, MapVillage } from '~/types/map'
definePageMeta({ layout: 'game' })
const route = useRoute()
const router = useRouter()
const worldId = Number(route.params.worldId)
const { view, error, busy, load } = useMap(worldId)
useCurrentWorld().enter(worldId)
const ZOOM = [36, 52, 72]
const zoom = ref(1)
const field = computed(() => ZOOM[zoom.value]!)
const RULER = 26
const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n))
// On the fullscreen stage the map fills the screen under the menu bar, with the village
// bar and the dock floating over it; without one it fills its box on the page.
const stage = useStage()
const staged = !!stage
/** The frame's border around the map, in px; none on the stage. */
const edge = staged ? 0 : 2
const box = ref<HTMLElement | null>(null)
const area = ref({ w: 800, h: 520 })
function measure() {
if (!box.value) return
const rect = box.value.getBoundingClientRect()
area.value = staged
? { w: Math.floor(rect.width), h: Math.floor(rect.height) }
: { w: Math.floor(rect.width) - 8, h: Math.max(360, Math.floor(window.innerHeight - rect.top - 32)) }
}
let observer: ResizeObserver | undefined
onMounted(() => {
measure()
observer = new ResizeObserver(measure)
if (box.value) observer.observe(box.value)
})
onBeforeUnmount(() => observer?.disconnect())
/**
* The field in the middle of the map, fractional while dragging. Null until known:
* without ?x=&y= the server opens on the player's village.
*/
const center = ref<{ x: number; y: number } | null>(null)
const mapSize = computed(() => view.value?.size ?? 1000)
/** Lowest and highest coordinate: the world starts at 0|0, negative included. */
const lo = computed(() => view.value?.min ?? mapMin(mapSize.value))
const hi = computed(() => lo.value + mapSize.value - 1)
const rounded = computed(() => (center.value ? { x: Math.round(center.value.x), y: Math.round(center.value.y) } : null))
/** The visible area in fields. */
const visible = computed(() => {
if (!center.value) return null
const cols = (area.value.w - RULER) / field.value
const rows = (area.value.h - RULER) / field.value
return { left: center.value.x + 0.5 - cols / 2, top: center.value.y + 0.5 - rows / 2, cols, rows }
})
// Load a window with some margin around what is visible, whenever the visible fields
// leave what is loaded (or already on its way).
const MARGIN = 6
let requested: { x0: number; y0: number; x1: number; y1: number } | null = null
function ensureLoaded() {
const v = visible.value
if (!v || !rounded.value) return
const need = { x0: Math.floor(v.left) - 1, y0: Math.floor(v.top) - 1, x1: Math.ceil(v.left + v.cols) + 1, y1: Math.ceil(v.top + v.rows) + 1 }
const covers = (r: typeof requested) => !!r && need.x0 >= r.x0 && need.y0 >= r.y0 && need.x1 <= r.x1 && need.y1 <= r.y1
const have = view.value
if (have && covers({ x0: have.x, y0: have.y, x1: have.x + have.w, y1: have.y + have.h })) return
if (covers(requested)) return
const w = Math.min(61, need.x1 - need.x0 + MARGIN * 2)
const h = Math.min(61, need.y1 - need.y0 + MARGIN * 2)
const { x, y } = rounded.value
requested = { x0: x - Math.floor(w / 2), y0: y - Math.floor(h / 2), x1: x - Math.floor(w / 2) + w, y1: y - Math.floor(h / 2) + h }
load({ x, y }, w, h)
}
watch(visible, ensureLoaded)
// ?x=&y= is where the map is; it changes on jumps, the minimap and after a drag.
const queryCenter = computed(() => {
const x = Number(route.query.x)
const y = Number(route.query.y)
return route.query.x !== undefined && Number.isFinite(x) && Number.isFinite(y) ? { x, y } : null
})
watch(
queryCenter,
(q) => {
if (!q) {
// Home: let the server centre on the player's village.
center.value = null
requested = null
load(null, 41, 31)
return
}
if (!rounded.value || rounded.value.x !== q.x || rounded.value.y !== q.y) center.value = { ...q }
},
{ immediate: true },
)
watch(view, (v) => {
if (v && !center.value) center.value = { ...v.center }
})
function goTo(at: { x: number; y: number }) {
router.replace({ query: { x: clamp(Math.round(at.x), lo.value, hi.value), y: clamp(Math.round(at.y), lo.value, hi.value) } })
}
function onDrag(dx: number, dy: number) {
if (!center.value) return
center.value = {
x: clamp(center.value.x - dx / field.value, lo.value, hi.value),
y: clamp(center.value.y - dy / field.value, lo.value, hi.value),
}
}
function pan(dx: number, dy: number) {
if (rounded.value) goTo({ x: rounded.value.x + dx, y: rounded.value.y + dy })
}
// The minimap: a 61 × 61 window, refetched once the map has moved a few fields from it.
const overview = useMap(worldId)
watch(rounded, (c) => {
const o = overview.view.value?.center
if (c && (!o || Math.abs(o.x - c.x) > 8 || Math.abs(o.y - c.y) > 8)) overview.load(c, 61, 61)
})
// Jump-to form, prefilled with the centre.
const jumpX = ref<number | null>(null)
const jumpY = ref<number | null>(null)
watch(rounded, (c) => {
if (c) {
jumpX.value = c.x
jumpY.value = c.y
}
})
function jump() {
if (jumpX.value !== null && jumpY.value !== null) goTo({ x: jumpX.value, y: jumpY.value })
}
const selected = ref<{ x: number; y: number } | null>(null)
const hovered = ref<MapVillage | null>(null)
const selectedVillage = computed(() =>
selected.value ? (view.value?.villages.find((v) => v.x === selected.value!.x && v.y === selected.value!.y) ?? null) : null,
)
const shown = computed(() => hovered.value ?? selectedVillage.value)
// Up close on the map, like a village's popup: the facts while hovering, actions on a click.
const bar = useVillageContextOrNull()
const from = computed(() => {
const v = bar?.village.value
return v && v.world_id === worldId ? { id: v.id, x: v.x, y: v.y } : null
})
/** Where a field sits inside the map frame, in px. */
function fieldAt(x: number, y: number) {
const v = visible.value!
return { left: edge + RULER + (x - v.left + 0.5) * field.value, top: edge + RULER + (y - v.top) * field.value }
}
const popupAt = (x: number, y: number, below: boolean) => {
const p = fieldAt(x, y)
const half = 120
return {
left: `${clamp(p.left, half + 4, area.value.w - half)}px`,
top: below ? `${p.top + field.value + 4}px` : `${p.top - 4}px`,
}
}
const tip = computed(() => (hovered.value && hovered.value !== selectedVillage.value && visible.value ? hovered.value : null))
/** While the map is dragged, the click menu stays hidden. */
const dragging = ref(false)
const menu = computed(() => (selectedVillage.value && visible.value && !dragging.value ? selectedVillage.value : null))
function onDragMove(dx: number, dy: number) {
dragging.value = true
onDrag(dx, dy)
}
function onDragEnd() {
dragging.value = false
if (rounded.value) goTo(rounded.value)
}
const clock = useNow()
// A group on the march, clicked on the map or in a village's list: its card floats at the
// group and moves with it. It keeps its id when it turns home, so the card follows it back.
const march = ref<number | null>(null)
const marchBusy = ref(false)
const marchError = ref<string | null>(null)
const selectedMarch = computed(() => (march.value === null ? null : (view.value?.movements.find((m) => m.id === march.value) ?? null)))
/** Where the group is now, in fields. */
const marchAt = computed(() => {
const m = selectedMarch.value
if (!m || !visible.value || dragging.value) return null
const start = Date.parse(m.sent_at)
const end = Date.parse(m.arrives_at)
if (clock.value >= end) return null
const p = end > start ? clamp((clock.value - start) / (end - start), 0, 1) : 1
return { x: m.from.x + (m.to.x - m.from.x) * p, y: m.from.y + (m.to.y - m.from.y) * p }
})
function pickMarch(id: number) {
selected.value = null
marchError.value = null
march.value = march.value === id ? null : id
}
function pickField(at: { x: number; y: number }) {
march.value = null
selected.value = at
}
const errorText = useErrorText()
async function cancelMarch(m: MapMovement) {
marchBusy.value = true
marchError.value = null
try {
await ws.send('rally.cancel', { village_id: m.from.id, movement_id: m.id })
reload()
if (bar?.village.value?.id === m.from.id) bar.refresh()
} catch (e) {
marchError.value = errorText(e)
} finally {
marchBusy.value = false
}
}
// Groups leave the map when they arrive. Reload then, and whenever the village bar learns
// of a change (a battle, a return), so the group's way home shows up.
function reload() {
const v = view.value
if (v) load(v.center, v.w, v.h)
}
const nextArrival = computed(() => {
const times = (view.value?.movements ?? []).map((m) => Date.parse(m.arrives_at))
return times.length ? Math.min(...times) : null
})
watch(
() => nextArrival.value !== null && clock.value >= nextArrival.value + 1500,
(due) => {
if (due) reload()
},
)
watch(
() => bar?.village.value?.movements.map((m) => `${m.id}:${m.type}:${m.arrives_at}`).join(),
(now, before) => {
if (before !== undefined && now !== before) reload()
},
)
// The server pushes village:updated to the player's villages when something changes round
// them, a wave of new barbarian villages settling nearby among others: reload the map and the
// minimap once, a second after a burst of pushes is over.
let pushed: ReturnType<typeof setTimeout> | undefined
ws.listenWhileMounted<VillageUpdated>('village:updated', null, () => {
clearTimeout(pushed)
pushed = setTimeout(() => {
reload()
const o = overview.view.value
if (o) overview.load(o.center, o.w, o.h)
}, 1000)
})
onBeforeUnmount(() => clearTimeout(pushed))
const LEGEND: MapRelationKind[] = ['own', 'tribe', 'ally', 'nap', 'enemy', 'none', 'barbarian']
const currentVillage = computed(() => useCurrentWorld().current.value?.villageId ?? null)
// The panels in the dock fold and move like the village's boxes.
const { t } = useI18n()
const mapCards = computed<DockItem[]>(() => [
{ key: 'view', title: t('map.continent', { k: continent.value }) },
{ key: 'minimap', title: t('map.minimap') },
{ key: 'field', title: t('map.info.title') },
{ key: 'legend', title: t('map.legend.title') },
])
/** Villages in the visible area, for the legend. */
const counts = computed(() => {
const v = visible.value
const villages = (view.value?.villages ?? []).filter(
(village) => v && village.x >= v.left - 1 && village.x < v.left + v.cols && village.y >= v.top - 1 && village.y < v.top + v.rows,
)
const by = (r: MapRelationKind) => villages.filter((v) => v.relation === r && !v.crown).length
return {
own: by('own'),
tribe: by('tribe'),
ally: by('ally'),
nap: by('nap'),
enemy: by('enemy'),
none: by('none'),
barbarian: by('barbarian'),
crowns: villages.filter((v) => v.crown).length,
}
})
const continent = computed(() => (rounded.value ? continentOf(rounded.value.x, rounded.value.y, mapSize.value) : ''))
</script>
<template>
<div>
<div
ref="box"
:class="staged ? 'fixed inset-x-0 bottom-0 z-0' : 'relative min-w-0 p-2.5'"
:style="staged ? { top: `${stage!.menuBottom.value}px` } : undefined"
>
<!-- A dark wooden frame around the map on a page; edge to edge on the stage. -->
<div class="h-full overflow-hidden bg-[#585e3c]" :class="staged ? '' : 'border-2 border-wood-900'">
<MapWorldMap
v-if="visible"
:view="view"
:left="visible.left"
:top="visible.top"
:cols="visible.cols"
:rows="visible.rows"
:width="area.w"
:height="area.h"
:field="field"
:selected="selected"
:current="currentVillage"
:now="clock"
:march="march"
@select="pickField"
@march="pickMarch"
@hover="hovered = $event"
@drag="onDragMove"
@dragend="onDragEnd"
@pan="pan"
/>
<p v-else class="py-24 text-center text-sm text-parchment-100">{{ $t('common.loading') }}</p>
</div>
<MapFieldPopup
v-if="tip"
:village="tip"
:from="from"
class="pointer-events-none absolute z-20 -translate-x-1/2 -translate-y-full"
:style="popupAt(tip.x, tip.y, false)"
/>
<MapFieldPopup
v-if="menu"
:village="menu"
:from="from"
actions
:movements="view?.movements ?? []"
:now="clock"
class="absolute z-20 -translate-x-1/2"
:style="popupAt(menu.x, menu.y, true)"
@center="goTo(menu)"
@close="selected = null"
@march="pickMarch"
/>
<MapMarchCard
v-if="selectedMarch && marchAt"
:march="selectedMarch"
:now="clock"
:busy="marchBusy"
:error="marchError"
class="absolute z-20 -translate-x-1/2"
:style="popupAt(marchAt.x, marchAt.y, true)"
@close="march = null"
@cancel="cancelMarch(selectedMarch)"
@center="goTo"
/>
<!-- Phones have no dock: home and zoom float over the map instead. -->
<div v-if="staged" class="float absolute bottom-16 left-2 z-20 flex border border-wood-900 bg-parchment-200 lg:hidden">
<button type="button" class="btn btn-ghost" @click="router.replace({ query: {} })">{{ $t('map.home') }}</button>
<button type="button" class="btn btn-ghost px-2.5" :disabled="zoom === 0" :aria-label="$t('map.zoom_out')" @click="zoom--">−</button>
<button type="button" class="btn btn-ghost px-2.5" :disabled="zoom === ZOOM.length - 1" :aria-label="$t('map.zoom_in')" @click="zoom++">+</button>
</div>
</div>
<!-- The map's panels go into the stage's dock on the right. -->
<Teleport defer to="#stage-dock" :disabled="!staged">
<div :class="staged ? 'text-sm' : 'p-2.5 pt-0 text-sm'">
<UiDock scope="map" :cards="mapCards">
<template #view-extra>
<span v-if="rounded" class="text-sm font-normal text-ink-500 normal-case tabular-nums">{{ rounded.x }}|{{ rounded.y }}</span>
</template>
<template #view>
<div class="flex items-center gap-1.5 p-2">
<button type="button" class="btn btn-outline" @click="router.replace({ query: {} })">{{ $t('map.home') }}</button>
<div class="ml-auto flex items-center border border-wood-600 bg-parchment-50">
<button type="button" class="btn btn-ghost px-2.5" :disabled="zoom === 0" :aria-label="$t('map.zoom_out')" @click="zoom--">−</button>
<button type="button" class="btn btn-ghost px-2.5" :disabled="zoom === ZOOM.length - 1" :aria-label="$t('map.zoom_in')" @click="zoom++">+</button>
</div>
</div>
<p v-if="error" class="alert m-2 mt-0" role="alert">{{ error }}</p>
</template>
<template #minimap-extra>
<span v-if="overview.view.value" class="text-xs font-normal text-ink-500 normal-case tabular-nums">{{ overview.view.value.w }}×{{ overview.view.value.h }}</span>
</template>
<template #minimap>
<div class="border-b border-wood-700">
<MapMiniMap
v-if="overview.view.value"
:overview="overview.view.value"
:frame="visible ? { x: visible.left, y: visible.top, w: visible.cols, h: visible.rows } : null"
:current="currentVillage"
@center="goTo"
/>
<p v-else class="py-16 text-center text-sm text-ink-500">{{ $t('common.loading') }}</p>
</div>
<form class="flex items-center gap-1 p-2" @submit.prevent="jump">
<label class="sr-only" for="jump-x">x</label>
<input id="jump-x" v-model.number="jumpX" class="input w-16 px-1.5 py-1 text-center tabular-nums" type="number" :min="lo" :max="hi" />
<span class="font-semibold text-ink-500">|</span>
<label class="sr-only" for="jump-y">y</label>
<input id="jump-y" v-model.number="jumpY" class="input w-16 px-1.5 py-1 text-center tabular-nums" type="number" :min="lo" :max="hi" />
<button type="submit" class="btn btn-primary ml-auto py-1">{{ $t('map.jump') }}</button>
</form>
</template>
<template #field>
<MapInfoCard :village="shown" :at="selected" :movements="view?.movements ?? []" :now="clock" @center="goTo" @march="pickMarch" />
</template>
<template #legend>
<ul class="panel-body space-y-1.5 text-sm">
<li class="flex items-center gap-2">
<span class="size-3 border border-wood-900" :style="{ background: RELATION_COLOURS.current }" /> {{ $t('map.legend.current') }}
</li>
<template v-for="r in LEGEND" :key="r">
<li v-if="r === 'own' || r === 'none' || r === 'barbarian' || counts[r]" class="flex items-center gap-2">
<span class="size-3 border border-wood-900" :style="{ background: RELATION_COLOURS[r] }" /> {{ $t(`map.legend.${r}`) }}
<span class="ml-auto tabular-nums text-ink-500">{{ counts[r] }}</span>
</li>
</template>
<li v-if="counts.crowns" class="flex items-center gap-2"><span class="size-3 border border-[#6b4f16] bg-[#d9b44a]" /> {{ $t('map.legend.crowns') }} <span class="ml-auto tabular-nums text-ink-500">{{ counts.crowns }}</span></li>
<li class="flex flex-wrap items-center gap-x-3 gap-y-1 pt-1 text-xs">
<span v-for="(c, k) in MARCH_COLOURS" :key="k" class="inline-flex items-center gap-1">
<span class="inline-block h-0.5 w-4" :style="{ background: c }" />{{ $t(`map.march.legend.${k}`) }}
</span>
</li>
<li class="pt-1 text-xs text-ink-500">{{ $t('map.legend.lines') }}</li>
<li class="text-xs text-ink-500">{{ $t('map.controls') }}<template v-if="busy"> · {{ $t('common.loading') }}</template></li>
</ul>
</template>
</UiDock>
</div>
</Teleport>
</div>
</template>