feat: levy in the troops panel: draft villagers as militia, countdown back to work, end early

Recruiting and the idle count leave the militia out. The mock drafts too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-28 21:58:09 +01:00
parent 18232e9c59
commit 9878fb0527
9 changed files with 153 additions and 14 deletions

View File

@ -1,7 +1,8 @@
<script setup lang="ts"> <script setup lang="ts">
import type { UnitType } from '~/types/game' import type { UnitType } from '~/types/game'
defineProps<{ unit: UnitType }>() /** `militia` are villagers drafted by a levy, not a trainable unit. */
defineProps<{ unit: UnitType | 'militia' }>()
</script> </script>
<!-- Line glyphs in currentColor, one per unit type. --> <!-- Line glyphs in currentColor, one per unit type. -->
@ -65,6 +66,11 @@ defineProps<{ unit: UnitType }>()
<path d="M5 21c0-4 3-6.5 7-6.5s7 2.5 7 6.5" /> <path d="M5 21c0-4 3-6.5 7-6.5s7 2.5 7 6.5" />
<path d="M8.5 6.5L9 3.5l1.5 1.5L12 3l1.5 2L15 3.5l.5 3z" /> <path d="M8.5 6.5L9 3.5l1.5 1.5L12 3l1.5 2L15 3.5l.5 3z" />
</g> </g>
<g v-else-if="unit === 'militia'">
<path d="M12 21V9" />
<path d="M7 3v4a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V3" />
<path d="M12 3v6" />
</g>
<g v-else> <g v-else>
<path d="M12 3l7 3v5c0 5-3 8.5-7 10-4-1.5-7-5-7-10V6z" /> <path d="M12 3l7 3v5c0 5-3 8.5-7 10-4-1.5-7-5-7-10V6z" />
</g> </g>

View File

@ -1,12 +1,16 @@
<script setup lang="ts"> <script setup lang="ts">
import type { Population } from '~/types/game' import type { Population } from '~/types/game'
const props = defineProps<{ population: Population }>() const props = defineProps<{
population: Population
/** Villagers drafted by a levy: neither working nor idle. */
militia: number
}>()
const stats = computed(() => [ const stats = computed(() => [
{ key: 'villagers', value: props.population.villagers }, { key: 'villagers', value: props.population.villagers },
{ key: 'workers', value: props.population.workers }, { key: 'workers', value: props.population.workers },
{ key: 'idle', value: props.population.villagers - props.population.workers }, { key: 'idle', value: props.population.villagers - props.population.workers - props.militia },
{ key: 'soldiers', value: props.population.soldiers }, { key: 'soldiers', value: props.population.soldiers },
]) ])
</script> </script>

View File

