diff --git a/app/Actions/VillageAction.php b/app/Actions/VillageAction.php index 80df30a..2dd88a6 100644 --- a/app/Actions/VillageAction.php +++ b/app/Actions/VillageAction.php @@ -5,6 +5,7 @@ namespace App\Actions; use App\Engine\Engine; use App\Engine\Military; use App\Engine\Simulation; +use App\Engine\Starvation; use App\Game\GameRuleViolation; use App\Models\Building; use App\Models\User; @@ -33,6 +34,7 @@ abstract class VillageAction $sim->settle($now); Military::of($village, $sim)->settle($now); $change($sim, $village, $now); + Starvation::of($village, $sim)->sync($now); $village->save(); return $village; diff --git a/app/Engine/Engine.php b/app/Engine/Engine.php index 92a55cf..7a0d7d6 100644 --- a/app/Engine/Engine.php +++ b/app/Engine/Engine.php @@ -66,6 +66,7 @@ final class Engine } $event->update(['processed_at' => $now]); $this->handle($village, $event); + Starvation::of($village)->sync($event->fire_at); $village->save(); return true; @@ -87,6 +88,9 @@ final class Engine 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), + // The stock just hit 0; the sync() after every event starts the grace timer. + GameEvent::FOOD_RUNS_OUT => null, + GameEvent::DESERTION => Starvation::of($village)->wave($event->fire_at), }; } diff --git a/app/Engine/Starvation.php b/app/Engine/Starvation.php new file mode 100644 index 0000000..ee4f8c2 --- /dev/null +++ b/app/Engine/Starvation.php @@ -0,0 +1,169 @@ +sim->settle($at); + $starving = $this->starving(); + $this->schedule(GameEvent::FOOD_RUNS_OUT, $starving ? null : $this->emptyAt()); + + if (! $starving) { + $this->village->starving_since = null; + $this->schedule(GameEvent::DESERTION, null); + + return; + } + $this->village->starving_since ??= $at; + if (! $this->pending(GameEvent::DESERTION)) { + $first = $this->village->starving_since->addSeconds($this->seconds('grace')); + $this->schedule(GameEvent::DESERTION, $first->max($at)); + } + } + + /** When the stock runs out at the current rates, or null if it doesn't. */ + public function emptyAt(): ?CarbonImmutable + { + $rate = $this->sim->rates()['food']; + if ($rate >= 0 || $this->village->food <= self::EMPTY) { + return null; + } + + return $this->village->resources_at->addMilliseconds((int) ceil($this->village->food / -$rate * 3_600_000)); + } + + public function nextDesertion(): ?CarbonImmutable + { + return $this->pending(GameEvent::DESERTION)?->fire_at; + } + + /** + * One desertion wave at $at: own soldiers at home leave, highest upkeep first, as + * few as it takes for income to cover upkeep; if that isn't enough, the levy ends. + * When the village still goes hungry, the next wave follows after `wave_every`. + * + * @return array what left, by unit; `militia` for an ended levy + */ + public function wave(CarbonImmutable $at): array + { + $this->sim->settle($at); + if (! $this->starving()) { + return []; + } + + $units = new UnitRules($this->sim->config()); + $stacks = $this->village->troops + ->where('home_village_id', $this->village->id) + ->sortByDesc(fn (UnitStack $s) => $units->upkeep($s->unit)); + $gone = []; + foreach ($stacks as $stack) { + if ($this->fed()) { + break; + } + $gone[$stack->unit] = $this->fewestToFeed($stack); + } + foreach ($stacks as $stack) { + $stack->count > 0 ? $stack->save() : $stack->delete(); + } + $this->village->setRelation('troops', $this->village->troops->filter(fn (UnitStack $s) => $s->count > 0)->values()); + + if (! $this->fed() && $this->village->militia > 0) { + $gone['militia'] = (int) $this->village->militia; + Military::of($this->village, $this->sim)->endLevy($at); + } + if (! $this->fed()) { + $this->schedule(GameEvent::DESERTION, $at->addSeconds($this->seconds('wave_every'))); + } + + return array_filter($gone); + } + + /** Take units out of the stack until the village is fed or the stack is empty; returns how many left. */ + private function fewestToFeed(UnitStack $stack): int + { + $count = $stack->count; + $stack->count = 0; + if (! $this->fed()) { + return $count; + } + // Feeding never gets worse with fewer soldiers, so search the smallest number. + [$low, $high] = [1, $count]; + while ($low < $high) { + $mid = intdiv($low + $high, 2); + $stack->count = $count - $mid; + $this->fed() ? $high = $mid : $low = $mid + 1; + } + $stack->count = $count - $low; + + return $low; + } + + private function fed(): bool + { + return $this->sim->rates()['food'] >= 0; + } + + private function starving(): bool + { + return $this->village->food <= self::EMPTY && ! $this->fed(); + } + + private function seconds(string $key): int + { + return max(1, (int) ceil($this->sim->config()->get("economy.starvation.$key", 3600) / $this->sim->config()->speed())); + } + + private function pending(string $type): ?GameEvent + { + return GameEvent::where('type', $type)->where('village_id', $this->village->id)->whereNull('processed_at')->first(); + } + + /** Keep exactly one pending event of this type at $at, or none for null. */ + private function schedule(string $type, ?CarbonImmutable $at): void + { + $pending = $this->pending($type); + if (! $at) { + $pending?->delete(); + + return; + } + if ($pending) { + if ($pending->fire_at->getTimestampMs() !== $at->getTimestampMs()) { + $pending->update(['fire_at' => $at]); + } + + return; + } + GameEvent::create([ + 'world_id' => $this->village->world_id, + 'village_id' => $this->village->id, + 'type' => $type, + 'subject_id' => $this->village->id, + 'fire_at' => $at, + ]); + } +} diff --git a/app/Game/ConfigLint.php b/app/Game/ConfigLint.php index 3488079..8397957 100644 --- a/app/Game/ConfigLint.php +++ b/app/Game/ConfigLint.php @@ -23,9 +23,26 @@ final class ConfigLint ...self::costsFitStorage($config, $rules), ...self::requirementsReachable($config, $rules), ...self::unitsTrainable($config, $rules), + ...self::timersRun($config), ]; } + /** A levy has to end and desertion waves have to come apart in time, or the village stays stuck. */ + private static function timersRun(WorldConfig $config): array + { + $problems = []; + foreach (['economy.levy.duration', 'economy.starvation.wave_every'] as $key) { + if ($config->get($key, 1) <= 0) { + $problems[] = "[$key] must be more than 0 seconds."; + } + } + if ($config->get('economy.starvation.grace', 0) < 0) { + $problems[] = '[economy.starvation.grace] cannot be negative.'; + } + + return $problems; + } + /** * The start buildings must exist and fit the building space together, and every * type must fit next to them, or it could never be built. diff --git a/app/Models/GameEvent.php b/app/Models/GameEvent.php index 1ff0848..2350c70 100644 --- a/app/Models/GameEvent.php +++ b/app/Models/GameEvent.php @@ -16,6 +16,10 @@ class GameEvent extends Model public const LEVY_ENDS = 'levy.ends'; + public const FOOD_RUNS_OUT = 'food.runs_out'; + + public const DESERTION = 'starvation.desertion'; + protected $guarded = []; protected $dateFormat = 'Y-m-d H:i:s.v'; diff --git a/app/Models/Village.php b/app/Models/Village.php index 06bf5f7..3baf908 100644 --- a/app/Models/Village.php +++ b/app/Models/Village.php @@ -23,6 +23,7 @@ class Village extends Model 'resources_at' => 'immutable_datetime', 'militia' => 'integer', 'levy_until' => 'immutable_datetime', + 'starving_since' => 'immutable_datetime', ]; } diff --git a/app/Presenters/VillagePresenter.php b/app/Presenters/VillagePresenter.php index f2d1454..ba87802 100644 --- a/app/Presenters/VillagePresenter.php +++ b/app/Presenters/VillagePresenter.php @@ -4,6 +4,7 @@ namespace App\Presenters; use App\Engine\Military; use App\Engine\Simulation; +use App\Engine\Starvation; use App\Game\Map\Continent; use App\Models\Building; use App\Models\BuildOrder; @@ -22,6 +23,7 @@ final class VillagePresenter $sim = Simulation::of($village); $sim->settle($now); $military = Military::of($village, $sim); + $starvation = Starvation::of($village, $sim); $troops = $military->troopsAtHome(); $workforce = $sim->workforce(); $rules = $sim->rules(); @@ -50,10 +52,17 @@ final class VillagePresenter ], 'levy' => [ 'militia' => $workforce->militia, - 'until' => $village->levy_until ? self::iso($village->levy_until) : null, + 'until' => self::isoOrNull($village->levy_until), // How long a new levy would last. 'seconds' => $military->levySeconds(), ], + 'starvation' => [ + // When the stock runs out at the current rates (null when it doesn't). + 'food_empty_at' => self::isoOrNull($starvation->emptyAt()), + // Set while the stock is empty and upkeep exceeds income. + 'since' => self::isoOrNull($village->starving_since), + 'desertion_at' => self::isoOrNull($starvation->nextDesertion()), + ], 'troops' => (object) $troops, 'military' => self::military($village, $military, $now), 'builders' => $sim->builders(), @@ -140,4 +149,9 @@ final class VillagePresenter { return $at->utc()->format('Y-m-d\TH:i:s.v\Z'); } + + private static function isoOrNull(?CarbonImmutable $at): ?string + { + return $at ? self::iso($at) : null; + } } diff --git a/config/game/economy.php b/config/game/economy.php index 8fb818b..3d0dc21 100644 --- a/config/game/economy.php +++ b/config/game/economy.php @@ -27,4 +27,9 @@ return [ // 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], + + // Starvation: once the food stock is empty and upkeep still exceeds income, soldiers + // desert after `grace` and then every `wave_every` (seconds at world speed 1), each + // wave just enough to feed the rest. Income covering upkeep again stops the clock. + 'starvation' => ['grace' => 24 * 3600, 'wave_every' => 3600], ]; diff --git a/database/migrations/2026_10_29_170000_add_starving_since_to_villages.php b/database/migrations/2026_10_29_170000_add_starving_since_to_villages.php new file mode 100644 index 0000000..1fc3282 --- /dev/null +++ b/database/migrations/2026_10_29_170000_add_starving_since_to_villages.php @@ -0,0 +1,23 @@ +dateTime('starving_since', 3)->nullable()->after('levy_until'); + }); + } + + public function down(): void + { + Schema::table('villages', function (Blueprint $table) { + $table->dropColumn('starving_since'); + }); + } +}; diff --git a/docs/architecture.md b/docs/architecture.md index a42ec12..500e7aa 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -67,7 +67,9 @@ Each village has `builders` (default 2, +1 at the HQ levels listed in world conf ### Starvation -When upkeep exceeds income, food stock drains. The engine computes the exact moment the stock reaches 0 and schedules an event there. At that point a grace timer starts (`starvation.grace`, default 24h). If the village is still in deficit when it runs out, units desert in hourly waves until upkeep fits the budget. The order is foreign support first, then own soldiers from the highest upkeep down, then villagers that are not working on farms. Farm workers never desert. The timer resets as soon as income covers upkeep again. +When upkeep exceeds income, the food stock drains. `AppngineStarvation::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: foreign support first (M5), 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 @@ -104,7 +106,7 @@ A village may fail through war or bad play, but it must never get stuck. Every l | Building space full | Demolishing is always allowed, costs nothing, and refunds. Core buildings (HQ, one storage, one farm) cannot go below level 0. 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, non-farm villagers. Farm workers stay, so food income can't collapse. | +| 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. | diff --git a/docs/roadmap.md b/docs/roadmap.md index 1713f25..8762725 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -34,7 +34,7 @@ Each milestone ends with tests green, `ConfigLint` green, and something playable - [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 - [x] Levy: draft workers as militia, automatic return -- [ ] Starvation: zero-crossing event, grace timer, desertion order +- [x] Starvation: zero-crossing event, grace timer, desertion order - [ ] UI: recruit forms, troops overview, food balance warnings ## M4: Attacks, combat, looting @@ -42,7 +42,7 @@ Each milestone ends with tests green, `ConfigLint` green, and something playable - [ ] `TravelTime` (slowest unit, distance, unit speed, travel mode) with unit tests - [ ] Travel modes from `movement.php`; warning time from visibility and detection radius; watchtower - [ ] Send attack or support (host pays upkeep), send support home, recall, return trips -- [ ] `CombatResolver` and `LootCalculator` (wall, morale, luck, hiding place, rams, catapults) with unit tests +- [ ] `CombatResolver` and `LootCalculator` (wall, morale, luck, hiding place, rams, catapults), with levied militia defending, with unit tests - [ ] Reports - [ ] Incoming-attack push and UI diff --git a/tests/Feature/StarvationTest.php b/tests/Feature/StarvationTest.php new file mode 100644 index 0000000..0a00483 --- /dev/null +++ b/tests/Feature/StarvationTest.php @@ -0,0 +1,93 @@ + $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00'))); + +/** A start village (farm 0: 24 villagers' worth of food) with soldiers stationed at home. */ +function garrisoned(array $troops): Village +{ + $village = startVillage(); + foreach ($troops as $unit => $count) { + $village->troops()->create(['home_village_id' => $village->id, 'unit' => $unit, 'count' => $count]); + } + + return $village->fresh(); +} + +function iso(CarbonImmutable $at): string +{ + return $at->utc()->format('Y-m-d\TH:i:s.v\Z'); +} + +it('knows when the food runs out and starts the grace timer right then', function () { + // 10 light cavalry eat 30 food/h: no villagers are left to work the farm. + $village = garrisoned(['light_cavalry' => 10]); + $state = shown($village); + $hours = 300 / -$state['rates']['food']; + expect($state['starvation'])->toMatchArray(['since' => null, 'desertion_at' => null]) + ->and(CarbonImmutable::parse($state['starvation']['food_empty_at'])->getTimestampMs()) + ->toEqualWithDelta(now()->getTimestampMs() + $hours * 3_600_000, 1000); + + $this->travel(12)->hours(); + $this->artisan('game:events --once')->assertSuccessful(); + $state = shown($village); + $since = CarbonImmutable::parse($state['starvation']['since']); + expect($state['resources']['food'])->toBe(0.0) + ->and($state['starvation']['food_empty_at'])->toBeNull() + ->and($since->getTimestampMs())->toEqualWithDelta(now()->subHours(12)->getTimestampMs() + $hours * 3_600_000, 1000) + ->and($state['starvation']['desertion_at'])->toBe(iso($since->addDay())); +}); + +it('lets just enough soldiers desert after the grace, highest upkeep first', function () { + // 35 food/h of soldiers; the farm needs 2 workers, so they may eat at most 22. + $village = garrisoned(['spear' => 5, 'light_cavalry' => 10]); + shown($village); + + $this->travel(12)->hours(); + $this->artisan('game:events --once')->assertSuccessful(); + $this->travel(1)->days(); + $this->artisan('game:events --once')->assertSuccessful(); + + $state = shown($village); + expect((array) $state['troops'])->toBe(['spear' => 5, 'light_cavalry' => 5]) + ->and($state['rates']['food'])->toBeGreaterThanOrEqual(0) + ->and($state['starvation'])->toBe(['food_empty_at' => null, 'since' => null, 'desertion_at' => null]) + ->and(GameEvent::whereIn('type', [GameEvent::FOOD_RUNS_OUT, GameEvent::DESERTION])->whereNull('processed_at')->count())->toBe(0); +}); + +it('stops the grace timer as soon as income covers upkeep again', function () { + // Drafting every villager leaves the farm empty; with little food it runs out fast. + $village = startVillage(); + $village->update(['food' => 50]); + app(Levy::class)(owner($village), $village->id, 24); + + $this->travel(3)->hours(); + $this->artisan('game:events --once')->assertSuccessful(); + expect(shown($village)['starvation']['since'])->not->toBeNull(); + + app(EndLevy::class)(owner($village), $village->id); + expect(shown($village)['starvation'])->toMatchArray(['since' => null, 'desertion_at' => null]) + ->and(GameEvent::where('type', GameEvent::DESERTION)->whereNull('processed_at')->count())->toBe(0); +}); + +it('ends the levy when no soldiers are left to desert', function () { + $village = startVillage(); + World::whereKey($village->world_id)->update(['config' => ['economy' => ['levy' => ['duration' => 48 * 3600]]]]); + $village->update(['food' => 50]); + app(Levy::class)(owner($village), $village->id, 24); + + $this->travel(3)->hours(); + $this->artisan('game:events --once')->assertSuccessful(); + $this->travel(1)->days(); + $this->artisan('game:events --once')->assertSuccessful(); + + $state = shown($village); + expect($state['levy'])->toMatchArray(['militia' => 0, 'until' => null]) + ->and($state['starvation']['since'])->toBeNull(); +}); diff --git a/tests/Unit/Game/ConfigLintTest.php b/tests/Unit/Game/ConfigLintTest.php index 34ee54c..590959b 100644 --- a/tests/Unit/Game/ConfigLintTest.php +++ b/tests/Unit/Game/ConfigLintTest.php @@ -52,3 +52,12 @@ it('reports a villager share that leaves no food surplus', function () { expect(ConfigLint::check(gameConfig(['economy' => ['villager_share' => 1.0]]))) ->toBe(['economy.villager_share must be between 0 and 1 (is 1), so farms leave a surplus.']); }); + +it('reports a levy or desertion timer that never runs out', function () { + $config = gameConfig(['economy' => ['levy' => ['duration' => 0], 'starvation' => ['grace' => -1]]]); + + expect(ConfigLint::check($config))->toBe([ + '[economy.levy.duration] must be more than 0 seconds.', + '[economy.starvation.grace] cannot be negative.', + ]); +});