From ab35b277ac3f591984a5cf4ff77577d468fc05a6 Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Wed, 28 Oct 2026 21:32:09 +0100 Subject: [PATCH] feat: spawn ring that grows with the world, and barbarian villages that grow over time Co-Authored-By: Claude Opus 5.5 --- app/Actions/JoinWorld.php | 2 +- app/Actions/SeedBarbarians.php | 26 ++++++++++ app/Engine/Engine.php | 27 ++++++++++ app/Engine/VillageFactory.php | 23 ++++++++- app/Game/Map/BarbarianGrowth.php | 34 +++++++++++++ app/Game/Map/SpawnRing.php | 67 +++++++++++++++++++++++++ app/Models/GameEvent.php | 2 + config/game/world.php | 11 +++- database/seeders/WorldSeeder.php | 4 +- docs/architecture.md | 2 +- docs/roadmap.md | 4 +- tests/Feature/JoinWorldTest.php | 20 +++++--- tests/Feature/MapTest.php | 37 ++++++++++++-- tests/Unit/Game/BarbarianGrowthTest.php | 17 +++++++ tests/Unit/Game/SpawnRingTest.php | 33 ++++++++++++ 15 files changed, 291 insertions(+), 18 deletions(-) create mode 100644 app/Game/Map/BarbarianGrowth.php create mode 100644 app/Game/Map/SpawnRing.php create mode 100644 tests/Unit/Game/BarbarianGrowthTest.php create mode 100644 tests/Unit/Game/SpawnRingTest.php diff --git a/app/Actions/JoinWorld.php b/app/Actions/JoinWorld.php index e8ca25c..7ee540f 100644 --- a/app/Actions/JoinWorld.php +++ b/app/Actions/JoinWorld.php @@ -26,7 +26,7 @@ final class JoinWorld } $taken = VillageFactory::takenSpots($world); - [$x, $y] = VillageFactory::freeSpot($world, $taken); + [$x, $y] = VillageFactory::spawnSpot($world, $taken); $levels = array_fill_keys($world->gameConfig()->get('world.village.start_buildings'), 0); return $this->villages->create($world, $player, "{$user->name}'s village", $x, $y, $levels); diff --git a/app/Actions/SeedBarbarians.php b/app/Actions/SeedBarbarians.php index 1708685..cd6e425 100644 --- a/app/Actions/SeedBarbarians.php +++ b/app/Actions/SeedBarbarians.php @@ -3,6 +3,8 @@ namespace App\Actions; use App\Engine\VillageFactory; +use App\Game\Map\BarbarianGrowth; +use App\Models\GameEvent; use App\Models\World; use Illuminate\Support\Facades\DB; @@ -16,6 +18,30 @@ final class SeedBarbarians public function __construct(private readonly VillageFactory $villages) {} + /** + * 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. + * + * @return int events scheduled + */ + public function scheduleGrowth(World $world): int + { + $interval = (new BarbarianGrowth($world->gameConfig()))->interval(); + $waiting = GameEvent::where('type', GameEvent::BARBARIAN_GROWS)->whereNull('processed_at')->select('village_id'); + $villages = $world->villages()->whereNull('player_id')->whereNotIn('id', $waiting)->pluck('id'); + $now = now()->toImmutable(); + foreach ($villages as $id) { + GameEvent::create([ + 'world_id' => $world->id, + 'village_id' => $id, + 'type' => GameEvent::BARBARIAN_GROWS, + 'fire_at' => $now->addSeconds((int) round($interval * (0.5 + mt_rand() / (mt_getrandmax() + 1)))), + ]); + } + + return $villages->count(); + } + /** @return int villages created */ public function __invoke(World $world): int { diff --git a/app/Engine/Engine.php b/app/Engine/Engine.php index 98aaee3..1f660e1 100644 --- a/app/Engine/Engine.php +++ b/app/Engine/Engine.php @@ -2,6 +2,7 @@ namespace App\Engine; +use App\Game\Map\BarbarianGrowth; use App\Models\GameEvent; use App\Models\Village; use Carbon\CarbonImmutable; @@ -83,9 +84,35 @@ final class Engine { match ($event->type) { GameEvent::BUILD_ORDER_FINISHED => $this->finishBuildOrder($village, $event), + GameEvent::BARBARIAN_GROWS => $this->growBarbarian($village, $event), }; } + /** One building of a barbarian village goes up a level; the next step is scheduled. */ + private function growBarbarian(Village $village, GameEvent $event): void + { + if ($village->player_id !== null) { + return; + } + $sim = Simulation::of($village); + $growth = new BarbarianGrowth($sim->config()); + // Seeded per event, so a replayed event picks the same building. + mt_srand($event->id); + $state = $growth->pick($sim->states(), mt_rand() / (mt_getrandmax() + 1)); + if (! $state) { + return; + } + $sim->settle($event->fire_at); + $village->buildings->firstWhere('id', $state->id)->increment('level'); + $village->points = $sim->points(); + GameEvent::create([ + 'world_id' => $village->world_id, + 'village_id' => $village->id, + 'type' => GameEvent::BARBARIAN_GROWS, + 'fire_at' => $event->fire_at->addSeconds($growth->interval()), + ]); + } + private function finishBuildOrder(Village $village, GameEvent $event): void { $sim = Simulation::of($village); diff --git a/app/Engine/VillageFactory.php b/app/Engine/VillageFactory.php index 2aef658..7e96385 100644 --- a/app/Engine/VillageFactory.php +++ b/app/Engine/VillageFactory.php @@ -3,6 +3,7 @@ namespace App\Engine; use App\Game\GameRuleViolation; +use App\Game\Map\SpawnRing; use App\Models\Player; use App\Models\Village; use App\Models\World; @@ -37,10 +38,28 @@ final class VillageFactory return $village; } + /** + * Where a new player starts: on the spawn ring, which moves outward as the world + * fills. Falls back to the nearest free field if the ring has no room. + * + * @param array $taken "x|y" => true, updated with the result + * @return array{0: int, 1: int} + */ + public static function spawnSpot(World $world, array &$taken): array + { + $players = $world->villages()->whereNotNull('player_id')->count(); + $spot = (new SpawnRing($world->gameConfig()))->pick($players, $taken, fn () => mt_rand() / (mt_getrandmax() + 1)); + if (! $spot) { + return self::freeSpot($world, $taken); + } + $taken["{$spot[0]}|{$spot[1]}"] = true; + + return $spot; + } + /** * First free coordinate on square rings around the map centre, every second field - * so villages don't touch. Stand-in for M2's spawn ring that moves outward as the - * world fills. + * so villages don't touch. * * @param array $taken "x|y" => true, updated with the result * @return array{0: int, 1: int} diff --git a/app/Game/Map/BarbarianGrowth.php b/app/Game/Map/BarbarianGrowth.php new file mode 100644 index 0000000..aad7d39 --- /dev/null +++ b/app/Game/Map/BarbarianGrowth.php @@ -0,0 +1,34 @@ +config->get('world.map.barbarians.growth.every_hours', 8); + + return max(1, (int) round($hours * 3600 / $this->config->speed())); + } + + /** + * Which building grows next, or null when all of them reached the cap. + * + * @param list $buildings + * @param float $random uniform in [0, 1) + */ + public function pick(array $buildings, float $random): ?BuildingState + { + $cap = $this->config->get('world.map.barbarians.growth.max_level', 10); + $open = array_values(array_filter($buildings, fn (BuildingState $b) => $b->level < $cap)); + + return $open ? $open[(int) floor($random * count($open))] : null; + } +} diff --git a/app/Game/Map/SpawnRing.php b/app/Game/Map/SpawnRing.php new file mode 100644 index 0000000..2e1917d --- /dev/null +++ b/app/Game/Map/SpawnRing.php @@ -0,0 +1,67 @@ +config->get('world.map.spawn'); + + return $spawn['start_radius'] + sqrt($playerVillages / (M_PI * $spawn['density'])); + } + + /** + * A free field near the ring with no village on any of its 8 neighbours, or null if + * none turned up. Each failed try widens the band around the ring a little. + * + * @param array $taken "x|y" => true + * @param Closure(): float $random uniform in [0, 1) + * @return array{0: int, 1: int}|null + */ + public function pick(int $playerVillages, array $taken, Closure $random): ?array + { + $size = $this->config->get('world.map.size', 1000); + $centre = $size / 2; + $radius = $this->radius($playerVillages); + $band = $this->config->get('world.map.spawn.band', 2); + + for ($try = 0; $try < 400; $try++) { + $angle = $random() * 2 * M_PI; + $distance = $radius + ($random() * 2 - 1) * ($band + $try / 40); + $x = (int) round($centre + cos($angle) * $distance); + $y = (int) round($centre + sin($angle) * $distance); + if ($x < 0 || $y < 0 || $x >= $size || $y >= $size || ! self::clear($x, $y, $taken)) { + continue; + } + + return [$x, $y]; + } + + return null; + } + + /** @param array $taken */ + private static function clear(int $x, int $y, array $taken): bool + { + for ($dy = -1; $dy <= 1; $dy++) { + for ($dx = -1; $dx <= 1; $dx++) { + if (isset($taken[($x + $dx).'|'.($y + $dy)])) { + return false; + } + } + } + + return true; + } +} diff --git a/app/Models/GameEvent.php b/app/Models/GameEvent.php index f77f2e8..1b4506d 100644 --- a/app/Models/GameEvent.php +++ b/app/Models/GameEvent.php @@ -10,6 +10,8 @@ class GameEvent extends Model { public const BUILD_ORDER_FINISHED = 'build_order.finished'; + public const BARBARIAN_GROWS = 'barbarian.grows'; + protected $guarded = []; protected $dateFormat = 'Y-m-d H:i:s.v'; diff --git a/config/game/world.php b/config/game/world.php index 60edc63..5a9f4be 100644 --- a/config/game/world.php +++ b/config/game/world.php @@ -25,6 +25,15 @@ return [ // Most fields one map.view may cover in each direction. 'max_view' => 61, // Seeded once per world around the map centre, buildings at random levels up to max_level. - 'barbarians' => ['count' => 120, 'radius' => 25, 'max_level' => 3], + // Every few hours (at world speed) one building of each grows a level, up to growth.max_level. + 'barbarians' => [ + 'count' => 120, + 'radius' => 25, + 'max_level' => 3, + 'growth' => ['every_hours' => 8, 'max_level' => 10], + ], + // New players start on a ring around the centre: start_radius + sqrt(players / (π·density)), + // ± band fields, never next to another village. + 'spawn' => ['start_radius' => 6, 'density' => 0.08, 'band' => 2], ], ]; diff --git a/database/seeders/WorldSeeder.php b/database/seeders/WorldSeeder.php index 7240e28..db57b7f 100644 --- a/database/seeders/WorldSeeder.php +++ b/database/seeders/WorldSeeder.php @@ -19,8 +19,10 @@ class WorldSeeder extends Seeder 'started_at' => now(), ]), ]; + $barbarians = app(SeedBarbarians::class); foreach ($worlds as $world) { - app(SeedBarbarians::class)($world); + $barbarians($world); + $barbarians->scheduleGrowth($world); } } } diff --git a/docs/architecture.md b/docs/architecture.md index df6c507..d21507b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -153,7 +153,7 @@ The map is square (`map.size`, default 1000 × 1000) and split into TW-style con `map.view {world_id, x, y, w, h}` returns the villages in a `w × h` window (at most `map.max_view` per side) centred on `x|y`, kept inside the map; without a centre it opens on the player's first village. Each village comes with its coordinates, continent, name, points, owner (null for barbarians) and whether it is the player's own. The client draws it like the Die Stämme map: a top-down field grid with coordinate rulers and continent lines. -So far (M2 in progress) players spawn on rings of every second field around the centre, and `SeedBarbarians` scatters `map.barbarians.count` barbarian villages with random low building levels within `radius` of the centre, once per world, keeping the inner spawn area free. +New players spawn on the spawn ring (`SpawnRing`): radius `start_radius + sqrt(players / (π · density))`, ± `band` fields, at a random angle, never on a field next to another village. `SeedBarbarians` scatters `map.barbarians.count` barbarian villages with random low building levels within `radius` of the centre, once per world, and every barbarian village has a `barbarian.grows` event: every `growth.every_hours` (at world speed) one building goes up a level, up to `growth.max_level`. ## Movements and encounters diff --git a/docs/roadmap.md b/docs/roadmap.md index 57b0563..fd0ba20 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -22,9 +22,9 @@ Each milestone ends with tests green, `ConfigLint` green, and something playable ## M2: Map and barbarian villages -- [ ] Map generation and spawn placement (for now: rings of every second field around the centre) +- [x] Spawn placement: a ring around the centre that grows with the number of players, never next to another village - [x] Barbarian villages: seeding around the centre with random levels, once per world -- [ ] Barbarian growth over time (world config) +- [x] Barbarian growth over time (world config) - [x] `map.view {world_id, x, y, w, h}` with village owner, points and continent; village points from building levels - [x] UI: Die Stämme-style coordinate map with rulers, continent lines, jump-to and village info diff --git a/tests/Feature/JoinWorldTest.php b/tests/Feature/JoinWorldTest.php index b126d1a..d35560a 100644 --- a/tests/Feature/JoinWorldTest.php +++ b/tests/Feature/JoinWorldTest.php @@ -3,13 +3,16 @@ use App\Actions\JoinWorld; use App\Actions\ListWorlds; use App\Actions\ShowVillage; +use App\Game\Map\Continent; use App\Models\User; use App\Models\World; it('starts a village with HQ, storage and farm at level 0', function () { $village = startVillage(); - expect($village->only('x', 'y', 'space', 'points'))->toBe(['x' => 500, 'y' => 500, 'space' => 50, 'points' => 21]) + // On the spawn ring: start radius 6 ± 2 around 500|500. + expect(hypot($village->x - 500, $village->y - 500))->toBeBetween(3.0, 9.0) + ->and($village->only('space', 'points'))->toBe(['space' => 50, 'points' => 21]) ->and($village->resources())->toBe(['wood' => 500.0, 'clay' => 500.0, 'iron' => 500.0, 'food' => 300.0]) ->and($village->buildings->map->only('type', 'level')->all())->toBe([ ['type' => 'headquarters', 'level' => 0], @@ -24,11 +27,16 @@ it('returns the same village when joining again', function () { expect(app(JoinWorld::class)(owner($village), $village->world_id)->id)->toBe($village->id); }); -it('spawns the next player on a free coordinate', function () { - $first = startVillage(); - $second = startVillage(User::factory()->create()); +it('spawns players on the ring, never next to another village', function () { + $villages = collect(range(1, 6))->map(fn () => startVillage(User::factory()->create())); - expect([$second->x, $second->y])->not->toBe([$first->x, $first->y]); + foreach ($villages as $a) { + foreach ($villages as $b) { + if ($a->isNot($b)) { + expect(max(abs($a->x - $b->x), abs($a->y - $b->y)))->toBeGreaterThanOrEqual(2); + } + } + } }); it('lists worlds with their speed and the player village', function () { @@ -46,7 +54,7 @@ it('shows a start village to its owner only', function () { $state = shown($village); expect($state['space'])->toBe(['used' => 17, 'max' => 50]) - ->and($state['continent'])->toBe('K55') + ->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]) diff --git a/tests/Feature/MapTest.php b/tests/Feature/MapTest.php index 89334de..2a7e257 100644 --- a/tests/Feature/MapTest.php +++ b/tests/Feature/MapTest.php @@ -2,6 +2,8 @@ use App\Actions\SeedBarbarians; use App\Actions\ShowMap; +use App\Game\Map\Continent; +use App\Models\GameEvent; use App\Models\User; use App\Models\Village; use App\Models\World; @@ -10,13 +12,20 @@ it('opens on the player village and marks it as their own', function () { $village = startVillage(); $other = startVillage(User::factory()->create(['name' => 'Bea'])); - $map = app(ShowMap::class)(owner($village), $village->world_id, null, null, 15, 15); + $map = app(ShowMap::class)(owner($village), $village->world_id, null, null, 41, 41); - expect($map)->toMatchArray(['center' => ['x' => 500, 'y' => 500], 'x' => 493, 'y' => 493, 'w' => 15, 'h' => 15, 'size' => 1000]) + expect($map)->toMatchArray([ + 'center' => ['x' => $village->x, 'y' => $village->y], + 'x' => $village->x - 20, + 'y' => $village->y - 20, + 'w' => 41, + 'h' => 41, + 'size' => 1000, + ]) ->and(collect($map['villages'])->keyBy('id')->sortKeys()->map(fn ($v) => [$v['x'], $v['y'], $v['own'], $v['player']['name'] ?? null, $v['continent']])->all()) ->toBe([ - $village->id => [500, 500, true, owner($village)->name, 'K55'], - $other->id => [498, 498, false, 'Bea', 'K44'], + $village->id => [$village->x, $village->y, true, owner($village)->name, Continent::of($village->x, $village->y)], + $other->id => [$other->x, $other->y, false, 'Bea', Continent::of($other->x, $other->y)], ]); }); @@ -45,3 +54,23 @@ it('seeds barbarian villages once per world, away from the spawn centre', functi $map = app(ShowMap::class)(owner($village), $world->id, 500, 500, 41, 41); expect(collect($map['villages'])->whereNull('player'))->toHaveCount(20); }); + +it('lets barbarian villages grow over time, one building per step', function () { + config(['game.world.map.barbarians' => ['count' => 3, 'radius' => 20, 'max_level' => 3, 'growth' => ['every_hours' => 1, 'max_level' => 10]]]); + $this->travelTo(now()->startOfMinute()); + $world = startVillage()->world_id; + $barbarians = fn () => Village::where('world_id', $world)->whereNull('player_id')->with('buildings')->get(); + $levels = fn () => $barbarians()->sum(fn ($v) => $v->buildings->sum('level')); + $pending = fn () => GameEvent::where('world_id', $world)->where('type', GameEvent::BARBARIAN_GROWS)->whereNull('processed_at')->count(); + $before = ['levels' => $levels(), 'points' => $barbarians()->sum('points')]; + + expect($pending())->toBe(3); + + // Each first step lands within 0.5–1.5 h, the next one an hour later. + $this->travel(3)->hours(); + $this->artisan('game:events --once')->assertSuccessful(); + + expect($levels())->toBeGreaterThanOrEqual($before['levels'] + 6) + ->and($barbarians()->sum('points'))->toBeGreaterThan($before['points']) + ->and($pending())->toBe(3); +}); diff --git a/tests/Unit/Game/BarbarianGrowthTest.php b/tests/Unit/Game/BarbarianGrowthTest.php new file mode 100644 index 0000000..b47b027 --- /dev/null +++ b/tests/Unit/Game/BarbarianGrowthTest.php @@ -0,0 +1,17 @@ +interval())->toBe(8 * 3600) + ->and((new BarbarianGrowth(gameConfig(['world' => ['speed' => 100]])))->interval())->toBe(288); +}); + +it('only grows buildings below the cap', function () { + $growth = new BarbarianGrowth(gameConfig()); + $buildings = [building(1, 'headquarters', 10), building(2, 'farm', 3), building(3, 'storage', 10)]; + + expect($growth->pick($buildings, 0.0)->id)->toBe(2) + ->and($growth->pick($buildings, 0.99)->id)->toBe(2) + ->and($growth->pick([building(1, 'farm', 10)], 0.5))->toBeNull(); +}); diff --git a/tests/Unit/Game/SpawnRingTest.php b/tests/Unit/Game/SpawnRingTest.php new file mode 100644 index 0000000..5f33072 --- /dev/null +++ b/tests/Unit/Game/SpawnRingTest.php @@ -0,0 +1,33 @@ +radius(0))->toBe(6.0) + ->and($ring->radius(100))->toEqualWithDelta(6 + sqrt(100 / (M_PI * 0.08)), 1e-9) + ->and($ring->radius(1000))->toBeGreaterThan($ring->radius(100)); +}); + +it('picks a field on the ring', function () { + // Angle 0 and no offset: straight east of the centre at the start radius. + expect((new SpawnRing(gameConfig()))->pick(0, [], sequence(0.0, 0.5)))->toBe([506, 500]); +}); + +it('never picks a field next to another village', function () { + $ring = new SpawnRing(gameConfig()); + + expect($ring->pick(0, ['507|501' => true], sequence(0.0, 0.5)))->toBeNull() + ->and($ring->pick(0, ['508|502' => true], sequence(0.0, 0.5)))->toBe([506, 500]); +});