refactor: building space instead of grid positions in the contract and the mock

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-28 19:54:19 +01:00
parent 938e7429dc
commit f5e03d3500
5 changed files with 42 additions and 193 deletions

View File

@ -1,120 +0,0 @@
<script setup lang="ts">
import type { BuildingType, VillageState } from '~/types/game'
const props = defineProps<{ village: VillageState }>()
const selected = defineModel<{ x: number; y: number } | null>('selected', { default: null })
const { t } = useI18n()
interface Tile {
key: string
type: BuildingType
level: number
x: number
y: number
w: number
h: number
planned: boolean
}
// Buildings and queued new buildings as tiles spanning their footprint. The wall takes
// no cells; it shows as the frame around the grid instead.
const tiles = computed<Tile[]>(() => [
...props.village.buildings.map((b) => ({ ...b, key: `b${b.id}`, planned: false })),
...props.village.queue
.filter((o) => o.action === 'build')
.map((o) => ({ ...o, key: `o${o.id}`, level: 0, planned: true })),
].flatMap((it) => {
const [w, h] = it.footprint
return w && h ? [{ key: it.key, type: it.type, level: it.level, x: it.x, y: it.y, w, h, planned: it.planned }] : []
}))
const freeCells = computed(() => {
const taken = new Set<string>()
for (const t of tiles.value)
for (let dy = 0; dy < t.h; dy++) for (let dx = 0; dx < t.w; dx++) taken.add(`${t.x + dx},${t.y + dy}`)
const cells: { x: number; y: number }[] = []
for (let y = 0; y < props.village.grid.h; y++)
for (let x = 0; x < props.village.grid.w; x++) if (!taken.has(`${x},${y}`)) cells.push({ x, y })
return cells
})
const hasWall = computed(() => props.village.buildings.some((b) => b.type === 'wall'))
const gridStyle = computed(() => ({
gridTemplateColumns: `repeat(${props.village.grid.w}, minmax(0, 1fr))`,
gridTemplateRows: `repeat(${props.village.grid.h}, minmax(0, 1fr))`,
aspectRatio: `${props.village.grid.w} / ${props.village.grid.h}`,
}))
const place = (x: number, y: number, w = 1, h = 1) => ({
gridColumn: `${x + 1} / span ${w}`,
gridRow: `${y + 1} / span ${h}`,
})
const isSelected = (x: number, y: number) => selected.value?.x === x && selected.value?.y === y
function toggle(x: number, y: number) {
selected.value = isSelected(x, y) ? null : { x, y }
}
function tileTitle(tile: Tile) {
const name = t(`buildings.${tile.type}`)
return tile.planned ? `${name} (${t('village.grid.planned')})` : `${name}, ${t('village.buildings.level_n', { level: tile.level })}`
}
</script>
<template>
<section class="panel">
<div class="panel-head">
<h2 class="panel-title">{{ $t('village.grid.title') }}</h2>
<p class="text-xs text-ink-500">{{ $t('village.grid.hint') }}</p>
</div>
<div class="panel-body">
<div
class="rounded-xl bg-[#e6d6b5] p-1.5 sm:p-2"
:class="hasWall ? 'ring-[6px] ring-stone-400' : 'ring-1 ring-parchment-300'"
:title="hasWall ? $t('buildings.wall') : undefined"
>
<div class="grid gap-1" :style="gridStyle">
<button
v-for="c in freeCells"
:key="`${c.x},${c.y}`"
type="button"
class="group grid place-items-center rounded-md border transition-colors"
:class="
isSelected(c.x, c.y)
? 'border-amber-600 bg-amber-100 text-amber-700 ring-2 ring-amber-500'
: 'border-dashed border-[#cdb68c] bg-[#efe3c9] text-transparent hover:border-amber-500 hover:bg-amber-50 hover:text-amber-500'
"
:style="place(c.x, c.y)"
:title="`${$t('village.grid.free_cell')} ${c.x}|${c.y}`"
:aria-pressed="isSelected(c.x, c.y)"
@click="toggle(c.x, c.y)"
>
<IconUi name="pin" class="size-3/5 max-h-5 max-w-5" />
</button>
<div
v-for="tile in tiles"
:key="tile.key"
class="relative flex min-w-0 flex-col items-center justify-center gap-0.5 overflow-hidden rounded-lg border-2 p-1 text-center"
:class="tile.planned ? 'border-dashed opacity-60' : 'shadow-sm'"
:style="{ ...place(tile.x, tile.y, tile.w, tile.h), ...buildingTileStyle(tile.type) }"
:title="tileTitle(tile)"
>
<IconBuilding :type="tile.type" :class="tile.w > 1 ? 'size-6 sm:size-9' : 'size-4 sm:size-6'" />
<span v-if="tile.w > 1" class="hidden max-w-full truncate text-xs font-medium text-ink-700 sm:block">
{{ $t(`buildings.${tile.type}`) }}
</span>
<span
class="absolute top-0.5 right-0.5 rounded bg-white/85 px-1 text-[10px] leading-4 font-semibold text-ink-700 tabular-nums"
:class="tile.w > 1 ? '' : 'hidden sm:block'"
>
{{ tile.planned ? '…' : tile.level }}
</span>
</div>
</div>
</div>
</div>
</section>
</template>

