feat: rally point, troop movements, support, reports, scouts, battle simulator and village rename
Send attacks and support from the rally point with a live travel-time preview, see own commands and spotted incoming attacks with countdowns and call-back, send support home or withdraw it, read battle and support reports with an unread badge, run the battle simulator, rename villages, and send troops straight from the map. The watchtower gets a diorama model; the mock server answers every new intent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2a2e2fd855
commit
d12443bf18
12
app/app.vue
12
app/app.vue
|
|
@ -4,9 +4,10 @@ const { user, logout } = useAuth()
|
|||
const notices = useNotices()
|
||||
const route = useRoute()
|
||||
const { current } = useCurrentWorld()
|
||||
const unreadReports = useUnreadReports()
|
||||
|
||||
/** Inside a world (village or map) the header is that world's navigation. */
|
||||
const inWorld = computed(() => !!current.value && /^\/(village|map)\//.test(route.path))
|
||||
/** Inside a world (village, map or reports) the header is that world's navigation. */
|
||||
const inWorld = computed(() => !!current.value && /^\/(village|map|reports)\//.test(route.path))
|
||||
const home = computed(() =>
|
||||
inWorld.value && current.value?.villageId ? `/village/${current.value.villageId}` : '/worlds',
|
||||
)
|
||||
|
|
@ -57,6 +58,13 @@ useHead({ title: () => t('app.title') })
|
|||
<IconUi name="pin" class="size-4" />
|
||||
{{ t('app.map') }}
|
||||
</NuxtLink>
|
||||
<NuxtLink :to="`/reports/${current.worldId}`" class="nav-link" active-class="nav-link-active">
|
||||
<IconUi name="report" class="size-4" />
|
||||
<span class="hidden sm:inline">{{ t('app.reports') }}</span>
|
||||
<span v-if="unreadReports" class="badge badge-gold px-1.5 py-0" :title="t('app.unread_reports', { count: unreadReports })">
|
||||
{{ unreadReports }}
|
||||
</span>
|
||||
</NuxtLink>
|
||||
</nav>
|
||||
|
||||
<div class="ml-auto flex min-w-0 items-center gap-2">
|
||||
|
|
|
|||
|
|
@ -76,6 +76,12 @@ defineProps<{ type: BuildingType }>()
|
|||
<path d="M3 20V8h3v3h3V8h3v3h3V8h3v3h3V8v12z" />
|
||||
<path d="M3 15.5h18M9 15.5V20M15 15.5V20M6 11v4.5M12 11v4.5M18 11v4.5" />
|
||||
</g>
|
||||
<g v-else-if="type === 'watchtower'">
|
||||
<path d="M8 21l1.5-11h5L16 21" />
|
||||
<path d="M6.5 10h11l-1.5-3h-8z" />
|
||||
<path d="M8 7V4h8v3M10.5 4V2.5h3V4" />
|
||||
<path d="M9 15h6M5 21h14" />
|
||||
</g>
|
||||
<g v-else>
|
||||
<path d="M6 21V3" />
|
||||
<path d="M6 4h11l-2.5 4L17 12H6" />
|
||||
|
|
|
|||
|
|
@ -1,5 +1,21 @@
|
|||
<script setup lang="ts">
|
||||
export type UiIconName = 'close' | 'clock' | 'hammer' | 'up' | 'minus' | 'plus' | 'pin' | 'users' | 'globe' | 'logout'
|
||||
export type UiIconName =
|
||||
| 'close'
|
||||
| 'clock'
|
||||
| 'hammer'
|
||||
| 'up'
|
||||
| 'minus'
|
||||
| 'plus'
|
||||
| 'pin'
|
||||
| 'users'
|
||||
| 'globe'
|
||||
| 'logout'
|
||||
| 'attack'
|
||||
| 'support'
|
||||
| 'return'
|
||||
| 'report'
|
||||
| 'eye'
|
||||
| 'edit'
|
||||
|
||||
defineProps<{ name: UiIconName }>()
|
||||
</script>
|
||||
|
|
@ -41,6 +57,26 @@ defineProps<{ name: UiIconName }>()
|
|||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M3 12h18M12 3c2.5 2.7 3.8 5.7 3.8 9s-1.3 6.3-3.8 9c-2.5-2.7-3.8-5.7-3.8-9S9.5 5.7 12 3z" />
|
||||
</g>
|
||||
<g v-else-if="name === 'attack'">
|
||||
<path d="M4 4l10 10M4 4h3l9 9M4 4v3l9 9" />
|
||||
<path d="M13 17l4-4M15 19l4-4M17 17l3 3" />
|
||||
</g>
|
||||
<g v-else-if="name === 'support'">
|
||||
<path d="M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z" />
|
||||
</g>
|
||||
<g v-else-if="name === 'return'">
|
||||
<path d="M9 14l-5-5 5-5" />
|
||||
<path d="M4 9h10a6 6 0 0 1 0 12h-3" />
|
||||
</g>
|
||||
<g v-else-if="name === 'report'">
|
||||
<path d="M6 3h9l4 4v14H6z" />
|
||||
<path d="M14 3v5h5M9 12h7M9 16h7" />
|
||||
</g>
|
||||
<path v-else-if="name === 'edit'" d="M4 20l1-4L16 5l3 3L8 19zM14 7l3 3" />
|
||||
<g v-else-if="name === 'eye'">
|
||||
<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z" />
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
</g>
|
||||
<g v-else>
|
||||
<path d="M15 4h3a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-3" />
|
||||
<path d="M10 16l-4-4 4-4M6 12h10" />
|
||||
|
|
|
|||
|
|
@ -36,6 +36,12 @@ defineProps<{ unit: UnitType | 'militia' }>()
|
|||
<path d="M19 12l-3-2.5M19 12l-3 2.5" />
|
||||
<path d="M3 12l-1-1.5M3 12l-1 1.5" />
|
||||
</g>
|
||||
<g v-else-if="unit === 'scout'">
|
||||
<!-- A spyglass. -->
|
||||
<path d="M3 15l11-7 2 3.2-11 7z" />
|
||||
<path d="M14 8l4.5-2.8 2 3.2L16 11.2" />
|
||||
<path d="M8 16.5l1 4.5M8 16.5L5 21" />
|
||||
</g>
|
||||
<g v-else-if="unit === 'light_cavalry'">
|
||||
<path d="M9 21c0-3-.8-4.8-2.6-5.8L4 13.8l1-3 3.5-2.2L10 4l2 2.6c4.3.8 7 4.4 7 8.6V21" />
|
||||
<path d="M9.5 10h.01" />
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ defineProps<{
|
|||
at: { x: number; y: number } | null
|
||||
}>()
|
||||
const emit = defineEmits<{ center: [at: { x: number; y: number }] }>()
|
||||
const { current } = useCurrentWorld()
|
||||
|
||||
const continentOf = (x: number, y: number) => `K${Math.floor(y / 100)}${Math.floor(x / 100)}`
|
||||
</script>
|
||||
|
|
@ -28,6 +29,14 @@ const continentOf = (x: number, y: number) => `K${Math.floor(y / 100)}${Math.flo
|
|||
</dl>
|
||||
<div class="mt-4 flex flex-wrap gap-2">
|
||||
<NuxtLink v-if="village.own" :to="`/village/${village.id}`" class="btn btn-primary">{{ $t('map.info.open') }}</NuxtLink>
|
||||
<NuxtLink
|
||||
v-if="current?.villageId && current.villageId !== village.id"
|
||||
:to="{ path: `/village/${current.villageId}/rally`, query: { x: village.x, y: village.y } }"
|
||||
class="btn btn-outline"
|
||||
>
|
||||
<IconUi name="attack" class="size-4" />
|
||||
{{ $t('map.info.send') }}
|
||||
</NuxtLink>
|
||||
<button type="button" class="btn btn-outline" @click="emit('center', { x: village.x, y: village.y })">
|
||||
{{ $t('map.info.center') }}
|
||||
</button>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,110 @@
|
|||
<script setup lang="ts">
|
||||
import type { BattleReport, VillageRef } from '~/types/game'
|
||||
|
||||
const props = defineProps<{ report: BattleReport; worldId: number }>()
|
||||
const { t } = useI18n()
|
||||
|
||||
const sides = computed(() => [
|
||||
{ key: 'attacker', label: t('reports.battle.attacker'), place: t('reports.battle.origin'), side: props.report.attacker },
|
||||
{ key: 'defender', label: t('reports.battle.defender'), place: t('reports.battle.destination'), side: props.report.defender },
|
||||
])
|
||||
const mapLink = (v: VillageRef) => ({ path: `/map/${props.worldId}`, query: { x: v.x, y: v.y } })
|
||||
const looted = computed(() => props.report.loot.wood + props.report.loot.clay + props.report.loot.iron)
|
||||
/** Marker position on the luck bar, 0..100 from −25% to +25%. */
|
||||
const luckAt = computed(() => Math.max(0, Math.min(100, ((props.report.luck + 25) / 50) * 100)))
|
||||
</script>
|
||||
|
||||
<!-- A battle report laid out like Die Stämme's: who won, luck and morale, both sides' units, siege damage, haul. -->
|
||||
<template>
|
||||
<div class="space-y-5 text-sm">
|
||||
<h2 class="font-display text-xl font-semibold" :class="report.won ? 'text-moss-700' : 'text-blood-700'">
|
||||
{{ report.won ? $t('reports.battle.attacker_won') : $t('reports.battle.defender_won') }}
|
||||
</h2>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-x-8 gap-y-2">
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="text-ink-500">{{ $t('reports.battle.luck') }}</span>
|
||||
<!-- −25% … +25%, red on the left half, green on the right. -->
|
||||
<span class="relative inline-flex h-3 w-40 overflow-hidden rounded-sm border border-wood-700" aria-hidden="true">
|
||||
<span class="h-full w-1/2 bg-[#d9b3a8]" />
|
||||
<span class="h-full w-1/2 bg-[#b9c79a]" />
|
||||
<span class="absolute top-0 h-full w-1 bg-wood-900" :style="{ left: `calc(${luckAt}% - 2px)` }" />
|
||||
</span>
|
||||
<span class="font-semibold tabular-nums" :class="report.luck < 0 ? 'text-blood-700' : 'text-moss-700'">{{ report.luck > 0 ? '+' : '' }}{{ report.luck }}%</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-ink-500">{{ $t('reports.battle.morale') }}</span>
|
||||
<span class="ml-2 font-semibold tabular-nums">{{ report.morale }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="report.night" class="text-ink-700">{{ $t('reports.battle.night') }}</p>
|
||||
|
||||
<section v-for="s in sides" :key="s.key" class="rounded-sm border-2 border-wood-700 bg-parchment-50">
|
||||
<dl class="grid grid-cols-[6rem_1fr] gap-x-3 gap-y-0.5 border-b border-wood-700 bg-parchment-200 px-3 py-1.5">
|
||||
<dt class="font-semibold">{{ s.label }}</dt>
|
||||
<dd>{{ s.side.village.player?.name ?? $t('common.barbarian') }}</dd>
|
||||
<dt class="text-ink-500">{{ s.place }}</dt>
|
||||
<dd>
|
||||
<NuxtLink :to="mapLink(s.side.village)" class="font-semibold text-blood-700 hover:underline">{{ villageLabel(s.side.village) }}</NuxtLink>
|
||||
</dd>
|
||||
</dl>
|
||||
<div class="px-3 py-2">
|
||||
<p v-if="s.side.units === null" class="text-ink-500">{{ $t('reports.battle.no_info') }}</p>
|
||||
<p v-else-if="!unitRows(s.side.units).length" class="text-ink-500">{{ $t('reports.battle.no_troops') }}</p>
|
||||
<ReportUnits v-else :units="s.side.units" :lost="s.side.lost" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div v-if="report.wall || report.building" class="space-y-1">
|
||||
<p v-if="report.wall">
|
||||
{{
|
||||
report.wall.after < report.wall.before
|
||||
? $t('reports.battle.wall', report.wall)
|
||||
: $t('reports.battle.wall_held', { level: report.wall.after })
|
||||
}}
|
||||
</p>
|
||||
<p v-if="report.building">
|
||||
{{
|
||||
report.building.after < report.building.before
|
||||
? $t('reports.battle.building', { ...report.building, type: $t(`buildings.${report.building.type}`) })
|
||||
: $t('reports.battle.building_held', { type: $t(`buildings.${report.building.type}`), level: report.building.after })
|
||||
}}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<section v-if="report.scouting" class="space-y-2">
|
||||
<h3 class="font-semibold">{{ $t('reports.battle.scouting') }}</h3>
|
||||
<p>
|
||||
{{
|
||||
report.scouting.through
|
||||
? $t('reports.battle.scouts_through', { sent: report.scouting.sent, lost: report.scouting.lost })
|
||||
: $t('reports.battle.scouts_failed', { sent: report.scouting.sent })
|
||||
}}
|
||||
</p>
|
||||
<div v-if="report.scouting.resources" class="flex flex-wrap items-center gap-x-4 gap-y-1">
|
||||
<span class="text-ink-500">{{ $t('reports.battle.scouted_resources') }}</span>
|
||||
<span v-for="r in (['wood', 'clay', 'iron'] as const)" :key="r" class="inline-flex items-center gap-1 tabular-nums">
|
||||
<IconResource :resource="r" class="size-4" />{{ report.scouting.resources[r] }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="report.scouting.buildings">
|
||||
<p class="mb-1 text-ink-500">{{ $t('reports.battle.scouted_buildings') }}</p>
|
||||
<ul class="grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-x-4 gap-y-0.5">
|
||||
<li v-for="type in BUILDING_TYPES.filter((b) => report.scouting!.buildings![b]?.length)" :key="type" class="flex items-center gap-2">
|
||||
<IconBuilding :type="type" class="size-4 text-wood-800" />
|
||||
<span class="flex-1">{{ $t(`buildings.${type}`) }}</span>
|
||||
<span class="font-semibold tabular-nums">{{ report.scouting.buildings[type]!.join(', ') }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div v-if="report.won && report.capacity > 0" class="flex flex-wrap items-center gap-x-4 gap-y-1">
|
||||
<span class="font-semibold">{{ $t('reports.battle.haul') }}</span>
|
||||
<span v-for="r in (['wood', 'clay', 'iron'] as const)" :key="r" class="inline-flex items-center gap-1 tabular-nums">
|
||||
<IconResource :resource="r" class="size-4" />{{ report.loot[r] }}
|
||||
</span>
|
||||
<span class="text-ink-500 tabular-nums">{{ $t('reports.battle.haul_of', { loot: looted, capacity: report.capacity }) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
<script setup lang="ts">
|
||||
import type { UnitType } from '~/types/game'
|
||||
|
||||
const props = defineProps<{
|
||||
units: Partial<Record<string, number>>
|
||||
/** null hides the losses row. */
|
||||
lost: Record<string, number> | null
|
||||
}>()
|
||||
const columns = computed(() => unitRows(props.units).map(([u]) => u))
|
||||
</script>
|
||||
|
||||
<!-- A Die Stämme report table: one column per unit, quantity and losses below. -->
|
||||
<template>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="text-sm tabular-nums">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="pr-3" />
|
||||
<th v-for="unit in columns" :key="unit" class="min-w-12 px-1.5 py-1 text-center" :title="$t(`units.${unit}`)">
|
||||
<IconUnit :unit="unit as UnitType" class="mx-auto size-5 text-wood-800" />
|
||||
<span class="sr-only">{{ $t(`units.${unit}`) }}</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr class="border-t border-parchment-300">
|
||||
<th class="pr-3 py-1 text-left text-xs font-semibold text-ink-500">{{ $t('reports.battle.units') }}</th>
|
||||
<td v-for="unit in columns" :key="unit" class="px-1.5 py-1 text-center">{{ units[unit] }}</td>
|
||||
</tr>
|
||||
<tr v-if="lost" class="border-t border-parchment-300">
|
||||
<th class="pr-3 py-1 text-left text-xs font-semibold text-ink-500">{{ $t('reports.battle.losses') }}</th>
|
||||
<td v-for="unit in columns" :key="unit" class="px-1.5 py-1 text-center" :class="lost[unit] ? 'text-blood-700' : 'text-ink-400'">
|
||||
{{ lost[unit] ?? 0 }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
<script setup lang="ts">
|
||||
import type { Movement, UnitType, VillageRef } from '~/types/game'
|
||||
|
||||
const props = defineProps<{
|
||||
movements: Movement[]
|
||||
worldId: number
|
||||
now: number
|
||||
secondsUntil: (iso: string) => number
|
||||
busy: boolean
|
||||
}>()
|
||||
const emit = defineEmits<{ cancel: [movementId: number] }>()
|
||||
const { t } = useI18n()
|
||||
|
||||
const incoming = computed(() => props.movements.filter((m) => m.direction === 'in'))
|
||||
const own = computed(() => props.movements.filter((m) => m.direction !== 'in'))
|
||||
|
||||
function title(m: Movement) {
|
||||
if (m.direction === 'home') return t('village.movements.return_from', { from: villageLabel(m.from) })
|
||||
if (m.direction === 'in') {
|
||||
return t(m.type === 'attack' ? 'village.movements.attack_from' : 'village.movements.support_from', { from: villageLabel(m.from) })
|
||||
}
|
||||
return t(m.type === 'attack' ? 'village.movements.attack_on' : 'village.movements.support_for', { target: villageLabel(m.to) })
|
||||
}
|
||||
|
||||
/** The other end of the movement, for the map link. */
|
||||
const other = (m: Movement): VillageRef => (m.direction === 'out' ? m.to : m.from)
|
||||
const icon = (m: Movement) => (m.type === 'return' ? 'return' : m.type)
|
||||
const canCancel = (m: Movement) => !!m.cancel_until && props.secondsUntil(m.cancel_until) > 0
|
||||
</script>
|
||||
|
||||
<!-- Commands under way, like the Die Stämme rally point's troop movements: incoming first, red for attacks. -->
|
||||
<template>
|
||||
<section class="panel">
|
||||
<div class="panel-head">
|
||||
<h2 class="panel-title">{{ $t('village.movements.title') }}</h2>
|
||||
</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(`village.movements.${list.key}`) }}</h3>
|
||||
<table v-if="list.rows.length" class="w-full text-sm">
|
||||
<thead class="sr-only">
|
||||
<tr>
|
||||
<th>{{ $t('reports.subject') }}</th>
|
||||
<th>{{ $t('village.movements.arrival') }}</th>
|
||||
<th>{{ $t('village.movements.arrives_in') }}</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-parchment-300">
|
||||
<tr v-for="m in list.rows" :key="m.id" :class="m.direction === 'in' && m.type === 'attack' ? 'text-blood-700' : ''">
|
||||
<td class="py-1.5 pr-2">
|
||||
<div class="flex items-start gap-2">
|
||||
<IconUi :name="icon(m)" class="mt-0.5 size-4 shrink-0" />
|
||||
<div class="min-w-0">
|
||||
<NuxtLink
|
||||
:to="{ path: `/map/${worldId}`, query: { x: other(m).x, y: other(m).y } }"
|
||||
class="font-semibold hover:underline"
|
||||
>
|
||||
{{ title(m) }}
|
||||
</NuxtLink>
|
||||
<span v-if="m.direction === 'in' && m.from.player" class="text-ink-500"> {{ $t('village.movements.by', { player: m.from.player.name }) }}</span>
|
||||
<div v-if="m.units" class="mt-0.5 flex flex-wrap gap-x-2.5 gap-y-0.5 text-xs text-ink-700">
|
||||
<span v-for="[unit, count] in unitRows(m.units)" :key="unit" class="inline-flex items-center gap-1 tabular-nums">
|
||||
<IconUnit :unit="unit as UnitType" class="size-3.5" />{{ count }}
|
||||
</span>
|
||||
<span v-if="m.cargo" class="inline-flex items-center gap-1 tabular-nums" :title="$t('village.movements.loot')">
|
||||
<template v-for="r in (['wood', 'clay', 'iron'] as const)" :key="r">
|
||||
<IconResource :resource="r" class="size-3.5" />{{ m.cargo[r] }}
|
||||
</template>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="py-1.5 pr-2 whitespace-nowrap text-ink-700 tabular-nums">{{ formatArrival(Date.parse(m.arrives_at), now, t) }}</td>
|
||||
<td class="py-1.5 pr-2 text-right font-semibold whitespace-nowrap tabular-nums">{{ formatDuration(secondsUntil(m.arrives_at)) }}</td>
|
||||
<td class="py-1.5 text-right">
|
||||
<button v-if="canCancel(m)" type="button" class="btn btn-outline px-2 py-0.5 text-xs" :disabled="busy" @click="emit('cancel', m.id)">
|
||||
{{ $t('village.movements.cancel') }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p v-else class="text-sm text-ink-500">{{ $t(list.key === 'incoming' ? 'village.movements.none_incoming' : 'village.movements.none') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -13,6 +13,8 @@ const production = computed(() => (['wood', 'clay', 'iron', 'food'] as const).ma
|
|||
const troops = computed(() => (Object.entries(props.village.troops) as [UnitType, number][]).filter(([, n]) => n > 0))
|
||||
const idle = computed(() => props.village.population.villagers - props.village.population.workers - props.village.levy.militia)
|
||||
const spaceShare = computed(() => props.village.space.used / props.village.space.max)
|
||||
const incoming = computed(() => props.village.movements.filter((m) => m.direction === 'in' && m.type === 'attack'))
|
||||
const commands = computed(() => props.village.movements.filter((m) => m.direction !== 'in').length)
|
||||
|
||||
function order(o: BuildOrder) {
|
||||
const type = t(`buildings.${o.type}`)
|
||||
|
|
@ -24,6 +26,17 @@ function order(o: BuildOrder) {
|
|||
<!-- The column beside the village: small boxes with the numbers that matter at a glance. -->
|
||||
<template>
|
||||
<aside class="space-y-3 bg-parchment-100 p-3 text-sm">
|
||||
<section v-if="incoming.length" class="side-box border-blood-700">
|
||||
<h2 class="side-title bg-blood-700 text-parchment-50">{{ $t('village.side.incoming') }}</h2>
|
||||
<ul class="side-body">
|
||||
<li v-for="m in incoming" :key="m.id" class="flex items-center gap-2 text-blood-700">
|
||||
<IconUi name="attack" class="size-4" />
|
||||
<span class="min-w-0 flex-1 truncate">{{ villageLabel(m.from) }}</span>
|
||||
<span class="font-semibold tabular-nums">{{ formatDuration(secondsUntil(m.arrives_at)) }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section class="side-box">
|
||||
<h2 class="side-title">{{ $t('village.side.production') }}</h2>
|
||||
<ul class="side-body">
|
||||
|
|
@ -54,7 +67,9 @@ function order(o: BuildOrder) {
|
|||
</ul>
|
||||
<p v-else class="text-ink-500">{{ $t('village.troops.none') }}</p>
|
||||
<p v-if="village.population.training" class="text-xs text-ink-500">{{ $t('village.troops.training', { count: village.population.training }) }}</p>
|
||||
<p v-if="commands" class="text-xs text-ink-500">{{ $t('village.side.commands') }}: {{ commands }}</p>
|
||||
<NuxtLink :to="`${base}/recruit`" class="side-link">» {{ $t('village.side.recruit') }}</NuxtLink>
|
||||
<NuxtLink :to="`${base}/rally`" class="side-link">» {{ $t('village.side.rally') }}</NuxtLink>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,187 @@
|
|||
<script setup lang="ts">
|
||||
import type { BuildingType, MarchPlan, MovementType, TravelMode, Units, UnitType, VillageState } from '~/types/game'
|
||||
|
||||
const props = defineProps<{
|
||||
village: VillageState
|
||||
busy: boolean
|
||||
/** Field to aim at, e.g. from the map. */
|
||||
initialTarget: { x: number; y: number } | null
|
||||
now: number
|
||||
preview: (x: number, y: number, units: Units, mode: TravelMode) => Promise<MarchPlan | null>
|
||||
/** Resolves false when the server refused. */
|
||||
send: (type: Exclude<MovementType, 'return'>, x: number, y: number, units: Units, mode: TravelMode, catapultTarget: BuildingType | null) => Promise<boolean>
|
||||
}>()
|
||||
const { t } = useI18n()
|
||||
|
||||
// Like the Die Stämme rally point: the units at home in groups, each with an amount
|
||||
// field and its (count); the target field; then Attack or Support.
|
||||
const amounts = reactive<Units>({})
|
||||
const target = ref(props.initialTarget ? `${props.initialTarget.x}|${props.initialTarget.y}` : '')
|
||||
const mode = ref<TravelMode>(props.village.rally.default_mode)
|
||||
const catapultTarget = ref<BuildingType>('headquarters')
|
||||
|
||||
const home = (unit: UnitType) => props.village.troops[unit] ?? 0
|
||||
const picked = computed<Units>(() => {
|
||||
const units: Units = {}
|
||||
for (const unit of UNIT_ORDER) {
|
||||
const n = Math.min(home(unit), Math.floor(Number(amounts[unit]) || 0))
|
||||
if (n > 0) units[unit] = n
|
||||
}
|
||||
return units
|
||||
})
|
||||
const hasUnits = computed(() => Object.keys(picked.value).length > 0)
|
||||
const hasTroops = computed(() => UNIT_ORDER.some((u) => home(u) > 0))
|
||||
const coords = computed(() => parseCoords(target.value))
|
||||
|
||||
function all() {
|
||||
for (const unit of UNIT_ORDER) amounts[unit] = home(unit) || undefined
|
||||
}
|
||||
|
||||
// The server names the target and times the march; asked again a moment after each change.
|
||||
const plan = ref<MarchPlan | null>(null)
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
watch(
|
||||
[coords, picked, mode],
|
||||
() => {
|
||||
clearTimeout(timer)
|
||||
const c = coords.value
|
||||
if (!c) {
|
||||
plan.value = null
|
||||
return
|
||||
}
|
||||
timer = setTimeout(async () => {
|
||||
const result = await props.preview(c.x, c.y, picked.value, mode.value)
|
||||
// Drop answers for a target or mode that changed meanwhile.
|
||||
if (coords.value?.x === c.x && coords.value?.y === c.y) plan.value = result
|
||||
}, 250)
|
||||
},
|
||||
{ immediate: true, deep: true },
|
||||
)
|
||||
onBeforeUnmount(() => clearTimeout(timer))
|
||||
|
||||
const own = computed(() => !!plan.value?.target && plan.value.target.id === props.village.id)
|
||||
const canSend = computed(
|
||||
() => props.village.rally.has_rally_point && !props.busy && hasUnits.value && !!plan.value?.target && !own.value,
|
||||
)
|
||||
|
||||
async function submit(type: 'attack' | 'support') {
|
||||
const c = coords.value
|
||||
if (!c || !canSend.value) return
|
||||
const sent = await props.send(type, c.x, c.y, picked.value, mode.value, picked.value.catapult ? catapultTarget.value : null)
|
||||
if (sent) UNIT_ORDER.forEach((u) => delete amounts[u])
|
||||
}
|
||||
|
||||
function modeHint(m: VillageState['rally']['modes'][number]) {
|
||||
const speed = t('village.rally.mode_speed', { percent: Math.round(m.speed * 100) })
|
||||
const seen = m.visibility > 0 ? t('village.rally.mode_seen', { fields: m.visibility }) : t('village.rally.mode_unseen')
|
||||
return `${speed}, ${seen}`
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="panel">
|
||||
<div class="panel-head">
|
||||
<h2 class="panel-title">{{ $t('village.rally.send') }}</h2>
|
||||
<button v-if="hasTroops" type="button" class="text-sm font-semibold text-blood-700 hover:underline" @click="all">
|
||||
{{ $t('village.rally.all') }}
|
||||
</button>
|
||||
</div>
|
||||
<form class="panel-body space-y-4" @submit.prevent="submit('attack')">
|
||||
<p v-if="!village.rally.has_rally_point" class="alert">
|
||||
{{ $t('village.rally.no_rally_point') }}
|
||||
<NuxtLink :to="`/village/${village.id}/build`" class="font-semibold underline">{{ $t('village.rally.to_build') }}</NuxtLink>
|
||||
</p>
|
||||
<p v-if="village.rally.protected_until" class="text-sm text-ink-700">
|
||||
{{ $t('village.rally.protected', { time: formatArrival(Date.parse(village.rally.protected_until), now, t) }) }}
|
||||
</p>
|
||||
|
||||
<div class="grid gap-x-6 gap-y-3 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<fieldset v-for="group in UNIT_GROUPS" :key="group.name">
|
||||
<legend class="mb-1 text-xs font-semibold tracking-wide text-ink-500 uppercase">{{ $t(`village.rally.groups.${group.name}`) }}</legend>
|
||||
<div v-for="unit in group.units" :key="unit" class="flex items-center gap-2 py-0.5" :class="home(unit) ? '' : 'opacity-50'">
|
||||
<IconUnit :unit="unit" class="size-5 text-wood-800" :title="$t(`units.${unit}`)" />
|
||||
<input
|
||||
v-model.number="amounts[unit]"
|
||||
type="number"
|
||||
min="0"
|
||||
:max="home(unit)"
|
||||
inputmode="numeric"
|
||||
class="input w-16 px-1.5 py-0.5 text-right tabular-nums"
|
||||
:disabled="!home(unit)"
|
||||
:aria-label="$t('village.rally.amount_of', { unit: $t(`units.${unit}`) })"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs font-semibold tabular-nums text-blood-700 hover:underline disabled:text-ink-400 disabled:no-underline"
|
||||
:disabled="!home(unit)"
|
||||
@click="amounts[unit] = home(unit)"
|
||||
>
|
||||
({{ home(unit) }})
|
||||
</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
<p v-if="!hasTroops" class="text-sm text-ink-500">{{ $t('village.rally.none_home') }}</p>
|
||||
|
||||
<div class="grid gap-3 border-t-2 border-parchment-300 pt-3 sm:grid-cols-[10rem_1fr]">
|
||||
<label for="send-target" class="label self-center">{{ $t('village.rally.target') }}</label>
|
||||
<input
|
||||
id="send-target"
|
||||
v-model="target"
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
autocomplete="off"
|
||||
:placeholder="$t('village.rally.target_placeholder')"
|
||||
class="input w-32 tabular-nums"
|
||||
/>
|
||||
|
||||
<label for="send-mode" class="label self-center">{{ $t('village.rally.mode') }}</label>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<select id="send-mode" v-model="mode" class="input w-auto py-1">
|
||||
<option v-for="m in village.rally.modes" :key="m.mode" :value="m.mode">{{ $t(`village.rally.modes.${m.mode}`) }}</option>
|
||||
</select>
|
||||
<span class="text-xs text-ink-500">{{ modeHint(village.rally.modes.find((m) => m.mode === mode) ?? village.rally.modes[0]!) }}</span>
|
||||
</div>
|
||||
|
||||
<template v-if="picked.catapult">
|
||||
<label for="send-catapult" class="label self-center">{{ $t('village.rally.catapult_target') }}</label>
|
||||
<select id="send-catapult" v-model="catapultTarget" class="input w-auto py-1">
|
||||
<option v-for="type in BUILDING_TYPES" :key="type" :value="type">{{ $t(`buildings.${type}`) }}</option>
|
||||
</select>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- What the server says about the target and the march. -->
|
||||
<dl v-if="plan" class="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 rounded-sm border border-parchment-300 bg-parchment-50 px-3 py-2 text-sm">
|
||||
<template v-if="plan.target">
|
||||
<dt class="text-ink-500">{{ $t('village.rally.target') }}</dt>
|
||||
<dd class="font-semibold">
|
||||
{{ villageLabel(plan.target) }}
|
||||
<span class="font-normal text-ink-500">{{ own ? $t('village.rally.own') : (plan.target.player?.name ?? $t('common.barbarian')) }}</span>
|
||||
</dd>
|
||||
<dt class="text-ink-500">{{ $t('village.rally.distance') }}</dt>
|
||||
<dd class="tabular-nums">{{ $t('village.rally.fields', { fields: plan.distance.toFixed(1) }) }}</dd>
|
||||
<template v-if="plan.seconds !== null && !own">
|
||||
<dt class="text-ink-500">{{ $t('village.rally.duration') }}</dt>
|
||||
<dd class="tabular-nums">{{ formatDuration(plan.seconds) }}</dd>
|
||||
<dt class="text-ink-500">{{ $t('village.rally.arrival') }}</dt>
|
||||
<dd class="tabular-nums">{{ formatArrival(now + plan.seconds * 1000, now, t) }}</dd>
|
||||
</template>
|
||||
</template>
|
||||
<p v-else class="col-span-2 text-ink-700">{{ $t('village.rally.empty', { x: plan.x, y: plan.y }) }}</p>
|
||||
</dl>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button type="submit" class="btn btn-primary" :disabled="!canSend">
|
||||
<IconUi name="attack" class="size-4" />
|
||||
{{ $t('village.rally.attack') }}
|
||||
</button>
|
||||
<button type="button" class="btn btn-outline" :disabled="!canSend || !plan?.target?.player" @click="submit('support')">
|
||||
<IconUi name="support" class="size-4" />
|
||||
{{ $t('village.rally.support') }}
|
||||
</button>
|
||||
</div>
|
||||
<p class="text-xs text-ink-500">{{ $t('village.rally.detection', { fields: village.rally.detection }) }}</p>
|
||||
</form>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
<script setup lang="ts">
|
||||
import type { SimulatedBattle, Units } from '~/types/game'
|
||||
|
||||
const props = defineProps<{
|
||||
worldId: number
|
||||
/** Own units at home, for "own troops". */
|
||||
troops: Units
|
||||
}>()
|
||||
const errorText = useErrorText()
|
||||
|
||||
// The Die Stämme simulator: both sides' units, the wall and the modifiers, and the
|
||||
// server runs the world's real battle rules on them. Nothing in the game changes.
|
||||
const attack = reactive<Record<string, number | undefined>>({})
|
||||
const defense = reactive<Record<string, number | undefined>>({})
|
||||
const wall = ref(0)
|
||||
const morale = ref(100)
|
||||
const luck = ref(0)
|
||||
const night = ref(false)
|
||||
const building = ref(0)
|
||||
const result = ref<SimulatedBattle | null>(null)
|
||||
const error = ref<string | null>(null)
|
||||
const busy = ref(false)
|
||||
|
||||
const DEFENDERS = [...UNIT_ORDER, 'militia'] as const
|
||||
const counts = (units: Record<string, number | undefined>) =>
|
||||
Object.fromEntries(Object.entries(units).filter(([, n]) => Number(n) > 0).map(([u, n]) => [u, Math.floor(Number(n))]))
|
||||
|
||||
function ownTroops() {
|
||||
for (const unit of UNIT_ORDER) attack[unit] = props.troops[unit] || undefined
|
||||
}
|
||||
|
||||
async function run() {
|
||||
busy.value = true
|
||||
error.value = null
|
||||
try {
|
||||
result.value = await ws.send<SimulatedBattle>('rally.simulate', {
|
||||
world_id: props.worldId,
|
||||
attack: counts(attack),
|
||||
defense: counts(defense),
|
||||
wall: wall.value,
|
||||
morale: morale.value,
|
||||
luck: luck.value,
|
||||
night: night.value,
|
||||
building: building.value,
|
||||
})
|
||||
} catch (e) {
|
||||
error.value = errorText(e)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<details class="panel group">
|
||||
<summary class="panel-head cursor-pointer list-none">
|
||||
<h2 class="panel-title">{{ $t('village.simulator.title') }}</h2>
|
||||
<IconUi name="plus" class="size-4 text-ink-500 group-open:hidden" />
|
||||
<IconUi name="minus" class="hidden size-4 text-ink-500 group-open:block" />
|
||||
</summary>
|
||||
<form class="panel-body space-y-4" @submit.prevent="run">
|
||||
<div class="grid gap-x-6 gap-y-2 sm:grid-cols-[auto_6rem_6rem]">
|
||||
<span />
|
||||
<span class="text-xs font-semibold text-ink-500 uppercase">{{ $t('reports.battle.attacker') }}</span>
|
||||
<span class="text-xs font-semibold text-ink-500 uppercase">{{ $t('reports.battle.defender') }}</span>
|
||||
<template v-for="unit in DEFENDERS" :key="unit">
|
||||
<span class="flex items-center gap-2 text-sm">
|
||||
<IconUnit :unit="unit" class="size-5 text-wood-800" />
|
||||
{{ $t(`units.${unit}`) }}
|
||||
</span>
|
||||
<input
|
||||
v-if="unit !== 'militia'"
|
||||
v-model.number="attack[unit]"
|
||||
type="number"
|
||||
min="0"
|
||||
inputmode="numeric"
|
||||
class="input px-1.5 py-0.5 text-right tabular-nums"
|
||||
:aria-label="`${$t('reports.battle.attacker')}: ${$t(`units.${unit}`)}`"
|
||||
/>
|
||||
<span v-else />
|
||||
<input
|
||||
v-model.number="defense[unit]"
|
||||
type="number"
|
||||
min="0"
|
||||
inputmode="numeric"
|
||||
class="input px-1.5 py-0.5 text-right tabular-nums"
|
||||
:aria-label="`${$t('reports.battle.defender')}: ${$t(`units.${unit}`)}`"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-3 border-t-2 border-parchment-300 pt-3 sm:grid-cols-5">
|
||||
<label class="text-sm">
|
||||
<span class="label">{{ $t('buildings.wall') }}</span>
|
||||
<input v-model.number="wall" type="number" min="0" max="20" class="input px-1.5 py-0.5 tabular-nums" />
|
||||
</label>
|
||||
<label class="text-sm">
|
||||
<span class="label">{{ $t('reports.battle.morale') }} %</span>
|
||||
<input v-model.number="morale" type="number" min="30" max="100" class="input px-1.5 py-0.5 tabular-nums" />
|
||||
</label>
|
||||
<label class="text-sm">
|
||||
<span class="label">{{ $t('village.simulator.luck') }} %</span>
|
||||
<input v-model.number="luck" type="number" min="-25" max="25" class="input px-1.5 py-0.5 tabular-nums" />
|
||||
</label>
|
||||
<label class="text-sm">
|
||||
<span class="label">{{ $t('village.simulator.building') }}</span>
|
||||
<input v-model.number="building" type="number" min="0" max="30" class="input px-1.5 py-0.5 tabular-nums" />
|
||||
</label>
|
||||
<label class="flex items-center gap-2 self-end pb-1 text-sm">
|
||||
<input v-model="night" type="checkbox" />
|
||||
{{ $t('village.simulator.night') }}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button type="submit" class="btn btn-primary" :disabled="busy">{{ $t('village.simulator.run') }}</button>
|
||||
<button type="button" class="btn btn-outline" @click="ownTroops">{{ $t('village.simulator.own_troops') }}</button>
|
||||
</div>
|
||||
<p v-if="error" class="alert" role="alert">{{ error }}</p>
|
||||
|
||||
<div v-if="result" class="space-y-3 border-t-2 border-parchment-300 pt-3 text-sm">
|
||||
<p class="font-display text-lg font-semibold" :class="result.won ? 'text-moss-700' : 'text-blood-700'">
|
||||
{{ result.won ? $t('reports.battle.attacker_won') : $t('reports.battle.defender_won') }}
|
||||
</p>
|
||||
<p class="text-ink-500 tabular-nums">{{ $t('village.simulator.power', result.power) }}</p>
|
||||
<div v-for="side in (['attacker', 'defender'] as const)" :key="side">
|
||||
<p class="mb-1 font-semibold">{{ $t(`reports.battle.${side}`) }}</p>
|
||||
<ReportUnits v-if="unitRows(result[side].units).length" :units="result[side].units" :lost="result[side].lost" />
|
||||
<p v-else class="text-ink-500">{{ $t('reports.battle.no_troops') }}</p>
|
||||
</div>
|
||||
<p v-if="result.wall && result.wall.after < result.wall.before">{{ $t('reports.battle.wall', result.wall) }}</p>
|
||||
<p v-if="result.building">{{ $t('village.simulator.building_after', result.building) }}</p>
|
||||
</div>
|
||||
</form>
|
||||
</details>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
<script setup lang="ts">
|
||||
import type { SupportGroup, UnitType } from '~/types/game'
|
||||
|
||||
defineProps<{
|
||||
here: SupportGroup[]
|
||||
away: SupportGroup[]
|
||||
worldId: number
|
||||
busy: boolean
|
||||
}>()
|
||||
const emit = defineEmits<{ sendHome: [homeVillageId: number]; withdraw: [hostVillageId: number] }>()
|
||||
</script>
|
||||
|
||||
<!-- Support standing here (the host feeds it) and own troops standing elsewhere. -->
|
||||
<template>
|
||||
<section class="panel">
|
||||
<div class="panel-head">
|
||||
<h2 class="panel-title">{{ $t('village.support.title') }}</h2>
|
||||
</div>
|
||||
<div class="panel-body space-y-4 text-sm">
|
||||
<div
|
||||
v-for="list in [
|
||||
{ key: 'here', groups: here, action: 'send_home' },
|
||||
{ key: 'away', groups: away, action: 'withdraw' },
|
||||
]"
|
||||
:key="list.key"
|
||||
>
|
||||
<h3 class="mb-1 text-xs font-semibold tracking-wide text-ink-500 uppercase">{{ $t(`village.support.${list.key}`) }}</h3>
|
||||
<ul v-if="list.groups.length" class="divide-y divide-parchment-300">
|
||||
<li v-for="g in list.groups" :key="g.village.id" class="flex items-start gap-2 py-1.5">
|
||||
<div class="min-w-0 flex-1">
|
||||
<NuxtLink :to="{ path: `/map/${worldId}`, query: { x: g.village.x, y: g.village.y } }" class="font-semibold hover:underline">
|
||||
{{ villageLabel(g.village) }}
|
||||
</NuxtLink>
|
||||
<span v-if="g.village.player" class="text-ink-500"> {{ g.village.player.name }}</span>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2.5 gap-y-0.5 text-xs text-ink-700">
|
||||
<span v-for="[unit, count] in unitRows(g.units)" :key="unit" class="inline-flex items-center gap-1 tabular-nums">
|
||||
<IconUnit :unit="unit as UnitType" class="size-3.5" />{{ count }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-outline px-2 py-0.5 text-xs"
|
||||
:disabled="busy"
|
||||
@click="list.key === 'here' ? emit('sendHome', g.village.id) : emit('withdraw', g.village.id)"
|
||||
>
|
||||
{{ $t(`village.support.${list.action}`) }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="text-ink-500">{{ $t(`village.support.none_${list.key}`) }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
import type { Report, ReportPage } from '~/types/game'
|
||||
|
||||
/** Unread reports on the current world, for the header badge; every village state and report page updates it. */
|
||||
export const useUnreadReports = () => useState<number>('reports.unread', () => 0)
|
||||
|
||||
/** The player's reports on one world: a page of the list, one report, delete and mark read. */
|
||||
export function useReports(worldId: number) {
|
||||
const page = ref<ReportPage | null>(null)
|
||||
const error = ref<string | null>(null)
|
||||
const busy = ref(false)
|
||||
const unread = useUnreadReports()
|
||||
const errorText = useErrorText()
|
||||
|
||||
async function call<T>(event: string, data: object): Promise<T | null> {
|
||||
busy.value = true
|
||||
error.value = null
|
||||
try {
|
||||
return await ws.send<T>(event, data)
|
||||
} catch (e) {
|
||||
error.value = errorText(e)
|
||||
return null
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function list(event: string, data: object) {
|
||||
const result = await call<ReportPage>(event, { world_id: worldId, ...data })
|
||||
if (result) {
|
||||
page.value = result
|
||||
unread.value = result.unread
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
page,
|
||||
error,
|
||||
busy,
|
||||
load: (n = 1) => list('report.index', { page: n }),
|
||||
remove: (ids: number[]) => list('report.delete', { ids }),
|
||||
readAll: () => list('report.readAll', {}),
|
||||
/** One report; opening an unread one marks it read. */
|
||||
show: async (id: number) => {
|
||||
const report = await call<Report>('report.show', { id })
|
||||
// Opening it may have read the last unread one; the list knows the new count.
|
||||
if (report) ws.send<ReportPage>('report.index', { world_id: worldId, page: 1 }).then((p) => (unread.value = p.unread), () => {})
|
||||
return report
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import type { BuildingType, Cost, Resource, Resources, UnitType, VillageState, VillageUpdated } from '~/types/game'
|
||||
import type { BuildingType, Cost, MarchPlan, MovementType, Resource, Resources, TravelMode, Units, UnitType, VillageState, VillageUpdated } from '~/types/game'
|
||||
import type { InjectionKey } from 'vue'
|
||||
|
||||
const RESOURCES: Resource[] = ['wood', 'clay', 'iron', 'food']
|
||||
|
|
@ -13,6 +13,7 @@ export function useVillage(villageId: number) {
|
|||
const busy = ref(false)
|
||||
const errorText = useErrorText()
|
||||
const clock = useNow()
|
||||
const unreadReports = useUnreadReports()
|
||||
|
||||
// Server time minus client time, so projections use the server's clock.
|
||||
const offset = ref(0)
|
||||
|
|
@ -25,8 +26,11 @@ export function useVillage(villageId: number) {
|
|||
const state = await ws.send<VillageState>(event, { village_id: villageId, ...data })
|
||||
offset.value = Date.parse(state.server_time) - Date.now()
|
||||
village.value = state
|
||||
unreadReports.value = state.unread_reports
|
||||
return true
|
||||
} catch (e) {
|
||||
error.value = errorText(e)
|
||||
return false
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
|
|
@ -52,14 +56,15 @@ export function useVillage(villageId: number) {
|
|||
/** Whole seconds until a server timestamp, never below zero. */
|
||||
const secondsUntil = (iso: string) => Math.max(0, Math.ceil((Date.parse(iso) - now.value) / 1000))
|
||||
|
||||
// Refetch once when the next build order or the next unit in training is due, so
|
||||
// new buildings and trained troops show up without waiting for a push.
|
||||
// Refetch once when the next build order, unit in training or group under way is due,
|
||||
// so new buildings, trained troops and arrivals show up without waiting for a push.
|
||||
const nextDue = computed(() => {
|
||||
const v = village.value
|
||||
if (!v) return null
|
||||
const times = [
|
||||
...v.queue.flatMap((o) => (o.finishes_at ? [Date.parse(o.finishes_at)] : [])),
|
||||
...[v.levy.until, v.starvation.food_empty_at, v.starvation.desertion_at].flatMap((at) => (at ? [Date.parse(at)] : [])),
|
||||
...v.movements.map((m) => Date.parse(m.arrives_at)),
|
||||
...v.military.flatMap((m) =>
|
||||
m.queue.filter((o) => o.done < o.count).map((o) => Date.parse(o.starts_at) + (o.done + 1) * o.seconds_per_unit * 1000),
|
||||
),
|
||||
|
|
@ -80,6 +85,8 @@ export function useVillage(villageId: number) {
|
|||
return {
|
||||
village,
|
||||
resources,
|
||||
/** Milliseconds on the server clock, ticking. */
|
||||
now,
|
||||
error,
|
||||
busy,
|
||||
canAfford,
|
||||
|
|
@ -101,6 +108,20 @@ export function useVillage(villageId: number) {
|
|||
cancelRecruit: (orderId: number) => run('village.cancelRecruit', { order_id: orderId }),
|
||||
levy: (count: number) => run('village.levy', { count }),
|
||||
endLevy: () => run('village.endLevy'),
|
||||
/** Target, distance and travel time for the send form; null when the server refuses. */
|
||||
preview: async (x: number, y: number, units: Units, mode: TravelMode) => {
|
||||
try {
|
||||
return await ws.send<MarchPlan>('rally.preview', { village_id: villageId, x, y, units, mode })
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
send: (type: Exclude<MovementType, 'return'>, x: number, y: number, units: Units, mode: TravelMode, catapultTarget: BuildingType | null) =>
|
||||
run('rally.send', { type, x, y, units, mode, catapult_target: catapultTarget }),
|
||||
cancelMovement: (movementId: number) => run('rally.cancel', { movement_id: movementId }),
|
||||
sendHome: (homeVillageId: number) => run('rally.sendHome', { home_village_id: homeVillageId }),
|
||||
withdraw: (hostVillageId: number) => run('rally.withdraw', { host_village_id: hostVillageId }),
|
||||
rename: (name: string) => run('village.rename', { name }),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -413,6 +413,46 @@ const models: Record<BuildingType, (s: number, t: number) => Model> = {
|
|||
}
|
||||
},
|
||||
|
||||
// A lookout on stilts first, then a planked tower, then stone with a slate roof.
|
||||
watchtower(s, t) {
|
||||
// Four corner posts from z0 up to z0 + h, `r` from the middle.
|
||||
const corners = (r: number, z0: number, h: number) =>
|
||||
[-1, 1].flatMap((dx) => [-1, 1].flatMap((dy) => prism(rect(dx * r, dy * r, s * 0.1, s * 0.1), z0, h, C.woodDark)))
|
||||
if (t === 1) {
|
||||
return {
|
||||
faces: [
|
||||
...corners(s * 0.32, 0, s * 1.5),
|
||||
...box(0, 0, s * 0.85, s * 0.85, s * 1.5, s * 0.12, C.plank, C.wood),
|
||||
...corners(s * 0.36, s * 1.62, s * 0.25),
|
||||
...pyramid(rect(0, 0, s * 0.95, s * 0.95), s * 1.87, s * 0.45, C.thatch),
|
||||
],
|
||||
height: s * 2.3,
|
||||
}
|
||||
}
|
||||
if (t === 2) {
|
||||
return {
|
||||
faces: [
|
||||
...box(0, 0, s * 0.8, s * 0.8, 0, s * 1.7, C.plank, C.wood),
|
||||
...box(0, 0, s * 1.0, s * 1.0, s * 1.7, s * 0.14, C.wood),
|
||||
...corners(s * 0.44, s * 1.84, s * 0.28),
|
||||
...pyramid(rect(0, 0, s * 1.05, s * 1.05), s * 2.12, s * 0.5, C.roofRed),
|
||||
...banner(0, 0, s * 3.0, s * 0.55),
|
||||
],
|
||||
height: s * 3.0,
|
||||
}
|
||||
}
|
||||
return {
|
||||
faces: [
|
||||
...prism(ngon(0, 0, s * 0.55, 8), 0, s * 2.2, C.stone, C.stoneDark),
|
||||
...prism(ngon(0, 0, s * 0.7, 8), s * 2.2, s * 0.25, C.stoneDark, C.plank),
|
||||
...pyramid(ngon(0, 0, s * 0.72, 8), s * 2.45, s * 0.65, C.slate),
|
||||
plane([[s * 0.55, -s * 0.12, 0], [s * 0.55, s * 0.12, 0], [s * 0.55, s * 0.12, s * 0.45], [s * 0.55, -s * 0.12, s * 0.45]], C.dark),
|
||||
...banner(0, 0, s * 3.5, s * 0.6),
|
||||
],
|
||||
height: s * 3.5,
|
||||
}
|
||||
},
|
||||
|
||||
// Military: tents and a weapon rack at first, then a long hall that grows into stone.
|
||||
barracks(s, t) {
|
||||
if (t === 1) {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import type { BuildingType, Cost, Resource, Resources, UnitType } from '~/types/game'
|
||||
import type { BuildingType, Cost, Resource, Resources, TravelMode, UnitType } from '~/types/game'
|
||||
|
||||
// Placeholder numbers so the PoC has something to show. They scale linearly with the
|
||||
// level on purpose: the real values and formulas belong to the backend
|
||||
|
|
@ -37,6 +37,7 @@ export const CATALOG: Record<BuildingType, CatalogEntry> = {
|
|||
hiding_place: { space: 1, max_per_village: null, cost: { wood: 50, clay: 60, iron: 50 }, seconds: 10, workers: 0, production: null },
|
||||
wall: { space: 0, max_per_village: 1, cost: { wood: 50, clay: 100, iron: 20 }, seconds: 20, workers: 1, production: null },
|
||||
rally_point: { space: 1, max_per_village: 1, cost: { wood: 10, clay: 40, iron: 30 }, seconds: 10, workers: 0, production: null },
|
||||
watchtower: { space: 2, max_per_village: 1, cost: { wood: 1200, clay: 1400, iron: 1000 }, seconds: 40, workers: 1, production: null },
|
||||
barracks: { space: 6, max_per_village: null, cost: { wood: 200, clay: 170, iron: 90 }, seconds: 30, workers: 3, production: null },
|
||||
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 },
|
||||
|
|
@ -55,17 +56,44 @@ export interface UnitEntry {
|
|||
/** Seconds per unit, short so the mock shows progress. */
|
||||
seconds: number
|
||||
requires: Partial<Record<BuildingType, number>>
|
||||
/** Seconds per map field, short so marches finish while you watch. */
|
||||
speed: number
|
||||
/** Resources one unit carries home. */
|
||||
carry: number
|
||||
attack: number
|
||||
defense: number
|
||||
}
|
||||
|
||||
export const UNITS: Record<UnitType, UnitEntry> = {
|
||||
spear: { building: 'barracks', cost: { wood: 50, clay: 30, iron: 10 }, upkeep: 1, seconds: 10, requires: {} },
|
||||
sword: { building: 'barracks', cost: { wood: 30, clay: 30, iron: 70 }, upkeep: 1, seconds: 15, requires: {} },
|
||||
archer: { building: 'barracks', cost: { wood: 100, clay: 30, iron: 60 }, upkeep: 1, seconds: 18, requires: { barracks: 3 } },
|
||||
light_cavalry: { building: 'stable', cost: { wood: 125, clay: 100, iron: 250 }, upkeep: 3, seconds: 18, requires: {} },
|
||||
heavy_cavalry: { building: 'stable', cost: { wood: 200, clay: 150, iron: 600 }, upkeep: 4, seconds: 36, requires: { stable: 5 } },
|
||||
ram: { building: 'workshop', cost: { wood: 300, clay: 200, iron: 200 }, upkeep: 4, seconds: 48, requires: {} },
|
||||
catapult: { building: 'workshop', cost: { wood: 320, clay: 400, iron: 100 }, upkeep: 6, seconds: 72, requires: { workshop: 2 } },
|
||||
nobleman: { building: 'academy', cost: { wood: 40000, clay: 50000, iron: 50000 }, upkeep: 10, seconds: 108, requires: {} },
|
||||
spear: { building: 'barracks', cost: { wood: 50, clay: 30, iron: 10 }, upkeep: 1, seconds: 10, requires: {}, speed: 6, carry: 25, attack: 10, defense: 15 },
|
||||
sword: { building: 'barracks', cost: { wood: 30, clay: 30, iron: 70 }, upkeep: 1, seconds: 15, requires: {}, speed: 7, carry: 15, attack: 25, defense: 50 },
|
||||
archer: { building: 'barracks', cost: { wood: 100, clay: 30, iron: 60 }, upkeep: 1, seconds: 18, requires: { barracks: 3 }, speed: 6, carry: 10, attack: 15, defense: 45 },
|
||||
scout: { building: 'stable', cost: { wood: 50, clay: 50, iron: 20 }, upkeep: 2, seconds: 9, requires: {}, speed: 2, carry: 0, attack: 0, defense: 0 },
|
||||
light_cavalry: { building: 'stable', cost: { wood: 125, clay: 100, iron: 250 }, upkeep: 3, seconds: 18, requires: {}, speed: 3, carry: 80, attack: 130, defense: 30 },
|
||||
heavy_cavalry: { building: 'stable', cost: { wood: 200, clay: 150, iron: 600 }, upkeep: 4, seconds: 36, requires: { stable: 5 }, speed: 4, carry: 50, attack: 150, defense: 200 },
|
||||
ram: { building: 'workshop', cost: { wood: 300, clay: 200, iron: 200 }, upkeep: 4, seconds: 48, requires: {}, speed: 10, carry: 0, attack: 2, defense: 20 },
|
||||
catapult: { building: 'workshop', cost: { wood: 320, clay: 400, iron: 100 }, upkeep: 6, seconds: 72, requires: { workshop: 2 }, speed: 10, carry: 0, attack: 100, defense: 100 },
|
||||
nobleman: { building: 'academy', cost: { wood: 40000, clay: 50000, iron: 50000 }, upkeep: 10, seconds: 108, requires: {}, speed: 12, carry: 0, attack: 30, defense: 100 },
|
||||
}
|
||||
|
||||
export const UNIT_TYPES = Object.keys(UNITS) as UnitType[]
|
||||
|
||||
/** Defence of one drafted villager. */
|
||||
export const MILITIA_DEFENSE = 5
|
||||
|
||||
// Rally point placeholders: travel modes, spotting radius, recall window, barbarian stock.
|
||||
|
||||
export const TRAVEL_MODES: { mode: TravelMode; speed: number; visibility: number }[] = [
|
||||
{ mode: 'sneaky', speed: 0.5, visibility: 0 },
|
||||
{ mode: 'cautious', speed: 0.8, visibility: 4 },
|
||||
{ mode: 'normal', speed: 1, visibility: 15 },
|
||||
{ mode: 'fast', speed: 1.25, visibility: 30 },
|
||||
{ mode: 'forced', speed: 1.5, visibility: 60 },
|
||||
]
|
||||
export const DEFAULT_MODE: TravelMode = 'normal'
|
||||
/** Fields around a village within which incoming groups are spotted; a watchtower adds its level. */
|
||||
export const DETECTION = 2
|
||||
/** Seconds after sending during which a command can be called back. */
|
||||
export const CANCEL_WINDOW = 600
|
||||
/** Wood, clay and iron each in every barbarian village; it never runs out. */
|
||||
export const BARBARIAN_STOCK = 1000
|
||||
|
|
|
|||
|
|
@ -7,33 +7,52 @@ import { onUnmounted, ref } from 'vue'
|
|||
import type {
|
||||
AuthResult,
|
||||
AuthUser,
|
||||
BattleReport,
|
||||
BuildOption,
|
||||
BuildOrder,
|
||||
Building,
|
||||
BuildingType,
|
||||
Cost,
|
||||
GameError,
|
||||
MarchPlan,
|
||||
SimulatedBattle,
|
||||
MilitaryBuilding,
|
||||
Movement,
|
||||
MovementType,
|
||||
Offer,
|
||||
RallyInfo,
|
||||
Report,
|
||||
ReportPage,
|
||||
Resource,
|
||||
Resources,
|
||||
SupportGroup,
|
||||
SupportReport,
|
||||
TravelMode,
|
||||
UnitType,
|
||||
Units,
|
||||
VillageRef,
|
||||
VillageState,
|
||||
WorldSummary,
|
||||
} from '~/types/game'
|
||||
import type { MapVillage, MapView } from '~/types/map'
|
||||
import type { GameAuth, GameWs } from '~/utils/networking'
|
||||
import {
|
||||
BARBARIAN_STOCK,
|
||||
BASE_TRICKLE,
|
||||
BUILDERS,
|
||||
BUILDING_TYPES,
|
||||
CANCEL_WINDOW,
|
||||
CATALOG,
|
||||
DEFAULT_MODE,
|
||||
DEFAULT_PRIORITY,
|
||||
DEMOLISH_REFUND,
|
||||
DETECTION,
|
||||
MAX_SPACE,
|
||||
MILITIA_DEFENSE,
|
||||
SPACE_PER_HQ_LEVEL,
|
||||
MAX_LEVEL,
|
||||
START_RESOURCES,
|
||||
TRAVEL_MODES,
|
||||
UNITS,
|
||||
UNIT_TYPES,
|
||||
VILLAGER_UPKEEP,
|
||||
|
|
@ -78,8 +97,30 @@ interface MockVillage {
|
|||
recruits?: MockRecruit[]
|
||||
militia?: number
|
||||
levy_until?: number | null
|
||||
/** Support standing here, by home village id; it eats here. */
|
||||
support?: Record<number, Units>
|
||||
}
|
||||
|
||||
interface MockMovement {
|
||||
id: number
|
||||
world_id: number
|
||||
/** Owner of the troops. */
|
||||
user_id: number
|
||||
type: MovementType
|
||||
mode: TravelMode
|
||||
/** Village ids; negative for a made-up barbarian. */
|
||||
origin_id: number
|
||||
target_id: number
|
||||
/** Fields between origin and target, for the way back. */
|
||||
distance: number
|
||||
units: Units
|
||||
cargo: Cost | null
|
||||
sent_at: number
|
||||
arrives_at: number
|
||||
}
|
||||
|
||||
type MockReport = Report & { world_id: number; user_id: number }
|
||||
|
||||
/** Mock levy length; the backend's comes from the world config. */
|
||||
const LEVY_SECONDS = 120
|
||||
|
||||
|
|
@ -101,6 +142,9 @@ interface MockState {
|
|||
token: string | null
|
||||
users: AuthUser[]
|
||||
villages: MockVillage[]
|
||||
/** Missing in states stored before the rally point existed. */
|
||||
movements?: MockMovement[]
|
||||
reports?: MockReport[]
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'vp.mock.v3'
|
||||
|
|
@ -168,10 +212,23 @@ function foodBudget(v: MockVillage) {
|
|||
.reduce((sum, b) => sum + atLevel(CATALOG.farm.production!.per_hour, b.level), 0)
|
||||
}
|
||||
|
||||
/** Food the troops and the units in training eat; it comes out of the villagers' share. */
|
||||
/** Known unit types with a positive count. */
|
||||
const unitEntries = (units: Units) =>
|
||||
Object.entries(units).filter(([unit, n]) => unit in UNITS && (n ?? 0) > 0) as [UnitType, number][]
|
||||
const counts = (units: Units): Units => Object.fromEntries(unitEntries(units))
|
||||
const hasUnits = (units: Units) => unitEntries(units).length > 0
|
||||
const unitSum = (units: Units, per: (unit: UnitType) => number) => unitEntries(units).reduce((sum, [u, n]) => sum + per(u) * n, 0)
|
||||
|
||||
function addUnits(into: Units, units: Units) {
|
||||
for (const [u, n] of unitEntries(units)) into[u] = (into[u] ?? 0) + n
|
||||
return into
|
||||
}
|
||||
|
||||
/** Food the troops, the support standing here and the units in training eat; it comes out of the villagers' share. */
|
||||
function soldierUpkeep(v: MockVillage) {
|
||||
const home = Object.entries(v.troops ?? {}).reduce((sum, [unit, n]) => sum + UNITS[unit as UnitType].upkeep * (n ?? 0), 0)
|
||||
return home + (v.recruits ?? []).reduce((sum, o) => sum + UNITS[o.unit].upkeep * (o.count - o.done), 0)
|
||||
const home = unitSum(v.troops ?? {}, (u) => UNITS[u].upkeep)
|
||||
const support = Object.values(v.support ?? {}).reduce((sum, units) => sum + unitSum(units, (u) => UNITS[u].upkeep), 0)
|
||||
return home + support + (v.recruits ?? []).reduce((sum, o) => sum + UNITS[o.unit].upkeep * (o.count - o.done), 0)
|
||||
}
|
||||
|
||||
function villagers(v: MockVillage) {
|
||||
|
|
@ -455,7 +512,7 @@ function starvation(v: MockVillage) {
|
|||
}
|
||||
}
|
||||
|
||||
function view(v: MockVillage, now: number): VillageState {
|
||||
function view(state: MockState, v: MockVillage, now: number): VillageState {
|
||||
const assigned = assignWorkers(v)
|
||||
const pop = villagers(v)
|
||||
return {
|
||||
|
|
@ -483,6 +540,10 @@ function view(v: MockVillage, now: number): VillageState {
|
|||
starvation: starvation(v),
|
||||
troops: Object.fromEntries(Object.entries(v.troops ?? {}).filter(([, n]) => n)),
|
||||
military: military(v, now),
|
||||
movements: movements(state, v, now),
|
||||
support: support(state, v),
|
||||
rally: rallyInfo(v),
|
||||
unread_reports: (state.reports ?? []).filter((r) => r.user_id === v.user_id && r.world_id === v.world_id && !r.read).length,
|
||||
builders: BUILDERS,
|
||||
buildings: v.buildings.map(
|
||||
(b): Building => {
|
||||
|
|
@ -524,9 +585,19 @@ const continentOf = (x: number, y: number) => `K${Math.floor(y / 100)}${Math.flo
|
|||
/** Placeholder points: 5 per building level. */
|
||||
const points = (v: MockVillage) => v.buildings.reduce((sum, b) => sum + 5 * b.level, 0)
|
||||
|
||||
const MAP_SIZE = 1000
|
||||
const BARBARIAN_NAME = 'Barbarian village'
|
||||
|
||||
/** A barbarian made up from a hash of the field, near the map centre 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 - 500) <= 25 && Math.abs(y - 500) <= 25
|
||||
return near && r < 0.08 ? { id: -(y * MAP_SIZE + x), name: BARBARIAN_NAME, points: 20 + Math.floor(r * 1000) } : null
|
||||
}
|
||||
|
||||
/** Mock map: the stored player villages plus barbarians made up from a hash of the field. */
|
||||
function mapView(state: MockState, user: AuthUser, data: any): MapView {
|
||||
const size = 1000
|
||||
const size = MAP_SIZE
|
||||
const own = state.villages.find((v) => v.world_id === Number(data.world_id) && v.user_id === user.id)
|
||||
const cx = Number.isFinite(Number(data.x)) && data.x !== undefined ? Number(data.x) : (own?.x ?? 500)
|
||||
const cy = Number.isFinite(Number(data.y)) && data.y !== undefined ? Number(data.y) : (own?.y ?? 500)
|
||||
|
|
@ -552,25 +623,308 @@ function mapView(state: MockState, user: AuthUser, data: any): MapView {
|
|||
})
|
||||
continue
|
||||
}
|
||||
const r = (Math.imul(x * 73856093 ^ y * 19349663, 1274126177) >>> 0) / 4294967296
|
||||
const near = Math.abs(x - 500) <= 25 && Math.abs(y - 500) <= 25
|
||||
if (near && r < 0.08) {
|
||||
villages.push({
|
||||
id: -(y * size + x),
|
||||
x,
|
||||
y,
|
||||
name: 'Barbarian village',
|
||||
points: 20 + Math.floor(r * 1000),
|
||||
continent: continentOf(x, y),
|
||||
player: null,
|
||||
own: false,
|
||||
})
|
||||
const barbarian = barbarianAt(x, y)
|
||||
if (barbarian) {
|
||||
villages.push({ ...barbarian, x, y, continent: continentOf(x, y), player: null, own: false })
|
||||
}
|
||||
}
|
||||
}
|
||||
return { world_id: Number(data.world_id), size, center: { x: cx, y: cy }, x: x0, y: y0, w, h, villages }
|
||||
}
|
||||
|
||||
// Rally point: marches, battles and reports, crude stand-ins for app/Engine/Rally.php.
|
||||
|
||||
const REPORTS_PER_PAGE = 25
|
||||
const LOOTED = ['wood', 'clay', 'iron'] as const
|
||||
|
||||
function villageRef(state: MockState, id: number): VillageRef {
|
||||
if (id < 0) return { id, name: BARBARIAN_NAME, x: -id % MAP_SIZE, y: Math.floor(-id / MAP_SIZE), player: null }
|
||||
const v = state.villages.find((v) => v.id === id)
|
||||
if (!v) return { id, name: '?', x: 0, y: 0, player: null }
|
||||
const owner = state.users.find((u) => u.id === v.user_id)
|
||||
return { id: v.id, name: v.name, x: v.x, y: v.y, player: { id: v.user_id, name: owner?.name ?? '?' } }
|
||||
}
|
||||
|
||||
/** The stored player village on a field, else a made-up barbarian, else null. */
|
||||
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 barbarian = barbarianAt(x, y)
|
||||
return barbarian ? villageRef(state, barbarian.id) : null
|
||||
}
|
||||
|
||||
const field = (n: unknown) => Math.trunc(Number(n) || 0)
|
||||
const fieldDistance = (a: { x: number; y: number }, b: { x: number; y: number }) => Math.hypot(a.x - b.x, a.y - b.y)
|
||||
const travelMode = (mode: unknown) => TRAVEL_MODES.find((m) => m.mode === mode)
|
||||
const hasRallyPoint = (v: MockVillage) => v.buildings.some((b) => b.type === 'rally_point')
|
||||
|
||||
/** The slowest unit sets the pace. */
|
||||
function travelSeconds(units: Units, distance: number, mode: TravelMode) {
|
||||
const slowest = Math.max(0, ...unitEntries(units).map(([u]) => UNITS[u].speed))
|
||||
return Math.max(1, Math.round((slowest * distance) / (travelMode(mode)?.speed ?? 1)))
|
||||
}
|
||||
|
||||
/** What the player picked: known unit types with a positive count. */
|
||||
function pickUnits(raw: unknown): Units {
|
||||
const units: Units = {}
|
||||
for (const [unit, n] of Object.entries(raw && typeof raw === 'object' ? raw : {})) {
|
||||
const count = Math.floor(Number(n) || 0)
|
||||
if (unit in UNITS && count > 0) units[unit as UnitType] = count
|
||||
}
|
||||
return units
|
||||
}
|
||||
|
||||
/** Catch a village up to `at`, never backwards. */
|
||||
const advance = (state: MockState, v: MockVillage, at: number) => catchUp(state, v, Math.max(at, v.resources_at))
|
||||
|
||||
function march(state: MockState, m: Omit<MockMovement, 'id' | 'arrives_at'>) {
|
||||
const movement: MockMovement = { ...m, id: nextId(state), arrives_at: m.sent_at + travelSeconds(m.units, m.distance, m.mode) * 1000 }
|
||||
;(state.movements ??= []).push(movement)
|
||||
return movement
|
||||
}
|
||||
|
||||
/** Survivors head home from the target with what they carry. */
|
||||
function turnBack(state: MockState, m: MockMovement, units: Units, cargo: Cost | null, at: number) {
|
||||
march(state, { ...m, type: 'return', origin_id: m.target_id, target_id: m.origin_id, units, cargo, sent_at: at })
|
||||
}
|
||||
|
||||
/** The support of one home village standing in `host` goes home; settle the host first. */
|
||||
function sendSupportHome(state: MockState, host: MockVillage, homeId: number, now: number) {
|
||||
const units = counts(host.support?.[homeId] ?? {})
|
||||
if (!hasUnits(units)) fail('not_found')
|
||||
delete host.support![homeId]
|
||||
const home = state.villages.find((v) => v.id === homeId)
|
||||
// Its home is gone (mock.reset): the troops go with it.
|
||||
if (!home) return
|
||||
march(state, {
|
||||
world_id: host.world_id,
|
||||
user_id: home.user_id,
|
||||
type: 'return',
|
||||
mode: DEFAULT_MODE,
|
||||
origin_id: host.id,
|
||||
target_id: home.id,
|
||||
distance: fieldDistance(host, home),
|
||||
units,
|
||||
cargo: null,
|
||||
sent_at: now,
|
||||
})
|
||||
}
|
||||
|
||||
type ReportBody = { type: 'attack' | 'defense'; payload: BattleReport } | { type: 'support'; payload: SupportReport }
|
||||
|
||||
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 })
|
||||
}
|
||||
|
||||
/** Per unit: none of them. */
|
||||
const noLosses = (units: Units) => Object.fromEntries(unitEntries(units).map(([u]) => [u, 0]))
|
||||
|
||||
/** Barbarians have no troops: the attack always wins and loots the made-up stock. */
|
||||
function raid(state: MockState, m: MockMovement, at: number) {
|
||||
const capacity = unitSum(m.units, (u) => UNITS[u].carry)
|
||||
const each = Math.floor(Math.min(capacity, 3 * BARBARIAN_STOCK) / 3)
|
||||
const loot: Cost = { wood: each, clay: each, iron: each }
|
||||
writeReport(state, m.user_id, m.world_id, at, {
|
||||
type: 'attack',
|
||||
payload: {
|
||||
won: true,
|
||||
luck: 0,
|
||||
morale: 100,
|
||||
night: false,
|
||||
attacker: { village: villageRef(state, m.origin_id), units: counts(m.units), lost: noLosses(m.units) },
|
||||
defender: { village: villageRef(state, m.target_id), units: {}, lost: {} },
|
||||
wall: null,
|
||||
building: null,
|
||||
loot,
|
||||
capacity,
|
||||
},
|
||||
})
|
||||
turnBack(state, m, m.units, each > 0 ? loot : null, at)
|
||||
}
|
||||
|
||||
/**
|
||||
* Total attack against total defence (troops at home, support, militia). The winner loses
|
||||
* (loser / winner)^1.5 of every unit, the loser everything; survivors loot evenly up to their carry.
|
||||
*/
|
||||
function battle(state: MockState, m: MockMovement, d: MockVillage, at: number) {
|
||||
const drafted = militia(d)
|
||||
const defenders = addUnits({}, d.troops ?? {})
|
||||
for (const units of Object.values(d.support ?? {})) addUnits(defenders, units)
|
||||
const attack = unitSum(m.units, (u) => UNITS[u].attack)
|
||||
const defense = unitSum(defenders, (u) => UNITS[u].defense) + drafted * MILITIA_DEFENSE
|
||||
const won = attack > defense
|
||||
const attackRatio = won ? (defense / attack) ** 1.5 : 1
|
||||
const defenseRatio = won ? 1 : defense > 0 ? (attack / defense) ** 1.5 : 0
|
||||
const dead = (units: Units, ratio: number): Record<string, number> =>
|
||||
Object.fromEntries(unitEntries(units).map(([u, n]) => [u, Math.min(n, Math.round(n * ratio))]))
|
||||
const left = (units: Units, lost: Record<string, number>): Units =>
|
||||
Object.fromEntries(unitEntries(units).map(([u, n]) => [u, n - (lost[u] ?? 0)]).filter(([, n]) => Number(n) > 0))
|
||||
|
||||
// Defenders fall in every group alike, support included.
|
||||
const defenseLost: Record<string, number> = {}
|
||||
const troopsLost = dead(d.troops ?? {}, defenseRatio)
|
||||
addUnits(defenseLost, troopsLost)
|
||||
d.troops = left(d.troops ?? {}, troopsLost)
|
||||
const supporters = new Set<number>()
|
||||
for (const [home, units] of Object.entries(d.support ?? {})) {
|
||||
const lost = dead(units, defenseRatio)
|
||||
addUnits(defenseLost, lost)
|
||||
const rest = left(units, lost)
|
||||
if (hasUnits(rest)) d.support![Number(home)] = rest
|
||||
else delete d.support![Number(home)]
|
||||
const owner = state.villages.find((v) => v.id === Number(home))?.user_id
|
||||
if (owner !== undefined && owner !== d.user_id) supporters.add(owner)
|
||||
}
|
||||
const militiaLost = Math.min(drafted, Math.round(drafted * defenseRatio))
|
||||
if (militiaLost) {
|
||||
d.militia = drafted - militiaLost
|
||||
if (!d.militia) d.levy_until = null
|
||||
}
|
||||
|
||||
const attackLost = dead(m.units, attackRatio)
|
||||
const survivors = left(m.units, attackLost)
|
||||
const capacity = won ? unitSum(survivors, (u) => UNITS[u].carry) : 0
|
||||
const loot: Cost = { wood: 0, clay: 0, iron: 0 }
|
||||
for (const r of LOOTED) {
|
||||
loot[r] = Math.floor(Math.min(capacity / 3, d.resources[r]))
|
||||
d.resources[r] -= loot[r]
|
||||
}
|
||||
|
||||
const wall = d.buildings.find((b) => b.type === 'wall')
|
||||
const report: BattleReport = {
|
||||
won,
|
||||
luck: 0,
|
||||
morale: 100,
|
||||
night: false,
|
||||
attacker: { village: villageRef(state, m.origin_id), units: counts(m.units), lost: attackLost },
|
||||
defender: {
|
||||
village: villageRef(state, d.id),
|
||||
units: drafted ? { ...defenders, militia: drafted } : { ...defenders },
|
||||
lost: drafted ? { ...defenseLost, militia: militiaLost } : defenseLost,
|
||||
},
|
||||
wall: wall ? { before: wall.level, after: wall.level } : null,
|
||||
building: null,
|
||||
loot,
|
||||
capacity,
|
||||
}
|
||||
// An attacker with no survivors learns nothing about the defence.
|
||||
const seen: BattleReport = hasUnits(survivors)
|
||||
? report
|
||||
: { ...report, defender: { village: report.defender.village, units: null, lost: null }, wall: null }
|
||||
writeReport(state, m.user_id, m.world_id, at, { type: 'attack', payload: seen })
|
||||
writeReport(state, d.user_id, d.world_id, at, { type: 'defense', payload: report })
|
||||
supporters.forEach((userId) => writeReport(state, userId, d.world_id, at, { type: 'defense', payload: report }))
|
||||
|
||||
if (hasUnits(survivors)) turnBack(state, m, survivors, capacity > 0 ? loot : null, at)
|
||||
}
|
||||
|
||||
/** A movement reaches its target, which was caught up to the arrival first. */
|
||||
function arrive(state: MockState, m: MockMovement) {
|
||||
const at = m.arrives_at
|
||||
const target = m.target_id > 0 ? state.villages.find((v) => v.id === m.target_id) : undefined
|
||||
if (m.type === 'return') {
|
||||
// Its home is gone (mock.reset): the troops go with it.
|
||||
if (!target) return
|
||||
advance(state, target, at)
|
||||
addUnits((target.troops ??= {}), m.units)
|
||||
if (m.cargo) refund(target, m.cargo)
|
||||
return
|
||||
}
|
||||
if (m.type === 'attack' && m.target_id < 0) return raid(state, m, at)
|
||||
// The target is gone (mock.reset): the group just turns around.
|
||||
if (!target) return turnBack(state, m, m.units, null, at)
|
||||
advance(state, target, at)
|
||||
if (m.type === 'attack') return battle(state, m, target, at)
|
||||
|
||||
target.support ??= {}
|
||||
target.support[m.origin_id] = addUnits({ ...target.support[m.origin_id] }, m.units)
|
||||
const report: SupportReport = { from: villageRef(state, m.origin_id), to: villageRef(state, target.id), units: counts(m.units) }
|
||||
writeReport(state, m.user_id, m.world_id, at, { type: 'support', payload: report })
|
||||
if (target.user_id !== m.user_id) writeReport(state, target.user_id, m.world_id, at, { type: 'support', payload: report })
|
||||
}
|
||||
|
||||
/** Handle every movement that arrived by `now`, in arrival order; returns the villages involved. */
|
||||
function processMovements(state: MockState, now: number) {
|
||||
const touched = new Set<number>()
|
||||
for (;;) {
|
||||
const due = (state.movements ?? [])
|
||||
.filter((m) => m.arrives_at <= now)
|
||||
.sort((a, b) => a.arrives_at - b.arrives_at || a.id - b.id)[0]
|
||||
if (!due) break
|
||||
state.movements = state.movements!.filter((m) => m !== due)
|
||||
arrive(state, due)
|
||||
touched.add(due.origin_id).add(due.target_id)
|
||||
}
|
||||
return [...touched].filter((id) => id > 0)
|
||||
}
|
||||
|
||||
/** Own groups leaving here or coming home here, and every group coming here; strangers' show no details. */
|
||||
function movements(state: MockState, v: MockVillage, now: number): Movement[] {
|
||||
return (state.movements ?? [])
|
||||
.filter((m) => (m.type === 'return' ? m.target_id === v.id : m.origin_id === v.id || m.target_id === v.id))
|
||||
.sort((a, b) => a.arrives_at - b.arrives_at || a.id - b.id)
|
||||
.map((m): Movement => {
|
||||
const direction: Movement['direction'] = m.type === 'return' ? 'home' : m.origin_id === v.id ? 'out' : 'in'
|
||||
const mine = m.user_id === v.user_id
|
||||
const cancelUntil = m.sent_at + CANCEL_WINDOW * 1000
|
||||
return {
|
||||
id: m.id,
|
||||
type: m.type,
|
||||
direction,
|
||||
mode: mine ? m.mode : null,
|
||||
from: villageRef(state, m.origin_id),
|
||||
to: villageRef(state, m.target_id),
|
||||
units: mine ? counts(m.units) : null,
|
||||
cargo: mine ? m.cargo : null,
|
||||
sent_at: mine ? iso(m.sent_at) : null,
|
||||
arrives_at: iso(m.arrives_at),
|
||||
cancel_until: mine && direction === 'out' && cancelUntil > now ? iso(cancelUntil) : null,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function support(state: MockState, v: MockVillage): VillageState['support'] {
|
||||
const group = (villageId: number, units: Units): SupportGroup => ({ village: villageRef(state, villageId), units: counts(units) })
|
||||
return {
|
||||
here: Object.entries(v.support ?? {})
|
||||
.filter(([, units]) => hasUnits(units))
|
||||
.map(([home, units]) => group(Number(home), units)),
|
||||
away: state.villages
|
||||
.filter((host) => host.world_id === v.world_id && hasUnits(host.support?.[v.id] ?? {}))
|
||||
.map((host) => group(host.id, host.support![v.id]!)),
|
||||
}
|
||||
}
|
||||
|
||||
function rallyInfo(v: MockVillage): RallyInfo {
|
||||
return {
|
||||
has_rally_point: hasRallyPoint(v),
|
||||
modes: TRAVEL_MODES.map((m) => ({ ...m })),
|
||||
default_mode: DEFAULT_MODE,
|
||||
detection: DETECTION + (v.buildings.find((b) => b.type === 'watchtower')?.level ?? 0),
|
||||
cancel_window: CANCEL_WINDOW,
|
||||
// The mock skips beginner protection.
|
||||
protected_until: null,
|
||||
}
|
||||
}
|
||||
|
||||
const presentReport = (r: MockReport) =>
|
||||
({ id: r.id, type: r.type, happened_at: r.happened_at, read: r.read, payload: r.payload }) as Report
|
||||
|
||||
/** The player's reports on a world, newest first. */
|
||||
function reportPage(state: MockState, user: AuthUser, worldId: number, page = 1): ReportPage {
|
||||
const mine = (state.reports ?? [])
|
||||
.filter((r) => r.user_id === user.id && r.world_id === worldId)
|
||||
.sort((a, b) => Date.parse(b.happened_at) - Date.parse(a.happened_at) || b.id - a.id)
|
||||
const pages = Math.max(1, Math.ceil(mine.length / REPORTS_PER_PAGE))
|
||||
const current = Math.max(1, Math.min(pages, Math.floor(page) || 1))
|
||||
return {
|
||||
reports: mine.slice((current - 1) * REPORTS_PER_PAGE, current * REPORTS_PER_PAGE).map(presentReport),
|
||||
page: current,
|
||||
pages,
|
||||
unread: mine.filter((r) => !r.read).length,
|
||||
}
|
||||
}
|
||||
|
||||
function createVillage(state: MockState, user: AuthUser, worldId: number, now: number): MockVillage {
|
||||
const taken = new Set(state.villages.filter((v) => v.world_id === worldId).map((v) => `${v.x}|${v.y}`))
|
||||
let x = 500
|
||||
|
|
@ -630,7 +984,7 @@ const handlers: Record<string, Handler> = {
|
|||
return { village_id: v.id }
|
||||
},
|
||||
|
||||
'village.show': (state, user, data, now) => view(ownVillage(state, user, data.village_id, now), now),
|
||||
'village.show': (state, user, data, now) => view(state, ownVillage(state, user, data.village_id, now), now),
|
||||
|
||||
'map.view': (state, user, data) => mapView(state, user, data),
|
||||
|
||||
|
|
@ -643,7 +997,7 @@ const handlers: Record<string, Handler> = {
|
|||
const cost = levelCost(type, 1)
|
||||
pay(v, cost)
|
||||
enqueue(state, v, { building_id: null, type, action: 'build', target_level: 1, cost, seconds: levelSeconds(type, 1) }, now)
|
||||
return view(v, now)
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
'village.upgrade': (state, user, data, now) => {
|
||||
|
|
@ -652,7 +1006,7 @@ const handlers: Record<string, Handler> = {
|
|||
const offer = upgradeOffer(v, b) ?? fail('max_level')
|
||||
pay(v, offer.cost)
|
||||
enqueue(state, v, { building_id: b.id, type: b.type, action: 'upgrade', target_level: offer.target_level, cost: offer.cost, seconds: offer.seconds }, now)
|
||||
return view(v, now)
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
'village.demolish': (state, user, data, now) => {
|
||||
|
|
@ -660,7 +1014,7 @@ const handlers: Record<string, Handler> = {
|
|||
const b = ownBuilding(v, data.building_id)
|
||||
const offer = demolishOffer(v, b) ?? fail('core_building')
|
||||
enqueue(state, v, { building_id: b.id, type: b.type, action: 'demolish', target_level: offer.target_level, cost: { wood: 0, clay: 0, iron: 0 }, seconds: offer.seconds }, now)
|
||||
return view(v, now)
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
// Cancelling also cancels later orders for the same building, since they build on it.
|
||||
|
|
@ -674,14 +1028,14 @@ const handlers: Record<string, Handler> = {
|
|||
v.orders = v.orders.filter((o) => !cancelled.includes(o))
|
||||
cancelled.forEach((o) => refund(v, o.cost))
|
||||
startWaiting(v, now)
|
||||
return view(v, now)
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
'village.staff': (state, user, data, now) => {
|
||||
const v = ownVillage(state, user, data.village_id, now)
|
||||
const b = ownBuilding(v, data.building_id)
|
||||
b.priority = Math.min(9, Math.max(0, Math.round(Number(data.priority) || 0)))
|
||||
return view(v, now)
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
'village.recruit': (state, user, data, now) => {
|
||||
|
|
@ -702,7 +1056,7 @@ const handlers: Record<string, Handler> = {
|
|||
...(v.recruits ?? []),
|
||||
{ id: nextId(state), building_id: b.id, unit, count, done: 0, seconds_per_unit: seconds, cost: entry.cost, starts_at: starts, finishes_at: starts + seconds * count * 1000 },
|
||||
]
|
||||
return view(v, now)
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
// Refunds the untrained units; later orders at the same building move up.
|
||||
|
|
@ -721,7 +1075,7 @@ const handlers: Record<string, Handler> = {
|
|||
o.finishes_at = from + o.seconds_per_unit * o.count * 1000
|
||||
from = o.finishes_at
|
||||
}
|
||||
return view(v, now)
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
'village.levy': (state, user, data, now) => {
|
||||
|
|
@ -732,7 +1086,7 @@ const handlers: Record<string, Handler> = {
|
|||
if (count > villagers(v)) fail('villagers')
|
||||
v.militia = count
|
||||
v.levy_until = now + LEVY_SECONDS * 1000
|
||||
return view(v, now)
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
'village.endLevy': (state, user, data, now) => {
|
||||
|
|
@ -740,11 +1094,155 @@ const handlers: Record<string, Handler> = {
|
|||
if (!v.militia) fail('not_found')
|
||||
v.militia = 0
|
||||
v.levy_until = null
|
||||
return view(v, now)
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
'mock.reset': (state, user) => {
|
||||
state.villages = state.villages.filter((v) => v.user_id !== user.id)
|
||||
'village.rename': (state, user, data, now) => {
|
||||
const v = ownVillage(state, user, data.village_id, now)
|
||||
const name = String(data.name ?? '').replace(/s+/g, ' ').trim()
|
||||
if (!name || name.length > 32) fail('name')
|
||||
v.name = name
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
'rally.simulate': (_state, _user, data): SimulatedBattle => {
|
||||
// Crude stand-in for the backend's CombatResolver: totals against totals.
|
||||
const attack: Record<string, number> = {}
|
||||
const defense: Record<string, number> = {}
|
||||
for (const [u, n] of Object.entries(data.attack ?? {})) if (Number(n) > 0 && u in UNITS) attack[u] = Number(n)
|
||||
for (const [u, n] of Object.entries(data.defense ?? {})) if (Number(n) > 0 && (u in UNITS || u === 'militia')) defense[u] = Number(n)
|
||||
const a = Object.entries(attack).reduce((s, [u, n]) => s + n * UNITS[u as UnitType].attack, 0)
|
||||
const d = Object.entries(defense).reduce((s, [u, n]) => s + n * (u === 'militia' ? 5 : UNITS[u as UnitType].defense), 0) + 20 * Number(data.wall || 0)
|
||||
const won = a > d
|
||||
const ratio = won ? (d / a) ** 1.5 : a > 0 ? (a / d) ** 1.5 : 0
|
||||
const dead = (units: Record<string, number>, loss: number) => Object.fromEntries(Object.entries(units).map(([u, n]) => [u, Math.min(n, Math.round(n * loss))]))
|
||||
return {
|
||||
won,
|
||||
attacker: { units: attack, lost: dead(attack, won ? ratio : 1) },
|
||||
defender: { units: defense, lost: dead(defense, won ? 1 : ratio) },
|
||||
wall: Number(data.wall) > 0 ? { before: Number(data.wall), after: Number(data.wall) } : null,
|
||||
building: null,
|
||||
power: { attack: a, defense: d },
|
||||
}
|
||||
},
|
||||
|
||||
'rally.preview': (state, user, data, now): MarchPlan => {
|
||||
const v = ownVillage(state, user, data.village_id, now)
|
||||
const mode = travelMode(data.mode)?.mode ?? DEFAULT_MODE
|
||||
const units = pickUnits(data.units)
|
||||
const x = field(data.x)
|
||||
const y = field(data.y)
|
||||
const distance = fieldDistance(v, { x, y })
|
||||
return {
|
||||
x,
|
||||
y,
|
||||
target: villageAt(state, v.world_id, x, y),
|
||||
mode,
|
||||
distance: round(distance),
|
||||
seconds: hasUnits(units) && distance > 0 ? travelSeconds(units, distance, mode) : null,
|
||||
}
|
||||
},
|
||||
|
||||
// The troops leave at once. The mock knows no catapult damage, so catapult_target is ignored.
|
||||
'rally.send': (state, user, data, now) => {
|
||||
const v = ownVillage(state, user, data.village_id, now)
|
||||
const type = data.type as MovementType
|
||||
if (type !== 'attack' && type !== 'support') fail('not_found')
|
||||
if (!hasRallyPoint(v)) fail('no_rally_point')
|
||||
const mode = data.mode ? (travelMode(data.mode) ?? fail('not_found')).mode : DEFAULT_MODE
|
||||
const units = pickUnits(data.units)
|
||||
if (!hasUnits(units)) fail('count')
|
||||
if (unitEntries(units).some(([u, n]) => n > (v.troops?.[u] ?? 0))) fail('troops')
|
||||
const target = villageAt(state, v.world_id, field(data.x), field(data.y)) ?? fail('not_found')
|
||||
if (target.id === v.id) fail('same_village')
|
||||
if (type === 'attack' && target.player?.id === user.id) fail('own_village')
|
||||
if (type === 'support' && !target.player) fail('barbarian')
|
||||
v.troops ??= {}
|
||||
for (const [u, n] of unitEntries(units)) v.troops[u] = (v.troops[u] ?? 0) - n
|
||||
march(state, {
|
||||
world_id: v.world_id,
|
||||
user_id: user.id,
|
||||
type,
|
||||
mode,
|
||||
origin_id: v.id,
|
||||
target_id: target.id,
|
||||
distance: fieldDistance(v, target),
|
||||
units,
|
||||
cargo: null,
|
||||
sent_at: now,
|
||||
})
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
// Within the window the group turns around where it is: home after as long as it was under way.
|
||||
'rally.cancel': (state, user, data, now) => {
|
||||
const v = ownVillage(state, user, data.village_id, now)
|
||||
const m =
|
||||
(state.movements ?? []).find((m) => m.id === Number(data.movement_id) && m.origin_id === v.id && m.type !== 'return') ??
|
||||
fail('not_found')
|
||||
if (now > m.sent_at + CANCEL_WINDOW * 1000 || m.arrives_at <= now) fail('too_late')
|
||||
const elapsed = now - m.sent_at
|
||||
m.type = 'return'
|
||||
m.origin_id = m.target_id
|
||||
m.target_id = v.id
|
||||
m.sent_at = now
|
||||
m.arrives_at = now + elapsed
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
// The host sends support standing here home.
|
||||
'rally.sendHome': (state, user, data, now) => {
|
||||
const v = ownVillage(state, user, data.village_id, now)
|
||||
sendSupportHome(state, v, Number(data.home_village_id), now)
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
// This village calls its support at a host back.
|
||||
'rally.withdraw': (state, user, data, now) => {
|
||||
const v = ownVillage(state, user, data.village_id, now)
|
||||
const host = state.villages.find((h) => h.id === Number(data.host_village_id) && h.id !== v.id) ?? fail('not_found')
|
||||
advance(state, host, now)
|
||||
sendSupportHome(state, host, v.id, now)
|
||||
return view(state, v, now)
|
||||
},
|
||||
|
||||
'report.index': (state, user, data): ReportPage => reportPage(state, user, Number(data.world_id), Number(data.page) || 1),
|
||||
|
||||
// Opening a report marks it read.
|
||||
'report.show': (state, user, data): Report => {
|
||||
const report = (state.reports ?? []).find((r) => r.id === Number(data.id) && r.user_id === user.id) ?? fail('not_found')
|
||||
report.read = true
|
||||
return presentReport(report)
|
||||
},
|
||||
|
||||
'report.delete': (state, user, data): ReportPage => {
|
||||
const worldId = Number(data.world_id)
|
||||
const ids = new Set((Array.isArray(data.ids) ? data.ids : []).map(Number))
|
||||
state.reports = (state.reports ?? []).filter((r) => !(r.user_id === user.id && r.world_id === worldId && ids.has(r.id)))
|
||||
return reportPage(state, user, worldId)
|
||||
},
|
||||
|
||||
'report.readAll': (state, user, data): ReportPage => {
|
||||
const worldId = Number(data.world_id)
|
||||
for (const r of state.reports ?? []) {
|
||||
if (r.user_id === user.id && r.world_id === worldId) r.read = true
|
||||
}
|
||||
return reportPage(state, user, worldId)
|
||||
},
|
||||
|
||||
// Also drops the player's marches and reports; others' support standing in the removed villages goes home.
|
||||
'mock.reset': (state, user, _data, now) => {
|
||||
const gone = state.villages.filter((v) => v.user_id === user.id)
|
||||
const goneIds = new Set(gone.map((v) => v.id))
|
||||
for (const host of gone) {
|
||||
for (const [home, units] of Object.entries(host.support ?? {})) {
|
||||
if (!goneIds.has(Number(home)) && hasUnits(units)) sendSupportHome(state, host, Number(home), now)
|
||||
}
|
||||
}
|
||||
state.villages = state.villages.filter((v) => !goneIds.has(v.id))
|
||||
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)
|
||||
return true
|
||||
},
|
||||
}
|
||||
|
|
@ -752,11 +1250,13 @@ const handlers: Record<string, Handler> = {
|
|||
export function createMockServer(): { ws: GameWs; auth: GameAuth } {
|
||||
const bus = new EventTarget()
|
||||
const timers = new Map<number, ReturnType<typeof setTimeout>>()
|
||||
let marchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const emit = (event: string, data: unknown) =>
|
||||
bus.dispatchEvent(new CustomEvent(event, { detail: { event, data, channel: 'websocket' } }))
|
||||
|
||||
// Fire `village:updated` when a village's next order finishes, like the game:events worker.
|
||||
// Fire `village:updated` when a village's next order finishes or the next movement
|
||||
// arrives (for both ends), like the game:events worker.
|
||||
function schedule(state: MockState) {
|
||||
for (const v of state.villages) {
|
||||
clearTimeout(timers.get(v.id))
|
||||
|
|
@ -770,15 +1270,27 @@ export function createMockServer(): { ws: GameWs; auth: GameAuth } {
|
|||
v.id,
|
||||
setTimeout(() => {
|
||||
const fresh = load()
|
||||
const now = Date.now()
|
||||
const touched = processMovements(fresh, now)
|
||||
const village = fresh.villages.find((x) => x.id === v.id)
|
||||
if (!village) return
|
||||
catchUp(fresh, village, Date.now())
|
||||
if (village) catchUp(fresh, village, now)
|
||||
save(fresh)
|
||||
schedule(fresh)
|
||||
emit('village:updated', { village_id: v.id })
|
||||
new Set([...touched, ...(village ? [v.id] : [])]).forEach((id) => emit('village:updated', { village_id: id }))
|
||||
}, Math.max(0, next - Date.now()) + 20),
|
||||
)
|
||||
}
|
||||
|
||||
clearTimeout(marchTimer)
|
||||
const arrival = Math.min(...(state.movements ?? []).map((m) => m.arrives_at))
|
||||
if (arrival === Infinity) return
|
||||
marchTimer = setTimeout(() => {
|
||||
const fresh = load()
|
||||
const touched = processMovements(fresh, Date.now())
|
||||
save(fresh)
|
||||
schedule(fresh)
|
||||
touched.forEach((id) => emit('village:updated', { village_id: id }))
|
||||
}, Math.max(0, arrival - Date.now()) + 20)
|
||||
}
|
||||
|
||||
function currentUser(state: MockState) {
|
||||
|
|
@ -818,6 +1330,8 @@ export function createMockServer(): { ws: GameWs; auth: GameAuth } {
|
|||
const handler = handlers[event] ?? fail('not_found')
|
||||
const state = load()
|
||||
const now = Date.now()
|
||||
// Arrivals first, for every village, so the handler sees the world as of now.
|
||||
processMovements(state, now)
|
||||
const result = handler(state, currentUser(state), data, now)
|
||||
save(state)
|
||||
schedule(state)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,45 @@
|
|||
<script setup lang="ts">
|
||||
import type { Report } from '~/types/game'
|
||||
|
||||
const route = useRoute()
|
||||
const worldId = Number(route.params.worldId)
|
||||
const { error, show } = useReports(worldId)
|
||||
useCurrentWorld().enter(worldId)
|
||||
const { t } = useI18n()
|
||||
const clock = useNow()
|
||||
|
||||
const report = ref<Report | null>(null)
|
||||
watch(
|
||||
() => route.params.id,
|
||||
async (id) => (report.value = await show(Number(id))),
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
const subject = computed(() => {
|
||||
const r = report.value
|
||||
if (!r) return ''
|
||||
if (r.type === 'support') return t('reports.title_support', { from: villageLabel(r.payload.from), to: villageLabel(r.payload.to) })
|
||||
return t('reports.title_attack', { from: villageLabel(r.payload.attacker.village), to: villageLabel(r.payload.defender.village) })
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mx-auto max-w-4xl px-4 py-6 sm:px-6">
|
||||
<NuxtLink :to="`/reports/${worldId}`" class="mb-3 inline-block text-sm font-semibold text-blood-700 hover:underline">‹ {{ $t('reports.back') }}</NuxtLink>
|
||||
<p v-if="error" class="alert mb-3" role="alert">{{ error }}</p>
|
||||
<section v-if="report" class="panel">
|
||||
<div class="panel-head">
|
||||
<h1 class="panel-title">{{ subject }}</h1>
|
||||
<span class="text-sm whitespace-nowrap text-ink-700 tabular-nums">{{ formatArrival(Date.parse(report.happened_at), clock, t) }}</span>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<ReportBattle v-if="report.type !== 'support'" :report="report.payload" :world-id="worldId" />
|
||||
<div v-else class="space-y-3 text-sm">
|
||||
<p>{{ $t('reports.support.arrived', { to: villageLabel(report.payload.to) }) }}</p>
|
||||
<ReportUnits :units="report.payload.units" :lost="null" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<p v-else-if="!error" class="py-6 text-center text-sm text-ink-500">{{ $t('common.loading') }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
<script setup lang="ts">
|
||||
import type { Report } from '~/types/game'
|
||||
|
||||
const route = useRoute()
|
||||
const worldId = Number(route.params.worldId)
|
||||
const { page, error, busy, load, remove, readAll } = useReports(worldId)
|
||||
useCurrentWorld().enter(worldId)
|
||||
const { t } = useI18n()
|
||||
const clock = useNow()
|
||||
|
||||
load(Number(route.query.page) || 1)
|
||||
|
||||
const selected = ref<number[]>([])
|
||||
watch(page, () => (selected.value = []))
|
||||
const allSelected = computed(() => !!page.value?.reports.length && selected.value.length === page.value.reports.length)
|
||||
function toggleAll() {
|
||||
selected.value = allSelected.value ? [] : (page.value?.reports.map((r) => r.id) ?? [])
|
||||
}
|
||||
|
||||
function subject(r: Report) {
|
||||
if (r.type === 'support') return t('reports.title_support', { from: villageLabel(r.payload.from), to: villageLabel(r.payload.to) })
|
||||
return t('reports.title_attack', { from: villageLabel(r.payload.attacker.village), to: villageLabel(r.payload.defender.village) })
|
||||
}
|
||||
|
||||
const DOT = { won: 'bg-moss-600', losses: 'bg-gold-500', lost: 'bg-blood-700', info: 'bg-iron-400' }
|
||||
</script>
|
||||
|
||||
<!-- The report list, like Die Stämme's: a coloured dot for the outcome, unread in bold, newest first. -->
|
||||
<template>
|
||||
<div class="mx-auto max-w-4xl px-4 py-6 sm:px-6">
|
||||
<section class="panel">
|
||||
<div class="panel-head">
|
||||
<h1 class="panel-title">{{ $t('reports.title') }}</h1>
|
||||
<button v-if="page?.unread" type="button" class="text-sm font-semibold text-blood-700 hover:underline" :disabled="busy" @click="readAll()">
|
||||
{{ $t('reports.read_all') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<p v-if="error" class="alert mb-3" role="alert">{{ error }}</p>
|
||||
<p v-if="!page" class="py-6 text-center text-sm text-ink-500">{{ $t('common.loading') }}</p>
|
||||
<p v-else-if="!page.reports.length" class="py-6 text-center text-sm text-ink-500">{{ $t('reports.none') }}</p>
|
||||
<template v-else>
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-b-2 border-parchment-300 text-left text-xs text-ink-500">
|
||||
<th class="w-8 py-1.5">
|
||||
<input type="checkbox" :checked="allSelected" :aria-label="$t('reports.select_all')" @change="toggleAll" />
|
||||
</th>
|
||||
<th class="py-1.5 font-semibold">{{ $t('reports.subject') }}</th>
|
||||
<th class="py-1.5 text-right font-semibold">{{ $t('reports.received') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-parchment-300">
|
||||
<tr v-for="r in page.reports" :key="r.id">
|
||||
<td class="py-1.5">
|
||||
<input v-model="selected" type="checkbox" :value="r.id" :aria-label="$t('reports.select', { subject: subject(r) })" />
|
||||
</td>
|
||||
<td class="py-1.5 pr-2">
|
||||
<NuxtLink :to="`/reports/${worldId}/${r.id}`" class="flex items-center gap-2 hover:underline" :class="r.read ? '' : 'font-semibold'">
|
||||
<span class="size-2.5 shrink-0 rounded-full" :class="DOT[reportTone(r)]" :title="$t(`reports.tone.${reportTone(r)}`)" />
|
||||
<IconUi :name="r.type === 'support' ? 'support' : 'attack'" class="size-4 shrink-0 text-ink-500" />
|
||||
<span class="min-w-0">{{ subject(r) }}</span>
|
||||
<span v-if="!r.read" class="sr-only">({{ $t('reports.unread') }})</span>
|
||||
</NuxtLink>
|
||||
</td>
|
||||
<td class="py-1.5 text-right whitespace-nowrap text-ink-700 tabular-nums">{{ formatArrival(Date.parse(r.happened_at), clock, t) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="mt-3 flex flex-wrap items-center gap-2 border-t-2 border-parchment-300 pt-3">
|
||||
<button type="button" class="btn btn-outline px-2.5 py-1" :disabled="busy || !selected.length" @click="remove(selected)">
|
||||
{{ $t('reports.delete') }}
|
||||
</button>
|
||||
<div v-if="page.pages > 1" class="ml-auto flex items-center gap-2 text-sm">
|
||||
<button type="button" class="btn btn-ghost px-2 py-1" :disabled="busy || page.page <= 1" @click="load(page.page - 1)">‹ {{ $t('reports.prev') }}</button>
|
||||
<span class="tabular-nums text-ink-700">{{ $t('reports.page', { page: page.page, pages: page.pages }) }}</span>
|
||||
<button type="button" class="btn btn-ghost px-2 py-1" :disabled="busy || page.page >= page.pages" @click="load(page.page + 1)">{{ $t('reports.next') }} ›</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -12,11 +12,20 @@ watch(village, (state) => {
|
|||
|
||||
v.refresh()
|
||||
|
||||
/** The new name while the village is being renamed. */
|
||||
const renaming = ref<string | null>(null)
|
||||
async function rename() {
|
||||
if (renaming.value !== null && (await v.rename(renaming.value))) renaming.value = null
|
||||
}
|
||||
|
||||
const incomingAttacks = computed(() => village.value?.movements.filter((m) => m.direction === 'in' && m.type === 'attack') ?? [])
|
||||
|
||||
// The screens of a village, like the building links along the top in Die Stämme.
|
||||
const screens = [
|
||||
{ name: 'overview', path: '', icon: 'headquarters' },
|
||||
{ name: 'build', path: '/build', icon: 'storage' },
|
||||
{ name: 'recruit', path: '/recruit', icon: 'barracks' },
|
||||
{ name: 'rally', path: '/rally', icon: 'rally_point' },
|
||||
{ name: 'workforce', path: '/workforce', icon: 'farm' },
|
||||
] as const
|
||||
</script>
|
||||
|
|
@ -26,7 +35,25 @@ const screens = [
|
|||
<header class="sticky top-0 z-30 border-b-2 border-wood-700 bg-parchment-200">
|
||||
<div class="flex flex-wrap items-center gap-x-5 gap-y-2 px-4 py-2 sm:px-6">
|
||||
<div class="flex min-w-0 items-baseline gap-2">
|
||||
<form v-if="renaming !== null" class="flex items-center gap-1.5" @submit.prevent="rename">
|
||||
<input
|
||||
v-model="renaming"
|
||||
type="text"
|
||||
maxlength="32"
|
||||
class="input w-44 px-2 py-0.5"
|
||||
:aria-label="$t('village.rename')"
|
||||
@keydown.esc="renaming = null"
|
||||
/>
|
||||
<button type="submit" class="btn btn-primary px-2 py-0.5" :disabled="v.busy.value || !renaming.trim()">{{ $t('village.rename_save') }}</button>
|
||||
<button type="button" class="btn btn-ghost px-2 py-0.5" @click="renaming = null">{{ $t('village.rename_cancel') }}</button>
|
||||
</form>
|
||||
<template v-else>
|
||||
<h1 class="truncate font-display text-lg font-semibold text-wood-900" style="font-variant: small-caps">{{ village.name }}</h1>
|
||||
<button type="button" class="self-center text-ink-500 hover:text-blood-700" :title="$t('village.rename')" @click="renaming = village.name">
|
||||
<IconUi name="edit" class="size-3.5" />
|
||||
<span class="sr-only">{{ $t('village.rename') }}</span>
|
||||
</button>
|
||||
</template>
|
||||
<NuxtLink
|
||||
:to="{ path: `/map/${village.world_id}`, query: { x: village.x, y: village.y } }"
|
||||
class="text-sm whitespace-nowrap text-ink-700 tabular-nums hover:text-blood-700 hover:underline"
|
||||
|
|
@ -48,6 +75,15 @@ const screens = [
|
|||
<span :class="s.name === 'overview' ? 'hidden sm:inline' : ''">{{ $t(`village.screens.${s.name}`) }}</span>
|
||||
</NuxtLink>
|
||||
</nav>
|
||||
<NuxtLink
|
||||
v-if="incomingAttacks.length"
|
||||
:to="`/village/${id}/rally`"
|
||||
class="badge badge-blood"
|
||||
:title="$t('village.incoming', { count: incomingAttacks.length })"
|
||||
>
|
||||
<IconUi name="attack" class="size-3.5" />
|
||||
{{ incomingAttacks.length }}
|
||||
</NuxtLink>
|
||||
<VillageResourceBar class="lg:ml-auto" :village="village" :resources="resources" />
|
||||
</div>
|
||||
<VillageFoodWarning :starvation="village.starvation" :levy="village.levy" :seconds-until="v.secondsUntil" />
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ const screenLink = computed(() => {
|
|||
const b = selectedBuilding.value
|
||||
if (!b) return null
|
||||
if (b.type === 'headquarters') return { to: `${base}/build`, label: t('village.screens.build') }
|
||||
if (b.type === 'rally_point') return { to: `${base}/rally`, label: t('village.screens.rally') }
|
||||
if (village.value.military.some((m) => m.building_id === b.id)) {
|
||||
return { to: { path: `${base}/recruit`, query: { at: b.id } }, label: t('village.buildings.recruit') }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,43 @@
|
|||
<script setup lang="ts">
|
||||
const route = useRoute()
|
||||
const v = useVillageContext()
|
||||
const village = computed(() => v.village.value!)
|
||||
|
||||
/** `?x=&y=` from the map fills in the target. */
|
||||
const initialTarget = computed(() => (route.query.x && route.query.y ? { x: Number(route.query.x), y: Number(route.query.y) } : null))
|
||||
</script>
|
||||
|
||||
<!-- The rally point: send troops, the troop movements, and support. -->
|
||||
<template>
|
||||
<div class="grid gap-6 px-4 py-6 sm:px-6 lg:grid-cols-[minmax(0,1fr)_22rem] 2xl:grid-cols-[minmax(0,1fr)_26rem]">
|
||||
<div class="min-w-0 space-y-6">
|
||||
<VillageSendTroops
|
||||
:key="`${route.query.x}|${route.query.y}`"
|
||||
:village="village"
|
||||
:busy="v.busy.value"
|
||||
:initial-target="initialTarget"
|
||||
:now="v.now.value"
|
||||
:preview="v.preview"
|
||||
:send="v.send"
|
||||
/>
|
||||
<VillageMovements
|
||||
:movements="village.movements"
|
||||
:world-id="village.world_id"
|
||||
:now="v.now.value"
|
||||
:seconds-until="v.secondsUntil"
|
||||
:busy="v.busy.value"
|
||||
@cancel="v.cancelMovement"
|
||||
/>
|
||||
<VillageSimulator :world-id="village.world_id" :troops="village.troops" />
|
||||
</div>
|
||||
<VillageSupportPanel
|
||||
class="self-start"
|
||||
:here="village.support.here"
|
||||
:away="village.support.away"
|
||||
:world-id="village.world_id"
|
||||
:busy="v.busy.value"
|
||||
@send-home="v.sendHome"
|
||||
@withdraw="v.withdraw"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -15,6 +15,7 @@ export type BuildingType =
|
|||
| 'hiding_place'
|
||||
| 'wall'
|
||||
| 'rally_point'
|
||||
| 'watchtower'
|
||||
| 'barracks'
|
||||
| 'stable'
|
||||
| 'workshop'
|
||||
|
|
@ -24,12 +25,19 @@ export type UnitType =
|
|||
| 'spear'
|
||||
| 'sword'
|
||||
| 'archer'
|
||||
| 'scout'
|
||||
| 'light_cavalry'
|
||||
| 'heavy_cavalry'
|
||||
| 'ram'
|
||||
| 'catapult'
|
||||
| 'nobleman'
|
||||
|
||||
/** Units by type; missing types mean none. */
|
||||
export type Units = Partial<Record<UnitType, number>>
|
||||
|
||||
export type MovementType = 'attack' | 'support' | 'return'
|
||||
export type TravelMode = 'sneaky' | 'cautious' | 'normal' | 'fast' | 'forced'
|
||||
|
||||
/** Why the server refuses an offer. The client shows `village.blocked.<reason>`; no_space means not enough free building space. */
|
||||
export type BlockedReason = 'max_per_village' | 'no_space' | 'max_level' | 'requires'
|
||||
|
||||
|
|
@ -81,6 +89,17 @@ export interface VillageState {
|
|||
troops: Partial<Record<UnitType, number>>
|
||||
/** 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. */
|
||||
movements: Movement[]
|
||||
support: {
|
||||
/** Support from other villages standing here, by home village. */
|
||||
here: SupportGroup[]
|
||||
/** This village's troops standing in other villages, by host. */
|
||||
away: SupportGroup[]
|
||||
}
|
||||
rally: RallyInfo
|
||||
/** The player's unread reports on this world. */
|
||||
unread_reports: number
|
||||
builders: number
|
||||
buildings: Building[]
|
||||
queue: BuildOrder[]
|
||||
|
|
@ -89,6 +108,132 @@ export interface VillageState {
|
|||
server_time: string
|
||||
}
|
||||
|
||||
/** A village as movements and reports refer to it; player null for barbarians. */
|
||||
export interface VillageRef {
|
||||
id: number
|
||||
name: string
|
||||
x: number
|
||||
y: number
|
||||
player: { id: number; name: string } | null
|
||||
}
|
||||
|
||||
/** A group under way. Groups of other players show no units, mode or send time. */
|
||||
export interface Movement {
|
||||
id: number
|
||||
type: MovementType
|
||||
/** out: an own command leaving here; home: own troops coming back here; in: coming here. */
|
||||
direction: 'out' | 'in' | 'home'
|
||||
mode: TravelMode | null
|
||||
from: VillageRef
|
||||
to: VillageRef
|
||||
units: Units | null
|
||||
/** Loot on a return trip. */
|
||||
cargo: Cost | null
|
||||
sent_at: string | null
|
||||
arrives_at: string
|
||||
/** Until when the command can still be called back; null when it can't. */
|
||||
cancel_until: string | null
|
||||
}
|
||||
|
||||
export interface SupportGroup {
|
||||
village: VillageRef
|
||||
units: Units
|
||||
}
|
||||
|
||||
export interface RallyInfo {
|
||||
/** Nothing can be sent without a rally point. */
|
||||
has_rally_point: boolean
|
||||
/** speed multiplies the pace; visibility is the radius in fields the group is seen in (0: only on arrival). */
|
||||
modes: { mode: TravelMode; speed: number; visibility: number }[]
|
||||
default_mode: TravelMode
|
||||
/** Fields around the village within which incoming groups are spotted. */
|
||||
detection: number
|
||||
/** Seconds after sending during which a command can be called back. */
|
||||
cancel_window: number
|
||||
/** While set, players can't attack this player, and this player can only attack barbarians. */
|
||||
protected_until: string | null
|
||||
}
|
||||
|
||||
/** `rally.preview`: what the send form shows before sending. */
|
||||
export interface MarchPlan {
|
||||
x: number
|
||||
y: number
|
||||
/** The village on that field, or null for an empty one. */
|
||||
target: VillageRef | null
|
||||
mode: TravelMode
|
||||
distance: number
|
||||
/** Travel time; null without units or for the own field. */
|
||||
seconds: number | null
|
||||
}
|
||||
|
||||
export type ReportType = 'attack' | 'defense' | 'support'
|
||||
|
||||
export interface BattleSide {
|
||||
village: VillageRef
|
||||
/** By unit; defenders may include `militia`. null where an attacker without survivors learned nothing. */
|
||||
units: Record<string, number> | null
|
||||
lost: Record<string, number> | null
|
||||
}
|
||||
|
||||
export interface BattleReport {
|
||||
/** Whether the attacker won. */
|
||||
won: boolean
|
||||
/** Percent, between −25 and 25 by default. */
|
||||
luck: number
|
||||
/** Percent. */
|
||||
morale: number
|
||||
night: boolean
|
||||
attacker: BattleSide
|
||||
defender: BattleSide
|
||||
wall: { before: number; after: number } | null
|
||||
building: { type: BuildingType; before: number; after: number } | null
|
||||
loot: Cost
|
||||
capacity: number
|
||||
/** Only when scouts went along. Resources and buildings only when some got through. */
|
||||
scouting?: {
|
||||
sent: number
|
||||
lost: number
|
||||
through: boolean
|
||||
resources: Cost | null
|
||||
/** Levels of every instance, highest first. */
|
||||
buildings: Partial<Record<BuildingType, number[]>> | null
|
||||
} | null
|
||||
}
|
||||
|
||||
/** `rally.simulate`: a battle on paper with the world's rules. */
|
||||
export interface SimulatedBattle {
|
||||
won: boolean
|
||||
attacker: { units: Record<string, number>; lost: Record<string, number> }
|
||||
defender: { units: Record<string, number>; lost: Record<string, number> }
|
||||
wall: { before: number; after: number } | null
|
||||
building: { before: number; after: number } | null
|
||||
power: { attack: number; defense: number }
|
||||
}
|
||||
|
||||
export interface SupportReport {
|
||||
from: VillageRef
|
||||
to: VillageRef
|
||||
units: Units
|
||||
}
|
||||
|
||||
interface ReportBase {
|
||||
id: number
|
||||
happened_at: string
|
||||
read: boolean
|
||||
}
|
||||
|
||||
export type Report =
|
||||
| (ReportBase & { type: 'attack' | 'defense'; payload: BattleReport })
|
||||
| (ReportBase & { type: 'support'; payload: SupportReport })
|
||||
|
||||
/** `report.index`, `report.delete` and `report.readAll`. */
|
||||
export interface ReportPage {
|
||||
reports: Report[]
|
||||
page: number
|
||||
pages: number
|
||||
unread: number
|
||||
}
|
||||
|
||||
export interface Population {
|
||||
/** Food per hour the village can feed. */
|
||||
food_budget: number
|
||||
|
|
|
|||
|
|
@ -0,0 +1,59 @@
|
|||
import type { BattleSide, BuildingType, Report, UnitType, VillageRef } from '~/types/game'
|
||||
import { BUILDING_COLORS } from './palette'
|
||||
|
||||
/** Units in the order Die Stämme lists them, grouped like its rally point. */
|
||||
export const UNIT_GROUPS: { name: 'infantry' | 'cavalry' | 'siege' | 'other'; units: UnitType[] }[] = [
|
||||
{ name: 'infantry', units: ['spear', 'sword', 'archer'] },
|
||||
{ name: 'cavalry', units: ['scout', 'light_cavalry', 'heavy_cavalry'] },
|
||||
{ name: 'siege', units: ['ram', 'catapult'] },
|
||||
{ name: 'other', units: ['nobleman'] },
|
||||
]
|
||||
export const UNIT_ORDER: UnitType[] = UNIT_GROUPS.flatMap((g) => g.units)
|
||||
|
||||
/** Every building type, in building order: what catapults can aim at. */
|
||||
export const BUILDING_TYPES = Object.keys(BUILDING_COLORS) as BuildingType[]
|
||||
|
||||
/** "Name (500|500)" */
|
||||
export const villageLabel = (v: VillageRef) => `${v.name} (${v.x}|${v.y})`
|
||||
|
||||
/** "500|500", "500 500" or "500,500" → coordinates. */
|
||||
export function parseCoords(text: string): { x: number; y: number } | null {
|
||||
const m = /^\s*(\d{1,4})\s*[|,;\s]\s*(\d{1,4})\s*$/.exec(text)
|
||||
return m ? { x: Number(m[1]), y: Number(m[2]) } : null
|
||||
}
|
||||
|
||||
/** Unit counts above zero, in unit order, with `militia` last. */
|
||||
export function unitRows(units: Partial<Record<string, number>> | null | undefined): [string, number][] {
|
||||
if (!units) return []
|
||||
const order = [...UNIT_ORDER, 'militia'] as string[]
|
||||
return Object.entries(units)
|
||||
.filter((e): e is [string, number] => (e[1] ?? 0) > 0)
|
||||
.sort(([a], [b]) => order.indexOf(a) - order.indexOf(b))
|
||||
}
|
||||
|
||||
const lost = (side: BattleSide) => Object.values(side.lost ?? {}).reduce((a, b) => a + b, 0)
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function reportTone(r: Report): 'won' | 'losses' | 'lost' | 'info' {
|
||||
if (r.type === 'support') return 'info'
|
||||
const p = r.payload
|
||||
const ownSide = r.type === 'attack' ? p.attacker : p.defender
|
||||
const won = r.type === 'attack' ? p.won : !p.won
|
||||
if (!won) return 'lost'
|
||||
return lost(ownSide) > 0 ? 'losses' : 'won'
|
||||
}
|
||||
|
||||
/** "Today 13:30:05", "Tomorrow 08:00:00" or "31.10. 13:30:05" in the player's clock. */
|
||||
export function formatArrival(ms: number, now: number, t: (key: string, values?: Record<string, unknown>) => string) {
|
||||
const at = new Date(ms)
|
||||
const time = at.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false })
|
||||
const day = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
|
||||
const days = Math.round((day(at) - day(new Date(now))) / 86_400_000)
|
||||
if (days === 0) return t('time.today', { time })
|
||||
if (days === 1) return t('time.tomorrow', { time })
|
||||
if (days === -1) return t('time.yesterday', { time })
|
||||
return t('time.on', { date: at.toLocaleDateString(undefined, { day: '2-digit', month: '2-digit' }), time })
|
||||
}
|
||||
|
|
@ -11,6 +11,7 @@ export const BUILDING_COLORS: Record<BuildingType, { fill: string; line: string
|
|||
hiding_place: { fill: '#d4c2a8', line: '#4b3622' },
|
||||
wall: { fill: '#cfc7b6', line: '#4f4a42' },
|
||||
rally_point: { fill: '#e2b8a6', line: '#7b1e16' },
|
||||
watchtower: { fill: '#d6c9ad', line: '#4a3420' },
|
||||
barracks: { fill: '#d9b9a0', line: '#5c140f' },
|
||||
stable: { fill: '#d8c49a', line: '#5a3d24' },
|
||||
workshop: { fill: '#cbbfa8', line: '#3e2b1a' },
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ export default {
|
|||
app: {
|
||||
title: 'Village Politics',
|
||||
map: 'Map',
|
||||
reports: 'Reports',
|
||||
unread_reports: '{count} unread reports',
|
||||
village: 'Village',
|
||||
change_world: 'Change world',
|
||||
logout: 'Log out',
|
||||
|
|
@ -12,6 +14,13 @@ export default {
|
|||
common: {
|
||||
loading: 'Loading…',
|
||||
close: 'Close',
|
||||
barbarian: 'Barbarian village',
|
||||
},
|
||||
time: {
|
||||
today: 'today at {time}',
|
||||
tomorrow: 'tomorrow at {time}',
|
||||
yesterday: 'yesterday at {time}',
|
||||
on: 'on {date} at {time}',
|
||||
},
|
||||
resources: {
|
||||
wood: 'Wood',
|
||||
|
|
@ -29,6 +38,7 @@ export default {
|
|||
hiding_place: 'Hiding place',
|
||||
wall: 'Wall',
|
||||
rally_point: 'Rally point',
|
||||
watchtower: 'Watchtower',
|
||||
barracks: 'Barracks',
|
||||
stable: 'Stable',
|
||||
workshop: 'Workshop',
|
||||
|
|
@ -38,11 +48,13 @@ export default {
|
|||
spear: 'Spear fighter',
|
||||
sword: 'Swordsman',
|
||||
archer: 'Archer',
|
||||
scout: 'Scout',
|
||||
light_cavalry: 'Light cavalry',
|
||||
heavy_cavalry: 'Heavy cavalry',
|
||||
ram: 'Ram',
|
||||
catapult: 'Catapult',
|
||||
nobleman: 'Nobleman',
|
||||
militia: 'Militia',
|
||||
},
|
||||
errors: {
|
||||
unknown: 'Something went wrong.',
|
||||
|
|
@ -59,6 +71,15 @@ export default {
|
|||
villagers: 'Not enough villagers to train that many.',
|
||||
count: 'Pick at least one.',
|
||||
levy_active: 'A levy is already under way.',
|
||||
no_rally_point: 'Build a rally point first.',
|
||||
troops: 'Not that many troops in the village.',
|
||||
same_village: 'Pick another village.',
|
||||
own_village: 'That is your own village.',
|
||||
barbarian: 'Barbarian villages take no support.',
|
||||
protected: 'That player is still under beginner protection.',
|
||||
protected_self: 'Under beginner protection you can only attack barbarian villages.',
|
||||
too_late: 'Too late to call it back.',
|
||||
name: 'A village name has 1 to 32 characters.',
|
||||
world_full: 'This world is full.',
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,11 +3,12 @@ import networking from '@blax-software/networking/i18n'
|
|||
import en from './locales/en'
|
||||
import auth from './pages/auth'
|
||||
import map from './pages/map'
|
||||
import reports from './pages/reports'
|
||||
import village from './pages/village'
|
||||
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 }, [auth, map, village, worlds], { packages: [networking] }) as {
|
||||
export default mergeMessages({ en }, [auth, map, reports, village, worlds], { packages: [networking] }) as {
|
||||
en: Record<string, any>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ export default {
|
|||
owner: 'Owner',
|
||||
points: 'Points',
|
||||
open: 'Open village',
|
||||
send: 'Send troops',
|
||||
center: 'Centre here',
|
||||
empty: 'Empty field',
|
||||
hint: 'Hover or click a field to see who lives there.',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,55 @@
|
|||
import type { TranslationFile } from '@blax-software/i18n'
|
||||
|
||||
export default {
|
||||
en: {
|
||||
reports: {
|
||||
title: 'Reports',
|
||||
none: 'No reports yet.',
|
||||
subject: 'Subject',
|
||||
received: 'Received',
|
||||
select: 'Select {subject}',
|
||||
select_all: 'Select all',
|
||||
delete: 'Delete',
|
||||
read_all: 'Mark all as read',
|
||||
page: 'Page {page} of {pages}',
|
||||
prev: 'Newer',
|
||||
next: 'Older',
|
||||
back: 'All reports',
|
||||
unread: 'unread',
|
||||
title_attack: '{from} attacks {to}',
|
||||
title_support: '{from} supports {to}',
|
||||
tone: { won: 'Won', losses: 'Won with losses', lost: 'Lost', info: 'Support' },
|
||||
battle: {
|
||||
attacker_won: 'The attacker has won',
|
||||
defender_won: 'The defender has won',
|
||||
time: 'Battle time',
|
||||
luck: 'Luck (for the attacker)',
|
||||
morale: 'Morale',
|
||||
night: 'Night bonus: the defence counted double.',
|
||||
attacker: 'Attacker',
|
||||
defender: 'Defender',
|
||||
origin: 'Origin',
|
||||
destination: 'Destination',
|
||||
units: 'Quantity',
|
||||
losses: 'Losses',
|
||||
no_info: 'None of your troops came back, so nothing is known about the defenders.',
|
||||
no_troops: 'No troops in the village.',
|
||||
wall: 'Rams: wall damaged from level {before} to level {after}.',
|
||||
wall_held: 'Rams: the wall held at level {level}.',
|
||||
building: 'Catapults: {type} damaged from level {before} to level {after}.',
|
||||
building_held: 'Catapults: {type} took no damage (level {level}).',
|
||||
haul: 'Haul',
|
||||
scouting: 'Scouts',
|
||||
scouts_through: '{sent} scouts sent, {lost} lost. They got through.',
|
||||
scouts_failed: '{sent} scouts sent, all lost to the scouts in the village.',
|
||||
scouted_resources: 'Resources',
|
||||
scouted_buildings: 'Buildings',
|
||||
haul_of: '{loot} of {capacity}',
|
||||
},
|
||||
support: {
|
||||
arrived: 'The support has arrived and now defends {to}.',
|
||||
units: 'Units',
|
||||
},
|
||||
},
|
||||
},
|
||||
} satisfies TranslationFile
|
||||
|
|
@ -5,11 +5,15 @@ export default {
|
|||
village: {
|
||||
title: 'Village',
|
||||
on_map: 'Show on the world map',
|
||||
rename: 'Rename village',
|
||||
rename_save: 'Save',
|
||||
rename_cancel: 'Cancel',
|
||||
screens: {
|
||||
label: 'Village screens',
|
||||
overview: 'Overview',
|
||||
build: 'Headquarters',
|
||||
recruit: 'Recruit',
|
||||
rally: 'Rally point',
|
||||
workforce: 'Workforce',
|
||||
},
|
||||
side: {
|
||||
|
|
@ -17,7 +21,11 @@ export default {
|
|||
units: 'Units',
|
||||
construction: 'Construction',
|
||||
recruit: 'Recruit',
|
||||
incoming: 'Incoming attacks',
|
||||
commands: 'Troop movements',
|
||||
rally: 'Rally point',
|
||||
},
|
||||
incoming: '{count} incoming attacks',
|
||||
plot: {
|
||||
all: 'All buildings in the headquarters',
|
||||
another: 'Room for another',
|
||||
|
|
@ -89,6 +97,70 @@ export default {
|
|||
fix: 'More farms or fewer soldiers stop it.',
|
||||
fix_levy: 'The drafted militia leave the farms unworked: ending the levy helps.',
|
||||
},
|
||||
rally: {
|
||||
send: 'Send troops',
|
||||
all: 'All troops',
|
||||
none_home: 'No troops in the village.',
|
||||
groups: { infantry: 'Infantry', cavalry: 'Cavalry', siege: 'Siege', other: 'Other' },
|
||||
amount_of: 'How many {unit}',
|
||||
target: 'Target',
|
||||
target_placeholder: "x{'|'}y",
|
||||
mode: 'March',
|
||||
modes: { sneaky: 'Sneaky', cautious: 'Cautious', normal: 'Normal', fast: 'Fast', forced: 'Forced march' },
|
||||
mode_speed: '{percent}% speed',
|
||||
mode_seen: 'seen {fields} fields out',
|
||||
mode_unseen: 'unseen until it arrives',
|
||||
catapult_target: 'Catapults aim at',
|
||||
empty: "No village on {x}{'|'}{y}.",
|
||||
own: 'This village.',
|
||||
owner: 'Owner',
|
||||
distance: 'Distance',
|
||||
fields: '{fields} fields',
|
||||
duration: 'Duration',
|
||||
arrival: 'Arrival',
|
||||
attack: 'Attack',
|
||||
support: 'Support',
|
||||
no_rally_point: 'Build a rally point to send troops.',
|
||||
to_build: 'Build it',
|
||||
protected: 'Beginner protection until {time}: players can’t attack you, and you can only attack barbarian villages.',
|
||||
detection: 'Your village spots incoming troops {fields} fields out.',
|
||||
},
|
||||
simulator: {
|
||||
title: 'Battle simulator',
|
||||
luck: 'Luck',
|
||||
night: 'Night bonus',
|
||||
building: 'Catapult target level',
|
||||
run: 'Simulate',
|
||||
own_troops: 'Own troops as attacker',
|
||||
power: 'Attack strength {attack} against defence {defense}',
|
||||
building_after: 'Catapults: the target building goes from level {before} to level {after}.',
|
||||
},
|
||||
movements: {
|
||||
title: 'Troop movements',
|
||||
incoming: 'Incoming',
|
||||
own: 'Own commands',
|
||||
none: 'No troops under way.',
|
||||
none_incoming: 'Nothing spotted coming.',
|
||||
arrival: 'Arrival',
|
||||
arrives_in: 'Arrives in',
|
||||
cancel: 'Call back',
|
||||
attack_on: 'Attack on {target}',
|
||||
support_for: 'Support for {target}',
|
||||
return_from: 'Return from {from}',
|
||||
attack_from: 'Attack from {from}',
|
||||
support_from: 'Support from {from}',
|
||||
by: 'by {player}',
|
||||
loot: 'Loot',
|
||||
},
|
||||
support: {
|
||||
title: 'Support',
|
||||
here: 'Support in this village',
|
||||
away: 'Own troops in other villages',
|
||||
none_here: 'No support from other villages.',
|
||||
none_away: 'No troops in other villages.',
|
||||
send_home: 'Send home',
|
||||
withdraw: 'Withdraw',
|
||||
},
|
||||
levy: {
|
||||
title: 'Levy',
|
||||
militia: 'Militia',
|
||||
|
|
|
|||
Loading…
Reference in New Issue