feat: levy: draft villagers as militia for a fixed time, back to work on their own
Drafted villagers still eat but stop working; recruiting trains only undrafted ones. A levy.ends event settles the village and sends them back; village.endLevy ends it early. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8fa7e9b649
commit
458ae1bfd6
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Engine\Military;
|
||||
use App\Engine\Simulation;
|
||||
use App\Game\GameRuleViolation;
|
||||
use App\Models\User;
|
||||
use App\Models\Village;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/** Send the militia back to work before the levy runs out. */
|
||||
final class EndLevy extends VillageAction
|
||||
{
|
||||
public function __invoke(User $user, int $villageId): Village
|
||||
{
|
||||
return $this->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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Engine\Military;
|
||||
use App\Engine\Simulation;
|
||||
use App\Models\User;
|
||||
use App\Models\Village;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/** Draft villagers as militia for the world's levy duration. */
|
||||
final class Levy extends VillageAction
|
||||
{
|
||||
public function __invoke(User $user, int $villageId, int $count): Village
|
||||
{
|
||||
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($count) {
|
||||
Military::of($village, $sim)->levy($count, $now);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -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),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -39,13 +39,15 @@ final class Population
|
|||
/**
|
||||
* @param list<BuildingState> $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,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -21,6 +21,8 @@ class Village extends Model
|
|||
'iron' => 'float',
|
||||
'food' => 'float',
|
||||
'resources_at' => 'immutable_datetime',
|
||||
'militia' => 'integer',
|
||||
'levy_until' => 'immutable_datetime',
|
||||
];
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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(),
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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],
|
||||
];
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
<?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) {
|
||||
// Villagers drafted as militia until levy_until; they stop working meanwhile.
|
||||
$table->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']);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -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) |
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,74 @@
|
|||
<?php
|
||||
|
||||
use App\Actions\EndLevy;
|
||||
use App\Actions\Levy;
|
||||
use App\Actions\Recruit;
|
||||
use App\Models\GameEvent;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
beforeEach(fn () => $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);
|
||||
});
|
||||
|
|
@ -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 = [
|
||||
|
|
|
|||
Loading…
Reference in New Issue