View File

@ -75,7 +75,7 @@ export function useVillage(villageId: number) {
canAfford, canAfford,
secondsUntil, secondsUntil,
refresh, refresh,
build: (type: BuildingType, at: { x: number; y: number } | null) => run('village.build', { type, ...at }), build: (type: BuildingType) => run('village.build', { type }),
upgrade: (buildingId: number) => run('village.upgrade', { building_id: buildingId }), upgrade: (buildingId: number) => run('village.upgrade', { building_id: buildingId }),
demolish: (buildingId: number) => run('village.demolish', { building_id: buildingId }), demolish: (buildingId: number) => run('village.demolish', { building_id: buildingId }),
cancel: (orderId: number) => run('village.cancel', { order_id: orderId }), cancel: (orderId: number) => run('village.cancel', { order_id: orderId }),

View File

@ -5,7 +5,8 @@ import type { BuildingType, Cost, Resource, Resources } from '~/types/game'
// (config/game/buildings.php and app/Game/), not to the client. // (config/game/buildings.php and app/Game/), not to the client.
export interface CatalogEntry { export interface CatalogEntry {
footprint: [number, number] /** Building space an instance takes (0 for the wall). */
space: number
max_per_village: number | null max_per_village: number | null
/** Level 0 values. Level n costs, takes, needs and produces (n + 1) times as much. */ /** Level 0 values. Level n costs, takes, needs and produces (n + 1) times as much. */
cost: Cost cost: Cost
@ -21,19 +22,19 @@ export const BASE_TRICKLE = 5
export const VILLAGER_UPKEEP = 1 export const VILLAGER_UPKEEP = 1
export const DEMOLISH_REFUND = 0.5 export const DEMOLISH_REFUND = 0.5
export const DEFAULT_PRIORITY = 5 export const DEFAULT_PRIORITY = 5
export const GRID = { w: 10, h: 5 } export const MAX_SPACE = 50
export const START_RESOURCES: Resources = { wood: 500, clay: 500, iron: 500, food: 100 } export const START_RESOURCES: Resources = { wood: 500, clay: 500, iron: 500, food: 100 }
export const CATALOG: Record<BuildingType, CatalogEntry> = { export const CATALOG: Record<BuildingType, CatalogEntry> = {
headquarters: { footprint: [3, 3], max_per_village: 1, cost: { wood: 90, clay: 80, iron: 70 }, seconds: 20, workers: 2, production: null }, headquarters: { space: 9, max_per_village: 1, cost: { wood: 90, clay: 80, iron: 70 }, seconds: 20, workers: 2, production: null },
storage: { footprint: [2, 2], max_per_village: null, cost: { wood: 60, clay: 50, iron: 40 }, seconds: 15, workers: 1, production: null, capacity: 1000 }, storage: { space: 4, max_per_village: null, cost: { wood: 60, clay: 50, iron: 40 }, seconds: 15, workers: 1, production: null, capacity: 1000 },
farm: { footprint: [2, 2], max_per_village: null, cost: { wood: 45, clay: 40, iron: 30 }, seconds: 15, workers: 2, production: { resource: 'food', per_hour: 20 } }, farm: { space: 4, max_per_village: null, cost: { wood: 45, clay: 40, iron: 30 }, seconds: 15, workers: 2, production: { resource: 'food', per_hour: 20 } },
timber_camp: { footprint: [2, 2], max_per_village: null, cost: { wood: 50, clay: 60, iron: 40 }, seconds: 12, workers: 2, production: { resource: 'wood', per_hour: 30 } }, timber_camp: { space: 4, max_per_village: null, cost: { wood: 50, clay: 60, iron: 40 }, seconds: 12, workers: 2, production: { resource: 'wood', per_hour: 30 } },
clay_pit: { footprint: [2, 2], max_per_village: null, cost: { wood: 65, clay: 50, iron: 40 }, seconds: 12, workers: 2, production: { resource: 'clay', per_hour: 30 } }, clay_pit: { space: 4, max_per_village: null, cost: { wood: 65, clay: 50, iron: 40 }, seconds: 12, workers: 2, production: { resource: 'clay', per_hour: 30 } },
iron_mine: { footprint: [2, 2], max_per_village: null, cost: { wood: 75, clay: 65, iron: 70 }, seconds: 14, workers: 2, production: { resource: 'iron', per_hour: 30 } }, iron_mine: { space: 4, max_per_village: null, cost: { wood: 75, clay: 65, iron: 70 }, seconds: 14, workers: 2, production: { resource: 'iron', per_hour: 30 } },
hiding_place: { footprint: [1, 1], max_per_village: null, cost: { wood: 50, clay: 60, iron: 50 }, seconds: 10, workers: 0, production: null }, hiding_place: { space: 1, max_per_village: null, cost: { wood: 50, clay: 60, iron: 50 }, seconds: 10, workers: 0, production: null },
wall: { footprint: [0, 0], max_per_village: 1, cost: { wood: 50, clay: 100, iron: 20 }, seconds: 20, workers: 1, production: null }, wall: { space: 0, max_per_village: 1, cost: { wood: 50, clay: 100, iron: 20 }, seconds: 20, workers: 1, production: null },
rally_point: { footprint: [1, 1], max_per_village: 1, cost: { wood: 10, clay: 40, iron: 30 }, seconds: 10, workers: 0, production: null }, rally_point: { space: 1, max_per_village: 1, cost: { wood: 10, clay: 40, iron: 30 }, seconds: 10, workers: 0, production: null },
} }
export const BUILDING_TYPES = Object.keys(CATALOG) as BuildingType[] export const BUILDING_TYPES = Object.keys(CATALOG) as BuildingType[]

View File

@ -27,7 +27,7 @@ import {
CATALOG, CATALOG,
DEFAULT_PRIORITY, DEFAULT_PRIORITY,
DEMOLISH_REFUND, DEMOLISH_REFUND,
GRID, MAX_SPACE,
MAX_LEVEL, MAX_LEVEL,
START_RESOURCES, START_RESOURCES,
VILLAGER_UPKEEP, VILLAGER_UPKEEP,
@ -38,8 +38,6 @@ interface MockBuilding {
id: number id: number
type: BuildingType type: BuildingType
level: number level: number
x: number
y: number
priority: number priority: number
} }
@ -49,8 +47,6 @@ interface MockOrder {
type: BuildingType type: BuildingType
action: BuildOrder['action'] action: BuildOrder['action']
target_level: number target_level: number
x: number
y: number
cost: Cost cost: Cost
seconds: number seconds: number
builder: number | null builder: number | null
@ -65,7 +61,7 @@ interface MockVillage {
name: string name: string
x: number x: number
y: number y: number
grid: { w: number; h: number } space_max: number
resources: Resources resources: Resources
resources_at: number resources_at: number
buildings: MockBuilding[] buildings: MockBuilding[]
@ -79,7 +75,7 @@ interface MockState {
villages: MockVillage[] villages: MockVillage[]
} }
const STORAGE_KEY = 'vp.mock.v1' const STORAGE_KEY = 'vp.mock.v2'
const LATENCY_MS = 60 const LATENCY_MS = 60
const WORLDS = [ const WORLDS = [
{ id: 1, name: 'World 1', slug: 'w1', speed: 1 }, { id: 1, name: 'World 1', slug: 'w1', speed: 1 },
@ -212,31 +208,15 @@ function refund(v: MockVillage, amount: Cost) {
v.resources.iron = Math.min(cap, v.resources.iron + amount.iron) v.resources.iron = Math.min(cap, v.resources.iron + amount.iron)
} }
/** Cells taken by buildings and by queued new buildings. */ /** Building space taken by buildings and by queued new buildings. */
function occupied(v: MockVillage) { function spaceUsed(v: MockVillage) {
const cells = new Set<string>() return (
const mark = (type: BuildingType, x: number, y: number) => { v.buildings.reduce((sum, b) => sum + CATALOG[b.type].space, 0) +
const [w, h] = CATALOG[type].footprint v.orders.filter((o) => o.action === 'build').reduce((sum, o) => sum + CATALOG[o.type].space, 0)
for (let dy = 0; dy < h; dy++) for (let dx = 0; dx < w; dx++) cells.add(`${x + dx},${y + dy}`) )
}
v.buildings.forEach((b) => mark(b.type, b.x, b.y))
v.orders.filter((o) => o.action === 'build').forEach((o) => mark(o.type, o.x, o.y))
return cells
} }
function fits(v: MockVillage, type: BuildingType, x: number, y: number) { const spaceFits = (v: MockVillage, type: BuildingType) => spaceUsed(v) + CATALOG[type].space <= v.space_max
const [w, h] = CATALOG[type].footprint
if (w === 0 || h === 0) return true
if (x < 0 || y < 0 || x + w > v.grid.w || y + h > v.grid.h) return false
const cells = occupied(v)
for (let dy = 0; dy < h; dy++) for (let dx = 0; dx < w; dx++) if (cells.has(`${x + dx},${y + dy}`)) return false
return true
}
function freeSlot(v: MockVillage, type: BuildingType) {
for (let y = 0; y < v.grid.h; y++) for (let x = 0; x < v.grid.w; x++) if (fits(v, type, x, y)) return { x, y }
return null
}
/** Level after everything already queued for this building; -1 if it is being removed. */ /** Level after everything already queued for this building; -1 if it is being removed. */
function queuedLevel(v: MockVillage, b: MockBuilding) { function queuedLevel(v: MockVillage, b: MockBuilding) {
@ -277,10 +257,10 @@ function buildOptions(v: MockVillage): BuildOption[] {
const blocked = const blocked =
entry.max_per_village !== null && instances(v, type) >= entry.max_per_village entry.max_per_village !== null && instances(v, type) >= entry.max_per_village
? 'max_per_village' ? 'max_per_village'
: freeSlot(v, type) === null : !spaceFits(v, type)
? 'no_space' ? 'no_space'
: null : null
return { type, footprint: entry.footprint, target_level: 0, cost, seconds: levelSeconds(type, 0), blocked } return { type, space: entry.space, target_level: 0, cost, seconds: levelSeconds(type, 0), blocked }
}) })
} }
@ -307,7 +287,7 @@ function startWaiting(v: MockVillage, at: number) {
function finish(state: MockState, v: MockVillage, o: MockOrder) { function finish(state: MockState, v: MockVillage, o: MockOrder) {
if (o.action === 'build') { if (o.action === 'build') {
v.buildings.push({ id: nextId(state), type: o.type, level: 0, x: o.x, y: o.y, priority: DEFAULT_PRIORITY }) v.buildings.push({ id: nextId(state), type: o.type, level: 0, priority: DEFAULT_PRIORITY })
return return
} }
const b = v.buildings.find((b) => b.id === o.building_id) const b = v.buildings.find((b) => b.id === o.building_id)
@ -347,7 +327,7 @@ function view(v: MockVillage, now: number): VillageState {
name: v.name, name: v.name,
x: v.x, x: v.x,
y: v.y, y: v.y,
grid: { ...v.grid }, space: { used: spaceUsed(v), max: v.space_max },
resources: { ...v.resources }, resources: { ...v.resources },
resources_at: iso(v.resources_at), resources_at: iso(v.resources_at),
rates: rates(v), rates: rates(v),
@ -367,9 +347,7 @@ function view(v: MockVillage, now: number): VillageState {
id: b.id, id: b.id,
type: b.type, type: b.type,
level: b.level, level: b.level,
x: b.x, space: CATALOG[b.type].space,
y: b.y,
footprint: CATALOG[b.type].footprint,
priority: b.priority, priority: b.priority,
workers: { assigned: assigned.get(b.id) ?? 0, required: requiredWorkers(b) }, workers: { assigned: assigned.get(b.id) ?? 0, required: requiredWorkers(b) },
staffing: staffing(b, assigned), staffing: staffing(b, assigned),
@ -385,9 +363,7 @@ function view(v: MockVillage, now: number): VillageState {
type: o.type, type: o.type,
action: o.action, action: o.action,
target_level: o.target_level, target_level: o.target_level,
x: o.x, space: CATALOG[o.type].space,
y: o.y,
footprint: CATALOG[o.type].footprint,
cost: o.cost, cost: o.cost,
position: i + 1, position: i + 1,
builder: o.builder, builder: o.builder,
@ -414,15 +390,14 @@ function createVillage(state: MockState, user: AuthUser, worldId: number, now: n
name: `${user.name}'s village`, name: `${user.name}'s village`,
x, x,
y, y,
grid: { ...GRID }, space_max: MAX_SPACE,
resources: { ...START_RESOURCES }, resources: { ...START_RESOURCES },
resources_at: now, resources_at: now,
buildings: [], buildings: [],
orders: [], orders: [],
} }
for (const type of ['headquarters', 'storage', 'farm'] as const) { for (const type of ['headquarters', 'storage', 'farm'] as const) {
const at = freeSlot(v, type)! v.buildings.push({ id: nextId(state), type, level: 0, priority: DEFAULT_PRIORITY })
v.buildings.push({ id: nextId(state), type, level: 0, x: at.x, y: at.y, priority: DEFAULT_PRIORITY })
} }
return v return v
} }
@ -466,15 +441,10 @@ const handlers: Record<string, Handler> = {
const type = data.type as BuildingType const type = data.type as BuildingType
const entry = CATALOG[type] ?? fail('not_found') const entry = CATALOG[type] ?? fail('not_found')
if (entry.max_per_village !== null && instances(v, type) >= entry.max_per_village) fail('max_per_village') if (entry.max_per_village !== null && instances(v, type) >= entry.max_per_village) fail('max_per_village')
const at = if (!spaceFits(v, type)) fail('no_space')
typeof data.x === 'number' && typeof data.y === 'number'
? fits(v, type, data.x, data.y)
? { x: data.x, y: data.y }
: fail('no_space')
: (freeSlot(v, type) ?? fail('no_space'))
const cost = levelCost(type, 0) const cost = levelCost(type, 0)
pay(v, cost) pay(v, cost)
enqueue(state, v, { building_id: null, type, action: 'build', target_level: 0, x: at.x, y: at.y, cost, seconds: levelSeconds(type, 0) }, now) enqueue(state, v, { building_id: null, type, action: 'build', target_level: 0, cost, seconds: levelSeconds(type, 0) }, now)
return view(v, now) return view(v, now)
}, },
@ -483,7 +453,7 @@ const handlers: Record<string, Handler> = {
const b = ownBuilding(v, data.building_id) const b = ownBuilding(v, data.building_id)
const offer = upgradeOffer(v, b) ?? fail('max_level') const offer = upgradeOffer(v, b) ?? fail('max_level')
pay(v, offer.cost) pay(v, offer.cost)
enqueue(state, v, { building_id: b.id, type: b.type, action: 'upgrade', target_level: offer.target_level, x: b.x, y: b.y, cost: offer.cost, seconds: offer.seconds }, now) 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(v, now)
}, },
@ -491,7 +461,7 @@ const handlers: Record<string, Handler> = {
const v = ownVillage(state, user, data.village_id, now) const v = ownVillage(state, user, data.village_id, now)
const b = ownBuilding(v, data.building_id) const b = ownBuilding(v, data.building_id)
const offer = demolishOffer(v, b) ?? fail('core_building') 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, x: b.x, y: b.y, cost: { wood: 0, clay: 0, iron: 0 }, seconds: offer.seconds }, now) 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(v, now)
}, },

