feat: starvation: food zero-crossing event, grace timer, desertion waves

Starvation::sync() runs after every mutation and event: it keeps food.runs_out at
the moment the stock hits 0, starts the grace timer once the village starves and
stops it when income covers upkeep again. Each desertion wave takes the fewest
soldiers, highest upkeep first, that feed the rest; then the levy ends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-28 22:03:33 +01:00
parent 458ae1bfd6
commit 93e9b09c5c
13 changed files with 348 additions and 5 deletions

View File

@ -5,6 +5,7 @@ namespace App\Actions;
use App\Engine\Engine; use App\Engine\Engine;
use App\Engine\Military; use App\Engine\Military;
use App\Engine\Simulation; use App\Engine\Simulation;
use App\Engine\Starvation;
use App\Game\GameRuleViolation; use App\Game\GameRuleViolation;
use App\Models\Building; use App\Models\Building;
use App\Models\User; use App\Models\User;
@ -33,6 +34,7 @@ abstract class VillageAction
$sim->settle($now); $sim->settle($now);
Military::of($village, $sim)->settle($now); Military::of($village, $sim)->settle($now);
$change($sim, $village, $now); $change($sim, $village, $now);
Starvation::of($village, $sim)->sync($now);
$village->save(); $village->save();
return $village; return $village;

View File

@ -66,6 +66,7 @@ final class Engine
} }
$event->update(['processed_at' => $now]); $event->update(['processed_at' => $now]);
$this->handle($village, $event); $this->handle($village, $event);
Starvation::of($village)->sync($event->fire_at);
$village->save(); $village->save();
return true; return true;
@ -87,6 +88,9 @@ final class Engine
GameEvent::BARBARIAN_GROWS => $this->growBarbarian($village, $event), GameEvent::BARBARIAN_GROWS => $this->growBarbarian($village, $event),
GameEvent::RECRUIT_FINISHED => Military::of($village)->settle($event->fire_at), GameEvent::RECRUIT_FINISHED => Military::of($village)->settle($event->fire_at),
GameEvent::LEVY_ENDS => Military::of($village)->endLevy($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),
}; };
} }

169
app/Engine/Starvation.php Normal file
View File

@ -0,0 +1,169 @@
<?php
namespace App\Engine;
use App\Game\Military\UnitRules;
use App\Models\GameEvent;
use App\Models\UnitStack;
use App\Models\Village;
use Carbon\CarbonImmutable;
/**
* Food running out and what follows (architecture.md, "Starvation"). sync() runs after
* every mutation and event: it keeps a food.runs_out event at the moment the stock
* hits 0, starts the grace timer once the village starves, and stops it as soon as
* income covers upkeep again. wave() is one desertion wave.
*/
final class Starvation
{
/** Food at or below this counts as none, so float rest can't hold off starvation. */
private const EMPTY = 0.001;
private function __construct(private readonly Village $village, private readonly Simulation $sim) {}
public static function of(Village $village, ?Simulation $sim = null): self
{
return new self($village, $sim ?? Simulation::of($village));
}
public function sync(CarbonImmutable $at): void
{
$this->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<string, int> 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,
]);
}
}

View File

@ -23,9 +23,26 @@ final class ConfigLint
...self::costsFitStorage($config, $rules), ...self::costsFitStorage($config, $rules),
...self::requirementsReachable($config, $rules), ...self::requirementsReachable($config, $rules),
...self::unitsTrainable($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 * 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. * type must fit next to them, or it could never be built.

View File

@ -16,6 +16,10 @@ class GameEvent extends Model
public const LEVY_ENDS = 'levy.ends'; public const LEVY_ENDS = 'levy.ends';
public const FOOD_RUNS_OUT = 'food.runs_out';
public const DESERTION = 'starvation.desertion';
protected $guarded = []; protected $guarded = [];
protected $dateFormat = 'Y-m-d H:i:s.v'; protected $dateFormat = 'Y-m-d H:i:s.v';

View File

@ -23,6 +23,7 @@ class Village extends Model
'resources_at' => 'immutable_datetime', 'resources_at' => 'immutable_datetime',
'militia' => 'integer', 'militia' => 'integer',
'levy_until' => 'immutable_datetime', 'levy_until' => 'immutable_datetime',
'starving_since' => 'immutable_datetime',
]; ];
} }

