diff --git a/app/Actions/SpawnBarbarians.php b/app/Actions/SpawnBarbarians.php index 56d5392..940fda9 100644 --- a/app/Actions/SpawnBarbarians.php +++ b/app/Actions/SpawnBarbarians.php @@ -16,7 +16,8 @@ use Illuminate\Support\Facades\DB; * Barbarian villages come with the players, as in Die Stämme: each joining player brings * `barbarians.per_join` of them on average, here placed within a few fields of the new * village so even a small world has something to loot from the start. They then grow - * by themselves (BarbarianGrowth). + * by themselves (BarbarianGrowth). Waves (Engine\Waves) bring more near the active + * players every few world days. */ final class SpawnBarbarians { @@ -32,29 +33,45 @@ final class SpawnBarbarians */ public function around(World $world, Village $village, array &$taken): array { - $config = $world->gameConfig(); - $frontier = new Frontier($config); - $maxLevel = $config->get('world.map.barbarians.max_level', 3); $created = []; - for ($n = $frontier->barbariansPerJoin(VillageFactory::random(...)); $n > 0; $n--) { - $spot = $frontier->near($village->x, $village->y, $taken, VillageFactory::random(...)); - if (! $spot) { + for ($n = (new Frontier($world->gameConfig()))->barbariansPerJoin(VillageFactory::random(...)); $n > 0; $n--) { + $barbarian = $this->near($world, $village, $taken); + if (! $barbarian) { break; } - $taken["{$spot[0]}|{$spot[1]}"] = false; - $levels = []; - foreach (self::BUILDINGS as $type) { - $levels[$type] = mt_rand(1, $maxLevel); - } - $barbarian = $this->villages->create($world, null, 'Barbarian village', $spot[0], $spot[1], $levels); - Barbarians::of($barbarian)->fill(); - $this->scheduleFirstGrowth($world, $barbarian); $created[] = $barbarian; } return $created; } + /** + * One barbarian village on a free field near a player's village, within $reach fields + * (`barbarians.near` unless given): buildings at random levels up to `max_level`, a + * full garrison and its first growth step. Null when no field near enough is free. + * + * @param array $taken updated with the new village + */ + public function near(World $world, Village $village, array &$taken, ?float $reach = null): ?Village + { + $config = $world->gameConfig(); + $spot = (new Frontier($config))->near($village->x, $village->y, $taken, VillageFactory::random(...), $reach); + if (! $spot) { + return null; + } + $taken["{$spot[0]}|{$spot[1]}"] = false; + $maxLevel = $config->get('world.map.barbarians.max_level', 3); + $levels = []; + foreach (self::BUILDINGS as $type) { + $levels[$type] = mt_rand(1, $maxLevel); + } + $barbarian = $this->villages->create($world, null, 'Barbarian village', $spot[0], $spot[1], $levels); + Barbarians::of($barbarian)->fill(); + $this->scheduleFirstGrowth($world, $barbarian); + + return $barbarian; + } + /** * Give every barbarian village without one a pending growth event, spread over one * interval so they don't all grow at once. Safe to run on every deploy. diff --git a/app/Console/Commands/ProcessGameEvents.php b/app/Console/Commands/ProcessGameEvents.php index 85b52f2..e8744f5 100644 --- a/app/Console/Commands/ProcessGameEvents.php +++ b/app/Console/Commands/ProcessGameEvents.php @@ -6,6 +6,7 @@ use App\Engine\Abandon; use App\Engine\Engine; use App\Engine\Push; use App\Engine\Seasons; +use App\Engine\Waves; use Illuminate\Console\Command; use Throwable; @@ -27,6 +28,8 @@ class ProcessGameEvents extends Command $now = now()->toImmutable(); // Crowns that are due appear, and a holder who kept them long enough wins. Seasons::tick($now); + // A barbarian wave that is due settles near the active players. + Waves::tick($now); // Once a minute: abandoned accounts lose their villages to the barbarians. if ($now->getTimestamp() - $lastAbandonCheck >= 60) { $lastAbandonCheck = $now->getTimestamp(); diff --git a/app/Console/Commands/ResetWorld.php b/app/Console/Commands/ResetWorld.php index efe9816..e24fd97 100644 --- a/app/Console/Commands/ResetWorld.php +++ b/app/Console/Commands/ResetWorld.php @@ -40,7 +40,8 @@ class ResetWorld extends Command Movement::where('world_id', $world->id)->delete(); Village::where('world_id', $world->id)->delete(); Player::where('world_id', $world->id)->delete(); - $world->update(['started_at' => now(), 'crowns_placed_at' => null, 'holder_player_id' => null, 'winner_player_id' => null, 'ends_at' => null, 'ended_at' => null]); + // The next barbarian wave is planned again from now, on the worker's next loop. + $world->update(['started_at' => now(), 'crowns_placed_at' => null, 'barbarians_at' => null, 'holder_player_id' => null, 'winner_player_id' => null, 'ends_at' => null, 'ended_at' => null]); }); $this->info("{$world->name} is empty again: $villages villages and $players players removed."); diff --git a/app/Engine/Waves.php b/app/Engine/Waves.php new file mode 100644 index 0000000..876fcb5 --- /dev/null +++ b/app/Engine/Waves.php @@ -0,0 +1,132 @@ +get() as $world) { + try { + if (! (new BarbarianWaves($world->gameConfig()))->enabled()) { + continue; + } + if (! $world->barbarians_at) { + self::start($world, $now); + } elseif ($world->barbarians_at->lessThanOrEqualTo($now)) { + Push::villages(self::wave($world->id, $now)); + } + } catch (Throwable $e) { + // One broken world must not stop the others or the worker. + report($e); + } + } + } + + /** A world without a next wave gets one an interval after $from. */ + public static function start(World $world, CarbonImmutable $from): void + { + $waves = new BarbarianWaves($world->gameConfig()); + if (! $waves->enabled() || $world->ended_at || $world->barbarians_at) { + return; + } + $at = $from->addSeconds($waves->interval(self::draw($world->id, $from))); + World::whereKey($world->id)->whereNull('barbarians_at')->update(['barbarians_at' => Engine::stamp($at)]); + $world->barbarians_at = $at; + } + + /** + * The world's due wave: per_player new barbarian villages for every active player, + * each near a random village of theirs, then the next wave an interval after this one. + * Seeded per world and wave, so a replay draws the same; the moved timer keeps a + * second run from spawning again. + * + * @return list the player villages that got new neighbours, for the push + */ + public static function wave(int $worldId, CarbonImmutable $now): array + { + return DB::transaction(function () use ($worldId, $now) { + $world = World::whereKey($worldId)->lockForUpdate()->first(); + $at = $world?->barbarians_at; + if (! $world || $world->ended_at || ! $at || $at->greaterThan($now)) { + return []; + } + $waves = new BarbarianWaves($world->gameConfig()); + mt_srand(self::seed($world->id, $at)); + try { + $next = $at->addSeconds($waves->interval(VillageFactory::random())); + $taken = VillageFactory::takenSpots($world); + $spawn = app(SpawnBarbarians::class); + $neighbours = []; + foreach (self::activePlayers($world, $at) as $player) { + $villages = $player->villages; + for ($n = $waves->perPlayer(VillageFactory::random()); $n > 0; $n--) { + $home = $villages[(int) floor(VillageFactory::random() * $villages->count())]; + if ($spawn->near($world, $home, $taken, $waves->near())) { + $neighbours[$home->id] = true; + } + } + } + } finally { + // Back to an unpredictable stream for everything after the wave. + mt_srand(); + } + $world->update(['barbarians_at' => $next]); + + return array_keys($neighbours); + }); + } + + /** + * Players with a village who were seen within world.inactive_days (real days) before + * the wave, or every player with a village when that rule is off. + * + * @return Collection + */ + private static function activePlayers(World $world, CarbonImmutable $at): Collection + { + $days = (float) $world->gameConfig()->get('world.inactive_days', 0); + $players = Player::where('world_id', $world->id)->whereHas('villages') + ->with(['villages' => fn ($q) => $q->orderBy('id')])->orderBy('id'); + if ($days > 0) { + $players->where('last_active_at', '>=', Engine::stamp($at->subSeconds((int) round($days * 86400)))); + } + + return $players->get(); + } + + /** Uniform in [0, 1), the same for one world and moment every time. */ + private static function draw(int $worldId, CarbonImmutable $at): float + { + mt_srand(self::seed($worldId, $at)); + try { + return VillageFactory::random(); + } finally { + mt_srand(); + } + } + + private static function seed(int $worldId, CarbonImmutable $at): int + { + return crc32("barbarian.wave|$worldId|{$at->getTimestamp()}"); + } +} diff --git a/app/Models/World.php b/app/Models/World.php index e461ea5..f73af00 100644 --- a/app/Models/World.php +++ b/app/Models/World.php @@ -18,6 +18,8 @@ class World extends Model 'config' => 'array', 'started_at' => 'immutable_datetime', 'crowns_placed_at' => 'immutable_datetime', + // When the next barbarian wave settles near the active players. + 'barbarians_at' => 'immutable_datetime', // When the holder wins if they keep the crowns; ended_at once someone has. 'ends_at' => 'immutable_datetime', 'ended_at' => 'immutable_datetime', diff --git a/database/migrations/2026_11_03_150000_barbarian_waves.php b/database/migrations/2026_11_03_150000_barbarian_waves.php new file mode 100644 index 0000000..ca4dd4b --- /dev/null +++ b/database/migrations/2026_11_03_150000_barbarian_waves.php @@ -0,0 +1,23 @@ +dateTime('barbarians_at', 3)->nullable()->after('crowns_placed_at'); + }); + } + + public function down(): void + { + Schema::table('worlds', function (Blueprint $table) { + $table->dropColumn('barbarians_at'); + }); + } +}; diff --git a/database/seeders/WorldSeeder.php b/database/seeders/WorldSeeder.php index 868d006..41ba75b 100644 --- a/database/seeders/WorldSeeder.php +++ b/database/seeders/WorldSeeder.php @@ -3,12 +3,14 @@ namespace Database\Seeders; use App\Actions\SpawnBarbarians; +use App\Engine\Waves; use App\Models\World; use Illuminate\Database\Seeder; /** * The default world and a fast dev world. They start empty: villages, barbarian ones - * included, come with the players who join. Safe to run on every deploy. + * included, come with the players who join and the barbarian waves near them. Safe to + * run on every deploy. */ class WorldSeeder extends Seeder { @@ -29,5 +31,9 @@ class WorldSeeder extends Seeder app(SpawnBarbarians::class)->scheduleGarrisons($world); app(SpawnBarbarians::class)->scheduleRaids($world); } + // Every open world without a barbarian wave planned gets one an interval from now. + foreach (World::whereNull('ended_at')->whereNull('barbarians_at')->get() as $world) { + Waves::start($world, now()->toImmutable()); + } } } diff --git a/tests/Pest.php b/tests/Pest.php index d11ca6e..04ce2ec 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -13,9 +13,14 @@ use Database\Seeders\WorldSeeder; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; -// Feature tests start without barbarians, raids and the inactivity rule unless a test asks for them. +// Feature tests start without barbarians, their waves, raids and the inactivity rule unless a test asks for them. pest()->extend(TestCase::class)->use(RefreshDatabase::class) - ->beforeEach(fn () => config(['game.world.map.barbarians.per_join' => 0, 'game.raids.enabled' => false, 'game.world.inactive_days' => 0])) + ->beforeEach(fn () => config([ + 'game.world.map.barbarians.per_join' => 0, + 'game.world.map.barbarians.waves.enabled' => false, + 'game.raids.enabled' => false, + 'game.world.inactive_days' => 0, + ])) ->in('Feature'); /** The default game config without booting Laravel, so unit tests stay pure. */