From 1319276e2fca9859a6c3962b4c375500ac918d21 Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Thu, 29 Oct 2026 16:07:54 +0100 Subject: [PATCH] feat: raiders: the nearest barbarian camp raids every player village about once a day A raid.planned event per village picks the nearest camp in range, announces a band sized by the village's points hours before it marches, and plans the next one. On arrival the band is as strong as its camp; a beaten camp's band scatters. Loot goes back to the camp, a beaten band pays a bounty. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/Actions/JoinWorld.php | 2 + app/Actions/SpawnBarbarians.php | 18 +++ app/Engine/Engine.php | 1 + app/Engine/Nobility.php | 3 + app/Engine/Raiders.php | 141 +++++++++++++++++ app/Engine/Rally.php | 33 ++++ app/Game/Combat/Raids.php | 147 +++++++++++++++++ app/Game/ConfigLint.php | 29 ++++ app/Game/WorldConfig.php | 2 +- app/Models/GameEvent.php | 3 + app/Models/World.php | 1 + app/Presenters/RallyPresenter.php | 3 + config/game/raids.php | 35 +++++ .../migrations/2026_10_31_090000_raids.php | 23 +++ database/seeders/WorldSeeder.php | 4 +- docs/architecture.md | 11 ++ tests/Feature/RaidTest.php | 148 ++++++++++++++++++ tests/Pest.php | 5 +- tests/Unit/Game/ConfigLintTest.php | 8 + tests/Unit/Game/RaidsTest.php | 56 +++++++ 20 files changed, 669 insertions(+), 4 deletions(-) create mode 100644 app/Engine/Raiders.php create mode 100644 app/Game/Combat/Raids.php create mode 100644 config/game/raids.php create mode 100644 database/migrations/2026_10_31_090000_raids.php create mode 100644 tests/Feature/RaidTest.php create mode 100644 tests/Unit/Game/RaidsTest.php diff --git a/app/Actions/JoinWorld.php b/app/Actions/JoinWorld.php index cd4086e..029f5cc 100644 --- a/app/Actions/JoinWorld.php +++ b/app/Actions/JoinWorld.php @@ -2,6 +2,7 @@ namespace App\Actions; +use App\Engine\Raiders; use App\Engine\VillageFactory; use App\Game\GameRuleViolation; use App\Game\Map\Frontier; @@ -38,6 +39,7 @@ final class JoinWorld $levels = array_fill_keys($world->gameConfig()->get('world.village.start_buildings'), 1); $village = $this->villages->create($world, $player, "{$user->name}'s village", $x, $y, $levels); $this->barbarians->around($world, $village, $taken); + Raiders::of($village)->ensurePlanned(now()->toImmutable()); return $village; }); diff --git a/app/Actions/SpawnBarbarians.php b/app/Actions/SpawnBarbarians.php index 93a881d..80b4312 100644 --- a/app/Actions/SpawnBarbarians.php +++ b/app/Actions/SpawnBarbarians.php @@ -3,6 +3,7 @@ namespace App\Actions; use App\Engine\Barbarians; +use App\Engine\Raiders; use App\Engine\VillageFactory; use App\Game\Map\BarbarianGrowth; use App\Game\Map\Frontier; @@ -108,6 +109,23 @@ final class SpawnBarbarians return $changed; } + /** + * Plan a raid for every player village without one, from now or the end of its + * owner's beginner protection. Safe to run on every deploy. + */ + public function scheduleRaids(World $world): void + { + $now = now()->toImmutable(); + foreach ($world->villages()->whereNotNull('player_id')->pluck('id') as $id) { + DB::transaction(function () use ($id, $now) { + $village = Village::whereKey($id)->lockForUpdate()->first(); + if ($village?->player_id !== null) { + Raiders::of($village)->ensurePlanned($now); + } + }); + } + } + /** The first growth step lands 0.5–1.5 intervals out, so villages don't grow in step. */ private function scheduleFirstGrowth(World $world, Village $village): void { diff --git a/app/Engine/Engine.php b/app/Engine/Engine.php index 016d72e..2c51cd4 100644 --- a/app/Engine/Engine.php +++ b/app/Engine/Engine.php @@ -114,6 +114,7 @@ final class Engine GameEvent::BUILD_ORDER_FINISHED => $this->finishBuildOrder($village, $event), GameEvent::BARBARIAN_GROWS => $this->growBarbarian($village, $event), GameEvent::BARBARIAN_REGROUPS => Barbarians::of($village)->regroup($event->fire_at), + 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), // The stock just hit 0; the sync() after every event starts the grace timer. diff --git a/app/Engine/Nobility.php b/app/Engine/Nobility.php index f38d03e..ada59df 100644 --- a/app/Engine/Nobility.php +++ b/app/Engine/Nobility.php @@ -107,8 +107,11 @@ final class Nobility } $village->player_id = $playerId; + $village->setRelation('player', Player::find($playerId)); $village->loyalty = $this->rules->afterConquest(); $village->loyalty_at = $at; + // Raiders come for the new owner's village too. + Raiders::of($village)->ensurePlanned($at); return array_values(array_unique($touched)); } diff --git a/app/Engine/Raiders.php b/app/Engine/Raiders.php new file mode 100644 index 0000000..d3d0517 --- /dev/null +++ b/app/Engine/Raiders.php @@ -0,0 +1,141 @@ +raids = new Raids($sim->config()); + } + + public static function of(Village $village, ?Simulation $sim = null): self + { + return new self($village, $sim ?? Simulation::of($village)); + } + + public function rules(): Raids + { + return $this->raids; + } + + /** Make sure a raid is planned, no earlier than $earliest or the end of beginner protection. */ + public function ensurePlanned(CarbonImmutable $earliest): void + { + if ($this->village->player_id === null || ! $this->raids->enabled()) { + return; + } + $waiting = GameEvent::where('type', GameEvent::RAID_PLANNED)->where('village_id', $this->village->id)->whereNull('processed_at')->exists(); + if (! $waiting) { + $protected = Rally::of($this->village, $this->sim)->protectedUntil($this->village->player); + $this->schedule($protected->greaterThan($earliest) ? $protected : $earliest); + } + } + + /** The `raid.planned` handler: send a band from the nearest camp and plan the next raid. */ + public function plan(GameEvent $event): void + { + $at = $event->fire_at; + if ($this->village->player_id === null || ! $this->raids->enabled()) { + return; + } + $protected = Rally::of($this->village, $this->sim)->protectedUntil($this->village->player); + if ($protected->greaterThan($at)) { + $this->schedule($protected); + + return; + } + // Seeded per event, so a replayed event draws the same interval. + mt_srand($event->id); + $interval = $this->raids->interval(mt_rand() / (mt_getrandmax() + 1)); + $camp = $this->camp(); + $wall = $this->village->buildings->firstWhere('type', 'wall')?->level ?? 0; + $units = $camp ? $this->raids->band(Barbarians::of($camp)->profile(), (int) $this->village->points, $wall) : []; + if (! $units) { + $this->schedule($at->addSeconds($interval)); + + return; + } + + $travel = new TravelTime($this->sim->config()); + $marches = $at->addSeconds($this->raids->gatherSeconds()); + $arrives = $marches->addSeconds($travel->seconds($units, TravelTime::distance($camp->x, $camp->y, $this->village->x, $this->village->y), $this->raids->mode())); + $movement = Movement::create([ + 'world_id' => $this->village->world_id, + 'player_id' => null, + 'type' => Movement::ATTACK, + 'mode' => $this->raids->mode(), + 'origin_id' => $camp->id, + 'target_id' => $this->village->id, + 'units' => $units, + 'rng_seed' => mt_rand(1, 2_000_000_000), + // It gathers until it marches, and is seen from the start. + 'sent_at' => $marches, + 'arrives_at' => $arrives, + 'visible_at' => $at, + ]); + GameEvent::create([ + 'world_id' => $this->village->world_id, + 'village_id' => $this->village->id, + 'type' => GameEvent::MOVEMENT_ARRIVES, + 'subject_id' => $movement->id, + 'fire_at' => $arrives, + ]); + Push::queue($this->village->id); + $this->schedule($arrives->addSeconds($interval)); + } + + /** + * The band as it reaches the village: as strong as its camp is now. Empty when it + * scatters (the camp was beaten down or changed hands). + * + * @return array + */ + public function muster(Movement $movement): array + { + $camp = Village::find($movement->origin_id); + if (! $camp || $camp->player_id !== null) { + return []; + } + + return $this->raids->muster($movement->units, Barbarians::of($camp)->strength()); + } + + /** The nearest barbarian village in range. */ + private function camp(): ?Village + { + $range = $this->raids->range(); + $camps = Village::where('world_id', $this->village->world_id)->whereNull('player_id') + ->whereBetween('x', [$this->village->x - $range, $this->village->x + $range]) + ->whereBetween('y', [$this->village->y - $range, $this->village->y + $range]) + ->get(['id', 'x', 'y']); + $id = $this->raids->nearest($camps->map(fn (Village $v) => ['id' => $v->id, 'x' => $v->x, 'y' => $v->y]), $this->village->x, $this->village->y); + + return $id ? Village::find($id) : null; + } + + private function schedule(CarbonImmutable $at): void + { + GameEvent::create([ + 'world_id' => $this->village->world_id, + 'village_id' => $this->village->id, + 'type' => GameEvent::RAID_PLANNED, + 'fire_at' => $at, + ]); + } +} diff --git a/app/Engine/Rally.php b/app/Engine/Rally.php index 6574297..0d1c389 100644 --- a/app/Engine/Rally.php +++ b/app/Engine/Rally.php @@ -5,6 +5,7 @@ namespace App\Engine; use App\Game\Combat\Battle; use App\Game\Combat\CombatResolver; use App\Game\Combat\LootCalculator; +use App\Game\Combat\Raids; use App\Game\GameRuleViolation; use App\Game\Travel\TravelTime; use App\Models\Building; @@ -252,6 +253,17 @@ final class Rally private function battle(Movement $movement, CarbonImmutable $at): void { $config = $this->sim->config(); + // Raiders are as strong as their camp is when they arrive; a beaten camp's band scatters. + $raid = $movement->player_id === null; + if ($raid) { + $units = Raiders::of($this->village, $this->sim)->muster($movement); + if (! $units) { + $this->scatter($movement, $at); + + return; + } + $movement->units = $units; + } $combat = new CombatResolver($config); $stacks = $this->village->troops->filter(fn (UnitStack $s) => $s->count > 0); $defense = []; @@ -359,6 +371,12 @@ final class Rally if ($damaged) { $this->village->points = $this->sim->points(); } + // A beaten band leaves its bounty behind. + $bounty = null; + if ($raid && $battle && ! $battle->attackerWon) { + $bounty = (new Raids($config))->bounty($army); + $this->sim->refund($bounty); + } $origin = Village::with('player')->find($movement->origin_id); $scouted = $through && $scoutsLost < array_sum($scouts); @@ -374,6 +392,8 @@ final class Rally 'loot' => $loot, 'capacity' => $capacity, 'loyalty' => $loyalty, + 'raid' => $raid, + 'bounty' => $bounty, // What scouts that got through saw, after the battle. 'scouting' => $scouts ? [ 'sent' => array_sum($scouts), @@ -408,6 +428,19 @@ final class Rally $survivors ? $this->turnBack($movement, $survivors, $loot, $at) : $movement->delete(); } + /** A band whose camp was beaten down never arrives; the village hears of it. */ + private function scatter(Movement $movement, CarbonImmutable $at): void + { + $origin = Village::with('player')->find($movement->origin_id); + Report::write($this->village->player_id, Report::DEFENSE, [ + 'raid' => true, + 'scattered' => true, + 'attacker' => ['village' => $origin ? self::summary($origin) : null, 'units' => null, 'lost' => null], + 'defender' => ['village' => self::summary($this->village), 'units' => null, 'lost' => null], + ], $at); + $movement->delete(); + } + /** * The attacker takes the village: one nobleman settles, the other survivors stay as * support from the village they came from. diff --git a/app/Game/Combat/Raids.php b/app/Game/Combat/Raids.php new file mode 100644 index 0000000..e9e082a --- /dev/null +++ b/app/Game/Combat/Raids.php @@ -0,0 +1,147 @@ +garrison = new BarbarianGarrison($config); + } + + public function enabled(): bool + { + return (bool) $this->config->get('raids.enabled', false); + } + + /** Attack strength of a band against a village with these points. */ + public function attack(int $points): float + { + $attack = $this->config->get('raids.attack'); + + return $attack['base'] + $attack['per_point'] * max(0, $points); + } + + /** + * The band a camp sends: heads in the camp's profile until they reach the attack + * strength, plus rams against the wall once the village is big enough. + * + * @return array + */ + public function band(?string $profile, int $points, int $wall): array + { + if ($profile === null) { + return []; + } + $shares = $this->garrison->shares($profile); + $total = array_sum($shares); + $perHead = $total > 0 ? array_sum(array_map(fn (string $u, float $s) => $s / $total * $this->unitAttack($u), array_keys($shares), $shares)) : 0; + if ($perHead <= 0) { + return []; + } + $units = BarbarianGarrison::split((int) ceil($this->attack($points) / $perHead), $shares); + $rams = $this->config->get('raids.rams'); + if ($points >= $rams['from_points'] && $wall > 0 && $this->config->get('units.ram')) { + $count = (int) round($wall * $rams['per_wall_level']); + if ($count > 0) { + $units['ram'] = $count; + } + } + + return $units; + } + + /** + * The band as it arrives, as strong as its camp is now (share of full strength). + * Below scatter_below nothing is left of it. + * + * @param array $units + * @return array + */ + public function muster(array $units, float $strength): array + { + if ($strength < (float) $this->config->get('raids.scatter_below', 0)) { + return []; + } + + return array_filter(array_map(fn (int $n) => (int) round($n * min(1.0, $strength)), $units)); + } + + /** + * What a beaten band leaves: bounty × its attack strength, a third each of wood, + * clay and iron. + * + * @param array $units + * @return array{wood: int, clay: int, iron: int} + */ + public function bounty(array $units): array + { + $strength = array_sum(array_map(fn (string $u, int $n) => $n * $this->unitAttack($u), array_keys($units), $units)); + $each = (int) floor($this->config->get('raids.bounty', 0) * $strength / count(self::RESOURCES)); + + return array_fill_keys(self::RESOURCES, $each); + } + + /** Seconds until the next raid, at world speed, from a roll in [0, 1). */ + public function interval(float $roll): int + { + [$min, $max] = $this->config->get('raids.every_hours'); + + return max(1, (int) round(($min + ($max - $min) * $roll) * 3600 / $this->config->speed())); + } + + /** How long a band gathers at its camp before it marches, at world speed. */ + public function gatherSeconds(): int + { + return (int) round($this->config->get('raids.gather_hours', 0) * 3600 / $this->config->speed()); + } + + public function mode(): string + { + return (string) $this->config->get('raids.mode', 'normal'); + } + + /** + * The nearest camp within range of x|y, the lower id on a tie. + * + * @param iterable $camps + */ + public function nearest(iterable $camps, int $x, int $y): ?int + { + $range = (float) $this->config->get('raids.range', 0); + $best = null; + $bestDistance = INF; + foreach ($camps as $camp) { + $distance = TravelTime::distance($x, $y, $camp['x'], $camp['y']); + if ($distance <= $range && ($distance < $bestDistance || ($distance === $bestDistance && $camp['id'] < $best))) { + $best = $camp['id']; + $bestDistance = $distance; + } + } + + return $best; + } + + public function range(): int + { + return (int) ceil($this->config->get('raids.range', 0)); + } + + private function unitAttack(string $unit): float + { + return (float) $this->config->get("units.$unit.attack", 0); + } +} diff --git a/app/Game/ConfigLint.php b/app/Game/ConfigLint.php index d573f7e..78a91c8 100644 --- a/app/Game/ConfigLint.php +++ b/app/Game/ConfigLint.php @@ -26,6 +26,7 @@ final class ConfigLint ...self::timersRun($config), ...self::questsReachable($config, $rules), ...self::garrisonsRegroup($config), + ...self::raidsPause($config), ]; } @@ -104,6 +105,34 @@ final class ConfigLint return $problems; } + /** + * Raids come apart in time, with a warning, from camps in range, in a travel mode + * that exists, and a camp beaten down to nothing sends no band. + */ + private static function raidsPause(WorldConfig $config): array + { + if (! $config->get('raids.enabled', false)) { + return []; + } + $problems = []; + [$min, $max] = $config->get('raids.every_hours', [0, 0]) + [0, 0]; + if ($min <= 0 || $max < $min) { + $problems[] = '[raids.every_hours] must be two hours above 0, the smaller first, so a village gets time between raids.'; + } + if ($config->get('raids.gather_hours', 0) < 0 || $config->get('raids.range', 0) <= 0) { + $problems[] = '[raids.gather_hours] cannot be negative and [raids.range] must be above 0.'; + } + $scatter = $config->get('raids.scatter_below', 0); + if ($scatter <= 0 || $scatter > 1) { + $problems[] = '[raids.scatter_below] must be above 0 and at most 1, or beating the camp would not stop its raid.'; + } + if (! $config->get('movement.modes.'.$config->get('raids.mode', 'normal'))) { + $problems[] = '[raids.mode] is not a travel mode.'; + } + + return $problems; + } + /** 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 { diff --git a/app/Game/WorldConfig.php b/app/Game/WorldConfig.php index 3fc7cff..f99a7fb 100644 --- a/app/Game/WorldConfig.php +++ b/app/Game/WorldConfig.php @@ -14,7 +14,7 @@ final class WorldConfig private function __construct(private readonly array $values) {} /** - * @param array $defaults keyed by file: world, economy, buildings + * @param array $defaults keyed by file: world, economy, buildings, ... * @param array $overrides the same shape, e.g. ['world' => ['speed' => 100]] */ public static function make(array $defaults, array $overrides = []): self diff --git a/app/Models/GameEvent.php b/app/Models/GameEvent.php index 9d72baa..a1fab02 100644 --- a/app/Models/GameEvent.php +++ b/app/Models/GameEvent.php @@ -15,6 +15,9 @@ class GameEvent extends Model // A barbarian garrison gets part of its full strength back. public const BARBARIAN_REGROUPS = 'barbarian.regroups'; + // Raiders from the nearest barbarian camp gather against this village; plans the next raid too. + public const RAID_PLANNED = 'raid.planned'; + public const RECRUIT_FINISHED = 'recruit.finished'; public const LEVY_ENDS = 'levy.ends'; diff --git a/app/Models/World.php b/app/Models/World.php index 9912888..140fb79 100644 --- a/app/Models/World.php +++ b/app/Models/World.php @@ -29,6 +29,7 @@ class World extends Model 'units' => config('game.units'), 'combat' => config('game.combat'), 'movement' => config('game.movement'), + 'raids' => config('game.raids'), 'quests' => config('game.quests'), ], $this->config ?? []); } diff --git a/app/Presenters/RallyPresenter.php b/app/Presenters/RallyPresenter.php index 7ffdd34..6192dc5 100644 --- a/app/Presenters/RallyPresenter.php +++ b/app/Presenters/RallyPresenter.php @@ -44,6 +44,9 @@ final class RallyPresenter 'cargo' => $mine ? $m->cargo : null, 'sent_at' => $mine ? self::iso($m->sent_at) : null, 'arrives_at' => self::iso($m->arrives_at), + // Raiders from a barbarian camp, gathering there until marches_at. + 'raid' => $m->player_id === null, + 'marches_at' => $m->player_id === null && $m->sent_at->greaterThan($now) ? self::iso($m->sent_at) : null, 'cancel_until' => $mine && ! $incoming && $m->type !== Movement::RETURN && $cancelUntil->greaterThan($now) ? self::iso($cancelUntil) : null, ]; })->values()->all(); diff --git a/config/game/raids.php b/config/game/raids.php new file mode 100644 index 0000000..8003891 --- /dev/null +++ b/config/game/raids.php @@ -0,0 +1,35 @@ + true, + + // Hours between two raids on one village, drawn evenly between the two. The first + // comes when beginner protection ends. + 'every_hours' => [18, 30], + + // The band gathers this long at its camp before it marches; the village sees it + // coming from the start, so this is the least warning it gets. + 'gather_hours' => 3, + + // Only barbarian villages this many fields away or closer raid a village; the nearest one does. + 'range' => 15, + + // Attack strength of a band: base + per_point × the village's points, in its camp's profile. + 'attack' => ['base' => 50, 'per_point' => 1.5], + + // From this many village points on, rams come along: per_wall_level for each wall level. + 'rams' => ['from_points' => 300, 'per_wall_level' => 1.0], + + // On arrival the band is as strong as its camp's garrison is (share of full strength); + // below scatter_below it scatters, so hitting the camp first breaks the raid. + 'scatter_below' => 0.25, + + // A beaten band leaves bounty × its attack strength in resources, a third each of + // wood, clay and iron, up to what the storage holds. + 'bounty' => 0.5, + + 'mode' => 'normal', +]; diff --git a/database/migrations/2026_10_31_090000_raids.php b/database/migrations/2026_10_31_090000_raids.php new file mode 100644 index 0000000..bc6e829 --- /dev/null +++ b/database/migrations/2026_10_31_090000_raids.php @@ -0,0 +1,23 @@ +unsignedBigInteger('player_id')->nullable()->change(); + }); + } + + public function down(): void + { + Schema::table('movements', function (Blueprint $table) { + $table->unsignedBigInteger('player_id')->nullable(false)->change(); + }); + } +}; diff --git a/database/seeders/WorldSeeder.php b/database/seeders/WorldSeeder.php index 2e5f11f..868d006 100644 --- a/database/seeders/WorldSeeder.php +++ b/database/seeders/WorldSeeder.php @@ -22,10 +22,12 @@ class WorldSeeder extends Seeder 'started_at' => now(), ]), ]; - // Barbarian villages that lost their growth event get it back, and their garrison. + // Barbarian villages that lost their growth event get it back, and their garrison; + // player villages get a raid planned. foreach ($worlds as $world) { app(SpawnBarbarians::class)->scheduleGrowth($world); app(SpawnBarbarians::class)->scheduleGarrisons($world); + app(SpawnBarbarians::class)->scheduleRaids($world); } } } diff --git a/docs/architecture.md b/docs/architecture.md index f5dcd07..780513d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -124,6 +124,7 @@ A village may fail through war or bad play, but it must never get stuck. Every l | 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. | | Player loses every village | The player can restart on the same world with a fresh village. | +| Raids bleed a village dry | Raids come `every_hours` apart, after beginner protection, and loot only what the hiding places don't cover; rams never take a wall below 1, and no band takes a village. Beating the camp down scatters its next band. Lint: intervals above 0, `scatter_below` above 0. | ## Config @@ -232,6 +233,16 @@ The visibility radius decides two things: Tribes arrive in M6, with ally, NAP (non-aggression pact), and enemy states between them. Until then, every other player is hostile. Hostility is checked at encounter time, not at send time. +## Raids + +Barbarian camps raid the player villages around them (`config/game/raids.php`, rules in `Raids`, rows in `Raiders`), so a village has something to defend against even on a quiet world. + +- Every player village has one `raid.planned` event waiting. The first fires when the owner's beginner protection ends (`world.join`, a conquest, or the seeder on deploy for villages from before raids). It picks the nearest barbarian village within `range` (15) fields and sends a band at the village, then plans the next raid `every_hours` (18 to 30, drawn per event) after this one arrives. With no camp in range it tries again after that interval. +- The band attacks with `attack.base + attack.per_point × village points` (50 + 1.5 × points) in its camp's garrison profile, plus `rams.per_wall_level` rams per wall level once the village has `rams.from_points` (300) points. It is an attack movement without a player (`player_id` null): it gathers at the camp for `gather_hours` (3) and then marches (`sent_at`), and the village sees it from the moment it is planned (`visible_at`). The payload marks it `raid` with `marches_at` while it gathers. +- On arrival it is as strong as its camp is then: each unit × the camp garrison's share of full strength. Below `scatter_below` (25%), or when the camp changed hands, it scatters and the village gets a report saying so. So striking the camp in the hours before a raid weakens or stops it. A conquered camp's raids are deleted with its other commands. +- The battle is an ordinary one at full morale. A won raid loots and returns to its camp, which keeps the loot (stock to raid back) and takes the survivors in as far as its garrison has room. A beaten band leaves `bounty` × its attack strength (0.5), a third each of wood, clay and iron, in the village. Reports carry `raid` and `bounty`. +- Feature tests run with raids off (`tests/Pest.php`), like barbarian spawns; `RaidTest` turns them on. + ## Conquest Villages change hands the Die Stämme way (`combat.conquest`, rules in `Conquest`, rows in `Nobility`): diff --git a/tests/Feature/RaidTest.php b/tests/Feature/RaidTest.php new file mode 100644 index 0000000..b36cbcd --- /dev/null +++ b/tests/Feature/RaidTest.php @@ -0,0 +1,148 @@ +travelTo(CarbonImmutable::parse('2026-10-29 12:00:00')); + config([ + 'game.raids.enabled' => true, + // One profile, so the band is known: 0.7 × 10 + 0.3 × 25 = 14.5 attack a head. + 'game.world.map.barbarians.garrison.profiles' => ['spearmen' => ['spear' => 0.7, 'sword' => 0.3]], + ]); +}); + +/** A barbarian camp at full strength 3 fields east of the village. */ +function raidCamp(Village $near, int $dx = 3): Village +{ + $types = ['headquarters', 'storage', 'farm', 'timber_camp', 'clay_pit', 'iron_mine']; + $camp = app(VillageFactory::class)->create($near->world, null, 'Barbarian village', $near->x + $dx, $near->y, array_fill_keys($types, 8)); + Barbarians::of($camp)->fill(); + + return $camp->fresh(); +} + +function pendingRaid(Village $village): ?CarbonImmutable +{ + return GameEvent::where('type', GameEvent::RAID_PLANNED)->where('village_id', $village->id)->whereNull('processed_at')->value('fire_at'); +} + +/** Past beginner protection, with the band announced. */ +function announced(Village $village): Movement +{ + test()->travel(3)->days(); + test()->artisan('game:events --once')->assertSuccessful(); + + return Movement::where('target_id', $village->id)->sole(); +} + +function arrive(Movement $movement): void +{ + test()->travelTo($movement->arrives_at); + test()->artisan('game:events --once')->assertSuccessful(); +} + +it('plans the first raid for when beginner protection ends', function () { + $village = startVillage(); + + expect(pendingRaid($village)->toDateTimeString())->toBe('2026-11-01 12:00:00'); +}); + +it('announces a band from the nearest camp hours before it arrives, and plans the next raid', function () { + $village = startVillage(); + raidCamp($village, 6); + $camp = raidCamp($village); + $movement = announced($village); + + // 50 + 1.5 × 21 points = 81.5 attack: 6 heads. They gather 3 h, then march 3 fields at 22 min. + expect($movement->origin_id)->toBe($camp->id) + ->and($movement->player_id)->toBeNull() + ->and($movement->units)->toBe(['spear' => 4, 'sword' => 2]) + ->and($movement->arrives_at->toDateTimeString())->toBe('2026-11-01 16:06:00'); + + $incoming = shown($village)['movements'][0]; + expect($incoming)->toMatchArray(['type' => 'attack', 'direction' => 'in', 'raid' => true, 'marches_at' => '2026-11-01T15:00:00.000Z', 'arrives_at' => '2026-11-01T16:06:00.000Z']) + ->and($incoming['units'])->toBeNull(); + + $next = pendingRaid($village); + expect($next->greaterThanOrEqualTo($movement->arrives_at->addHours(18)))->toBeTrue() + ->and($next->lessThanOrEqualTo($movement->arrives_at->addHours(30)))->toBeTrue(); +}); + +it('loots an undefended village and carries the loot back to its camp', function () { + $village = startVillage(); + $camp = raidCamp($village); + $movement = announced($village); + $campWood = $camp->fresh()->wood; + arrive($movement); + + $report = Report::where('player_id', $village->player_id)->sole(); + // 4 spears and 2 swords carry 4 × 25 + 2 × 15 = 130. + expect($report->type)->toBe('defense') + ->and($report->payload['won'])->toBeTrue() + ->and($report->payload['raid'])->toBeTrue() + ->and(array_sum($report->payload['loot']))->toBe(130); + + $home = $movement->fresh(); + expect($home->type)->toBe('return')->and($home->target_id)->toBe($camp->id); + arrive($home); + expect($camp->fresh()->wood)->toBeGreaterThan($campWood) + ->and(Barbarians::of($camp->fresh())->current())->toEqual(Barbarians::of($camp->fresh())->full()); +}); + +it('pays a bounty when the village beats the band', function () { + $village = startVillage(); + raidCamp($village); + $village->troops()->create(['home_village_id' => $village->id, 'unit' => 'sword', 'count' => 20]); + $movement = announced($village); + $wood = shown($village)['resources']['wood']; + arrive($movement); + + $report = Report::where('player_id', $village->player_id)->sole(); + // 4 × 10 + 2 × 25 = 90 attack → 45, a third each. + expect($report->payload['won'])->toBeFalse() + ->and($report->payload['bounty'])->toBe(['wood' => 15, 'clay' => 15, 'iron' => 15]) + ->and($report->payload['attacker']['lost'])->toBe(['spear' => 4, 'sword' => 2]) + ->and(Movement::count())->toBe(0) + ->and(shown($village)['resources']['wood'])->toBeGreaterThan($wood + 14); +}); + +it('sends a weaker band from a weakened camp, and none from a beaten one', function () { + $village = startVillage(); + $camp = raidCamp($village); + $movement = announced($village); + $camp->troops()->update(['count' => 0]); + $camp->troops()->where('unit', 'spear')->update(['count' => 6]); + arrive($movement); + + // 6 of 10 spears and no swords: 6 of 10 food → the band at 60%. + $report = Report::where('player_id', $village->player_id)->sole(); + expect($report->payload['attacker']['units'])->toBe(['spear' => 2, 'sword' => 1]); + + // Once the band is back, the camp is beaten down to nothing. + arrive($movement->fresh()); + $camp->troops()->delete(); + $this->travelTo(pendingRaid($village)); + $this->artisan('game:events --once')->assertSuccessful(); + arrive(Movement::where('target_id', $village->id)->where('type', 'attack')->sole()); + $scattered = Report::where('player_id', $village->player_id)->latest('id')->first(); + expect($scattered->payload)->toMatchArray(['raid' => true, 'scattered' => true]) + ->and(Movement::where('target_id', $village->id)->where('type', 'attack')->exists())->toBeFalse(); +}); + +it('plans raids for villages from before raids on deploy', function () { + $village = startVillage(); + GameEvent::where('type', GameEvent::RAID_PLANNED)->delete(); + + (new WorldSeeder)->run(); + expect(pendingRaid($village)->toDateTimeString())->toBe('2026-11-01 12:00:00'); + + (new WorldSeeder)->run(); + expect(GameEvent::where('type', GameEvent::RAID_PLANNED)->count())->toBe(1); +}); diff --git a/tests/Pest.php b/tests/Pest.php index 71667d3..23b8432 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -13,9 +13,9 @@ use Database\Seeders\WorldSeeder; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; -// Feature tests start without barbarians unless a test asks for them, so tests can place their own. +// Feature tests start without barbarians and raids unless a test asks for them, so tests can place their own. pest()->extend(TestCase::class)->use(RefreshDatabase::class) - ->beforeEach(fn () => config(['game.world.map.barbarians.per_join' => 0])) + ->beforeEach(fn () => config(['game.world.map.barbarians.per_join' => 0, 'game.raids.enabled' => false])) ->in('Feature'); /** The default game config without booting Laravel, so unit tests stay pure. */ @@ -30,6 +30,7 @@ function gameConfig(array $overrides = []): WorldConfig 'units' => require "$dir/units.php", 'combat' => require "$dir/combat.php", 'movement' => require "$dir/movement.php", + 'raids' => require "$dir/raids.php", 'quests' => require "$dir/quests.php", ], $overrides); } diff --git a/tests/Unit/Game/ConfigLintTest.php b/tests/Unit/Game/ConfigLintTest.php index a3c4296..4a19fd2 100644 --- a/tests/Unit/Game/ConfigLintTest.php +++ b/tests/Unit/Game/ConfigLintTest.php @@ -74,3 +74,11 @@ it('reports garrisons that would starve their village or never regroup', functio ->toContain('Barbarian garrisons must regroup: [regroup.every_hours] and [regroup.share] above 0.') ->toContain('[garrison.max_food_share] must stay below [economy.villager_share], or a garrison starves its village.'); }); +it('reports raids that never pause or that a beaten camp still sends', function () { + $config = gameConfig(['raids' => ['every_hours' => [0, 5], 'scatter_below' => 0, 'mode' => 'teleport']]); + + expect(ConfigLint::check($config)) + ->toContain('[raids.every_hours] must be two hours above 0, the smaller first, so a village gets time between raids.') + ->toContain('[raids.scatter_below] must be above 0 and at most 1, or beating the camp would not stop its raid.') + ->toContain('[raids.mode] is not a travel mode.'); +}); diff --git a/tests/Unit/Game/RaidsTest.php b/tests/Unit/Game/RaidsTest.php new file mode 100644 index 0000000..b4d1491 --- /dev/null +++ b/tests/Unit/Game/RaidsTest.php @@ -0,0 +1,56 @@ +attack(300))->toBe(500.0) + ->and($raids->band('spearmen', 300, 0))->toBe(['spear' => 25, 'sword' => 10]) + // Riders: 0.5 × 130 + 0.5 × 10 = 70 a head, 155 / 70 → 3 heads. + ->and($raids->band('riders', 70, 0))->toBe(['light_cavalry' => 2, 'spear' => 1]) + ->and($raids->band(null, 300, 0))->toBe([]); +}); + +it('brings rams against the wall of a big enough village', function () { + $raids = new Raids(gameConfig()); + + expect($raids->band('swordsmen', 300, 5))->toHaveKey('ram', 5) + ->and($raids->band('swordsmen', 299, 5))->not->toHaveKey('ram') + ->and($raids->band('swordsmen', 300, 0))->not->toHaveKey('ram'); +}); + +it('shrinks the band with its camp and scatters it below a quarter', function () { + $raids = new Raids(gameConfig()); + $band = ['spear' => 25, 'sword' => 10]; + + expect($raids->muster($band, 1.0))->toBe($band) + ->and($raids->muster($band, 0.5))->toBe(['spear' => 13, 'sword' => 5]) + ->and($raids->muster($band, 0.25))->toBe(['spear' => 6, 'sword' => 3]) + ->and($raids->muster($band, 0.24))->toBe([]); +}); + +it('leaves half its attack strength as bounty when beaten', function () { + // 25 × 10 + 10 × 25 = 500 attack → 250, a third each. + expect((new Raids(gameConfig()))->bounty(['spear' => 25, 'sword' => 10]))->toBe(['wood' => 83, 'clay' => 83, 'iron' => 83]); +}); + +it('comes every 18 to 30 hours at world speed, after a few hours of warning', function () { + $raids = new Raids(gameConfig()); + $fast = new Raids(gameConfig(['world' => ['speed' => 100]])); + + expect($raids->interval(0.0))->toBe(18 * 3600) + ->and($raids->interval(0.5))->toBe(24 * 3600) + ->and($fast->interval(0.5))->toBe(864) + ->and($raids->gatherSeconds())->toBe(3 * 3600) + ->and($fast->gatherSeconds())->toBe(108); +}); + +it('picks the nearest camp in range', function () { + $raids = new Raids(gameConfig()); + $camps = [['id' => 7, 'x' => 10, 'y' => 0], ['id' => 3, 'x' => 0, 'y' => 4], ['id' => 2, 'x' => 4, 'y' => 0], ['id' => 9, 'x' => 16, 'y' => 0]]; + + expect($raids->nearest($camps, 0, 0))->toBe(2) + ->and($raids->nearest([['id' => 9, 'x' => 16, 'y' => 0]], 0, 0))->toBeNull(); +});