View File

@ -4,6 +4,7 @@ namespace App\Presenters;
use App\Engine\Military; use App\Engine\Military;
use App\Engine\Simulation; use App\Engine\Simulation;
use App\Engine\Starvation;
use App\Game\Map\Continent; use App\Game\Map\Continent;
use App\Models\Building; use App\Models\Building;
use App\Models\BuildOrder; use App\Models\BuildOrder;
@ -22,6 +23,7 @@ final class VillagePresenter
$sim = Simulation::of($village); $sim = Simulation::of($village);
$sim->settle($now); $sim->settle($now);
$military = Military::of($village, $sim); $military = Military::of($village, $sim);
$starvation = Starvation::of($village, $sim);
$troops = $military->troopsAtHome(); $troops = $military->troopsAtHome();
$workforce = $sim->workforce(); $workforce = $sim->workforce();
$rules = $sim->rules(); $rules = $sim->rules();
@ -50,10 +52,17 @@ final class VillagePresenter
], ],
'levy' => [ 'levy' => [
'militia' => $workforce->militia, '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. // How long a new levy would last.
'seconds' => $military->levySeconds(), '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, 'troops' => (object) $troops,
'military' => self::military($village, $military, $now), 'military' => self::military($village, $military, $now),
'builders' => $sim->builders(), 'builders' => $sim->builders(),
@ -140,4 +149,9 @@ final class VillagePresenter
{ {
return $at->utc()->format('Y-m-d\TH:i:s.v\Z'); 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;
}
} }

View File

@ -27,4 +27,9 @@ return [
// Levy: villagers drafted as militia stop working for this long (seconds at world // 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. // speed 1), then return to work on their own. One levy at a time; it can end early.
'levy' => ['duration' => 6 * 3600], '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],
]; ];

View File

@ -0,0 +1,23 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('villages', function (Blueprint $table) {
// Set while the food stock is empty and upkeep exceeds income: the grace timer.
$table->dateTime('starving_since', 3)->nullable()->after('levy_until');
});
}
public function down(): void
{
Schema::table('villages', function (Blueprint $table) {
$table->dropColumn('starving_since');
});
}
};

View File

@ -67,7 +67,9 @@ Each village has `builders` (default 2, +1 at the HQ levels listed in world conf
### Starvation ### 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 ## 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. | | 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. | | 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. | | 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. | | 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. | | 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. | | All merchants killed | Merchants are trained at the market like units, so dead merchants can always be replaced. |

View File

@ -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] 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] Recruiting turns villagers into soldiers; lazy per-unit completion
- [x] Levy: draft workers as militia, automatic return - [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 - [ ] UI: recruit forms, troops overview, food balance warnings
## M4: Attacks, combat, looting ## 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 - [ ] `TravelTime` (slowest unit, distance, unit speed, travel mode) with unit tests
- [ ] Travel modes from `movement.php`; warning time from visibility and detection radius; watchtower - [ ] 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 - [ ] 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 - [ ] Reports
- [ ] Incoming-attack push and UI - [ ] Incoming-attack push and UI

View File

@ -0,0 +1,93 @@
<?php
use App\Actions\EndLevy;
use App\Actions\Levy;
use App\Models\GameEvent;
use App\Models\Village;
use App\Models\World;
use Carbon\CarbonImmutable;
beforeEach(fn () => $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();
});

View File

@ -52,3 +52,12 @@ it('reports a villager share that leaves no food surplus', function () {
expect(ConfigLint::check(gameConfig(['economy' => ['villager_share' => 1.0]]))) 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.']); ->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.',
]);
});