diff --git a/app/Actions/CancelRecruit.php b/app/Actions/CancelRecruit.php new file mode 100644 index 0000000..502c00c --- /dev/null +++ b/app/Actions/CancelRecruit.php @@ -0,0 +1,23 @@ +mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($orderId) { + $order = $village->recruits->firstWhere('id', $orderId) + ?? throw new GameRuleViolation('not_found', 'Order not found.'); + Military::of($village, $sim)->cancel($order, $now); + }); + } +} diff --git a/app/Actions/Recruit.php b/app/Actions/Recruit.php new file mode 100644 index 0000000..19d8218 --- /dev/null +++ b/app/Actions/Recruit.php @@ -0,0 +1,20 @@ +mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($buildingId, $unit, $count) { + Military::of($village, $sim)->recruit($this->building($village, $buildingId), $unit, $count, $now); + }); + } +} diff --git a/app/Actions/ShowVillage.php b/app/Actions/ShowVillage.php index d13845a..1d5d7ce 100644 --- a/app/Actions/ShowVillage.php +++ b/app/Actions/ShowVillage.php @@ -2,21 +2,14 @@ namespace App\Actions; -use App\Game\GameRuleViolation; use App\Models\User; use App\Models\Village; +/** The village as it is now; units trained since the last look are settled into it. */ final class ShowVillage extends VillageAction { public function __invoke(User $user, int $villageId): Village { - $this->engine->catchUp($villageId, now()->toImmutable()); - - $village = Village::with('player')->find($villageId); - if (! $village || $village->player?->user_id !== $user->id) { - throw new GameRuleViolation('not_found', 'Village not found.'); - } - - return $village; + return $this->mutate($user, $villageId, fn () => null); } } diff --git a/app/Actions/VillageAction.php b/app/Actions/VillageAction.php index d002b54..80df30a 100644 --- a/app/Actions/VillageAction.php +++ b/app/Actions/VillageAction.php @@ -3,6 +3,7 @@ namespace App\Actions; use App\Engine\Engine; +use App\Engine\Military; use App\Engine\Simulation; use App\Game\GameRuleViolation; use App\Models\Building; @@ -30,6 +31,7 @@ abstract class VillageAction } $sim = Simulation::of($village); $sim->settle($now); + Military::of($village, $sim)->settle($now); $change($sim, $village, $now); $village->save(); diff --git a/app/Engine/Engine.php b/app/Engine/Engine.php index 1f660e1..5a7cb09 100644 --- a/app/Engine/Engine.php +++ b/app/Engine/Engine.php @@ -85,6 +85,7 @@ final class Engine match ($event->type) { 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), }; } diff --git a/app/Engine/Military.php b/app/Engine/Military.php new file mode 100644 index 0000000..cb39b5e --- /dev/null +++ b/app/Engine/Military.php @@ -0,0 +1,197 @@ +units = new UnitRules($sim->config()); + } + + public static function of(Village $village, ?Simulation $sim = null): self + { + return new self($village, $sim ?? Simulation::of($village)); + } + + public function units(): UnitRules + { + return $this->units; + } + + /** Move the units trained by $at from their queues into the village. */ + public function settle(CarbonImmutable $at): void + { + foreach ($this->village->recruits as $order) { + $done = $order->doneAt($at); + if ($done > $order->done) { + $this->addTroops($order->unit, $done - $order->done); + $order->done = $done; + } + if ($order->done >= $order->count) { + $this->drop($order); + } elseif ($order->isDirty()) { + $order->save(); + } + } + } + + /** @return array own units standing at home */ + public function troopsAtHome(): array + { + return $this->village->troops + ->where('home_village_id', $this->village->id) + ->mapWithKeys(fn (UnitStack $s) => [$s->unit => $s->count]) + ->filter() + ->all(); + } + + /** @return list */ + public function missingRequirements(string $unit): array + { + $missing = []; + foreach ($this->units->requires($unit) as $type => $level) { + if (! $this->village->buildings->where('type', $type)->where('level', '>=', $level)->count()) { + $missing[] = ['type' => $type, 'level' => $level]; + } + } + + return $missing; + } + + /** Most units of this type the village can pay for and spare villagers for now. */ + public function maxRecruitable(string $unit): int + { + $cost = $this->units->cost($unit); + $byResources = min(array_map( + 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)); + + return max(0, min($byResources, $byVillagers)); + } + + /** Seconds per unit at this building instance, from its level and staffing. */ + public function secondsPerUnit(Building $building, string $unit): int + { + $staffing = $this->sim->staffingFactor($this->sim->workforce()->ratio($building->id)); + + return $this->units->seconds($unit, $building->level, $staffing); + } + + /** Queue units at a military building. Pays up front; the villagers stop working at once. */ + public function recruit(Building $building, string $unit, int $count, CarbonImmutable $now): RecruitOrder + { + if (! $this->units->exists($unit) || $this->units->building($unit) !== $building->type) { + throw new GameRuleViolation('not_found', "This building cannot train [$unit]."); + } + if ($count < 1) { + throw new GameRuleViolation('count', 'Recruit at least one unit.'); + } + if ($this->missingRequirements($unit)) { + throw new GameRuleViolation('requires', 'Requirements not met.'); + } + if ($count * $this->units->upkeep($unit) > $this->sim->workforce()->villagers) { + throw new GameRuleViolation('villagers', 'Not enough villagers to train that many.'); + } + $this->sim->pay($this->units->cost($unit, $count)); + + $seconds = $this->secondsPerUnit($building, $unit); + $last = $this->village->recruits->where('building_id', $building->id)->last(); + $starts = $last && $last->finishes_at->greaterThan($now) ? $last->finishes_at : $now; + $order = $this->village->recruits()->create([ + 'building_id' => $building->id, + 'unit' => $unit, + 'count' => $count, + 'done' => 0, + 'seconds_per_unit' => $seconds, + 'cost' => $this->units->cost($unit), + 'starts_at' => $starts, + 'finishes_at' => $starts->addSeconds($seconds * $count), + ]); + $this->village->recruits->push($order); + $this->schedule($order); + + return $order; + } + + /** + * Cancel what is left of an order with a full refund for the untrained units, and + * move the later orders at the same building forward. + */ + public function cancel(RecruitOrder $order, CarbonImmutable $now): void + { + $this->settle($now); + if (! $this->village->recruits->contains($order)) { + return; + } + $this->sim->refund(array_map(fn (int $n) => $n * ($order->count - $order->done), $order->cost)); + $this->drop($order); + + // Orders queued after it at this building haven't started yet: they follow on + // from the one before it, or from now. + $queue = $this->village->recruits->where('building_id', $order->building_id); + $before = $queue->where('id', '<', $order->id)->last(); + $from = $before && $before->finishes_at->greaterThan($now) ? $before->finishes_at : $now; + foreach ($queue->where('id', '>', $order->id) as $later) { + $later->starts_at = $from; + $later->finishes_at = $from->addSeconds($later->seconds_per_unit * $later->count); + $later->save(); + $this->reschedule($later); + $from = $later->finishes_at; + } + } + + 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); + if ($stack) { + $stack->increment('count', $count); + + return; + } + $stack = $this->village->troops()->create(['home_village_id' => $this->village->id, 'unit' => $unit, 'count' => $count]); + $this->village->troops->push($stack); + } + + private function drop(RecruitOrder $order): void + { + GameEvent::where('type', GameEvent::RECRUIT_FINISHED)->where('subject_id', $order->id)->whereNull('processed_at')->delete(); + $order->delete(); + $this->village->setRelation('recruits', $this->village->recruits->reject(fn (RecruitOrder $o) => $o->is($order))->values()); + } + + private function schedule(RecruitOrder $order): void + { + GameEvent::create([ + 'world_id' => $this->village->world_id, + 'village_id' => $this->village->id, + 'type' => GameEvent::RECRUIT_FINISHED, + 'subject_id' => $order->id, + 'fire_at' => $order->finishes_at, + ]); + } + + private function reschedule(RecruitOrder $order): void + { + GameEvent::where('type', GameEvent::RECRUIT_FINISHED)->where('subject_id', $order->id)->whereNull('processed_at') + ->update(['fire_at' => Engine::stamp($order->finishes_at)]); + } +} diff --git a/app/Engine/Simulation.php b/app/Engine/Simulation.php index 8d0f1bd..8c0e37b 100644 --- a/app/Engine/Simulation.php +++ b/app/Engine/Simulation.php @@ -10,10 +10,13 @@ use App\Game\Economy\Production; use App\Game\Economy\Settle; use App\Game\Economy\Workforce; use App\Game\GameRuleViolation; +use App\Game\Military\UnitRules; use App\Game\WorldConfig; use App\Models\Building; use App\Models\BuildOrder; use App\Models\GameEvent; +use App\Models\RecruitOrder; +use App\Models\UnitStack; use App\Models\Village; use Carbon\CarbonImmutable; @@ -41,7 +44,7 @@ final class Simulation public static function of(Village $village): self { - return new self($village->loadMissing(['world', 'buildings', 'orders'])); + return new self($village->loadMissing(['world', 'buildings', 'orders', 'troops', 'recruits'])); } public function config(): WorldConfig @@ -64,7 +67,20 @@ final class Simulation public function workforce(): Workforce { - return $this->population->workforce($this->states()); + return $this->population->workforce($this->states(), $this->soldierUpkeep()); + } + + /** + * Food per hour eaten by troops standing here and by units still in training: a + * queued unit takes its villager's place at once. + */ + public function soldierUpkeep(): float + { + $units = new UnitRules($this->config); + $standing = $this->village->troops->mapWithKeys(fn (UnitStack $s) => [$s->id => $units->upkeep($s->unit) * $s->count])->sum(); + $training = $this->village->recruits->sum(fn (RecruitOrder $o) => $units->upkeep($o->unit) * ($o->count - $o->done)); + + return $standing + $training; } /** @return array{wood: float, clay: float, iron: float, food: float} */ @@ -349,6 +365,12 @@ final class Simulation } $building->level = $order->target_level; if ($building->level < 0) { + // Units still in training there go back to being villagers, with a refund. + foreach ($this->village->recruits->where('building_id', $building->id) as $order) { + $this->refund(array_map(fn (int $n) => $n * ($order->count - $order->done), $order->cost)); + GameEvent::where('type', GameEvent::RECRUIT_FINISHED)->where('subject_id', $order->id)->whereNull('processed_at')->delete(); + } + $this->village->setRelation('recruits', $this->village->recruits->reject(fn (RecruitOrder $o) => $o->building_id === $building->id)->values()); $building->delete(); $this->village->setRelation('buildings', $this->village->buildings->reject(fn (Building $b) => $b->is($building))->values()); } else { diff --git a/app/Game/ConfigLint.php b/app/Game/ConfigLint.php index 98408a3..3488079 100644 --- a/app/Game/ConfigLint.php +++ b/app/Game/ConfigLint.php @@ -3,6 +3,7 @@ namespace App\Game; use App\Game\Buildings\BuildingRules; +use App\Game\Military\UnitRules; /** * Proves a world config has no locks (architecture.md, "No locks"). @@ -21,6 +22,7 @@ final class ConfigLint ...self::farmsFeedTheirWorkers($config, $rules), ...self::costsFitStorage($config, $rules), ...self::requirementsReachable($config, $rules), + ...self::unitsTrainable($config, $rules), ]; } @@ -116,6 +118,32 @@ final class ConfigLint } /** Requirements name real types and levels, and have no cycles. */ + /** Every unit has a real building to train at, reachable requirements, and a cost storage can hold. */ + private static function unitsTrainable(WorldConfig $config, BuildingRules $rules): array + { + $units = new UnitRules($config); + $maxCap = max(array_map(fn (string $t) => $rules->capacity($t, $rules->maxLevel($t)), $config->buildingTypes())); + $problems = []; + foreach ($units->units() as $unit) { + if (! $config->hasBuilding($units->building($unit))) { + $problems[] = "[$unit] is trained at unknown building [{$units->building($unit)}]."; + } + foreach ($units->requires($unit) as $type => $level) { + if (! $config->hasBuilding($type) || $level > $rules->maxLevel($type)) { + $problems[] = "[$unit] requires [$type] level $level, which can't be built."; + } + } + if (max($units->cost($unit)) > $maxCap) { + $problems[] = "[$unit] costs more than the largest storage holds."; + } + if ($units->upkeep($unit) <= 0) { + $problems[] = "[$unit] must eat food (upkeep > 0), or armies grow without limit."; + } + } + + return $problems; + } + private static function requirementsReachable(WorldConfig $config, BuildingRules $rules): array { $problems = []; diff --git a/app/Game/Military/UnitRules.php b/app/Game/Military/UnitRules.php new file mode 100644 index 0000000..3d63ba4 --- /dev/null +++ b/app/Game/Military/UnitRules.php @@ -0,0 +1,86 @@ + */ + public function units(): array + { + return array_keys($this->config->get('units', [])); + } + + public function exists(string $unit): bool + { + return array_key_exists($unit, $this->config->get('units', [])); + } + + /** @return list units trained at this building type */ + public function trainedAt(string $buildingType): array + { + return array_values(array_filter($this->units(), fn (string $u) => $this->unit($u)['building'] === $buildingType)); + } + + public function building(string $unit): string + { + return $this->unit($unit)['building']; + } + + /** @return array{wood: int, clay: int, iron: int} */ + public function cost(string $unit, int $count = 1): array + { + return array_map(fn (int $n) => $n * $count, $this->unit($unit)['cost']); + } + + /** Food per hour one unit eats. */ + public function upkeep(string $unit): float + { + return (float) $this->unit($unit)['upkeep']; + } + + /** + * Seconds to train one unit, at world speed, sped up by the training building's + * level and slowed by its staffing (output factor 0..1). + */ + public function seconds(string $unit, int $buildingLevel, float $staffing): int + { + $seconds = $this->unit($unit)['build_time'] + / $this->config->speed() + / (1 + $this->config->get('economy.recruit_speed_per_level', 0) * $buildingLevel) + / max($staffing, 0.01); + + return max(1, (int) ceil($seconds)); + } + + /** @return array building type => minimum level of any instance */ + public function requires(string $unit): array + { + return $this->unit($unit)['requires'] ?? []; + } + + /** + * Food per hour these troops eat. + * + * @param array $counts unit => count + */ + public function upkeepOf(array $counts): float + { + $total = 0.0; + foreach ($counts as $unit => $n) { + $total += $this->upkeep($unit) * $n; + } + + return $total; + } + + /** @return array */ + private function unit(string $unit): array + { + return $this->config->get("units.$unit") ?? throw new \InvalidArgumentException("Unknown unit [$unit]."); + } +} diff --git a/app/Models/GameEvent.php b/app/Models/GameEvent.php index 1b4506d..356468f 100644 --- a/app/Models/GameEvent.php +++ b/app/Models/GameEvent.php @@ -12,6 +12,8 @@ class GameEvent extends Model public const BARBARIAN_GROWS = 'barbarian.grows'; + public const RECRUIT_FINISHED = 'recruit.finished'; + protected $guarded = []; protected $dateFormat = 'Y-m-d H:i:s.v'; diff --git a/app/Models/RecruitOrder.php b/app/Models/RecruitOrder.php new file mode 100644 index 0000000..c11676f --- /dev/null +++ b/app/Models/RecruitOrder.php @@ -0,0 +1,42 @@ + 'integer', + 'done' => 'integer', + 'seconds_per_unit' => 'integer', + 'cost' => 'array', + 'starts_at' => 'immutable_datetime', + 'finishes_at' => 'immutable_datetime', + ]; + } + + /** Units trained by $at, never more than ordered. */ + public function doneAt(CarbonImmutable $at): int + { + if ($at->lessThan($this->starts_at)) { + return 0; + } + $elapsed = ($at->getTimestampMs() - $this->starts_at->getTimestampMs()) / 1000; + + return min($this->count, (int) floor($elapsed / $this->seconds_per_unit)); + } + + public function building(): BelongsTo + { + return $this->belongsTo(Building::class); + } +} diff --git a/app/Models/UnitStack.php b/app/Models/UnitStack.php new file mode 100644 index 0000000..8c6ea73 --- /dev/null +++ b/app/Models/UnitStack.php @@ -0,0 +1,22 @@ + 'integer']; + } + + public function village(): BelongsTo + { + return $this->belongsTo(Village::class); + } +} diff --git a/app/Models/Village.php b/app/Models/Village.php index aa38133..bb5e7a9 100644 --- a/app/Models/Village.php +++ b/app/Models/Village.php @@ -45,6 +45,18 @@ class Village extends Model return $this->hasMany(BuildOrder::class)->orderBy('id'); } + /** Troops standing here, own and (from M4) supporting. */ + public function troops(): HasMany + { + return $this->hasMany(UnitStack::class)->orderBy('id'); + } + + /** Recruiting queues of all military buildings, in queue order. */ + public function recruits(): HasMany + { + return $this->hasMany(RecruitOrder::class)->orderBy('id'); + } + /** @return array{wood: float, clay: float, iron: float, food: float} */ public function resources(): array { diff --git a/app/Models/World.php b/app/Models/World.php index b248a17..fdbeac8 100644 --- a/app/Models/World.php +++ b/app/Models/World.php @@ -26,6 +26,7 @@ class World extends Model 'world' => config('game.world'), 'economy' => config('game.economy'), 'buildings' => config('game.buildings'), + 'units' => config('game.units'), ], $this->config ?? []); } diff --git a/app/Presenters/VillagePresenter.php b/app/Presenters/VillagePresenter.php index 8d13d8f..c3cb871 100644 --- a/app/Presenters/VillagePresenter.php +++ b/app/Presenters/VillagePresenter.php @@ -2,10 +2,12 @@ namespace App\Presenters; +use App\Engine\Military; use App\Engine\Simulation; use App\Game\Map\Continent; use App\Models\Building; use App\Models\BuildOrder; +use App\Models\RecruitOrder; use App\Models\Village; use Carbon\CarbonImmutable; @@ -19,6 +21,8 @@ final class VillagePresenter { $sim = Simulation::of($village); $sim->settle($now); + $military = Military::of($village, $sim); + $troops = $military->troopsAtHome(); $workforce = $sim->workforce(); $rules = $sim->rules(); $position = 0; @@ -41,8 +45,11 @@ final class VillagePresenter 'upkeep' => round($workforce->upkeep, 2), 'villagers' => $workforce->villagers, 'workers' => $workforce->workers(), - 'soldiers' => 0, + 'soldiers' => array_sum($troops), + 'training' => $village->recruits->sum(fn (RecruitOrder $o) => $o->count - $o->done), ], + 'troops' => (object) $troops, + 'military' => self::military($village, $military, $now), 'builders' => $sim->builders(), 'buildings' => $village->buildings->map(function (Building $b) use ($sim, $workforce, $rules) { $output = $sim->output($b, $workforce); @@ -78,6 +85,51 @@ final class VillagePresenter ]; } + /** + * Every building that trains units: what it can train (with cost, time, upkeep, how + * many fit now, and missing requirements) and its own queue. + */ + private static function military(Village $village, Military $military, CarbonImmutable $now): array + { + $units = $military->units(); + $out = []; + foreach ($village->buildings as $b) { + $trainable = $units->trainedAt($b->type); + if (! $trainable) { + continue; + } + $out[] = [ + 'building_id' => $b->id, + 'type' => $b->type, + 'level' => $b->level, + 'units' => array_map(function (string $unit) use ($military, $units, $b) { + $missing = $military->missingRequirements($unit); + + return [ + 'unit' => $unit, + 'cost' => $units->cost($unit), + 'seconds' => $military->secondsPerUnit($b, $unit), + 'upkeep' => $units->upkeep($unit), + 'max' => $missing ? 0 : $military->maxRecruitable($unit), + 'blocked' => $missing ? 'requires' : null, + 'requires' => $missing, + ]; + }, $trainable), + 'queue' => $village->recruits->where('building_id', $b->id)->map(fn (RecruitOrder $o) => [ + 'id' => $o->id, + 'unit' => $o->unit, + 'count' => $o->count, + 'done' => $o->doneAt($now), + 'seconds_per_unit' => $o->seconds_per_unit, + 'starts_at' => self::iso($o->starts_at), + 'finishes_at' => self::iso($o->finishes_at), + ])->values()->all(), + ]; + } + + return $out; + } + private static function iso(CarbonImmutable $at): string { return $at->utc()->format('Y-m-d\TH:i:s.v\Z'); diff --git a/app/Websocket/Controllers/VillageController.php b/app/Websocket/Controllers/VillageController.php index 23c1a7b..dd49dee 100644 --- a/app/Websocket/Controllers/VillageController.php +++ b/app/Websocket/Controllers/VillageController.php @@ -3,9 +3,11 @@ namespace App\Websocket\Controllers; use App\Actions\CancelOrder; +use App\Actions\CancelRecruit; use App\Actions\QueueBuild; use App\Actions\QueueDemolish; use App\Actions\QueueUpgrade; +use App\Actions\Recruit; use App\Actions\SetPriority; use App\Actions\ShowVillage; use App\Models\User; @@ -14,7 +16,7 @@ use App\Presenters\VillagePresenter; use App\Websocket\GameController; use Closure; -/** village.show|build|upgrade|demolish|cancel|staff. Each answers with the fresh village state. */ +/** village.show|build|upgrade|demolish|cancel|staff|recruit|cancelRecruit. Each answers with the fresh village state. */ class VillageController extends GameController { public function show() @@ -47,6 +49,22 @@ class VillageController extends GameController return $this->village(fn ($user, $id) => app(SetPriority::class)($user, $id, (int) request('building_id'), (int) request('priority'))); } + public function recruit() + { + return $this->village(fn ($user, $id) => app(Recruit::class)( + $user, + $id, + (int) request('building_id'), + (string) request('unit'), + (int) request('count'), + )); + } + + public function cancelRecruit() + { + return $this->village(fn ($user, $id) => app(CancelRecruit::class)($user, $id, (int) request('order_id'))); + } + /** @param Closure(User, int): Village $action */ private function village(Closure $action) { diff --git a/config/game/buildings.php b/config/game/buildings.php index 40ad8a8..4912fa5 100644 --- a/config/game/buildings.php +++ b/config/game/buildings.php @@ -118,4 +118,56 @@ return [ 'points' => ['base' => 2, 'factor' => 1.2], 'requires' => [], ], + + // Military buildings. Each instance runs its own recruiting queue; its level and + // staffing speed up training there (economy.recruit_speed_per_level). + 'barracks' => [ + 'space' => 6, + 'max_per_village' => null, + 'max_level' => 25, + 'cost' => ['wood' => 200, 'clay' => 170, 'iron' => 90, 'factor' => 1.26], + 'build_time' => ['base' => 600, 'factor' => 1.2], + 'workers' => ['base' => 3, 'factor' => 1.1], + 'production' => null, + 'instance_cost_factor' => 1.5, + 'points' => ['base' => 16, 'factor' => 1.2], + 'requires' => [], + ], + 'stable' => [ + 'space' => 6, + 'max_per_village' => null, + 'max_level' => 20, + 'cost' => ['wood' => 270, 'clay' => 240, 'iron' => 260, 'factor' => 1.26], + 'build_time' => ['base' => 1200, 'factor' => 1.2], + 'workers' => ['base' => 3, 'factor' => 1.1], + 'production' => null, + 'instance_cost_factor' => 1.5, + 'points' => ['base' => 20, 'factor' => 1.2], + 'requires' => ['barracks' => 3], + ], + 'workshop' => [ + 'space' => 6, + 'max_per_village' => null, + 'max_level' => 15, + 'cost' => ['wood' => 300, 'clay' => 240, 'iron' => 260, 'factor' => 1.26], + 'build_time' => ['base' => 1800, 'factor' => 1.2], + 'workers' => ['base' => 4, 'factor' => 1.1], + 'production' => null, + 'instance_cost_factor' => 1.5, + 'points' => ['base' => 24, 'factor' => 1.2], + 'requires' => ['barracks' => 5], + ], + // The Adelshof: trains noblemen. The one advanced building with real requirements. + 'academy' => [ + 'space' => 9, + 'max_per_village' => 1, + 'max_level' => 3, + 'cost' => ['wood' => 15000, 'clay' => 25000, 'iron' => 10000, 'factor' => 2.0], + 'build_time' => ['base' => 5400, 'factor' => 1.5], + 'workers' => ['base' => 5, 'factor' => 1.2], + 'production' => null, + 'instance_cost_factor' => 1.0, + 'points' => ['base' => 512, 'factor' => 1.2], + 'requires' => ['headquarters' => 5, 'barracks' => 1], + ], ]; diff --git a/config/game/economy.php b/config/game/economy.php index aa7d2c4..ee909fc 100644 --- a/config/game/economy.php +++ b/config/game/economy.php @@ -20,4 +20,7 @@ return [ // Each headquarters level makes building this much faster (time / (1 + x·level)). 'hq_build_speed_per_level' => 0.05, + + // Each level of a military building makes training there this much faster. + 'recruit_speed_per_level' => 0.05, ]; diff --git a/config/game/units.php b/config/game/units.php new file mode 100644 index 0000000..e42189b --- /dev/null +++ b/config/game/units.php @@ -0,0 +1,105 @@ + [ + 'building' => 'barracks', + 'cost' => ['wood' => 50, 'clay' => 30, 'iron' => 10], + 'upkeep' => 1, + 'build_time' => 1020, + 'attack' => 10, + 'defense' => ['infantry' => 15, 'cavalry' => 45, 'archer' => 20], + 'class' => 'infantry', + 'speed' => 18, + 'carry' => 25, + 'requires' => [], + ], + 'sword' => [ + 'building' => 'barracks', + 'cost' => ['wood' => 30, 'clay' => 30, 'iron' => 70], + 'upkeep' => 1, + 'build_time' => 1500, + 'attack' => 25, + 'defense' => ['infantry' => 50, 'cavalry' => 15, 'archer' => 40], + 'class' => 'infantry', + 'speed' => 22, + 'carry' => 15, + 'requires' => [], + ], + 'archer' => [ + 'building' => 'barracks', + 'cost' => ['wood' => 100, 'clay' => 30, 'iron' => 60], + 'upkeep' => 1, + 'build_time' => 1800, + 'attack' => 15, + 'defense' => ['infantry' => 50, 'cavalry' => 40, 'archer' => 5], + 'class' => 'archer', + 'speed' => 18, + 'carry' => 10, + 'requires' => ['barracks' => 3], + ], + 'light_cavalry' => [ + 'building' => 'stable', + 'cost' => ['wood' => 125, 'clay' => 100, 'iron' => 250], + 'upkeep' => 3, + 'build_time' => 1800, + 'attack' => 130, + 'defense' => ['infantry' => 30, 'cavalry' => 40, 'archer' => 30], + 'class' => 'cavalry', + 'speed' => 10, + 'carry' => 80, + 'requires' => [], + ], + 'heavy_cavalry' => [ + 'building' => 'stable', + 'cost' => ['wood' => 200, 'clay' => 150, 'iron' => 600], + 'upkeep' => 4, + 'build_time' => 3600, + 'attack' => 150, + 'defense' => ['infantry' => 200, 'cavalry' => 80, 'archer' => 180], + 'class' => 'cavalry', + 'speed' => 11, + 'carry' => 50, + 'requires' => ['stable' => 5], + ], + 'ram' => [ + 'building' => 'workshop', + 'cost' => ['wood' => 300, 'clay' => 200, 'iron' => 200], + 'upkeep' => 4, + 'build_time' => 4800, + 'attack' => 2, + 'defense' => ['infantry' => 20, 'cavalry' => 50, 'archer' => 20], + 'class' => 'infantry', + 'speed' => 30, + 'carry' => 0, + 'requires' => [], + ], + 'catapult' => [ + 'building' => 'workshop', + 'cost' => ['wood' => 320, 'clay' => 400, 'iron' => 100], + 'upkeep' => 6, + 'build_time' => 7200, + 'attack' => 100, + 'defense' => ['infantry' => 100, 'cavalry' => 50, 'archer' => 100], + 'class' => 'infantry', + 'speed' => 30, + 'carry' => 0, + 'requires' => ['workshop' => 2], + ], + 'nobleman' => [ + 'building' => 'academy', + 'cost' => ['wood' => 40000, 'clay' => 50000, 'iron' => 50000], + 'upkeep' => 10, + 'build_time' => 10800, + 'attack' => 30, + 'defense' => ['infantry' => 100, 'cavalry' => 50, 'archer' => 100], + 'class' => 'infantry', + 'speed' => 35, + 'carry' => 0, + 'requires' => [], + ], +]; diff --git a/database/migrations/2026_10_29_120000_create_military_tables.php b/database/migrations/2026_10_29_120000_create_military_tables.php new file mode 100644 index 0000000..aab6675 --- /dev/null +++ b/database/migrations/2026_10_29_120000_create_military_tables.php @@ -0,0 +1,45 @@ +id(); + $table->foreignId('village_id')->constrained()->cascadeOnDelete(); + $table->foreignId('home_village_id')->constrained('villages')->cascadeOnDelete(); + $table->string('unit', 32); + $table->unsignedInteger('count')->default(0); + $table->timestamps(); + $table->unique(['village_id', 'home_village_id', 'unit']); + }); + + // One queue per military building instance. Times are fixed when queued, so units + // arrive lazily: done = floor((now − starts_at) / seconds_per_unit). + Schema::create('recruit_orders', function (Blueprint $table) { + $table->id(); + $table->foreignId('village_id')->constrained()->cascadeOnDelete(); + $table->foreignId('building_id')->constrained()->cascadeOnDelete(); + $table->string('unit', 32); + $table->unsignedInteger('count'); + $table->unsignedInteger('done')->default(0); + $table->unsignedInteger('seconds_per_unit'); + // Per unit, refunded for the ones not trained when cancelled. + $table->json('cost'); + $table->dateTime('starts_at', 3); + $table->dateTime('finishes_at', 3); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('recruit_orders'); + Schema::dropIfExists('unit_stacks'); + } +}; diff --git a/docs/architecture.md b/docs/architecture.md index d21507b..94517f4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -83,6 +83,15 @@ When upkeep exceeds income, food stock drains. The engine computes the exact mom 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. diff --git a/docs/roadmap.md b/docs/roadmap.md index fd0ba20..a842346 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -30,9 +30,9 @@ Each milestone ends with tests green, `ConfigLint` green, and something playable ## M3: Units, upkeep, starvation -- [ ] `config/game/units.php`: spear, sword, archer, light cav, heavy cav, ram, catapult, nobleman, with food upkeep -- [ ] 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 -- [ ] Recruiting turns villagers into soldiers; lazy per-unit completion +- [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 - [ ] Starvation: zero-crossing event, grace timer, desertion order - [ ] UI: recruit forms, troops overview, food balance warnings diff --git a/tests/Feature/JoinWorldTest.php b/tests/Feature/JoinWorldTest.php index d35560a..b75b8af 100644 --- a/tests/Feature/JoinWorldTest.php +++ b/tests/Feature/JoinWorldTest.php @@ -57,7 +57,7 @@ it('shows a start village to its owner only', function () { ->and($state['continent'])->toBe(Continent::of($village->x, $village->y)) ->and($state['rates'])->toBe(['wood' => 5.0, 'clay' => 5.0, 'iron' => 5.0, 'food' => 6.0]) ->and($state['storage_cap'])->toEqual(1000) - ->and($state['population'])->toEqual(['food_budget' => 30, 'upkeep' => 24, 'villagers' => 24, 'workers' => 5, 'soldiers' => 0]) + ->and($state['population'])->toEqual(['food_budget' => 30, 'upkeep' => 24, 'villagers' => 24, 'workers' => 5, 'soldiers' => 0, 'training' => 0]) ->and($state['builders'])->toBe(2) ->and(collect($state['buildable'])->firstWhere('type', 'headquarters')['blocked'])->toBe('max_per_village') ->and(collect($state['buildable'])->firstWhere('type', 'wall')['blocked'])->toBeNull() diff --git a/tests/Feature/RecruitTest.php b/tests/Feature/RecruitTest.php new file mode 100644 index 0000000..68b20e8 --- /dev/null +++ b/tests/Feature/RecruitTest.php @@ -0,0 +1,122 @@ + $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00'))); + +/** A start village with a barracks at level 0 and a full storage. */ +function withBarracks(): array +{ + $village = startVillage(); + $barracks = $village->buildings()->create(['type' => 'barracks', 'level' => 0]); + $village->update(['wood' => 1000, 'clay' => 1000, 'iron' => 1000]); + + return [$village->fresh(), $barracks]; +} + +function barracksQueue(Village $village): array +{ + return collect(shown($village)['military'])->firstWhere('type', 'barracks')['queue']; +} + +it('turns villagers into units at once and trains them one by one', function () { + [$village, $barracks] = withBarracks(); + + app(Recruit::class)(owner($village), $village->id, $barracks->id, 'spear', 10); + $state = shown($village); + expect($state['resources']['wood'])->toBe(500.0) + ->and($state['population'])->toMatchArray(['villagers' => 14, 'upkeep' => 24, 'soldiers' => 0, 'training' => 10]) + ->and($state['rates']['food'])->toBe(6.0) + ->and(barracksQueue($village)[0])->toMatchArray([ + 'unit' => 'spear', 'count' => 10, 'done' => 0, 'seconds_per_unit' => 1020, + 'starts_at' => '2026-10-29T12:00:00.000Z', 'finishes_at' => '2026-10-29T14:50:00.000Z', + ]); + + $this->travel(1020 * 3 + 10)->seconds(); + $state = shown($village); + expect((array) $state['troops'])->toBe(['spear' => 3]) + ->and($state['population'])->toMatchArray(['soldiers' => 3, 'training' => 7, 'villagers' => 14]); + + $this->travel(2)->hours(); + $this->artisan('game:events --once')->assertSuccessful(); + $state = shown($village); + expect((array) $state['troops'])->toBe(['spear' => 10]) + ->and(barracksQueue($village))->toBe([]) + ->and(GameEvent::where('type', GameEvent::RECRUIT_FINISHED)->whereNull('processed_at')->count())->toBe(0); +}); + +it('refunds the untrained units when cancelled and gives the villagers back', function () { + [$village, $barracks] = withBarracks(); + app(Recruit::class)(owner($village), $village->id, $barracks->id, 'spear', 10); + + $this->travel(1020 * 2 + 5)->seconds(); + $order = barracksQueue($village)[0]['id']; + app(CancelRecruit::class)(owner($village), $village->id, $order); + + $state = shown($village); + expect((array) $state['troops'])->toBe(['spear' => 2]) + ->and($state['population'])->toMatchArray(['villagers' => 22, 'training' => 0]) + ->and($state['resources']['wood'])->toEqualWithDelta(500 + 8 * 50 + 5 * 2045 / 3600, 0.01) + ->and(barracksQueue($village))->toBe([]); +}); + +it('queues orders at one barracks one after another, and moves them up on cancel', function () { + [$village, $barracks] = withBarracks(); + app(Recruit::class)(owner($village), $village->id, $barracks->id, 'spear', 2); + app(Recruit::class)(owner($village), $village->id, $barracks->id, 'sword', 3); + + $queue = barracksQueue($village); + expect($queue[1]['starts_at'])->toBe($queue[0]['finishes_at']); + + app(CancelRecruit::class)(owner($village), $village->id, $queue[0]['id']); + expect(barracksQueue($village)[0])->toMatchArray(['unit' => 'sword', 'starts_at' => '2026-10-29T12:00:00.000Z']); +}); + +it('runs a queue per barracks, side by side', function () { + [$village, $first] = withBarracks(); + $second = $village->buildings()->create(['type' => 'barracks', 'level' => 0]); + + app(Recruit::class)(owner($village), $village->id, $first->id, 'spear', 2); + app(Recruit::class)(owner($village), $village->id, $second->id, 'spear', 2); + + $starts = collect(shown($village)['military'])->flatMap(fn ($m) => array_column($m['queue'], 'starts_at'))->all(); + expect($starts)->toBe(['2026-10-29T12:00:00.000Z', '2026-10-29T12:00:00.000Z']); +}); + +it('refuses missing requirements, too few villagers and the wrong building', function () { + [$village, $barracks] = withBarracks(); + $archer = collect(collect(shown($village)['military'])->firstWhere('type', 'barracks')['units'])->firstWhere('unit', 'archer'); + + expect($archer)->toMatchArray(['blocked' => 'requires', 'requires' => [['type' => 'barracks', 'level' => 3]], 'max' => 0]) + ->and(rule(fn () => app(Recruit::class)(owner($village), $village->id, $barracks->id, 'archer', 1)))->toBe('requires') + ->and(rule(fn () => app(Recruit::class)(owner($village), $village->id, $barracks->id, 'spear', 25)))->toBe('villagers') + ->and(rule(fn () => app(Recruit::class)(owner($village), $village->id, $barracks->id, 'light_cavalry', 1)))->toBe('not_found'); +}); + +it('says how many units fit, by resources and villagers', function () { + [$village] = withBarracks(); + $units = collect(collect(shown($village)['military'])->firstWhere('type', 'barracks')['units'])->keyBy('unit'); + + // 24 villagers, and 1000 wood / 50 = 20 spears, 1000 iron / 70 = 14 swords. + expect($units['spear']['max'])->toBe(20) + ->and($units['sword']['max'])->toBe(14); +}); + +it('sends units in training back to work, refunded, when their barracks is torn down', function () { + [$village, $barracks] = withBarracks(); + app(Recruit::class)(owner($village), $village->id, $barracks->id, 'spear', 4); + // Taking level 0 down removes it after 5 minutes, before the first spear (17 minutes) is done. + app(QueueDemolish::class)(owner($village), $village->id, $barracks->id); + + $this->travel(1)->hours(); + $state = shown($village); + expect(collect($state['buildings'])->firstWhere('type', 'barracks'))->toBeNull() + ->and($state['population']['training'])->toBe(0) + ->and((array) $state['troops'])->toBe([]) + ->and($state['population']['villagers'])->toBe(24); +}); diff --git a/tests/Pest.php b/tests/Pest.php index c82aa53..d7afd4a 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -27,6 +27,7 @@ function gameConfig(array $overrides = []): WorldConfig 'world' => require "$dir/world.php", 'economy' => require "$dir/economy.php", 'buildings' => require "$dir/buildings.php", + 'units' => require "$dir/units.php", ], $overrides); } diff --git a/tests/Unit/Game/ConfigLintTest.php b/tests/Unit/Game/ConfigLintTest.php index f40f8e1..34ee54c 100644 --- a/tests/Unit/Game/ConfigLintTest.php +++ b/tests/Unit/Game/ConfigLintTest.php @@ -42,7 +42,10 @@ it('reports start buildings that take more space than a village has', function ( it('reports a type that can never fit next to the start buildings', function () { $config = gameConfig(['world' => ['village' => ['space' => 25]]]); - expect(ConfigLint::check($config))->toBe(['[headquarters] does not fit next to the start buildings.']); + expect(ConfigLint::check($config))->toBe([ + '[headquarters] does not fit next to the start buildings.', + '[academy] does not fit next to the start buildings.', + ]); }); it('reports a villager share that leaves no food surplus', function () { diff --git a/tests/Unit/Game/UnitRulesTest.php b/tests/Unit/Game/UnitRulesTest.php new file mode 100644 index 0000000..2be6485 --- /dev/null +++ b/tests/Unit/Game/UnitRulesTest.php @@ -0,0 +1,38 @@ +trainedAt('barracks'))->toBe(['spear', 'sword', 'archer']) + ->and($units->trainedAt('stable'))->toBe(['light_cavalry', 'heavy_cavalry']) + ->and($units->trainedAt('academy'))->toBe(['nobleman']) + ->and($units->trainedAt('farm'))->toBe([]); +}); + +it('multiplies cost by count and sums upkeep', function () { + $units = new UnitRules(gameConfig()); + + expect($units->cost('spear', 10))->toBe(['wood' => 500, 'clay' => 300, 'iron' => 100]) + ->and($units->upkeepOf(['spear' => 10, 'heavy_cavalry' => 2, 'nobleman' => 1]))->toBe(10.0 + 8 + 10); +}); + +it('trains faster at a higher level and slower when understaffed', function () { + $units = new UnitRules(gameConfig()); + $fast = new UnitRules(gameConfig(['world' => ['speed' => 100]])); + + expect($units->seconds('spear', 0, 1.0))->toBe(1020) + ->and($units->seconds('spear', 10, 1.0))->toBe(680) + ->and($units->seconds('spear', 0, 0.5))->toBe(2040) + ->and($fast->seconds('spear', 0, 1.0))->toBe(11); +}); + +it('lints units that point at unknown buildings or eat nothing', function () { + $config = gameConfig(['units' => ['spear' => ['building' => 'tavern', 'upkeep' => 0]]]); + + expect(ConfigLint::check($config)) + ->toContain('[spear] is trained at unknown building [tavern].') + ->toContain('[spear] must eat food (upkeep > 0), or armies grow without limit.'); +});