game-village-politics-frontend/app/utils/military.ts

60 lines
2.9 KiB
TypeScript

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 (12|-34)" */
export const villageLabel = (v: VillageRef) => `${v.name} (${v.x}|${v.y})`
/** "12|-34", "12 -34" or "12,-34" → coordinates; the world starts at 0|0, so they can be negative. */
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 })
}