From 46b3c6f2417a7e445ee3ebd473918d23825da14a Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Fri, 30 Oct 2026 13:45:02 +0100 Subject: [PATCH] feat: Lazarett: half of the own defenders who fall come back wounded into the hospital's beds, eat meanwhile and stand again after four hours Co-Authored-By: Claude Opus 5.5 (1M context) --- app/Engine/Engine.php | 1 + app/Engine/Hospital.php | 102 ++++++++++++++++ app/Engine/Military.php | 3 +- app/Engine/Nobility.php | 1 + app/Engine/Rally.php | 10 ++ app/Engine/Simulation.php | 16 ++- app/Game/Buildings/BuildingRules.php | 12 +- app/Game/ConfigLint.php | 19 +++ app/Game/Military/Wounds.php | 48 ++++++++ app/Models/GameEvent.php | 3 + app/Models/Village.php | 6 + app/Models/Wounded.php | 23 ++++ app/Presenters/VillagePresenter.php | 20 +++ config/game/buildings.php | 20 ++- config/game/combat.php | 5 + .../2026_11_02_090000_create_wounded.php | 26 ++++ tests/Feature/HospitalTest.php | 115 ++++++++++++++++++ tests/Unit/Game/BuildingRulesTest.php | 1 + tests/Unit/Game/WoundsTest.php | 31 +++++ 19 files changed, 453 insertions(+), 9 deletions(-) create mode 100644 app/Engine/Hospital.php create mode 100644 app/Game/Military/Wounds.php create mode 100644 app/Models/Wounded.php create mode 100644 database/migrations/2026_11_02_090000_create_wounded.php create mode 100644 tests/Feature/HospitalTest.php create mode 100644 tests/Unit/Game/WoundsTest.php diff --git a/app/Engine/Engine.php b/app/Engine/Engine.php index a9dc7d4..cde7e3e 100644 --- a/app/Engine/Engine.php +++ b/app/Engine/Engine.php @@ -121,6 +121,7 @@ final class Engine GameEvent::RAID_PLANNED => Raiders::of($village)->plan($event), GameEvent::RECRUIT_FINISHED => Military::of($village)->settle($event->fire_at), GameEvent::LEVY_ENDS => Military::of($village)->endLevy($event->fire_at), + GameEvent::WOUNDED_HEALED => Hospital::of($village)->heal($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/Hospital.php b/app/Engine/Hospital.php new file mode 100644 index 0000000..6c838ef --- /dev/null +++ b/app/Engine/Hospital.php @@ -0,0 +1,102 @@ +sim->config()); + } + + /** Beds of all hospitals here, each as far as it is staffed. */ + public function beds(): int + { + $rules = $this->sim->rules(); + $workforce = $this->sim->workforce(); + + return (int) floor($this->village->buildings->sum(function (Building $b) use ($rules, $workforce) { + $beds = $rules->beds($b->type, $b->level); + + return $beds > 0 ? $beds * $this->sim->staffingFactor($workforce->ratio($b->id)) : 0; + })); + } + + /** Beds the wounded lie in now. */ + public function occupied(): int + { + return $this->village->wounded->sum(fn (Wounded $w) => array_sum($w->units)); + } + + /** + * Take in the wounded among the own units that fell defending here at $at. Barbarian + * villages keep no hospital. + * + * @param array $dead + * @return Wounded|null the wounded of this battle, if any + */ + public function admit(array $dead, CarbonImmutable $at): ?Wounded + { + if ($this->village->player_id === null) { + return null; + } + $wounded = $this->rules()->admit($dead, max(0, $this->beds() - $this->occupied())); + if (! $wounded) { + return null; + } + $batch = $this->village->wounded()->create(['units' => $wounded, 'heals_at' => $at->addSeconds($this->rules()->healSeconds())]); + $this->village->wounded->push($batch); + GameEvent::create([ + 'world_id' => $this->village->world_id, + 'village_id' => $this->village->id, + 'type' => GameEvent::WOUNDED_HEALED, + 'subject_id' => $batch->id, + 'fire_at' => $batch->heals_at, + ]); + + return $batch; + } + + /** The wounded healed by $at stand at home again. They ate all along, so upkeep stays. */ + public function heal(CarbonImmutable $at): void + { + $military = Military::of($this->village, $this->sim); + $healed = $this->village->wounded->filter(fn (Wounded $w) => ! $w->heals_at->greaterThan($at)); + foreach ($healed as $batch) { + foreach ($batch->units as $unit => $count) { + $military->addTroops($unit, $count); + } + $batch->delete(); + } + $this->village->setRelation('wounded', $this->village->wounded->diff($healed)->values()); + } + + /** The wounded don't outlive the owner's rule: they are gone when the village changes hands. */ + public static function clear(Village $village): void + { + foreach ($village->wounded as $batch) { + GameEvent::where('type', GameEvent::WOUNDED_HEALED)->where('subject_id', $batch->id)->whereNull('processed_at')->delete(); + $batch->delete(); + } + $village->setRelation('wounded', collect()); + } +} diff --git a/app/Engine/Military.php b/app/Engine/Military.php index 11d7c9a..8fd6bbb 100644 --- a/app/Engine/Military.php +++ b/app/Engine/Military.php @@ -210,7 +210,8 @@ final class Military GameEvent::where('type', GameEvent::LEVY_ENDS)->where('village_id', $this->village->id)->whereNull('processed_at')->delete(); } - private function addTroops(string $unit, int $count): void + /** Own units standing at home, from training or back from the hospital. */ + public 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) { diff --git a/app/Engine/Nobility.php b/app/Engine/Nobility.php index dbe824f..a26d091 100644 --- a/app/Engine/Nobility.php +++ b/app/Engine/Nobility.php @@ -110,6 +110,7 @@ final class Nobility $village->militia = 0; $village->levy_until = null; $village->starving_since = null; + Hospital::clear($village); // The old owner's commands from here and troops on their way home here. $lost = Movement::where(fn ($q) => $q->where('origin_id', $village->id)->whereIn('type', [Movement::ATTACK, Movement::SUPPORT])) diff --git a/app/Engine/Rally.php b/app/Engine/Rally.php index 319ab10..128b062 100644 --- a/app/Engine/Rally.php +++ b/app/Engine/Rally.php @@ -312,6 +312,7 @@ final class Rally // Defenders fall in every stack alike, support included. $defenseLost = []; + $ownLost = []; $supporters = []; foreach ($stacks as $stack) { if ($stack->home_village_id !== $this->village->id) { @@ -319,6 +320,9 @@ final class Rally } $dead = Battle::dead([$stack->unit => $stack->count], $battle?->defenseLoss ?? 0.0)[$stack->unit]; $defenseLost[$stack->unit] = ($defenseLost[$stack->unit] ?? 0) + $dead; + if ($stack->home_village_id === $this->village->id && $dead > 0) { + $ownLost[$stack->unit] = $dead; + } $stack->count -= $dead; $stack->count > 0 ? $stack->save() : $stack->delete(); } @@ -382,6 +386,8 @@ final class Rally $loyalty = ['before' => (int) floor($before), 'after' => $conquered ? 0 : (int) floor($after), 'conquered' => $conquered]; } $conquered = $loyalty['conquered'] ?? false; + // Part of the own fallen come back wounded, unless the village falls with them. + $wounded = $conquered ? null : Hospital::of($this->village, $this->sim)->admit($ownLost, $at); $loot = ['wood' => 0, 'clay' => 0, 'iron' => 0]; $capacity = 0; @@ -413,6 +419,8 @@ final class Rally 'night' => $night > 1, 'attacker' => ['village' => self::summary($origin), 'units' => $movement->units, 'lost' => $attackLost], 'defender' => ['village' => self::summary($this->village), 'units' => $defense, 'lost' => $defenseLost], + // Of the lost, the ones in the defender's hospital, and when they stand again. + 'wounded' => $wounded ? ['units' => $wounded->units, 'heals_at' => $wounded->heals_at->utc()->format('Y-m-d\TH:i:s.v\Z')] : null, 'wall' => $wall && $battle ? ['before' => $battle->wallBefore, 'after' => $wall->level] : null, 'building' => $hit, 'loot' => $loot, @@ -432,6 +440,8 @@ final class Rally // An attacker learns about the defence from survivors of the battle or scouts that got through. $informed = ($battle && array_diff_key($survivors, $scouts)) || $scouted; $seen = $informed ? $report : ['defender' => ['village' => $report['defender']['village'], 'units' => null, 'lost' => null], 'wall' => null] + $report; + // The hospital stays the defender's business. + $seen['wounded'] = null; Report::write($movement->player_id, Report::ATTACK, $seen, $at); Report::write($this->village->player_id, Report::DEFENSE, $report, $at); foreach (Village::whereIn('id', array_keys($supporters))->get() as $home) { diff --git a/app/Engine/Simulation.php b/app/Engine/Simulation.php index 5c8776d..cb3900f 100644 --- a/app/Engine/Simulation.php +++ b/app/Engine/Simulation.php @@ -19,6 +19,7 @@ use App\Models\GameEvent; use App\Models\RecruitOrder; use App\Models\UnitStack; use App\Models\Village; +use App\Models\Wounded; use Carbon\CarbonImmutable; /** @@ -65,7 +66,7 @@ final class Simulation public static function of(Village $village): self { - return new self($village->loadMissing(['world', 'buildings', 'orders', 'troops', 'recruits'])); + return new self($village->loadMissing(['world', 'buildings', 'orders', 'troops', 'recruits', 'wounded'])); } public function config(): WorldConfig @@ -114,21 +115,28 @@ final class Simulation foreach ($this->village->recruits as $o) { $parts[] = "r$o->id:".($o->count - $o->done); } + foreach ($this->village->wounded as $w) { + $parts[] = "w$w->id"; + } return implode('|', $parts); } /** - * Food per hour eaten by troops standing here and by units still in training: a - * queued unit takes its villager's place at once. + * Food per hour eaten by troops standing here, by units still in training and by the + * wounded: a queued unit takes its villager's place at once, a wounded one keeps it. */ 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)); + $wounded = $this->village->wounded->sum(fn (Wounded $w) => array_sum(array_map( + fn (string $unit, int $count) => $units->exists($unit) ? $units->upkeep($unit) * $count : 0, + array_keys($w->units), $w->units, + ))); - return $standing + $training; + return $standing + $training + $wounded; } /** @return array{wood: float, clay: float, iron: float, food: float} */ diff --git a/app/Game/Buildings/BuildingRules.php b/app/Game/Buildings/BuildingRules.php index 5d72326..a23e571 100644 --- a/app/Game/Buildings/BuildingRules.php +++ b/app/Game/Buildings/BuildingRules.php @@ -115,9 +115,17 @@ final class BuildingRules return $detection ? $detection['base'] * $detection['factor'] ** self::above($level) : 0.0; } + /** Beds for the wounded this building has at full staffing (hospital), else 0. */ + public function beds(string $type, int $level): float + { + $beds = $this->config->building($type)['beds'] ?? null; + + return $beds ? $beds['base'] * $beds['factor'] ** self::above($level) : 0.0; + } + /** * What one instance does at a level, for the building's own screen: production at - * full staffing, storage, hiding, detection, the wall's defence, the headquarters' + * full staffing, storage, hiding, beds, detection, the wall's defence, the headquarters' * build speed, builders and space, a military building's training speed. Percentages * are the bonus over level 1 (or over no wall). * @@ -129,7 +137,7 @@ final class BuildingRules if ($output = $this->output($type, $level)) { $effects[] = ['key' => 'production', 'value' => round($output['per_hour'], 1), 'resource' => $output['resource']]; } - foreach (['capacity', 'hides'] as $key) { + foreach (['capacity', 'hides', 'beds'] as $key) { if ($value = $this->{$key}($type, $level)) { $effects[] = ['key' => $key, 'value' => (int) round($value)]; } diff --git a/app/Game/ConfigLint.php b/app/Game/ConfigLint.php index 28987c5..faa8aa3 100644 --- a/app/Game/ConfigLint.php +++ b/app/Game/ConfigLint.php @@ -29,9 +29,28 @@ final class ConfigLint ...self::raidsPause($config), ...self::rolesReachable($config), ...self::crownsHold($config), + ...self::woundedHeal($config), ]; } + /** + * The wounded stand again after a time above 0, and never more of them come back + * than fell: share between 0 and 1. + */ + private static function woundedHeal(WorldConfig $config): array + { + $hospital = $config->get('combat.hospital', []); + $problems = []; + if (($hospital['share'] ?? 0) < 0 || ($hospital['share'] ?? 0) > 1) { + $problems[] = '[combat.hospital.share] must be between 0 and 1, or more come back than fell.'; + } + if (($hospital['heal_time'] ?? 0) <= 0) { + $problems[] = '[combat.hospital.heal_time] must be more than 0 seconds.'; + } + + return $problems; + } + /** Counter keys the actions bump (App\Engine\Quests::bump), besides recruited.. */ public const QUEST_COUNTERS = [ 'attacks.sent', 'attacks.barbarian', 'support.sent', 'scouts.sent', 'village.renamed', diff --git a/app/Game/Military/Wounds.php b/app/Game/Military/Wounds.php new file mode 100644 index 0000000..7a68082 --- /dev/null +++ b/app/Game/Military/Wounds.php @@ -0,0 +1,48 @@ + $dead + * @return array + */ + public function admit(array $dead, int $freeBeds): array + { + $share = (float) $this->config->get('combat.hospital.share', 0); + $wounded = array_filter(array_map(fn (int $n) => (int) floor($n * $share), $dead)); + $total = array_sum($wounded); + if ($total <= $freeBeds) { + return $wounded; + } + $exact = array_map(fn (int $n) => $n * max(0, $freeBeds) / $total, $wounded); + $fits = array_map(fn (float $n) => (int) floor($n), $exact); + $rest = array_map(fn (float $n, int $floor) => $n - $floor, $exact, $fits); + $rest = array_combine(array_keys($exact), $rest); + arsort($rest); + foreach (array_slice(array_keys($rest), 0, max(0, $freeBeds) - array_sum($fits)) as $unit) { + $fits[$unit]++; + } + + return array_filter($fits); + } + + /** Seconds from the battle until its wounded stand again, at world speed. */ + public function healSeconds(): int + { + return max(1, (int) ceil($this->config->get('combat.hospital.heal_time', 0) / $this->config->speed())); + } +} diff --git a/app/Models/GameEvent.php b/app/Models/GameEvent.php index a1fab02..7f32fcb 100644 --- a/app/Models/GameEvent.php +++ b/app/Models/GameEvent.php @@ -22,6 +22,9 @@ class GameEvent extends Model public const LEVY_ENDS = 'levy.ends'; + // subject_id is a row of wounded in the village's hospital; they stand again. + public const WOUNDED_HEALED = 'wounded.healed'; + public const FOOD_RUNS_OUT = 'food.runs_out'; public const DESERTION = 'starvation.desertion'; diff --git a/app/Models/Village.php b/app/Models/Village.php index 0c42bf6..443360b 100644 --- a/app/Models/Village.php +++ b/app/Models/Village.php @@ -63,6 +63,12 @@ class Village extends Model return $this->hasMany(RecruitOrder::class)->orderBy('id'); } + /** The wounded in the village's hospitals, one row per battle, the first to heal first. */ + public function wounded(): HasMany + { + return $this->hasMany(Wounded::class)->orderBy('heals_at')->orderBy('id'); + } + /** @return array{wood: float, clay: float, iron: float, food: float} */ public function resources(): array { diff --git a/app/Models/Wounded.php b/app/Models/Wounded.php new file mode 100644 index 0000000..249d342 --- /dev/null +++ b/app/Models/Wounded.php @@ -0,0 +1,23 @@ + 'array', + 'heals_at' => 'immutable_datetime', + ]; + } +} diff --git a/app/Presenters/VillagePresenter.php b/app/Presenters/VillagePresenter.php index 2c23a43..1b4c7ca 100644 --- a/app/Presenters/VillagePresenter.php +++ b/app/Presenters/VillagePresenter.php @@ -2,6 +2,7 @@ namespace App\Presenters; +use App\Engine\Hospital; use App\Engine\Military; use App\Engine\Nobility; use App\Engine\Quests; @@ -15,6 +16,7 @@ use App\Models\RecruitOrder; use App\Models\Report; use App\Models\TribeInvite; use App\Models\Village; +use App\Models\Wounded; use Carbon\CarbonImmutable; /** @@ -70,6 +72,7 @@ final class VillagePresenter 'desertion_at' => self::isoOrNull($starvation->nextDesertion()), ], 'troops' => (object) $troops, + 'hospital' => self::hospital($village, $sim), 'military' => self::military($village, $military, $now), 'movements' => RallyPresenter::movements($village, $now), 'support' => RallyPresenter::support($village), @@ -122,6 +125,23 @@ final class VillagePresenter ]; } + /** + * The Lazarett: beds as far as the hospitals are staffed, beds taken, the share of the + * fallen that comes back, and the wounded of each battle with when they stand again. + */ + private static function hospital(Village $village, Simulation $sim): array + { + $hospital = Hospital::of($village, $sim); + + return [ + 'beds' => $hospital->beds(), + 'occupied' => $hospital->occupied(), + 'share' => (float) $sim->config()->get('combat.hospital.share', 0), + 'heal_seconds' => $hospital->rules()->healSeconds(), + 'wounded' => $village->wounded->map(fn (Wounded $w) => ['id' => $w->id, 'units' => (object) $w->units, 'heals_at' => self::iso($w->heals_at)])->values()->all(), + ]; + } + /** * Every building that trains units: what it can train (with cost, time, upkeep, how * many fit now, and missing requirements) and its own queue. diff --git a/config/game/buildings.php b/config/game/buildings.php index 893530c..7780790 100644 --- a/config/game/buildings.php +++ b/config/game/buildings.php @@ -3,8 +3,8 @@ // Values per building type. Levels start at 1, which has the base values. // `space` is how much of the village's building space an instance takes, at any level. // Level n: cost = cost × factor^(n−1), build time = base × factor^(n−1) seconds at world -// speed 1, workers = round(base × factor^(n−1)), and production, capacity, hides and -// detection = base × factor^(n−1). +// speed 1, workers = round(base × factor^(n−1)), and production, capacity, hides, +// detection and beds = base × factor^(n−1). // The n-th instance of a type (0-based) costs instance_cost_factor^n times as much. // Map points of an instance: round(points.base × points.factor^(level−1)). @@ -187,4 +187,20 @@ return [ 'points' => ['base' => 512, 'factor' => 1.2], 'requires' => ['headquarters' => 5, 'barracks' => 1], ], + // The Lazarett: a share of the own troops who fall defending the village come back + // wounded into its beds and heal after a while (combat.hospital). A bed holds one + // wounded; beds add up over instances and shrink with staffing like production. + 'hospital' => [ + 'space' => 4, + 'max_per_village' => null, + 'max_level' => 20, + 'cost' => ['wood' => 160, 'clay' => 200, 'iron' => 120, 'factor' => 1.26], + 'build_time' => ['base' => 900, 'factor' => 1.2], + 'workers' => ['base' => 2, 'factor' => 1.1], + 'production' => null, + 'beds' => ['base' => 20, 'factor' => 1.2], + 'instance_cost_factor' => 1.5, + 'points' => ['base' => 12, 'factor' => 1.2], + 'requires' => ['barracks' => 1], + ], ]; diff --git a/config/game/combat.php b/config/game/combat.php index 1bb4630..78c4b72 100644 --- a/config/game/combat.php +++ b/config/game/combat.php @@ -39,6 +39,11 @@ return [ // world speed 1), and can't attack players themselves meanwhile; barbarians are fine. 'beginner_protection' => 3 * 86400, + // Lazarett: of the own units that fall defending their village, `share` (rounded down) + // come back wounded, as far as its hospitals have free beds. The wounded eat like + // soldiers and stand again heal_time (seconds at world speed 1) after the battle. + 'hospital' => ['share' => 0.5, 'heal_time' => 4 * 3600], + // Taking villages, like Die Stämme. Loyalty runs from 0 to max and grows back // regen_per_hour × world speed. Every surviving nobleman of a won attack lowers it by // an even draw between drop[0] and drop[1]; at 0 or below the village changes hands, diff --git a/database/migrations/2026_11_02_090000_create_wounded.php b/database/migrations/2026_11_02_090000_create_wounded.php new file mode 100644 index 0000000..c7d2b01 --- /dev/null +++ b/database/migrations/2026_11_02_090000_create_wounded.php @@ -0,0 +1,26 @@ +id(); + $table->foreignId('village_id')->constrained()->cascadeOnDelete(); + // unit => count + $table->json('units'); + $table->dateTime('heals_at', 3); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('wounded'); + } +}; diff --git a/tests/Feature/HospitalTest.php b/tests/Feature/HospitalTest.php new file mode 100644 index 0000000..005af13 --- /dev/null +++ b/tests/Feature/HospitalTest.php @@ -0,0 +1,115 @@ + $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00'))); + +/** + * A defender with 20 swordsmen, a farm big enough to staff everything and, unless + * $hospital is 0, a hospital at that level; and an attacker with a rally point. + */ +function wardVillages(int $hospital = 1, array $world = []): array +{ + $attacker = startVillage(); + $attacker->buildings()->create(['type' => 'rally_point', 'level' => 1]); + $defender = startVillage(); + $defender->buildings()->where('type', 'farm')->update(['level' => 10]); + if ($hospital > 0) { + $defender->buildings()->create(['type' => 'hospital', 'level' => $hospital]); + } + $defender->troops()->create(['home_village_id' => $defender->id, 'unit' => 'sword', 'count' => 20]); + World::whereKey($defender->world_id)->update(['config' => array_replace_recursive(['combat' => ['beginner_protection' => 0, 'luck' => 0]], $world)]); + + return [$attacker->fresh(), $defender->fresh()]; +} + +/** Attack with $spears spearmen and let the battle happen; returns the arrival time. */ +function strike(Village $attacker, Village $defender, int $spears): CarbonImmutable +{ + $attacker->troops()->create(['home_village_id' => $attacker->id, 'unit' => 'spear', 'count' => $spears]); + app(SendTroops::class)(owner($attacker), $attacker->id, 'attack', $defender->x, $defender->y, ['spear' => $spears], null, null); + $arrives = Movement::where('target_id', $defender->id)->sole()->arrives_at; + test()->travelTo($arrives); + test()->artisan('game:events --once')->assertSuccessful(); + + return $arrives; +} + +it('brings half the fallen defenders back wounded; they eat meanwhile and stand at home after four hours', function () { + [$attacker, $defender] = wardVillages(); + + $at = strike($attacker, $defender, 60); + + // 600 attack against 1000 defence: the defenders lose 0.6^1.5 of 20 → 9, 4 of them wounded. + $defense = Report::where('player_id', $defender->player_id)->sole()->payload; + expect($defense['defender']['lost'])->toBe(['sword' => 9]) + ->and($defense['wounded'])->toBe(['units' => ['sword' => 4], 'heals_at' => $at->addHours(4)->utc()->format('Y-m-d\TH:i:s.v\Z')]) + ->and(Report::where('player_id', $attacker->player_id)->sole()->payload['wounded'])->toBeNull(); + + $state = shown($defender); + expect((array) $state['troops'])->toBe(['sword' => 11]) + ->and($state['hospital'])->toMatchArray(['beds' => 20, 'occupied' => 4, 'share' => 0.5, 'heal_seconds' => 14400]) + ->and((array) $state['hospital']['wounded'][0]['units'])->toBe(['sword' => 4]) + // Farm 10 feeds 0.8 × 123.2 = 98.6 heads: the 11 swordsmen and 4 wounded leave 83 villagers. + ->and($state['population']['villagers'])->toBe(83); + + $this->travel(4)->hours(); + $this->artisan('game:events --once')->assertSuccessful(); + $state = shown($defender); + expect((array) $state['troops'])->toBe(['sword' => 15]) + ->and($state['hospital'])->toMatchArray(['occupied' => 0, 'wounded' => []]) + ->and($state['population']['villagers'])->toBe(83); +}); + +it('takes in no more wounded than it has free beds', function () { + [$attacker, $defender] = wardVillages(1, ['buildings' => ['hospital' => ['beds' => ['base' => 3]]]]); + + strike($attacker, $defender, 60); + + expect(Report::where('player_id', $defender->player_id)->sole()->payload['wounded']['units'])->toBe(['sword' => 3]) + ->and(shown($defender)['hospital'])->toMatchArray(['beds' => 3, 'occupied' => 3]); +}); + +it('has no wounded without a hospital', function () { + [$attacker, $defender] = wardVillages(0); + + strike($attacker, $defender, 60); + + expect(Report::where('player_id', $defender->player_id)->sole()->payload['wounded'])->toBeNull() + ->and((array) shown($defender)['troops'])->toBe(['sword' => 11]) + ->and(shown($defender)['hospital'])->toMatchArray(['beds' => 0, 'occupied' => 0, 'wounded' => []]); +}); + +it('takes in only the own fallen, not the support', function () { + [$attacker, $defender] = wardVillages(); + $ally = startVillage(); + $defender->troops()->create(['home_village_id' => $ally->id, 'unit' => 'sword', 'count' => 20]); + + // 1500 attack against 2000 defence: 0.75^1.5 of each stack → 13 of 20 fall. + strike($attacker, $defender->fresh(), 150); + + $defense = Report::where('player_id', $defender->player_id)->sole()->payload; + expect($defense['defender']['lost'])->toBe(['sword' => 26]) + ->and($defense['wounded']['units'])->toBe(['sword' => 6]); +}); + +it('loses its wounded when the village turns barbarian', function () { + [$attacker, $defender] = wardVillages(); + strike($attacker, $defender, 60); + expect(Wounded::count())->toBe(1); + + $village = Village::whereKey($defender->id)->first(); + Abandon::village($village, now()->toImmutable()); + $village->save(); + + expect(Wounded::count())->toBe(0) + ->and(GameEvent::where('type', GameEvent::WOUNDED_HEALED)->whereNull('processed_at')->count())->toBe(0); +}); diff --git a/tests/Unit/Game/BuildingRulesTest.php b/tests/Unit/Game/BuildingRulesTest.php index 09d12ac..49683b4 100644 --- a/tests/Unit/Game/BuildingRulesTest.php +++ b/tests/Unit/Game/BuildingRulesTest.php @@ -97,6 +97,7 @@ it('lists what an instance does at a level', function () { expect($rules->effects('timber_camp', 1))->toBe([['key' => 'production', 'value' => 30.0, 'resource' => 'wood']]) ->and($rules->effects('storage', 2))->toBe([['key' => 'capacity', 'value' => 1230]]) ->and($rules->effects('hiding_place', 1))->toBe([['key' => 'hides', 'value' => 150]]) + ->and($rules->effects('hospital', 2))->toBe([['key' => 'beds', 'value' => 24]]) ->and($rules->effects('wall', 3))->toBe([['key' => 'wall_defense', 'value' => 60], ['key' => 'wall_bonus', 'value' => 12]]) ->and($rules->effects('headquarters', 3))->toBe([['key' => 'build_speed', 'value' => 10], ['key' => 'builders', 'value' => 2], ['key' => 'space', 'value' => 50]]) ->and($rules->effects('barracks', 6))->toBe([['key' => 'recruit_speed', 'value' => 25]]) diff --git a/tests/Unit/Game/WoundsTest.php b/tests/Unit/Game/WoundsTest.php new file mode 100644 index 0000000..b6ce804 --- /dev/null +++ b/tests/Unit/Game/WoundsTest.php @@ -0,0 +1,31 @@ +admit(['spear' => 10, 'sword' => 5, 'archer' => 1], 100))->toBe(['spear' => 5, 'sword' => 2]) + ->and($wounds->admit([], 100))->toBe([]); +}); + +it('shares scarce beds evenly, the leftover bed to the largest remainder', function () { + $wounds = new Wounds(gameConfig()); + + // 20 spear and 6 sword wounded for 13 beds: 10 and 3 exactly. + expect($wounds->admit(['spear' => 40, 'sword' => 12], 13))->toBe(['spear' => 10, 'sword' => 3]) + // 10 and 3 for 5 beds: 3.85 and 1.15 → 3 and 1, the fifth bed to spear. + ->and($wounds->admit(['spear' => 20, 'sword' => 6], 5))->toBe(['spear' => 4, 'sword' => 1]) + ->and($wounds->admit(['spear' => 20], 0))->toBe([]); +}); + +it('heals after four hours at world speed 1', function () { + expect((new Wounds(gameConfig()))->healSeconds())->toBe(14400) + ->and((new Wounds(gameConfig(['world' => ['speed' => 100]])))->healSeconds())->toBe(144); +}); + +it('lints a share outside 0..1 and a heal time of 0', function () { + expect(ConfigLint::check(gameConfig(['combat' => ['hospital' => ['share' => 1.5]]])))->toContain('[combat.hospital.share] must be between 0 and 1, or more come back than fell.') + ->and(ConfigLint::check(gameConfig(['combat' => ['hospital' => ['heal_time' => 0]]])))->toContain('[combat.hospital.heal_time] must be more than 0 seconds.'); +});