game-village-politics-backend/docs/architecture.md

374 lines
57 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

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

# Architecture
## Repos and runtime
| Repo | Stack | Local URL |
|---|---|---|
| `game-village-politics-backend` | Laravel 13, PHP 8.4 (`blaxsoftware/laravel:laravel13-php8.4`), MySQL, Redis, Pest, Sanctum, blax-software/laravel-websockets | `server-village.localhost.at`, `ws-server-village.localhost.at` |
| `game-village-politics-frontend` | Nuxt 4, TypeScript, `@blax-software/networking`, `@blax-software/i18n` | `village.localhost.at` |
Docker Compose and Traefik labels follow learn-atc. The `app` container runs nginx and php-fpm, plus supervisor programs for the queue worker, the scheduler, the WS server, and `game:events`.
The frontend builds with `ssr: false` for every target. It is a game behind a login, so SSR buys nothing. One static build then serves both the web and a later Steam wrapper (Electron or Tauri). This is a deliberate deviation from learn-atc, which uses SSR on the web.
## Transport and auth
- Accounts are email + password, with no verification for now. Steam login comes later as a second provider.
- HTTP `POST /api/auth/register|login` returns a Sanctum bearer token. The client stores it and passes it as `getAuthToken` to the WS client. The same flow works inside a Steam wrapper, where cookies across origins would not.
- Everything else runs over WS through native controllers (`<prefix>.<method>`), for example `village.show`, `village.build`, `village.demolish`, `village.cancel`, and `village.staff`.
- blax laravel-websockets authenticates a message only by its own `data.authtoken`, so the client adds the token to every `ws.send`. `App\Websocket\GameController::booted()` then caches the user as `socket_<id>` and calls `WebsocketService::setUserAuthed`, so the socket's later messages and the `game:events` pushes find the user. A frame without a token is refused.
- Push goes to the owner's sockets with `ws_whisper('village:updated', …)` after the engine processes an event. The client then refetches or patches its state.
## Backend layers
```
app/Game/ pure rules: no Eloquent, no now(), fully unit tested
WorldConfig.php defaults from config/game/* merged with worlds.config
Economy/Production.php rates per resource from buildings, staffing, base trickle
Economy/Population.php food budget, capacity, villagers, worker assignment
Economy/Settle.php stored + rate × elapsed, storage caps, food zero-crossing
Buildings/BuildingRules.php cost, time, workers, output, space, points per level, instance shares
Buildings/BuildQueue.php builders, next unblocked order
Map/Continent.php K-names of the 100 × 100 continents
Map/MapBounds.php coordinates from −size/2 to size/2 − 1 around 0|0
Map/Frontier.php where new villages settle as the world grows
Map/BarbarianWaves.php when the next barbarian wave comes and how many per player
Travel/TravelTime.php
Trade/TradeRules.php merchants, their pace, fair offers, route shipments
Combat/CombatResolver.php
Combat/LootCalculator.php
ConfigLint.php proves the config has no locks (see "No locks")
app/Actions/ use cases: transaction + lockForUpdate + calls into app/Game
app/Engine/ game_events processing and handlers per event type
app/Websocket/Controllers/ thin: validate, authorize, call an Action, return a Resource
app/Models/ Eloquent
```
## Economy
### Resources
There are four resources: wood, clay, iron, and food. Every village gets a base trickle of wood, clay, and iron (`economy.base_production`, for example 5/h each). That trickle ignores staffing. Buildings add to it. Food comes from farms only, and one farm feeds a full army: level 30 makes about 19,400 food/h at world speed 1. Storage caps all four resources.
Rates are constant between events. Any change to a rate settles the village first: it writes the current amounts and `resources_at = now`, then applies the change. Changes to rates include a build finishing, a worker change, levy, troops arriving or leaving, and a food delivery expiring.
### Population
Population counts in heads. A head is one food per hour at world speed 1. Farms make world speed times their output and every head eats world speed times its upkeep, so a village holds the same heads on every world speed and only the food rate scales.
- **Capacity** is a food budget in heads: `nominal farm output at world speed 1 + 24h average of food delivered to this village ÷ world speed`, a copy farm at its share (see "Copies"). Nominal means the output at full staffing, which avoids a loop between farms, workers, and capacity (see "No locks"). Capacity is TW-like and instant: no growth timer.
- **Upkeep**: every villager takes `upkeep.villager` heads (1), and soldiers take their unit's `upkeep` (for example spear 1, heavy cav 4, noble 10). Foreign support stationed in the village counts against the host's budget.
- **Food rate**: `rates.food` is the farms' output at world speed and staffing, minus upkeep × world speed. The food stock, starvation and its desertion waves run at world speed like every other resource; the heads stay the same.
- The village payload's `population` is in heads: `food_budget`, `upkeep`, `villagers`, `workers`, `idle` and `reserved` (see "Workers and staffing"); `soldiers` and `training` count units. `rates.food` is food per hour at world speed.
- Villages from before heads had their highest farm raised on deploy to the lowest level that feeds their soldiers and workers (migration `farms_feed_their_heads`); only the speed 100 dev world had such villages.
- **Villagers** fill instantly up to `economy.villager_share` (default 80%) of the budget, minus what soldiers and stationed support eat. Villagers are the workforce. The other 20% of the farms' output is surplus that goes into storage, so food builds up; expensive units eat into it, and a big enough army pushes the village into starvation.
- **Training a soldier** turns one villager into that unit and costs resources. The soldier's upkeep takes from the budget, so villagers shrink to match, the same as TW farm space.
- **Levy**: the player can draft villagers as militia for a fixed time (`economy.levy.duration`, divided by world speed), one levy at a time. The militia still eat but don't work, so their buildings run understaffed; recruiting can only train villagers who are not drafted. A `levy.ends` event at `levy_until` settles the village and sends them back to work; the player can also end the levy early. If villagers drop below the militia count (a farm torn down, soldiers trained), the militia shrink with them.
### Workers and staffing
- Each building level needs `workers` (config). Villagers are assigned to buildings automatically, highest `priority` first, then evenly. The player sets the priority per building instance.
- Output at staffing ratio `r = staffed / required` is `e^(k·(r−1))`, with `k` from world config (`staffing.k`, default 2.3). Full staffing gives 100% and an empty building gives about 10%, so output never reaches zero.
- Staffing scales resource production, and the HQ's staffing scales build speed.
- **A level needs villagers.** Queuing a new instance or an upgrade is refused (`villagers`) unless enough idle villagers stand ready for the workers it adds: workers(target) − workers(target − 1), all of level 1's for a new instance (`BuildingRules::extraWorkers`). Idle villagers are the villagers not drafted by a levy, minus the workers every standing building needs, minus what queued orders reserved, never below 0 (`Workforce::idle`).
- A queued new instance or upgrade reserves its extra workers until it finishes or is cancelled, the way a new instance reserves its space. A demolition frees its workers when it finishes.
- Farms are exempt: they need no idle villagers and reserve none. A farm brings more heads than it employs (lint), and without the exemption a full village could never grow.
- Build options and upgrade offers carry `villagers` (the idle villagers they need, 0 for farms) and `blocked: 'villagers'` when there aren't enough. Every queued order carries the `villagers` it holds back. `population.idle` and `population.reserved` give the numbers.
### Copies
One instance of each type is enough, as in Die Stämme. A copy works at a falling share (`economy.instance_share`, 0.5). The instances of one type rank by level, highest first, then lowest id, and the one at rank n works at `instance_share`^n: the first or only one in full, a second at half, a third at a quarter.
- The share scales production, a farm's nominal output in the food budget, storage capacity, hides, hospital beds and training speed (seconds per unit divide by it).
- Workers needed stay full, so a copy eats like a full building and gives half.
- The rank follows the standing buildings on every read (`BuildingRules::instanceRanks`). Upgrading a copy past the first swaps their shares and their costs: the copy that works at less is the one that pays more. A new instance ranks after all standing and queued ones.
- The village payload carries `instance_share` on every building, and on every build option the share a new instance would work at: `instance_share`^(standing + queued instances of that type).
### Builders
Each village has `builders` (default 2, +1 at the HQ levels listed in world config, for example 10 and 20). All orders share one queue. A free builder takes the first order that is not blocked by an order still running, for example a second upgrade of the same building instance. Build time is scaled by the HQ's level and staffing.
### Starvation
When upkeep exceeds income, the food stock drains. `Starvation::sync()` runs after every mutation and every event: it keeps a `food.runs_out` event at the exact moment the stock reaches 0. Once the stock is empty and the village is still in deficit, `villages.starving_since` is set and the grace timer runs (`economy.starvation.grace`, default 24h, divided by world speed). When it runs out, a `starvation.desertion` wave fires, and further waves follow every `economy.starvation.wave_every` (1h) while the deficit lasts.
A wave takes the fewest units that make income cover upkeep again: support stationed in the village first (whole groups go home, the hungriest first), then own soldiers at home from the highest upkeep down. Villagers are not stored, they follow the food budget, so they never desert; soldiers leaving frees villagers who staff the farms again. If no soldier is left and the village still goes hungry, the levy ends. Units still in training don't desert, but they finish and stand at home by the next wave. The timer stops as soon as income covers upkeep again or food comes in.
## Village space
- Each village has a building space budget that grows with its headquarters: `space + village.space_per_hq_level × (HQ level − 1)` (defaults 40 and 5, so 40 at level 1, 45 at level 2 and 85 at level 10). Space is scarce on purpose: one of every building type only fits from headquarters level 5, so what goes in is the village's main choice. The village row stores its own base `space`, so terrain or specials can change it per village later. The new space arrives when an HQ level finishes; a queued HQ demolition already counts, and the HQ can't be demolished below what stands.
- Each building type takes a fixed `space` from config, for example HQ 9, barracks 6, resource buildings 4, and hiding place 1. The level changes only the look, never the space. A building fits when the space of all buildings plus new buildings still in the queue, plus its own, stays within the budget. The space is reserved when the order is queued.
- There are no tiles and no stored positions. The client draws the village as a low-poly isometric diorama and lays the buildings out itself (HQ in the centre, the rest around it), so where a building stands is presentation, not game state.
- Levels start at 1, as in Die Stämme, and a new instance is built at level 1. Every per-level formula uses `level − 1` as the exponent of its factor, so level 1 has the base values.
- One of each type is enough: one storage, one farm, one barracks. Copies are the exception and pay twice. `max_per_village` keeps some types unique (HQ, rally point, wall, watchtower, academy). The instance at rank n (the same rank as its share) costs `instance_cost_factor`^n as much at every level (2: a second camp costs double, a third four times), and it works at a falling share (see "Copies"). Upgrading beats copying.
- Basic buildings have no requirements: everything in the core set, the wall included, can be built from the start. Only advanced buildings get `requires` (type => minimum level of any instance), for example the academy (Adelshof) needs the headquarters and a barracks (Kaserne). A build option lists what is still missing.
- Demolishing goes through the build queue. It lowers an instance by one level and refunds `demolish_refund` × that level's cost (default 0.5). Taking level 1 down removes the instance (an order with target level 0) and frees its space.
- The wall takes 0 space: it surrounds the village.
- **Roles** (`Specialisation`, `world.village.specialisation`): what fills the space gives a village a role. Resource buildings (timber camp, clay pit, iron mine) and military buildings (barracks, stable, workshop, academy) count; when one kind takes at least `share` (70%) of the space both kinds take together, and at least `min_space` (16), the village has that role. A resource village's camps produce `production` (+20%) more; a military village trains `recruit_speed` (+20%) faster and everyone defending it, support included, fights with `defense` (+10%) more. Farms, storage and the rest count for neither, since both kinds of village need them. Only standing buildings count, so a role starts and ends when an order finishes. The payload's `specialisation` carries the role, the space per role and the rules. A role now needs paid-for copies: one of each camp takes 12 space, short of `min_space`, and next to one of each camp the military buildings fall short of `share`.
- Each building level is worth `points` (config); a village's points are their sum, kept on the row when an order finishes and shown on the map.
- Every building in the village payload carries `effects` and `next_effects` (`BuildingRules::effects`): what one instance does at its level and one level up, at its instance share, as `{key, value, resource?}`: production at full staffing, capacity, hides, detection, the wall's flat defence and bonus %, the headquarters' build speed %, builders and village space, a military building's training speed %. The client shows them on the building's own screen.
A new village starts with HQ 0, storage 0, and farm 0, plus starting resources from world config.
## Military
Units live in `config/game/units.php` (Die Stämme-like stats): the building type that trains them, cost, food `upkeep` per hour, `build_time` per unit, attack, defence per class, speed and carry (both used from M4), and `requires` (building type => level).
- Barracks (spear, sword, archer), stable (light and heavy cavalry), workshop (ram, catapult) and academy (nobleman) are ordinary building instances. Each instance runs its own recruiting queue, so two barracks train side by side, the second at half speed (see "Copies"). Requirements: stable needs barracks 3, workshop barracks 5, academy headquarters 5 and barracks 1; the barracks itself needs nothing.
- Recruiting pays the full cost up front and takes the villagers at once: units in training count against the food budget like trained ones, so villagers shrink immediately and food income doesn't change while they train. A village can't queue more units than it has villagers for (`count × upkeep ≤ villagers`, in heads, so the same on every world speed).
- An order's times are fixed when it is queued: it starts when the previous order at that building ends (or now), and one unit takes `build_time / speed / (1 + recruit_speed_per_level × level) / staffing / share`, with the building's instance share. Units arrive lazily, `done = floor(elapsed / seconds_per_unit)`, and every read or action moves them into `unit_stacks`; a `recruit.finished` event settles the rest.
- Cancelling refunds the untrained units in full and moves later orders at that building forward. Tearing a military building down refunds what it was still training.
### Hospital
The Lazarett (`hospital`, needs barracks 1) brings part of the fallen back. Its instances add up their `beds`, each scaled by its staffing and instance share like production, and a bed holds one wounded of any unit.
- After a battle in the village, `combat.hospital.share` (50%) of each own unit that fell, rounded down, comes in as wounded (`Wounds::admit`). Support fell for another village and gets nothing. When they need more beds than are free, the beds are shared out evenly, the rest by largest remainder. A conquered village takes nobody in, and barbarian villages keep no hospital.
- One battle's wounded are one `wounded` row with `heals_at = battle + heal_time / speed` (4 hours). A `wounded.healed` event puts them back into the village's own stacks.
- The wounded eat like soldiers, so they keep their place in the food budget and the village's numbers don't jump when they heal. Starvation doesn't touch them: they stand again on a fixed timer and can desert from then on.
- The wounded die with their village's owner: conquest, turning barbarian and leaving all clear them (`Nobility::release`).
- The defence report carries `wounded: {units, heals_at}`; the attacker's copy never does. The village payload carries `hospital: {beds, occupied, share, heal_seconds, wounded}`.
## Quest book
The quest book guides new players through the game in parallel lines (`config/game/quests.php`): construction, army, and village, which covers what Die Stämme doesn't have (staffing priorities, a second instance, the levy). A line shows its first unclaimed quest; claiming it (`quest.claim {village_id, quest}`) pays its resources into that village, up to what the storage holds, and opens the next one. Titles and texts are client i18n.
- Goals are `building` (a type at a level in any of the player's villages), `instances` (that many of a type in one village) or `counter` (an action done that often). `QuestBook` (pure) measures them against `Facts` gathered per read; only claimed quests are stored (`player_quests`), so progress never drifts from the village.
- Counters live in `player_counters`, bumped by the actions (`Quests::bump`): `recruited.<unit>`, `attacks.sent`, `attacks.barbarian`, `scouts.sent`, `support.sent`, `village.renamed`, `priority.set`, `levy.called`, `reports.read`, and `map.viewed` (set once, not counted). `ConfigLint` proves every goal can be met.
- **Level rewards**: the first time a player reaches a level of a building type (any village, any instance), `quests.level_reward_share` (20%) of what that order cost waits in `level_rewards`. `quest.collect {village_id, ids?}` pays them into the current village. Demolishing pays nothing, and a second instance at the same level pays nothing again.
- `quest.index {village_id}` returns the lines, the rewards waiting, and what the next level of each building in the village would pay back. The village payload carries `quests: {claimable, rewards}` for the badge; the client opens the book by itself when `claimable` goes up.
## No locks
A village may fail through war or bad play, but it must never get stuck. Every lock below has a way out in the rules, and each one marked "lint" is proven by `ConfigLint`, which runs as a Pest test against the default config and every world's overrides.
| Lock | Rule that prevents it |
|---|---|
| No villagers, no food | Farm 0 (gatherers) has nominal output > 0, so capacity is never 0. Villagers fill instantly. Wood, clay, and iron trickle regardless of staffing. |
| Farm, workers, and capacity feeding each other | Capacity uses nominal farm output, not actual output. Farms are staffed before every other building. Lint: each farm level's worker upkeep < the heads it feeds. |
| Not enough villagers for a level | Farms need no idle villagers, so a village can always grow its farms, and a bigger farm brings more villagers. Demolishing frees a building's workers, cancelling frees what an order reserved, and support sent elsewhere or soldiers lost free heads. Drafted militia don't count as idle, but every levy ends on its timer. Lint: one of every building at max level, with its workers, fits the villagers one farm at max level feeds (at the villager share, without soldiers). |
| Copies that give nothing | A copy works at `instance_share`^n of a full building; one that eats more than it gives can always be demolished. Lint: `economy.instance_share` above 0 and at most 1, every `instance_cost_factor` at least 1. |
| Next upgrade costs more than storage holds | Lint: for every building and level, the cost fits the storage cap reachable without that building, and storage's own next level fits its current cap. |
| Building space full | Demolishing is always allowed, costs nothing, and refunds. Core buildings (HQ, one storage, one farm) cannot go below level 1. Lint: the start buildings fit the space, and every type fits next to them. |
| Queue blocked | A free builder skips blocked orders. Every order can be cancelled with a refund. |
| Building requirements | Lint: the requirement graph has no cycles, and every building and level is reachable from the start village. |
| Starvation spiral | Deserters leave in the order foreign support, soldiers, then the levy ends. Farms are staffed first, so food income recovers as soldiers leave. |
| Foreign support eats the host | The host can send any support home at any time. Foreign support deserts first. |
| Levy never returns | Militia return automatically on a timer. |
| Wounded never return | Each battle's wounded stand again at a fixed `heals_at`. Lint: `combat.hospital.heal_time` above 0 and `share` between 0 and 1. |
| Merchants never free again | Merchants come from the market's level, not from training. Every trip ends on a timer, cancelling an offer frees its merchants, and merchants a lost village had under way stop counting. Lint: every market level has at least 1 merchant, `market.carry` and `minutes_per_field` above 0, `max_ratio` at least 1. |
| Trade route stuck | A run sends what the stock and the free merchants allow, or nothing, and plans the next run either way. A route whose target changed hands pauses; the player can resume, change or delete it at any time. Lint: 0 < `route.min_every` ≤ `route.max_every`. |
| A world with few players runs out of targets | Barbarian waves bring new villages near every active player every few world days, never on a taken field. Where no field near a village is free, the wave brings fewer. Lint: `waves.every_days` above 0, the smaller first, `per_player` at least 0, `near` at least 1. |
| Player loses every village | The player can restart on the same world with a fresh village. |
| Raids bleed a village dry | Raids come `every_hours` apart in real hours on every world, after beginner protection, and loot only what the hiding places don't cover. Rams never take a wall below 1, a beaten band's rams fire only their first half, and no band takes a village. Beating the camp down scatters its next band, and a band facing a defence far too strong stays home. Lint: intervals above 0, `scatter_below` above 0, `dare` at least 0. |
## Config
`config/game/world.php`, `economy.php`, `buildings.php`, `units.php`, `combat.php`, `market.php` and the rest of `config/game/` hold the defaults. `worlds.config` (JSON) overrides any key, the way Die Stämme world settings do: speed, unit speed, morale, night bonus, beginner protection, map size, builders, refund rate, building space, staffing k, starvation grace, noble rules, and so on. `WorldConfig` merges the two and is the only reader.
A building entry looks like this (numbers start TW-like):
```php
'timber_camp' => [
'space' => 4,
'max_per_village' => null,
'max_level' => 30,
'cost' => ['wood' => 50, 'clay' => 60, 'iron' => 40, 'factor' => 1.25],
'build_time' => ['base' => 900, 'factor' => 1.2], // seconds at world speed 1
'workers' => ['base' => 2, 'factor' => 1.12],
'production' => ['resource' => 'wood', 'base' => 30, 'factor' => 1.163],
'requires' => [],
],
```
## Data model
| Table | Columns |
|---|---|
| `worlds` | name, slug, config json, started_at, ends_at null, barbarians_at null (the next barbarian wave) |
| `players` | user_id, world_id, name, points, coins. unique(user_id, world_id) |
| `villages` | world_id, player_id null (null = barbarian), name, x, y, space, wood/clay/iron/food decimal(14,4), resources_at datetime(3), villagers, militia, levy_until null, starving_since null, loyalty (0..100), loyalty_at null, points. unique(world_id, x, y) |
| `buildings` | village_id, type, level, priority (workers are derived on every read) |
| `build_orders` | village_id, building_id null (null = new instance), type, action (build/upgrade/demolish), target_level, cost json, builder null, starts_at null, finishes_at null. Queue order is id order |
| `unit_stacks` | village_id (where they stand), home_village_id (owner), unit, count. unique(village_id, home_village_id, unit) |
| `recruit_orders` | village_id, building_id, unit, count, done, seconds_per_unit, starts_at, finishes_at, game_event_id |
| `wounded` | village_id, units (json unit => count), heals_at datetime(3): one battle's wounded in the hospital |
| `food_deliveries` | village_id, amount, delivered_at. Feeds the 24h import average; each row's expiry is an event |
| `movements` | world_id, player_id (whose troops or merchants), type (attack/support/return/trade/trade_return), mode, origin_id, target_id, units json, cargo json null, catapult_target null, rng_seed, sent_at, arrives_at, visible_at, merchants (0 for troops), route_id null (the trade route that sent it), offer (sent for an accepted offer). destroyed_at comes with encounters |
| `trade_offers` | world_id, village_id, give_resource, give_amount, want_resource, want_amount, count (still open), merchants (reserved per unit of count) |
| `trade_routes` | village_id, target_id, target_player_id (the target's owner when made), wood, clay, iron, every (real seconds), next_at datetime(3), paused, paused_reason null, last_sent_at null, last_cargo json null |
| `tribes`, `tribe_members`, `tribe_invites`, `tribe_relations`, `tribe_events` | world_id, name, tag, description; tribe_id, player_id (unique), role; tribe_id, player_id, invited_by; tribe_id, other_tribe_id, state (ally/nap/enemy), confirmed_at, ends_at; tribe_id, type, payload, happened_at |
| `player_quests`, `player_counters` | player_id, quest, claimed_at; player_id, key, value. Progress is derived, not stored |
| `level_rewards` | player_id, village_id (where reached), type, level, reward json, reached_at, claimed_at null. unique(player_id, type, level) |
| `reports` | player_id, type (attack/defense/support/trade), payload json (a snapshot with village names, units, losses, loot), happened_at, read_at |
| `game_events` | world_id, type, subject_type, subject_id, fire_at datetime(3), processed_at null, attempts. index(processed_at, fire_at) |
## Event engine
Delayed queue jobs give no global order and can fire late or get lost. When an attack and a wall upgrade on the same village fall in the same second, the order decides the result. So:
1. Every timed effect writes a `game_events` row: `type`, `subject`, `fire_at` (datetime(3)), and `processed_at`.
2. The `game:events` worker loops. It takes due rows in `(fire_at, id)` order, locks the subject village, runs the handler, and sets `processed_at`, all in one transaction. When nothing is due, it sleeps until the next `fire_at`, at most 1 s.
3. Every read or action on a village first runs `CatchUp::village($id, now)`, which processes that village's due events inline. A lagging worker therefore never shows stale state, and tests need no worker at all.
Handlers are idempotent per event row: the transaction plus `processed_at` guards against double execution.
## Map
The map is square (`map.size`, default 1000 × 1000) with the world's start at **0|0**: coordinates run from −size/2 to size/2 − 1 (−500 to 499), negative included (`MapBounds`). Continents are 100 × 100 blocks named by row and column counted from the top-left corner, as in Die Stämme, so 0|0 is the corner of K44, K45, K54 and K55, −500|−500 lies in K00 and 499|499 in K99.
The world grows the way Die Stämme's does (measured on de261, see the research repo): a disc around 0|0 that spreads outward ring by ring as players join, at an even density, with barbarian villages arriving alongside the players. A world starts empty.
- **Frontier** (`Frontier`): a new player's village lands at a random angle on a ring of radius `start_radius + sqrt(villages / (π · density))`, ± `band` fields, where `villages` counts every village of the world, barbarians included. `density` is DS's 0.29 villages per field (about one in 3.4 fields). The first tries keep clear of the 8 fields around other players; barbarians may stand right next to a new village. If the ring has no room, the nearest free field around 0|0 is taken.
- **Direction**: when joining (`world.join {world_id, direction}`) a player picks random, nw, ne, sw or se, and the angle stays inside that quarter.
- **Barbarians come with players** (`SpawnBarbarians`): each join brings `barbarians.per_join` of them on average (1.3: one, and a second with 30% chance, as in DS), placed within `barbarians.near` fields of the new village so a small world has something to loot from the start (DS scatters them on the frontier instead; with thousands of players that ends up the same). Their buildings start at random levels up to `max_level`, and each has a `barbarian.grows` event: every `growth.every_hours` (at world speed) one building goes up a level, up to `growth.max_level`. Bonus villages (DS adds 0.4 per join) come later.
- **Barbarian waves** (`BarbarianWaves`, `Waves`): joins alone bring nothing new to a world with few players, so barbarian villages also come in waves. Every `waves.every_days` (5 to 9 world days, at world speed, drawn evenly per wave) each active player gets `per_player` of them (1.5: one, and a second with 50% chance), each within `near` (8) fields of a random village of theirs, placed and started like the ones that come with a join. Active means seen within `world.inactive_days`; when that rule is off, every player with a village counts. The world keeps its next wave in `barbarians_at`. The `game:events` worker ticks `Waves::tick` before every loop: it runs a due wave with the world row locked and plans the next from a draw seeded by the world and the wave, so a replay draws the same. A worker that was down runs one wave for all it missed, and the next comes an interval later. A world without a time gets one an interval out, on deploy (`WorldSeeder`) or from the worker for a new or reset world. A wave without active players brings nothing, so a world still starts empty. Ended worlds get none. Each player village that got new neighbours is pushed `village:updated`, so an open client refetches.
- **Garrisons** (`BarbarianGarrison`, `Barbarians`): a barbarian village holds troops, so raiding it takes scouting and an army sized for it. Full strength is `garrison.per_point × (points − free_points)` heads, split by the village's profile (spearmen, swordsmen, archers or riders, fixed by its id, so a scout report tells what to send), and its upkeep stays under `max_food_share` (50%) of the village's food budget, so it never starves. A new barbarian village starts at full strength. After a battle there, or when it grows, a `barbarian.regroups` event gives back `regroup.share` (25%, at least one per unit) every `regroup.every_hours` (2) until it is full again. Their stock grows from their own buildings, settled like any village, up to their storage. Barbarian villages from before garrisons get theirs on deploy (`WorldSeeder`).
- A village whose player has been inactive for too long turns barbarian (M6).
- `php artisan game:reset-world {slug}` wipes a world back to empty (villages, players, movements, reports, events) and keeps user accounts and the world's config.
`map.view {world_id, x, y, w, h}` returns the villages in a `w × h` window (at most `map.max_view` per side) centred on `x|y`, kept inside the map, plus `size` and `min` (the lowest coordinate); without a centre it opens on the player's first village, else on 0|0. Each village comes with its coordinates, continent, name, points, owner (null for barbarians) with their tribe tag, whether it is the player's own, and its `relation` to the viewer for the colour: own, tribe, ally, nap, enemy, none (another player) or barbarian. It also carries `movements`: the player's own commands and groups going home (with units, and `cancel_until` while an own attack or support can still be called back), and groups coming to their villages once spotted (with the size tier only: tiny under 50 heads, then small, medium, large and huge from `movement.size_tiers`). The client draws each as a line from origin to target with the group at its position, a straight line at constant speed from `sent_at` to `arrives_at`; raiders wait at their camp until they march. The client draws it like the Die Stämme map: a top-down field grid with coordinate rulers and continent lines.
## Movements and encounters
Every group on the map is a `movement`: an attack, support, return, or trade caravan (merchants, optionally with an escort). It moves in a straight line at constant speed, so its position at time t is a linear interpolation between origin and target.
### Sending troops
- The rally point sends an attack or support from the units at home to the village at x|y (`rally.send`; `rally.preview` shows the target, distance and travel time first). A village needs a rally point to send anything. Travel time is the slowest unit's minutes per field × distance / (world speed × `movement.unit_speed` × mode speed), with the distance as the crow flies.
- The troops leave at once. Their arrival is a `movement.arrives` event on the target, so it runs under the target's lock and in the target's event order; a `movement.spotted` event at `visible_at` only pushes the change. Reading a village first catches up the targets of its own due groups, so the owner never sees a group that should have arrived.
- Within `movement.cancel_window` (10 real minutes) the sender can call a command back. It turns around where it is and takes as long to get home as it had been under way. The return runs from the target with `sent_at` set as far back as the group still had to go, so the straight line from `sent_at` to `arrives_at` puts it where it turned.
- An attack with survivors turns into its own return trip with the loot, taking as long as the way there. Loot that doesn't fit the storage is lost on arrival.
- Support stands in the host village as unit stacks with their own `home_village_id`. The host feeds it (it counts against the host's food budget), and hunger sends it home before any own soldier deserts. The host can send any support home (`rally.sendHome`), and the owner can withdraw it (`rally.withdraw`, a `support.recalled` event on the host's queue); both start a return trip. Groups under way eat nothing.
- Barbarian villages take no support, and own villages can't be attacked.
- Beginner protection: for `combat.beginner_protection` (3 days, divided by world speed) after joining, a player can't be attacked by players and can only attack barbarians themselves.
- Every battle and every arriving support writes reports (`report.index|show|delete|readAll`): for the attacker, the defender, and every player whose support stood in the village. An attacker with no survivors learns nothing about the defence. The village payload carries the unread count, and the engine pushes `village:updated` to every village an event touched (an attacker's home, a supporter's village).
### Travel modes
Each movement has a mode, defined in `config/game/movement.php`:
| Mode | Speed | Visibility radius |
|---|---|---|
| sneaky | much slower | 0 (undetectable) |
| cautious | slower | small |
| normal | 1.0 | normal |
| fast | faster | large |
| forced (fighting march) | much faster | very large |
The visibility radius decides two things:
- **Warning time**: a target village sees an incoming movement once it is within `visibility radius + village detection radius`. The engine computes that moment and schedules it as an event. A watchtower raises the village's detection radius. A sneaky movement shows up only when it arrives.
- **Encounters**: another group can only engage a movement that comes within that movement's visibility radius.
### Encounters
- When a movement is sent, `EncounterFinder` (a pure function) computes its closest approach to every active movement in its bounding box. If two groups meet within range, an `encounter` event is scheduled at that exact time.
- A soldier group engages every hostile army or caravan it meets. Groups on a return trip never engage, but they can be engaged. Friendly groups (own, tribe, allies) pass each other.
- An encounter is a field battle: `CombatResolver` without wall or morale. The losing group dies. The winners carry on along their original path and schedule, so later encounters don't need recalculating, and the handler skips encounters whose group no longer exists.
- A caught caravan's escort fights first. If the escort loses, the merchants die and the winners take cargo up to their carry capacity. The rest is lost.
- Barbarian ambushes: a caravan has a small chance per hour of being ambushed, depending on its mode (sneaky never). The roll uses a seeded RNG per movement, so tests are deterministic.
### Diplomacy
See "Tribes". Encounters (M5) will check hostility at encounter time, not at send time.
## Market
Merchants carry wood, clay and iron between player villages (`config/game/market.php`, rules in `TradeRules`, rows in `Market`). Food is not traded yet.
- The market (`market`, one per village, needs headquarters 3 and storage 2) has merchants by its level, from Die Stämme's table (`buildings.market.merchants`: 1 at level 1, 11 at 11, 235 at 25). Staffing doesn't change them. A merchant carries `carry` (1000), so n resources need ceil(n / 1000) merchants.
- Busy merchants are the ones on the village's trades, out and back, plus the ones its open offers reserve. The rest are free, never fewer than 0.
- Merchants take `minutes_per_field` (6) per field, divided by the world speed and `movement.unit_speed` like troops. Travel modes don't apply.
- `market.send` takes the resources from the stock and the merchants leave at once, as a `trade` movement with `merchants` and `cargo`. It arrives by the target's `movement.arrives` event like troops (`Rally::arrive` hands it to `Market`), and reading the sender catches up the target first. The cargo goes into the target's storage, settled first; what doesn't fit is lost. The merchants turn round as a `trade_return` that takes as long as the way there, and are free again when it arrives.
- Trades are not troops. They never fight, are never attacked and can't be called back. They stay out of the rally lists, the incoming count, `map.view` and the noble slots. `market.show` lists them: `out` and `back` for the village's own merchants, `in` for anyone's merchants coming with cargo.
- **Offers** (`trade_offers`): a village offers `count` times an amount of one resource for an amount of another. Neither amount may be more than `max_ratio` (3) times the other. The goods for the whole count and ceil(amount / carry) merchants per unit are reserved at once. Cancelling gives back the goods of the open count, up to the storage, and frees the merchants. Another player takes part or all of the count: their merchants carry what the offer asks, the offer's reserved merchants carry what it gives, and both leave at once. The offer row stays locked meanwhile, so two buyers can't take the same count. `market.offers` lists the world's open offers, nearest first, at most 100.
- **Trade routes** (`trade_routes`): a shipment to another player village, repeated every `every` seconds, from `route.min_every` (10 minutes) to `route.max_every` (a week), at most `route.max_routes` (10) per village. These are real seconds: a route runs on the player's clock, not on world time. Each run is a `trade.route` event on the origin at `next_at`, the first one `every` after the route is made. A run sends of each resource what the route asks for as far as the stock has it, scaled down evenly to what the free merchants carry. With nothing in stock or no free merchant, nothing goes this time. Either way the next run comes `every` after this one, and `last_sent_at` and `last_cargo` record the run (all 0 when nothing went).
- A route remembers the target's owner. If the target has another owner when a run comes, the route pauses itself (`paused_reason: owner_changed`) instead of sending. Resuming plans the next run `every` from now and accepts the new owner. A new interval also counts from now.
- A `trade` report (`{from, to, cargo, offer}`) goes to the receiving player when the cargo arrives, and to the sender too. Deliveries between one player's own villages write none.
- A village that changes hands or turns barbarian (`Nobility::release`) loses its trades under way, out and back, its open offers with the goods they reserved, and its routes. Trades coming to it from others still arrive. On an ended world every market change is refused (`world_ended`) and routes stop sending; looking stays allowed.
- The village payload carries `market: {building_id, level, merchants, free, carry}`, or null without a market. The engine pushes `village:updated` to the target when a trade arrives, to the home village when the merchants are back, and to both villages when an offer is accepted.
## Raids
Barbarian camps raid the player villages around them (`config/game/raids.php`, rules in `Raids`, rows in `Raiders`), so a village has something to defend against even on a quiet world.
- Every player village has one `raid.planned` event waiting. The first fires when the owner's beginner protection ends (`world.join`, a conquest, or the seeder on deploy for villages from before raids). It picks the nearest barbarian village within `range` (15) fields and sends a band at the village, then plans the next raid `every_hours` (20 to 40, drawn per event) after this one arrives. With no camp in range it tries again after that interval.
- `every_hours` and `gather_hours` are real hours on every world, like `world.inactive_days`: they follow the player's day, not world time. Only the band's march runs at world speed.
- The band attacks with `attack.base + attack.per_point × village points` (50 + 1.5 × points) in its camp's garrison profile, plus `rams.per_wall_level` rams per wall level (0.5, rounded) once the village has `rams.from_points` (300) points. It is an attack movement without a player (`player_id` null): it gathers at the camp for `gather_hours` (3) and then marches (`sent_at`), and the village sees it from the moment it is planned (`visible_at`). The payload marks it `raid` with `marches_at` while it gathers.
- The camp sizes the village up first. It fights the battle on paper (`CombatResolver`, no luck, full morale) with its full band against everyone in the village, support and levied militia included, its wall, a military village's defence bonus and the night at the expected arrival. When the band would lose with less than `dare` (30%) of the defence's strength, or be shot down before the melee, it stays home: no movement, no report, and the next raid comes after the interval.
- On arrival it is as strong as its camp is then: each unit × the camp garrison's share of full strength. Below `scatter_below` (25%), or when the camp changed hands, it scatters and the village gets a report saying so. So striking the camp in the hours before a raid weakens or stops it. A conquered camp's raids are deleted with its other commands.
- The battle is an ordinary one at full morale. A won raid loots and returns to its camp, which keeps the loot (stock to raid back) and takes the survivors in as far as its garrison has room. A beaten band leaves `bounty` × its attack strength (0.5), a third each of wood, clay and iron, in the village. Reports carry `raid` and `bounty`.
- Feature tests run with raids off (`tests/Pest.php`), like barbarian spawns; `RaidTest` turns them on.
## Conquest
Villages change hands the Die Stämme way (`combat.conquest`, rules in `Conquest`, rows in `Nobility`):
- **Loyalty** runs from 0 to 100 and is stored with `loyalty_at`; it grows back `regen_per_hour` × world speed (1/h) lazily, like resources.
- **Coins** are minted at an academy (`village.mint {village_id, count}`, 28000/30000/25000 each) and belong to the player. They pay for villages, not noblemen. With c coins a player may hold 1 + slots(c) villages, and the n-th slot needs n more coins: the 2nd village needs 1 coin, the 3rd 3 in total, the 4th 6, the 5th 10. A conquest doesn't spend them; they are a threshold. Training a nobleman needs the academy and its cost, nothing else.
- Noblemen march at most `max_distance` (100) fields (`too_far`).
- Every nobleman that survives a won attack lowers loyalty by an even draw from 20 to 35 (the movement's seed, after the luck draw). At 0 or below the village goes to the attacker if the attacker's coins pay for one more village (`Conquest::canTake`): one nobleman settles, the other survivors stay as support from their home village, and nothing is looted. Loyalty starts again at 25. Without a free slot the village stays with its owner at loyalty 0 and grows back as usual. Every nobleman survives and goes home with the other survivors and the loot, as after any won attack.
- The handover (`Nobility::handOver`) ends the village's build and recruit queues and its levy without refunds, deletes the old owner's commands from it and troops on their way home to it, and drops its support standing elsewhere. Barbarian villages and crown forts can be taken too, under the same coin rule. Attack and defence reports carry `loyalty: {before, after, conquered, no_coins}`. `no_coins` is true when loyalty reached 0 but the coins paid for no more villages.
- A player who loses the last village joins the world again with a fresh one (`world.join`).
- The village payload carries `loyalty`, `conquest: {coins, slots, used, next_slot_coins, coin_cost, max_distance}` and `villages` (the player's villages in the world, for the switcher). `slots` are the villages beyond the first that the coins pay for, `used` the ones held, and `next_slot_coins` the coins in total for one more.
## Tribes
Players band together in tribes (`Tribes` action, `tribe.*` over WS, rules in `Diplomacy`, `config/game/tribes.php`).
- A player founds a tribe (name 3 to 32 characters, tag 2 to 6, both unique per world) and leads it. The leader and the council invite players by name; an invited player joins (up to `max_members`, 25) or refuses. A player belongs to one tribe at most. Members leave; the council removes plain members, the leader anyone. The leader sets roles (leader, council, member); making someone else leader hands the tribe over. A leader can't leave while others remain; the last member leaving, or the leader disbanding, ends the tribe.
- Diplomacy runs between tribes, one row per direction (`tribe_relations`). An alliance or a non-aggression pact is offered by one tribe and holds once the other accepts (or offers the same back); ending it from either side starts `notice_hours` (24, at world speed) of notice, and it holds until then, so nobody betrays a partner in the same breath. Enmity is declared by one side alone and needs no pact to end first, only to be declared. The council and the leader run diplomacy.
- Members of one tribe, allies and NAP partners can't attack each other (`own_tribe`, `pact` at the rally point). Support goes to anyone, as before.
- The tribe page (`tribe.show`) carries the members with points, the invites sent, the relations (holds, ending with `ends_at`, offered, incoming, enemy, hostile) and the last 30 events of its news; `tribe.list` every tribe with its size, points and relation. The village payload carries `tribe: {tribe, invites}` for the menu badge. The ranking has a tribe kind and tags players with their tribe.
## Accounts and leaving
- Registration (`POST /api/auth/register`) takes a player name (3 to 24 letters, digits, spaces, dots, dashes or underscores, unique across accounts, case aside), an email, a password of 8 characters or more, and the accepted terms (`terms_accepted_at`). A refusal answers `{code, message, field}`, so the form marks the field.
- `account.show|password|delete` over WS. Deleting needs the password: on every world the player's villages turn barbarian (`Abandon`), a tribe they lead goes to the strongest council member (else the strongest member) or ends with them, then the players and the account go, and with them their reports, quests and chat messages.
- **Losing a village** ("geadelt"): the conquest hands it over (`Nobility::handOver`, which shares `release()` with abandoning: queues end, the owner's groups from and to it are lost, its support elsewhere too), the old owner gets the defence report and a `village:lost {world_id, village_id, name, x, y, by}` whisper, so an open client leaves the village's screens. With no village left, `world.index` marks the world `fallen` and `world.join` starts the player over on the frontier, with fresh beginner protection (`players.protected_since`; protection lasts `combat.beginner_protection` from then, at world speed).
- **Abandoned accounts**: every village action records `players.last_active_at` (at most every 5 minutes). Once a minute the worker turns the villages of players not seen for `world.inactive_days` (14, real days: it measures people, not world time) barbarian (`Abandon::inactive`); the player can come back and start again. A barbarian made this way keeps its buildings and stock, sends other players' support home, loses the owner's troops and queues, grows, and holds a garrison like any other.
- `world.index` gives each world its players, villages, tribes, start, season state and the player's own state; `world.settings` the rules in plain units (durations in seconds at the world's speed, inactivity and raids in real seconds) for the world overview.
## Chat
Players talk on their world (`Chat` action, `chat.*` over WS). The client names channels from its own side: `world` (everyone on the world), `tribe` (the player's tribe) and `dm:<player id>` (a conversation with that player, opened by name with `chat.open`). Stored (`chat_messages`), they are `world`, `tribe:<id>` and `dm:<lower id>:<higher id>`, so a tribe's talk stays with the tribe even as members come and go.
- `chat.send` takes 1 to 500 characters, one message a second per player, on open worlds only. Every reader of the channel gets `chat:message {world_id, channel, message}` whispered to their sockets, with the channel in their own naming.
- `chat.channels` lists the channels with unread counts (`chat_reads` keeps each player's last read message per channel; direct conversations newest first), `chat.history` the last 50 messages (or 50 before an id) and marks them read, `chat.read` marks a channel read.
## Seasons
A world is a season with a winner (`world.season`, rules in `Season`, rows in `Seasons`).
- `crowns_after_days` (30, at world speed) after `started_at`, `crowns` (5) crown forts appear evenly round a ring of `radius` (10) fields about 0|0, each on the free field nearest its spot (`villages.crown`). They are barbarian villages with the `season.buildings` levels (wall 20, farm 30) and the fixed `season.garrison`, which regroups like any garrison (`Barbarians::full`). They never grow and never raid.
- A crown is taken like any village, by noblemen. Each handover of a crown recounts: the player who holds more than half (3 of 5) becomes the world's `holder_player_id`, and `ends_at` is set `hold_days` (7, at world speed) out. Losing the majority clears both; winning it back starts the clock over.
- The `game:events` worker ticks `Seasons::tick` before every loop: it places due crowns and ends a world whose holder reached `ends_at` (`ended_at` is that moment, `winner_player_id` the holder). The next world opens at once with the same config, its slug and name counted up (`w1` → `w2`). An ended world stays readable, but every change, join and raid there is refused (`world_ended`).
- The village payload carries `season` (`SeasonPresenter`): when the crowns come, the crowns with their owners, the holder, `ends_at`, and the winner. `world.index` carries `ended_at` and `winner`, `map.view` a `crown` flag.
## Ranking
`ranking.index {world_id, kind, page?}` (`Ranking`) lists a world like Die Stämme's ranking, 25 rows a page; without a page it opens on the page with the user's own row (`own: {rank, page}`). Ties go to the older player or village.
- `players`: players with villages, by the sum of their villages' points, with their village count.
- `villages`: player villages by points.
- `attack` and `defense`: opponents defeated. Every battle bumps `defeated.attack` for the attacker by the defenders who fell and `defeated.defense` for the defenders by the attackers who fell, each unit counted with the food it eats (`Defeated`: a nobleman is 10, a levied villager 1). Defenders share by what each home village had standing there, so support earns its part. Barbarian garrisons count as opponents; raiders earn nothing, but beating them counts in defence.
## Combat
Combat uses the TW model, in `CombatResolver` (pure, tested with fixed luck) and `config/game/combat.php`:
- **Volley.** Before the melee both sides shoot at once, from their numbers at the start. A side's volley is the sum of its units' `volley` (archer 0.1, catapult 0.5, every other unit 0). The defenders shoot from the wall (× `factor^L`, with L the wall before the rams), the attackers at it (÷ `factor^L`). A unit soaks as much as it eats, a levied villager one. The volley kills `min(1, volley / food the other side eats)` of every unit it hits. Scouts neither shoot nor get hit. Luck, morale and the night don't touch the volley.
- The melee runs with who is left. An attack shot to pieces has lost, and the defence loses only what the attackers' volley killed. A defence shot to pieces leaves the wall alone to fight, as in an empty village.
- Attack strength is split into infantry, cavalry and archer by each unit's class. Every defender, own or support, counts with its defence against each class, weighted by the attacker's mix. Levied militia defend with `combat.militia.defense` per head.
- The wall at level L adds `basic_defense × L` and multiplies the defence by `factor^L` (20 and 1.037). Each level L down needs `base × factor^(L − 1)` rams (2 and 1.09). Nothing drops below level 1.
- Rams fire in two phases. The rams the volley left fire `siege.ram.before_battle` (half) of their count before the melee, and the melee is fought at the lower wall. After a won battle the surviving rams fire the rest at the wall as it then stands; what the first ones did on the level they stopped at counts. A lost battle ends after the first phase.
- The attack is multiplied by morale and (1 + luck). Luck is drawn evenly from ±`combat.luck` (25%) with the movement's seed, so a replayed event fights the same battle. Morale is `min(1, 0.3 + 3 × defender points / attacker points)` and always 1 against barbarians. Worlds with a night bonus multiply the defence at night.
- With r = loser strength / winner strength, the winner loses `((r − t) / (1 − t))^1.5` of every unit, and nothing at r ≤ t (`loss_threshold`, 0.1). A side ten times stronger loses nobody; at even strength both sides fall. The loser loses everything.
- Every stack of a side, support included, falls alike: the volley's share first, then the melee's share of the rest, each rounded per stack (`Battle::defenseDead`). Volley deaths count like any other: in `lost`, in the hospital and in the ranking. Dead militia shrink the levy. Part of the defender's own dead come back from its hospital (see "Hospital").
- Attack and defence reports and the simulator (`rally.simulate`) carry `volley: {attacker: {unit: dead}, defender: {unit: dead}}`, null when nobody shot. Those dead are already inside `lost`. An attacker who learns nothing about the defence gets `volley.defender` null.
- Lint: `loss_threshold` at least 0 and below 1, `before_battle` between 0 and 1, no `volley` below 0.
- After a won battle, surviving catapults hit the highest instance of the chosen type (headquarters by default) by the same siege rule. A damaged building's queued orders are cancelled with a full refund, since their levels no longer fit.
- Scouts (units with `scout: true`) never fight. They meet the scouts in the village first: they get through when they outnumber `combat.scouting.defense` × the defending scouts, losing `(defence / attack)^1.5` of themselves; otherwise all of them die, and defending scouts never die in this. Scouts that get through add the village's resources and building levels, after the battle, to the attacker's report. Scouts alone cause no battle; defending scouts die with the village's other defenders when a battle is lost.
- `LootCalculator`: survivors carry `carry` per unit. They take wood, clay and iron evenly, above what the hiding places protect (`hides` per resource; instances add up). Food is not looted.