@ -1,17 +1,31 @@
<script setup lang="ts"> <script setup lang="ts">
import type { MilitaryBuilding, UnitType } from '~/types/game' import type { Levy, MilitaryBuilding, UnitType } from '~/types/game'
const props = defineProps<{ const props = defineProps<{
troops: Partial<Record<UnitType, number>> troops: Partial<Record<UnitType, number>>
military: MilitaryBuilding[] military: MilitaryBuilding[]
training: number training: number
levy: Levy
/** Villagers a new levy can draft. */
villagers: number
secondsUntil: (iso: string) => number
busy: boolean
}>() }>()
const emit = defineEmits<{ recruit: [] }>() const emit = defineEmits<{ recruit: []; levy: [count: number]; endLevy: [] }>()
const home = computed(() => (Object.entries(props.troops) as [UnitType, number][]).filter(([, n]) => n > 0)) const home = computed(() => (Object.entries(props.troops) as [UnitType, number][]).filter(([, n]) => n > 0))
const draft = ref<number | null>(null)
const draftCount = computed(() => Math.min(props.villagers, Math.floor(Number(draft.value) || 0)))
function submitLevy() {
if (draftCount.value < 1) return
emit('levy', draftCount.value)
draft.value = null
}
</script> </script>
<!-- Own units in the village, like the Die Stämme overview's unit box. --> <!-- Own units in the village, like the Die Stämme overview's unit box, and the levy. -->
<template> <template>
<section class="panel"> <section class="panel">
<div class="panel-head"> <div class="panel-head">
@ -22,18 +36,64 @@ const home = computed(() => (Object.entries(props.troops) as [UnitType, number][
</span> </span>
</div> </div>
<div class="panel-body"> <div class="panel-body">
<ul v-if="home.length" class="divide-y divide-parchment-300"> <ul v-if="home.length || levy.militia" class="divide-y divide-parchment-300">
<li v-for="[unit, count] in home" :key="unit" class="flex items-center gap-2 py-1 text-sm"> <li v-for="[unit, count] in home" :key="unit" class="flex items-center gap-2 py-1 text-sm">
<IconUnit :unit="unit" class="size-5 text-wood-800" /> <IconUnit :unit="unit" class="size-5 text-wood-800" />
<span class="flex-1">{{ $t(`units.${unit}`) }}</span> <span class="flex-1">{{ $t(`units.${unit}`) }}</span>
<span class="font-semibold tabular-nums">{{ count }}</span> <span class="font-semibold tabular-nums">{{ count }}</span>
</li> </li>
<li v-if="levy.militia" class="flex items-center gap-2 py-1 text-sm">
<IconUnit unit="militia" class="size-5 text-wood-800" />
<span class="flex-1">{{ $t('village.levy.militia') }}</span>
<span class="font-semibold tabular-nums">{{ levy.militia }}</span>
</li>
</ul> </ul>
<p v-else class="py-2 text-center text-sm text-ink-500">{{ $t('village.troops.none') }}</p> <p v-else class="py-2 text-center text-sm text-ink-500">{{ $t('village.troops.none') }}</p>
<button v-if="military.length" type="button" class="btn btn-outline mt-3 w-full" @click="emit('recruit')"> <button v-if="military.length" type="button" class="btn btn-outline mt-3 w-full" @click="emit('recruit')">
{{ $t('village.troops.recruit') }} {{ $t('village.troops.recruit') }}
</button> </button>
<p v-else class="mt-1 text-center text-xs text-ink-500">{{ $t('village.troops.hint') }}</p> <p v-else class="mt-1 text-center text-xs text-ink-500">{{ $t('village.troops.hint') }}</p>
<!-- Levy: draft villagers as militia for a fixed time. -->
<div class="mt-4 border-t-2 border-parchment-300 pt-3">
<div v-if="levy.militia && levy.until" class="flex items-center gap-2 text-sm">
<IconUi name="clock" class="size-3.5 text-ink-400" />
<span class="flex-1">
{{ $t('village.levy.returns_in') }}
<span class="font-semibold tabular-nums">{{ formatDuration(secondsUntil(levy.until)) }}</span>
</span>
<button type="button" class="btn btn-outline px-2.5 py-1" :disabled="busy" @click="emit('endLevy')">
{{ $t('village.levy.end') }}
</button>
</div>
<form v-else class="space-y-2" @submit.prevent="submitLevy">
<div class="flex items-center gap-2">
<label for="levy-count" class="flex-1 text-sm font-semibold">{{ $t('village.levy.title') }}</label>
<input
id="levy-count"
v-model.number="draft"
type="number"
min="0"
:max="villagers"
inputmode="numeric"
class="input w-16 px-1.5 py-0.5 text-right tabular-nums"
/>
<button
type="button"
class="w-12 text-left text-xs font-semibold tabular-nums text-blood-700 hover:underline disabled:text-ink-400 disabled:no-underline"
:title="$t('village.levy.all')"
:disabled="!villagers"
@click="draft = villagers"
>
({{ villagers }})
</button>
<button type="submit" class="btn btn-primary px-2.5 py-1" :disabled="busy || draftCount < 1">
{{ $t('village.levy.submit') }}
</button>
</div>
<p class="text-xs text-ink-500">{{ $t('village.levy.hint', { duration: formatDuration(levy.seconds) }) }}</p>
</form>
</div>
</div> </div>
</section> </section>
</template> </template>

View File

@ -58,6 +58,7 @@ export function useVillage(villageId: number) {
if (!v) return null if (!v) return null
const times = [ const times = [
...v.queue.flatMap((o) => (o.finishes_at ? [Date.parse(o.finishes_at)] : [])), ...v.queue.flatMap((o) => (o.finishes_at ? [Date.parse(o.finishes_at)] : [])),
...(v.levy.until ? [Date.parse(v.levy.until)] : []),
...v.military.flatMap((m) => ...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), m.queue.filter((o) => o.done < o.count).map((o) => Date.parse(o.starts_at) + (o.done + 1) * o.seconds_per_unit * 1000),
), ),
@ -97,5 +98,7 @@ export function useVillage(villageId: number) {
return true return true
}, },
cancelRecruit: (orderId: number) => run('village.cancelRecruit', { order_id: orderId }), cancelRecruit: (orderId: number) => run('village.cancelRecruit', { order_id: orderId }),
levy: (count: number) => run('village.levy', { count }),
endLevy: () => run('village.endLevy'),
} }
} }

