diff --git a/app/Actions/EndLevy.php b/app/Actions/EndLevy.php new file mode 100644 index 0000000..ea25a53 --- /dev/null +++ b/app/Actions/EndLevy.php @@ -0,0 +1,24 @@ +mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) { + if (! $village->militia) { + throw new GameRuleViolation('not_found', 'No levy under way.'); + } + Military::of($village, $sim)->endLevy($now); + }); + } +} diff --git a/app/Actions/Levy.php b/app/Actions/Levy.php new file mode 100644 index 0000000..98047e2 --- /dev/null +++ b/app/Actions/Levy.php @@ -0,0 +1,20 @@ +mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($count) { + Military::of($village, $sim)->levy($count, $now); + }); + } +} diff --git a/app/Engine/Engine.php b/app/Engine/Engine.php index 5a7cb09..92a55cf 100644 --- a/app/Engine/Engine.php +++ b/app/Engine/Engine.php @@ -86,6 +86,7 @@ final class Engine GameEvent::BUILD_ORDER_FINISHED => $this->finishBuildOrder($village, $event), GameEvent::BARBARIAN_GROWS => $this->growBarbarian($village, $event), GameEvent::RECRUIT_FINISHED => Military::of($village)->settle($event->fire_at), + GameEvent::LEVY_ENDS => Military::of($village)->endLevy($event->fire_at), }; } diff --git a/app/Engine/Military.php b/app/Engine/Military.php index cb39b5e..109b71c 100644 --- a/app/Engine/Military.php +++ b/app/Engine/Military.php @@ -83,7 +83,7 @@ final class Military fn (string $r) => $cost[$r] > 0 ? (int) floor($this->village->{$r} / $cost[$r]) : PHP_INT_MAX, array_keys($cost), )); - $byVillagers = (int) floor($this->sim->workforce()->villagers / $this->units->upkeep($unit)); + $byVillagers = (int) floor($this->sim->workforce()->undrafted() / $this->units->upkeep($unit)); return max(0, min($byResources, $byVillagers)); } @@ -108,7 +108,7 @@ final class Military if ($this->missingRequirements($unit)) { throw new GameRuleViolation('requires', 'Requirements not met.'); } - if ($count * $this->units->upkeep($unit) > $this->sim->workforce()->villagers) { + if ($count * $this->units->upkeep($unit) > $this->sim->workforce()->undrafted()) { throw new GameRuleViolation('villagers', 'Not enough villagers to train that many.'); } $this->sim->pay($this->units->cost($unit, $count)); @@ -159,6 +159,47 @@ final class Military } } + /** Seconds a levy lasts on this world. */ + public function levySeconds(): int + { + return max(1, (int) ceil($this->sim->config()->get('economy.levy.duration', 6 * 3600) / $this->sim->config()->speed())); + } + + /** + * Draft villagers as militia. They stop working at once (the caller settled the + * village to $now) and return on their own when the levy ends. + */ + public function levy(int $count, CarbonImmutable $now): void + { + if ($this->village->militia > 0) { + throw new GameRuleViolation('levy_active', 'A levy is already under way.'); + } + if ($count < 1) { + throw new GameRuleViolation('count', 'Draft at least one villager.'); + } + if ($count > $this->sim->workforce()->villagers) { + throw new GameRuleViolation('villagers', 'Not that many villagers.'); + } + $this->village->militia = $count; + $this->village->levy_until = $now->addSeconds($this->levySeconds()); + GameEvent::create([ + 'world_id' => $this->village->world_id, + 'village_id' => $this->village->id, + 'type' => GameEvent::LEVY_ENDS, + 'subject_id' => $this->village->id, + 'fire_at' => $this->village->levy_until, + ]); + } + + /** Send the militia back to work, on the timer or early; the village is settled to $at first. */ + public function endLevy(CarbonImmutable $at): void + { + $this->sim->settle($at); + $this->village->militia = 0; + $this->village->levy_until = null; + GameEvent::where('type', GameEvent::LEVY_ENDS)->where('village_id', $this->village->id)->whereNull('processed_at')->delete(); + } + private function addTroops(string $unit, int $count): void { $stack = $this->village->troops->first(fn (UnitStack $s) => $s->unit === $unit && $s->home_village_id === $this->village->id); diff --git a/app/Engine/Simulation.php b/app/Engine/Simulation.php index 8c0e37b..b3b7007 100644 --- a/app/Engine/Simulation.php +++ b/app/Engine/Simulation.php @@ -67,7 +67,7 @@ final class Simulation public function workforce(): Workforce { - return $this->population->workforce($this->states(), $this->soldierUpkeep()); + return $this->population->workforce($this->states(), $this->soldierUpkeep(), (int) $this->village->militia); } /** diff --git a/app/Game/Economy/Population.php b/app/Game/Economy/Population.php index a66c312..e73bbf6 100644 --- a/app/Game/Economy/Population.php +++ b/app/Game/Economy/Population.php @@ -39,13 +39,15 @@ final class Population /** * @param list $buildings * @param float $soldierUpkeep food/h eaten by soldiers and stationed support + * @param int $militia villagers drafted by a levy; they eat as before but don't work */ - public function workforce(array $buildings, float $soldierUpkeep = 0.0): Workforce + public function workforce(array $buildings, float $soldierUpkeep = 0.0, int $militia = 0): Workforce { $budget = $this->foodBudget($buildings); $perVillager = $this->config->get('economy.upkeep.villager', 1); $share = $this->config->get('economy.villager_share', 0.8); $villagers = max(0, (int) floor(($budget * $share - $soldierUpkeep) / $perVillager)); + $militia = min($militia, $villagers); $required = []; foreach ($buildings as $b) { @@ -56,8 +58,9 @@ final class Population foodBudget: $budget, villagers: $villagers, upkeep: $villagers * $perVillager + $soldierUpkeep, - assigned: $this->assign($buildings, $required, $villagers), + assigned: $this->assign($buildings, $required, $villagers - $militia), required: $required, + militia: $militia, ); } diff --git a/app/Game/Economy/Workforce.php b/app/Game/Economy/Workforce.php index 86a577b..13cd796 100644 --- a/app/Game/Economy/Workforce.php +++ b/app/Game/Economy/Workforce.php @@ -15,8 +15,16 @@ final class Workforce public readonly float $upkeep, public readonly array $assigned, public readonly array $required, + /** Villagers drafted by a levy, at most all of them. */ + public readonly int $militia = 0, ) {} + /** Villagers not drafted by a levy: the ones recruiting can train. */ + public function undrafted(): int + { + return $this->villagers - $this->militia; + } + public function workers(): int { return array_sum($this->assigned); diff --git a/app/Models/GameEvent.php b/app/Models/GameEvent.php index 356468f..1ff0848 100644 --- a/app/Models/GameEvent.php +++ b/app/Models/GameEvent.php @@ -14,6 +14,8 @@ class GameEvent extends Model public const RECRUIT_FINISHED = 'recruit.finished'; + public const LEVY_ENDS = 'levy.ends'; + protected $guarded = []; protected $dateFormat = 'Y-m-d H:i:s.v'; diff --git a/app/Models/Village.php b/app/Models/Village.php index bb5e7a9..06bf5f7 100644 --- a/app/Models/Village.php +++ b/app/Models/Village.php @@ -21,6 +21,8 @@ class Village extends Model 'iron' => 'float', 'food' => 'float', 'resources_at' => 'immutable_datetime', + 'militia' => 'integer', + 'levy_until' => 'immutable_datetime', ]; } diff --git a/app/Presenters/VillagePresenter.php b/app/Presenters/VillagePresenter.php index c3cb871..f2d1454 100644 --- a/app/Presenters/VillagePresenter.php +++ b/app/Presenters/VillagePresenter.php @@ -48,6 +48,12 @@ final class VillagePresenter 'soldiers' => array_sum($troops), 'training' => $village->recruits->sum(fn (RecruitOrder $o) => $o->count - $o->done), ], + 'levy' => [ + 'militia' => $workforce->militia, + 'until' => $village->levy_until ? self::iso($village->levy_until) : null, + // How long a new levy would last. + 'seconds' => $military->levySeconds(), + ], 'troops' => (object) $troops, 'military' => self::military($village, $military, $now), 'builders' => $sim->builders(), diff --git a/app/Websocket/Controllers/VillageController.php b/app/Websocket/Controllers/VillageController.php index dd49dee..07286a2 100644 --- a/app/Websocket/Controllers/VillageController.php +++ b/app/Websocket/Controllers/VillageController.php @@ -4,6 +4,8 @@ namespace App\Websocket\Controllers; use App\Actions\CancelOrder; use App\Actions\CancelRecruit; +use App\Actions\EndLevy; +use App\Actions\Levy; use App\Actions\QueueBuild; use App\Actions\QueueDemolish; use App\Actions\QueueUpgrade; @@ -16,7 +18,7 @@ use App\Presenters\VillagePresenter; use App\Websocket\GameController; use Closure; -/** village.show|build|upgrade|demolish|cancel|staff|recruit|cancelRecruit. Each answers with the fresh village state. */ +/** village.show|build|upgrade|demolish|cancel|staff|recruit|cancelRecruit|levy|endLevy. Each answers with the fresh village state. */ class VillageController extends GameController { public function show() @@ -65,6 +67,16 @@ class VillageController extends GameController return $this->village(fn ($user, $id) => app(CancelRecruit::class)($user, $id, (int) request('order_id'))); } + public function levy() + { + return $this->village(fn ($user, $id) => app(Levy::class)($user, $id, (int) request('count'))); + } + + public function endLevy() + { + return $this->village(fn ($user, $id) => app(EndLevy::class)($user, $id)); + } + /** @param Closure(User, int): Village $action */ private function village(Closure $action) { diff --git a/config/game/economy.php b/config/game/economy.php index ee909fc..8fb818b 100644 --- a/config/game/economy.php +++ b/config/game/economy.php @@ -23,4 +23,8 @@ return [ // Each level of a military building makes training there this much faster. 'recruit_speed_per_level' => 0.05, + + // Levy: villagers drafted as militia stop working for this long (seconds at world + // speed 1), then return to work on their own. One levy at a time; it can end early. + 'levy' => ['duration' => 6 * 3600], ]; diff --git a/database/migrations/2026_10_29_150000_add_levy_to_villages.php b/database/migrations/2026_10_29_150000_add_levy_to_villages.php new file mode 100644 index 0000000..c8961f2 --- /dev/null +++ b/database/migrations/2026_10_29_150000_add_levy_to_villages.php @@ -0,0 +1,24 @@ +unsignedInteger('militia')->default(0)->after('space'); + $table->dateTime('levy_until', 3)->nullable()->after('militia'); + }); + } + + public function down(): void + { + Schema::table('villages', function (Blueprint $table) { + $table->dropColumn(['militia', 'levy_until']); + }); + } +}; diff --git a/docs/architecture.md b/docs/architecture.md index 94517f4..a42ec12 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -53,7 +53,7 @@ Rates are constant between events. Any change to a rate settles the village firs - **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 workers as militia for a fixed time (world config). Their buildings run understaffed meanwhile, and the militia return to work automatically when the time ends. +- **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 @@ -135,7 +135,7 @@ A building entry looks like this (numbers start TW-like): |---|---| | `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, levy_until null, starving_since null, loyalty, loyalty_at, points. unique(world_id, x, y) | +| `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) | diff --git a/docs/roadmap.md b/docs/roadmap.md index a842346..1713f25 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -33,7 +33,7 @@ Each milestone ends with tests green, `ConfigLint` green, and something playable - [x] `config/game/units.php`: spear, sword, archer, light cav, heavy cav, ram, catapult, nobleman, with food upkeep - [x] Barracks, stable, workshop, academy as building instances (several barracks run parallel recruit queues); only these advanced buildings get requirements, e.g. academy needs headquarters + barracks - [x] Recruiting turns villagers into soldiers; lazy per-unit completion -- [ ] Levy: draft workers as militia, automatic return +- [x] Levy: draft workers as militia, automatic return - [ ] Starvation: zero-crossing event, grace timer, desertion order - [ ] UI: recruit forms, troops overview, food balance warnings diff --git a/tests/Feature/LevyTest.php b/tests/Feature/LevyTest.php new file mode 100644 index 0000000..14a3fd8 --- /dev/null +++ b/tests/Feature/LevyTest.php @@ -0,0 +1,74 @@ + $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00'))); + +it('drafts villagers, who stop working and return when the levy ends', function () { + $village = startVillage(); + $before = shown($village); + + app(Levy::class)(owner($village), $village->id, 24); + $state = shown($village); + expect($state['levy'])->toBe(['militia' => 24, 'until' => '2026-10-29T18:00:00.000Z', 'seconds' => 21600]) + ->and($state['population'])->toMatchArray(['villagers' => 24, 'workers' => 0]) + ->and($state['rates']['food'])->toBeLessThan($before['rates']['food']); + + $this->travel(6)->hours(); + $this->artisan('game:events --once')->assertSuccessful(); + $state = shown($village); + expect($state['levy'])->toMatchArray(['militia' => 0, 'until' => null]) + ->and($state['population']['workers'])->toBe($before['population']['workers']) + ->and(GameEvent::where('type', GameEvent::LEVY_ENDS)->whereNull('processed_at')->count())->toBe(0); +}); + +it('settles the village at the moment the militia return', function () { + $village = startVillage(); + $before = shown($village); + app(Levy::class)(owner($village), $village->id, 24); + $levied = shown($village)['rates']['food']; + + // No worker runs: showing the village catches the levy end up first. + $this->travel(7)->hours(); + expect(shown($village)['resources']['food']) + ->toEqualWithDelta($before['resources']['food'] + 6 * $levied + 1 * $before['rates']['food'], 0.01); +}); + +it('ends early on request', function () { + $village = startVillage(); + app(Levy::class)(owner($village), $village->id, 10); + $this->travel(1)->hours(); + + app(EndLevy::class)(owner($village), $village->id); + expect(shown($village)['levy'])->toMatchArray(['militia' => 0, 'until' => null]) + ->and(GameEvent::where('type', GameEvent::LEVY_ENDS)->whereNull('processed_at')->count())->toBe(0) + ->and(rule(fn () => app(EndLevy::class)(owner($village), $village->id)))->toBe('not_found'); +}); + +it('refuses a second levy, more than the villagers and nobody', function () { + $village = startVillage(); + + expect(rule(fn () => app(Levy::class)(owner($village), $village->id, 25)))->toBe('villagers') + ->and(rule(fn () => app(Levy::class)(owner($village), $village->id, 0)))->toBe('count'); + + app(Levy::class)(owner($village), $village->id, 5); + expect(rule(fn () => app(Levy::class)(owner($village), $village->id, 5)))->toBe('levy_active'); +}); + +it('trains soldiers only from villagers who are not drafted', function () { + $village = startVillage(); + $barracks = $village->buildings()->create(['type' => 'barracks', 'level' => 0]); + $village->update(['wood' => 1000, 'clay' => 1000, 'iron' => 1000]); + app(Levy::class)(owner($village), $village->id, 20); + + $spear = collect(collect(shown($village)['military'])->firstWhere('type', 'barracks')['units'])->firstWhere('unit', 'spear'); + expect($spear['max'])->toBe(4) + ->and(rule(fn () => app(Recruit::class)(owner($village), $village->id, $barracks->id, 'spear', 5)))->toBe('villagers'); + + app(Recruit::class)(owner($village), $village->id, $barracks->id, 'spear', 4); + expect(shown($village)['population']['training'])->toBe(4); +}); diff --git a/tests/Unit/Game/PopulationTest.php b/tests/Unit/Game/PopulationTest.php index 245e36c..24c79fb 100644 --- a/tests/Unit/Game/PopulationTest.php +++ b/tests/Unit/Game/PopulationTest.php @@ -19,6 +19,25 @@ it('leaves soldiers upkeep out of the villagers share', function () { ->and($workforce->upkeep)->toEqual(24); }); +it('keeps drafted militia out of work, but they still eat', function () { + // 24 villagers; 20 drafted leave 4, which go to the farm (2) first. + $buildings = [building(1, 'clay_pit', 30), building(2, 'farm')]; + $workforce = (new Population(gameConfig()))->workforce($buildings, militia: 20); + + expect($workforce->assigned)->toBe([1 => 2, 2 => 2]) + ->and($workforce->militia)->toBe(20) + ->and($workforce->undrafted())->toBe(4) + ->and($workforce->upkeep)->toEqual(24); +}); + +it('drafts no more militia than there are villagers', function () { + $workforce = (new Population(gameConfig()))->workforce([building(1, 'farm')], soldierUpkeep: 20, militia: 10); + + expect($workforce->villagers)->toBe(4) + ->and($workforce->militia)->toBe(4) + ->and($workforce->workers())->toBe(0); +}); + it('staffs farms first, then by priority', function () { // Farm 0 makes 30 food, so 24 villagers: the farm takes 2, priority 9 the other 22. $buildings = [