View File

@ -16,7 +16,7 @@ export type BuildingType =
| 'wall' | 'wall'
| 'rally_point' | 'rally_point'
/** Why the server refuses an offer. The client shows `village.blocked.<reason>`. */ /** 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' export type BlockedReason = 'max_per_village' | 'no_space' | 'max_level' | 'requires'
export interface AuthUser { export interface AuthUser {
@ -46,7 +46,8 @@ export interface VillageState {
name: string name: string
x: number x: number
y: number y: number
grid: { w: number; h: number } /** Building space: what buildings and queued new buildings take, out of the village maximum. */
space: { used: number; max: number }
/** Amounts stored at `resources_at`. */ /** Amounts stored at `resources_at`. */
resources: Resources resources: Resources
resources_at: string resources_at: string
@ -77,9 +78,8 @@ export interface Building {
id: number id: number
type: BuildingType type: BuildingType
level: number level: number
x: number /** Building space this instance takes, fixed per type (0 for the wall). */
y: number space: number
footprint: [number, number]
priority: number priority: number
workers: { assigned: number; required: number } workers: { assigned: number; required: number }
/** assigned / required, 0..1. */ /** assigned / required, 0..1. */
@ -101,7 +101,7 @@ export interface Offer {
export interface BuildOption extends Offer { export interface BuildOption extends Offer {
type: BuildingType type: BuildingType
footprint: [number, number] space: number
} }
export interface BuildOrder { export interface BuildOrder {
@ -112,9 +112,7 @@ export interface BuildOrder {
action: 'build' | 'upgrade' | 'demolish' action: 'build' | 'upgrade' | 'demolish'
/** -1 means the instance is removed. */ /** -1 means the instance is removed. */
target_level: number target_level: number
x: number space: number
y: number
footprint: [number, number]
cost: Cost cost: Cost
position: number position: number
/** Builder slot working on it, or null while it waits. */ /** Builder slot working on it, or null while it waits. */