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

25 KiB
Raw Blame 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.
  • 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 20, so 40 at level 1, 60 at level 2). 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.
  • 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.

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.

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.
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.

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):

'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. 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, loyalty_at, 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
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_relations name, tag; player_id, role; tribe_id, other_tribe_id, state (ally/nap/enemy). Arrives in M6
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.
  • 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) and whether it is the player's own. 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 and takes as long to get home as it had been under way.
  • 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

Tribes arrive in M6, with ally, NAP (non-aggression pact), and enemy states between them. Until then, every other player is hostile. Hostility is checked at encounter time, not at send time.

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.
  • 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.