View File

@ -74,8 +74,13 @@ interface MockVillage {
/** Missing in states stored before recruiting existed. */ /** Missing in states stored before recruiting existed. */
troops?: Partial<Record<UnitType, number>> troops?: Partial<Record<UnitType, number>>
recruits?: MockRecruit[] recruits?: MockRecruit[]
militia?: number
levy_until?: number | null
} }
/** Mock levy length; the backend's comes from the world config. */
const LEVY_SECONDS = 120
interface MockRecruit { interface MockRecruit {
id: number id: number
building_id: number building_id: number
@ -161,9 +166,12 @@ function villagers(v: MockVillage) {
return Math.max(0, Math.floor((foodBudget(v) - soldierUpkeep(v)) / VILLAGER_UPKEEP)) return Math.max(0, Math.floor((foodBudget(v) - soldierUpkeep(v)) / VILLAGER_UPKEEP))
} }
/** Drafted villagers, never more than there are. */
const militia = (v: MockVillage) => Math.min(v.militia ?? 0, villagers(v))
/** Farms first, then by priority, then oldest first. */ /** Farms first, then by priority, then oldest first. */
function assignWorkers(v: MockVillage) { function assignWorkers(v: MockVillage) {
let free = villagers(v) let free = villagers(v) - militia(v)
const assigned = new Map<number, number>() const assigned = new Map<number, number>()
const order = [...v.buildings].sort( const order = [...v.buildings].sort(
(a, b) => Number(b.type === 'farm') - Number(a.type === 'farm') || b.priority - a.priority || a.id - b.id, (a, b) => Number(b.type === 'farm') - Number(a.type === 'farm') || b.priority - a.priority || a.id - b.id,
@ -358,7 +366,7 @@ function missingRequirements(v: MockVillage, unit: UnitType) {
const secondsPerUnit = (b: MockBuilding, unit: UnitType) => Math.max(1, Math.ceil(UNITS[unit].seconds / (1 + 0.05 * b.level))) const secondsPerUnit = (b: MockBuilding, unit: UnitType) => Math.max(1, Math.ceil(UNITS[unit].seconds / (1 + 0.05 * b.level)))
function military(v: MockVillage, at: number): MilitaryBuilding[] { function military(v: MockVillage, at: number): MilitaryBuilding[] {
const pop = villagers(v) const pop = villagers(v) - militia(v)
return v.buildings return v.buildings
.filter((b) => UNIT_TYPES.some((u) => UNITS[u].building === b.type)) .filter((b) => UNIT_TYPES.some((u) => UNITS[u].building === b.type))
.map((b) => ({ .map((b) => ({
@ -399,6 +407,13 @@ function catchUp(state: MockState, v: MockVillage, now: number) {
const due = v.orders const due = v.orders
.filter((o) => o.finishes_at !== null && o.finishes_at <= now) .filter((o) => o.finishes_at !== null && o.finishes_at <= now)
.sort((a, b) => a.finishes_at! - b.finishes_at! || a.id - b.id)[0] .sort((a, b) => a.finishes_at! - b.finishes_at! || a.id - b.id)[0]
const levyEnds = v.levy_until != null && v.levy_until <= now ? v.levy_until : null
if (levyEnds !== null && (!due || levyEnds <= due.finishes_at!)) {
settle(v, levyEnds)
v.militia = 0
v.levy_until = null
continue
}
if (!due) break if (!due) break
settle(v, due.finishes_at!) settle(v, due.finishes_at!)
v.orders = v.orders.filter((o) => o !== due) v.orders = v.orders.filter((o) => o !== due)
@ -439,6 +454,7 @@ function view(v: MockVillage, now: number): VillageState {
soldiers: Object.values(v.troops ?? {}).reduce((a, b) => a + (b ?? 0), 0), soldiers: Object.values(v.troops ?? {}).reduce((a, b) => a + (b ?? 0), 0),
training: (v.recruits ?? []).reduce((sum, o) => sum + o.count - o.done, 0), training: (v.recruits ?? []).reduce((sum, o) => sum + o.count - o.done, 0),
}, },
levy: { militia: militia(v), until: v.levy_until ? iso(v.levy_until) : null, seconds: LEVY_SECONDS },
troops: Object.fromEntries(Object.entries(v.troops ?? {}).filter(([, n]) => n)), troops: Object.fromEntries(Object.entries(v.troops ?? {}).filter(([, n]) => n)),
military: military(v, now), military: military(v, now),
builders: BUILDERS, builders: BUILDERS,
@ -651,7 +667,7 @@ const handlers: Record<string, Handler> = {
const count = Math.floor(Number(data.count) || 0) const count = Math.floor(Number(data.count) || 0)
if (count < 1) fail('count') if (count < 1) fail('count')
if (missingRequirements(v, unit).length) fail('requires') if (missingRequirements(v, unit).length) fail('requires')
if (count * entry.upkeep > villagers(v)) fail('villagers') if (count * entry.upkeep > villagers(v) - militia(v)) fail('villagers')
pay(v, mapCost(entry.cost, (n) => n * count)) pay(v, mapCost(entry.cost, (n) => n * count))
const seconds = secondsPerUnit(b, unit) const seconds = secondsPerUnit(b, unit)
const last = (v.recruits ?? []).filter((o) => o.building_id === b.id).at(-1) const last = (v.recruits ?? []).filter((o) => o.building_id === b.id).at(-1)
@ -682,6 +698,25 @@ const handlers: Record<string, Handler> = {
return view(v, now) return view(v, now)
}, },
'village.levy': (state, user, data, now) => {
const v = ownVillage(state, user, data.village_id, now)
const count = Math.floor(Number(data.count) || 0)
if (v.militia) fail('levy_active')
if (count < 1) fail('count')
if (count > villagers(v)) fail('villagers')
v.militia = count
v.levy_until = now + LEVY_SECONDS * 1000
return view(v, now)
},
'village.endLevy': (state, user, data, now) => {
const v = ownVillage(state, user, data.village_id, now)
if (!v.militia) fail('not_found')
v.militia = 0
v.levy_until = null
return view(v, now)
},
'mock.reset': (state, user) => { 'mock.reset': (state, user) => {
state.villages = state.villages.filter((v) => v.user_id !== user.id) state.villages = state.villages.filter((v) => v.user_id !== user.id)
return true return true
@ -699,7 +734,11 @@ export function createMockServer(): { ws: GameWs; auth: GameAuth } {
function schedule(state: MockState) { function schedule(state: MockState) {
for (const v of state.villages) { for (const v of state.villages) {
clearTimeout(timers.get(v.id)) clearTimeout(timers.get(v.id))
const next = Math.min(...v.orders.map((o) => o.finishes_at ?? Infinity), ...(v.recruits ?? []).map((o) => o.finishes_at)) const next = Math.min(
...v.orders.map((o) => o.finishes_at ?? Infinity),
...(v.recruits ?? []).map((o) => o.finishes_at),
v.levy_until ?? Infinity,
)
if (next === Infinity) continue if (next === Infinity) continue
timers.set( timers.set(
v.id, v.id,

View File

@ -116,7 +116,7 @@ function openRecruit(buildingId?: number) {
v-model:selected="recruitAt" v-model:selected="recruitAt"
:military="village.military" :military="village.military"
:troops="village.troops" :troops="village.troops"
:villagers="village.population.villagers" :villagers="village.population.villagers - village.levy.militia"
:resources="resources" :resources="resources"
:seconds-until="v.secondsUntil" :seconds-until="v.secondsUntil"
:busy="busy" :busy="busy"
@ -132,12 +132,18 @@ function openRecruit(buildingId?: number) {
:busy="busy" :busy="busy"
@cancel="v.cancel" @cancel="v.cancel"
/> />
<VillagePopulationPanel :population="village.population" /> <VillagePopulationPanel :population="village.population" :militia="village.levy.militia" />
<VillageTroopsPanel <VillageTroopsPanel
:troops="village.troops" :troops="village.troops"
:military="village.military" :military="village.military"
:training="village.population.training" :training="village.population.training"
:levy="village.levy"
:villagers="village.population.villagers"
:seconds-until="v.secondsUntil"
:busy="busy"
@recruit="openRecruit()" @recruit="openRecruit()"
@levy="v.levy"
@end-levy="v.endLevy"
/> />
</div> </div>
</div> </div>

View File

@ -74,6 +74,8 @@ export interface VillageState {
rates: Resources rates: Resources
storage_cap: number storage_cap: number
population: Population population: Population
/** Villagers drafted as militia: they eat but don't work until `until`. */
levy: Levy
/** Own units standing in the village. */ /** Own units standing in the village. */
troops: Partial<Record<UnitType, number>> troops: Partial<Record<UnitType, number>>
/** One entry per building that trains units, in building order. */ /** One entry per building that trains units, in building order. */
@ -99,6 +101,15 @@ export interface Population {
training: number training: number
} }
export interface Levy {
/** 0 when no levy is under way. */
militia: number
/** When the militia go back to work on their own. */
until: string | null
/** How long a new levy would last. */
seconds: number
}
/** A barracks, stable, workshop or academy: what it trains and its own queue. */ /** A barracks, stable, workshop or academy: what it trains and its own queue. */
export interface MilitaryBuilding { export interface MilitaryBuilding {
building_id: number building_id: number

View File

@ -57,7 +57,8 @@ export default {
core_building: 'Core buildings cannot go below level 0.', core_building: 'Core buildings cannot go below level 0.',
requires: 'Build its requirements first.', requires: 'Build its requirements first.',
villagers: 'Not enough villagers to train that many.', villagers: 'Not enough villagers to train that many.',
count: 'Recruit at least one unit.', count: 'Pick at least one.',
levy_active: 'A levy is already under way.',
world_full: 'This world is full.', world_full: 'This world is full.',
}, },
} }

View File

@ -64,6 +64,15 @@ export default {
recruit: 'Recruit', recruit: 'Recruit',
hint: 'Build barracks to recruit units.', hint: 'Build barracks to recruit units.',
}, },
levy: {
title: 'Levy',
militia: 'Militia',
all: 'Draft every villager',
submit: 'Draft',
hint: 'Drafted villagers defend the village and stop working for {duration}, then go back to work.',
returns_in: 'Back to work in',
end: 'End levy',
},
diorama: { diorama: {
title: 'Village overview', title: 'Village overview',
hint: 'Select a building to see what it does and upgrade it.', hint: 'Select a building to see what it does and upgrade it.',