feat: barbarian waves: every few world days new barbarian villages settle near the active players (worlds.barbarians_at, ticked by game:events)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-11-03 09:33:52 +01:00
parent 118104ddef
commit cd1160800f
8 changed files with 208 additions and 19 deletions

View File

@ -16,7 +16,8 @@ use Illuminate\Support\Facades\DB;
* Barbarian villages come with the players, as in Die Stämme: each joining player brings * 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 * `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 * 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 final class SpawnBarbarians
{ {
@ -32,29 +33,45 @@ final class SpawnBarbarians
*/ */
public function around(World $world, Village $village, array &$taken): array 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 = []; $created = [];
for ($n = $frontier->barbariansPerJoin(VillageFactory::random(...)); $n > 0; $n--) { for ($n = (new Frontier($world->gameConfig()))->barbariansPerJoin(VillageFactory::random(...)); $n > 0; $n--) {
$spot = $frontier->near($village->x, $village->y, $taken, VillageFactory::random(...)); $barbarian = $this->near($world, $village, $taken);
if (! $spot) { if (! $barbarian) {
break; 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; $created[] = $barbarian;
} }
return $created; 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<string, bool> $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 * 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. * interval so they don't all grow at once. Safe to run on every deploy.

View File

@ -6,6 +6,7 @@ use App\Engine\Abandon;
use App\Engine\Engine; use App\Engine\Engine;
use App\Engine\Push; use App\Engine\Push;
use App\Engine\Seasons; use App\Engine\Seasons;
use App\Engine\Waves;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Throwable; use Throwable;
@ -27,6 +28,8 @@ class ProcessGameEvents extends Command
$now = now()->toImmutable(); $now = now()->toImmutable();
// Crowns that are due appear, and a holder who kept them long enough wins. // Crowns that are due appear, and a holder who kept them long enough wins.
Seasons::tick($now); 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. // Once a minute: abandoned accounts lose their villages to the barbarians.
if ($now->getTimestamp() - $lastAbandonCheck >= 60) { if ($now->getTimestamp() - $lastAbandonCheck >= 60) {
$lastAbandonCheck = $now->getTimestamp(); $lastAbandonCheck = $now->getTimestamp();

View File

@ -40,7 +40,8 @@ class ResetWorld extends Command
Movement::where('world_id', $world->id)->delete(); Movement::where('world_id', $world->id)->delete();
Village::where('world_id', $world->id)->delete(); Village::where('world_id', $world->id)->delete();
Player::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."); $this->info("{$world->name} is empty again: $villages villages and $players players removed.");

132
app/Engine/Waves.php Normal file
View File

@ -0,0 +1,132 @@
<?php
namespace App\Engine;
use App\Actions\SpawnBarbarians;
use App\Game\Map\BarbarianWaves;
use App\Models\Player;
use App\Models\World;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Throwable;
/**
* Barbarian waves (architecture.md, "Map"): every few world days new barbarian villages
* settle near the active players, so a world with few players keeps moving. Each world
* keeps its next wave in `barbarians_at`; the game:events worker ticks every loop.
*/
final class Waves
{
/**
* Start the timer of every open world that has none, and run each world's wave once
* it is due: one wave per world and tick, so a worker that was down catches up loop
* by loop.
*/
public static function tick(CarbonImmutable $now): void
{
foreach (World::whereNull('ended_at')->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<int> 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<int, Player>
*/
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()}");
}
}

View File

@ -18,6 +18,8 @@ class World extends Model
'config' => 'array', 'config' => 'array',
'started_at' => 'immutable_datetime', 'started_at' => 'immutable_datetime',
'crowns_placed_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. // When the holder wins if they keep the crowns; ended_at once someone has.
'ends_at' => 'immutable_datetime', 'ends_at' => 'immutable_datetime',
'ended_at' => 'immutable_datetime', 'ended_at' => 'immutable_datetime',

View File

@ -0,0 +1,23 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// Barbarian waves: when the next one settles new barbarian villages near the active players.
return new class extends Migration
{
public function up(): void
{
Schema::table('worlds', function (Blueprint $table) {
$table->dateTime('barbarians_at', 3)->nullable()->after('crowns_placed_at');
});
}
public function down(): void
{
Schema::table('worlds', function (Blueprint $table) {
$table->dropColumn('barbarians_at');
});
}
};

View File

@ -3,12 +3,14 @@
namespace Database\Seeders; namespace Database\Seeders;
use App\Actions\SpawnBarbarians; use App\Actions\SpawnBarbarians;
use App\Engine\Waves;
use App\Models\World; use App\Models\World;
use Illuminate\Database\Seeder; use Illuminate\Database\Seeder;
/** /**
* The default world and a fast dev world. They start empty: villages, barbarian ones * 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 class WorldSeeder extends Seeder
{ {
@ -29,5 +31,9 @@ class WorldSeeder extends Seeder
app(SpawnBarbarians::class)->scheduleGarrisons($world); app(SpawnBarbarians::class)->scheduleGarrisons($world);
app(SpawnBarbarians::class)->scheduleRaids($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());
}
} }
} }

View File

@ -13,9 +13,14 @@ use Database\Seeders\WorldSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase; 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) 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'); ->in('Feature');
/** The default game config without booting Laravel, so unit tests stay pure. */ /** The default game config without booting Laravel, so unit tests stay pure. */