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

323 lines
43 KiB
Markdown
Raw Normal View History

# 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
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
Travel/TravelTime.php
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. 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
- **Capacity** is a food budget in food/h: `nominal farm output + 24h average of food delivered to this village`. 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 eats `upkeep.villager` (for example 1 food/h), and soldiers eat per unit type (for example spear 1, heavy cav 4, noble 10). Foreign support stationed in the village counts against the host's budget.
- **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.
### 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.
- Multiple instances per type are allowed. `max_per_village` limits types that must stay unique (HQ, rally point, wall). `instance_cost_factor` makes the n-th instance of a type more expensive, so many cheap copies don't beat upgrading.
- 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.
- 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, 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. 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`).
- 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`. 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 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 < its output. |
| 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. |
| All merchants killed | Merchants are trained at the market like units, so dead merchants can always be replaced. |
| 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, after beginner protection, and loot only what the hiding places don't cover; rams never take a wall below 1, and no band takes a village. Beating the camp down scatters its next band. Lint: intervals above 0, `scatter_below` above 0. |
## Config
`config/game/world.php`, `economy.php`, `buildings.php`, `units.php`, and `combat.php` 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 |
| `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), type (attack/support/return), mode, origin_id, target_id, units json, cargo json null, catapult_target null, rng_seed, sent_at, arrives_at, visible_at. Trade, merchants and destroyed_at come with M5 |
| `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), 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.
- **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.
## 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` (18 to 30, drawn per event) after this one arrives. With no camp in range it tries again after that interval.
- 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 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.
- 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) 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`:
- 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). Rams lower the wall before the battle: each level L down needs `base × factor^(L − 1)` rams (2 and 1.09). Nothing drops below level 1.
- 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.
- The winner loses `(loser / winner)^1.5` of every unit, rounded per stack; the loser loses everything. Dead militia shrink the levy. Part of the defender's own dead come back from its hospital (see "Hospital").
- 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.