From 99d70ef10ee59dcbc7a0de6762198094c1a25f06 Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Thu, 29 Oct 2026 16:31:34 +0100 Subject: [PATCH] feat: seasons: crown forts appear round 0|0, holding three of five for a week wins the world The worker ticks seasons every loop: due crowns are placed, a holder who reached ends_at wins, the world closes and the next one opens with the same rules. Ended worlds refuse changes, joins and raids. Payloads carry the season, worlds their winner, the map a crown flag. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/Actions/JoinWorld.php | 1 + app/Actions/ListWorlds.php | 6 +- app/Actions/ShowMap.php | 3 +- app/Actions/ShowVillage.php | 5 + app/Actions/SpawnBarbarians.php | 2 +- app/Actions/VillageAction.php | 9 ++ app/Actions/WithdrawSupport.php | 1 + app/Console/Commands/ProcessGameEvents.php | 3 + app/Console/Commands/ResetWorld.php | 2 +- app/Engine/Barbarians.php | 5 + app/Engine/Nobility.php | 3 + app/Engine/Raiders.php | 6 +- app/Engine/Seasons.php | 119 ++++++++++++++++++ app/Game/ConfigLint.php | 43 +++++++ app/Game/Map/Season.php | 80 ++++++++++++ app/Models/Village.php | 1 + app/Models/World.php | 23 ++++ app/Presenters/SeasonPresenter.php | 51 ++++++++ app/Presenters/VillagePresenter.php | 1 + config/game/world.php | 13 ++ .../migrations/2026_10_31_120000_seasons.php | 35 ++++++ docs/architecture.md | 9 ++ tests/Feature/JoinWorldTest.php | 4 +- tests/Feature/SeasonTest.php | 97 ++++++++++++++ tests/Unit/Game/ConfigLintTest.php | 11 ++ tests/Unit/Game/SeasonTest.php | 31 +++++ 26 files changed, 554 insertions(+), 10 deletions(-) create mode 100644 app/Engine/Seasons.php create mode 100644 app/Game/Map/Season.php create mode 100644 app/Presenters/SeasonPresenter.php create mode 100644 database/migrations/2026_10_31_120000_seasons.php create mode 100644 tests/Feature/SeasonTest.php create mode 100644 tests/Unit/Game/SeasonTest.php diff --git a/app/Actions/JoinWorld.php b/app/Actions/JoinWorld.php index 029f5cc..4217efa 100644 --- a/app/Actions/JoinWorld.php +++ b/app/Actions/JoinWorld.php @@ -24,6 +24,7 @@ final class JoinWorld public function __invoke(User $user, int $worldId, string $direction = 'random'): Village { $world = World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.'); + $world->ensureOpen(); if (! in_array($direction, Frontier::DIRECTIONS, true)) { throw new GameRuleViolation('direction', "Unknown direction [$direction]."); } diff --git a/app/Actions/ListWorlds.php b/app/Actions/ListWorlds.php index 40840db..31fdca2 100644 --- a/app/Actions/ListWorlds.php +++ b/app/Actions/ListWorlds.php @@ -8,18 +8,20 @@ use App\Models\World; final class ListWorlds { - /** @return list */ + /** @return list */ public function __invoke(User $user): array { $villageIds = Player::where('user_id', $user->id)->with('villages:id,player_id')->get() ->mapWithKeys(fn (Player $p) => [$p->world_id => $p->villages->min('id')]); - return World::orderBy('id')->get()->map(fn (World $world) => [ + return World::with('winner')->orderBy('id')->get()->map(fn (World $world) => [ 'id' => $world->id, 'name' => $world->name, 'slug' => $world->slug, 'speed' => $world->gameConfig()->speed(), 'village_id' => $villageIds[$world->id] ?? null, + 'ended_at' => $world->ended_at?->utc()->format('Y-m-d\TH:i:s.v\Z'), + 'winner' => $world->winner ? ['id' => $world->winner->id, 'name' => $world->winner->name] : null, ])->all(); } } diff --git a/app/Actions/ShowMap.php b/app/Actions/ShowMap.php index 84e2a25..997da99 100644 --- a/app/Actions/ShowMap.php +++ b/app/Actions/ShowMap.php @@ -45,7 +45,7 @@ final class ShowMap ->whereBetween('x', [$left, $left + $w - 1]) ->whereBetween('y', [$top, $top + $h - 1]) ->with('player:id,user_id,name') - ->get(['id', 'player_id', 'name', 'x', 'y', 'points']) + ->get(['id', 'player_id', 'crown', 'name', 'x', 'y', 'points']) ->map(fn (Village $v) => [ 'id' => $v->id, 'x' => $v->x, @@ -55,6 +55,7 @@ final class ShowMap 'continent' => Continent::of($v->x, $v->y, $size), 'player' => $v->player ? ['id' => $v->player->id, 'name' => $v->player->name] : null, 'own' => $v->player?->user_id === $user->id, + 'crown' => $v->crown, ])->values()->all(); return [ diff --git a/app/Actions/ShowVillage.php b/app/Actions/ShowVillage.php index 1d5d7ce..1cd7000 100644 --- a/app/Actions/ShowVillage.php +++ b/app/Actions/ShowVillage.php @@ -12,4 +12,9 @@ final class ShowVillage extends VillageAction { return $this->mutate($user, $villageId, fn () => null); } + + protected function readOnly(): bool + { + return true; + } } diff --git a/app/Actions/SpawnBarbarians.php b/app/Actions/SpawnBarbarians.php index 80b4312..56d5392 100644 --- a/app/Actions/SpawnBarbarians.php +++ b/app/Actions/SpawnBarbarians.php @@ -64,7 +64,7 @@ final class SpawnBarbarians public function scheduleGrowth(World $world): int { $waiting = GameEvent::where('type', GameEvent::BARBARIAN_GROWS)->whereNull('processed_at')->select('village_id'); - $villages = $world->villages()->whereNull('player_id')->whereNotIn('id', $waiting)->get(); + $villages = $world->villages()->whereNull('player_id')->where('crown', false)->whereNotIn('id', $waiting)->get(); foreach ($villages as $village) { $this->scheduleFirstGrowth($world, $village); } diff --git a/app/Actions/VillageAction.php b/app/Actions/VillageAction.php index d447f2d..bfdd4fa 100644 --- a/app/Actions/VillageAction.php +++ b/app/Actions/VillageAction.php @@ -40,6 +40,9 @@ abstract class VillageAction if (! $village || $village->player?->user_id !== $user->id) { throw new GameRuleViolation('not_found', 'Village not found.'); } + if (! $this->readOnly()) { + $village->world->ensureOpen(); + } $sim = Simulation::of($village); $sim->settle($now); Military::of($village, $sim)->settle($now); @@ -51,6 +54,12 @@ abstract class VillageAction }); } + /** Looking is allowed after the world ended; changing is not. */ + protected function readOnly(): bool + { + return false; + } + protected function building(Village $village, int $buildingId): Building { return $village->buildings->firstWhere('id', $buildingId) diff --git a/app/Actions/WithdrawSupport.php b/app/Actions/WithdrawSupport.php index 1f39797..51aa811 100644 --- a/app/Actions/WithdrawSupport.php +++ b/app/Actions/WithdrawSupport.php @@ -24,6 +24,7 @@ final class WithdrawSupport if (! $home || $home->player?->user_id !== $user->id) { throw new GameRuleViolation('not_found', 'Village not found.'); } + $home->world->ensureOpen(); $now = now()->toImmutable(); // Support that should have arrived by now has. $this->engine->catchUpAround($villageId, $now); diff --git a/app/Console/Commands/ProcessGameEvents.php b/app/Console/Commands/ProcessGameEvents.php index 61eeab6..181fb7c 100644 --- a/app/Console/Commands/ProcessGameEvents.php +++ b/app/Console/Commands/ProcessGameEvents.php @@ -4,6 +4,7 @@ namespace App\Console\Commands; use App\Engine\Engine; use App\Engine\Push; +use App\Engine\Seasons; use Illuminate\Console\Command; use Throwable; @@ -22,6 +23,8 @@ class ProcessGameEvents extends Command { do { $now = now()->toImmutable(); + // Crowns that are due appear, and a holder who kept them long enough wins. + Seasons::tick($now); while ($villageId = $engine->nextDueVillage($now)) { try { $engine->catchUp($villageId, $now); diff --git a/app/Console/Commands/ResetWorld.php b/app/Console/Commands/ResetWorld.php index 7c567c1..efe9816 100644 --- a/app/Console/Commands/ResetWorld.php +++ b/app/Console/Commands/ResetWorld.php @@ -40,7 +40,7 @@ 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()]); + $world->update(['started_at' => now(), 'crowns_placed_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/Barbarians.php b/app/Engine/Barbarians.php index f73132c..83cf856 100644 --- a/app/Engine/Barbarians.php +++ b/app/Engine/Barbarians.php @@ -40,6 +40,11 @@ final class Barbarians /** @return array full strength now, from the village's points and food */ public function full(): array { + // A crown fort holds its fixed garrison. + if ($this->village->crown) { + return array_map('intval', $this->sim->config()->get('world.season.garrison', [])); + } + return $this->garrison->full($this->profile(), (int) $this->village->points, $this->sim->workforce()->foodBudget); } diff --git a/app/Engine/Nobility.php b/app/Engine/Nobility.php index ada59df..60fbd01 100644 --- a/app/Engine/Nobility.php +++ b/app/Engine/Nobility.php @@ -112,6 +112,9 @@ final class Nobility $village->loyalty_at = $at; // Raiders come for the new owner's village too. Raiders::of($village)->ensurePlanned($at); + if ($village->crown) { + Seasons::recount($village, $at); + } return array_values(array_unique($touched)); } diff --git a/app/Engine/Raiders.php b/app/Engine/Raiders.php index d3d0517..492b741 100644 --- a/app/Engine/Raiders.php +++ b/app/Engine/Raiders.php @@ -51,7 +51,7 @@ final class Raiders public function plan(GameEvent $event): void { $at = $event->fire_at; - if ($this->village->player_id === null || ! $this->raids->enabled()) { + if ($this->village->player_id === null || ! $this->raids->enabled() || $this->village->world->ended_at) { return; } $protected = Rally::of($this->village, $this->sim)->protectedUntil($this->village->player); @@ -116,11 +116,11 @@ final class Raiders return $this->raids->muster($movement->units, Barbarians::of($camp)->strength()); } - /** The nearest barbarian village in range. */ + /** The nearest barbarian village in range; crown forts never raid. */ private function camp(): ?Village { $range = $this->raids->range(); - $camps = Village::where('world_id', $this->village->world_id)->whereNull('player_id') + $camps = Village::where('world_id', $this->village->world_id)->whereNull('player_id')->where('crown', false) ->whereBetween('x', [$this->village->x - $range, $this->village->x + $range]) ->whereBetween('y', [$this->village->y - $range, $this->village->y + $range]) ->get(['id', 'x', 'y']); diff --git a/app/Engine/Seasons.php b/app/Engine/Seasons.php new file mode 100644 index 0000000..3bfc9ce --- /dev/null +++ b/app/Engine/Seasons.php @@ -0,0 +1,119 @@ +get() as $world) { + try { + $season = new Season($world->gameConfig()); + $crownsAt = $season->crownsAt($world->started_at); + if (! $world->crowns_placed_at && $season->count() > 0 && $crownsAt->lessThanOrEqualTo($now)) { + self::placeCrowns($world->id, $crownsAt); + } + $world->refresh(); + if ($world->holder_player_id && $world->ends_at?->lessThanOrEqualTo($now)) { + self::end($world->id, $world->ends_at); + } + } catch (Throwable $e) { + // One broken world must not stop the others or the worker. + report($e); + } + } + } + + /** The crown forts appear on their ring, each on the free field nearest its spot. */ + public static function placeCrowns(int $worldId, CarbonImmutable $at): void + { + DB::transaction(function () use ($worldId, $at) { + $world = World::whereKey($worldId)->lockForUpdate()->first(); + if (! $world || $world->crowns_placed_at) { + return; + } + $config = $world->gameConfig(); + $taken = VillageFactory::takenSpots($world); + $bounds = MapBounds::of($config); + foreach ((new Season($config))->spots() as [$x, $y]) { + [$x, $y] = self::nearestFree($x, $y, $taken, $bounds); + $taken["$x|$y"] = false; + $crown = app(VillageFactory::class)->create($world, null, self::CROWN_NAME, $x, $y, $config->get('world.season.buildings', [])); + $crown->update(['crown' => true]); + Barbarians::of($crown)->fill(); + } + $world->update(['crowns_placed_at' => $at]); + }); + } + + /** + * After a crown changed hands: whoever holds more than half of them now starts the + * clock (ends_at), or the clock stops. $changed carries its new owner, not saved yet. + */ + public static function recount(Village $changed, CarbonImmutable $at): void + { + $world = World::whereKey($changed->world_id)->lockForUpdate()->first(); + if (! $world || $world->ended_at) { + return; + } + $season = new Season($world->gameConfig()); + $owners = Village::where('world_id', $world->id)->where('crown', true)->pluck('player_id', 'id'); + $owners[$changed->id] = $changed->player_id; + $holder = $season->holder($owners->all()); + if ($holder !== $world->holder_player_id) { + $world->update(['holder_player_id' => $holder, 'ends_at' => $holder ? $at->addSeconds($season->holdSeconds()) : null]); + } + } + + /** The holder wins: the world ends at $at and the next one opens with the same rules. */ + public static function end(int $worldId, CarbonImmutable $at): void + { + DB::transaction(function () use ($worldId, $at) { + $world = World::whereKey($worldId)->lockForUpdate()->first(); + if (! $world || $world->ended_at || ! $world->holder_player_id) { + return; + } + $world->update(['ended_at' => $at, 'winner_player_id' => $world->holder_player_id]); + $slug = Season::next($world->slug); + while (World::where('slug', $slug)->exists()) { + $slug = Season::next($slug); + } + World::create(['slug' => $slug, 'name' => Season::next($world->name), 'config' => $world->config, 'started_at' => $at]); + }); + } + + /** + * @param array $taken + * @return array{0: int, 1: int} + */ + private static function nearestFree(int $x, int $y, array $taken, MapBounds $bounds): array + { + for ($r = 0; $r <= $bounds->max(); $r++) { + for ($dy = -$r; $dy <= $r; $dy++) { + for ($dx = -$r; $dx <= $r; $dx++) { + if (max(abs($dx), abs($dy)) === $r && ! isset($taken[($x + $dx).'|'.($y + $dy)]) && $bounds->contains($x + $dx, $y + $dy)) { + return [$x + $dx, $y + $dy]; + } + } + } + } + + return [$x, $y]; + } +} diff --git a/app/Game/ConfigLint.php b/app/Game/ConfigLint.php index 6b1754c..28987c5 100644 --- a/app/Game/ConfigLint.php +++ b/app/Game/ConfigLint.php @@ -28,6 +28,7 @@ final class ConfigLint ...self::garrisonsRegroup($config), ...self::raidsPause($config), ...self::rolesReachable($config), + ...self::crownsHold($config), ]; } @@ -167,6 +168,48 @@ final class ConfigLint return $problems; } + /** + * Crown forts stand on real buildings at levels that exist, field real units, and + * feed them, or they would starve and fall apart before anyone takes them. + */ + private static function crownsHold(WorldConfig $config): array + { + $season = $config->get('world.season'); + if (! $season || ($season['crowns'] ?? 0) < 1) { + return []; + } + $rules = new BuildingRules($config); + $units = new UnitRules($config); + $problems = []; + $food = 0.0; + foreach ($season['buildings'] ?? [] as $type => $level) { + if (! $config->hasBuilding($type) || $level < 1 || $level > $rules->maxLevel($type)) { + $problems[] = "Crown forts have [$type] at level $level, which can't stand."; + + continue; + } + $output = $rules->output($type, $level); + $food += ($output['resource'] ?? null) === 'food' ? $output['per_hour'] : 0; + } + $upkeep = 0.0; + foreach ($season['garrison'] ?? [] as $unit => $count) { + if (! $units->exists($unit)) { + $problems[] = "Crown forts field unknown unit [$unit]."; + + continue; + } + $upkeep += $units->upkeep($unit) * $count; + } + if ($upkeep > $config->get('economy.villager_share', 0.8) * $food) { + $problems[] = 'A crown fort\'s garrison eats more than its farms leave over, so it would starve.'; + } + if (($season['hold_days'] ?? 0) <= 0 || ($season['crowns_after_days'] ?? -1) < 0) { + $problems[] = '[season.hold_days] must be above 0 and [season.crowns_after_days] at least 0.'; + } + + 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/Map/Season.php b/app/Game/Map/Season.php new file mode 100644 index 0000000..6c2bdef --- /dev/null +++ b/app/Game/Map/Season.php @@ -0,0 +1,80 @@ +addSeconds((int) round($this->config->get('world.season.crowns_after_days', 30) * 86400 / $this->config->speed())); + } + + /** How long a holder must keep the crowns to win, at world speed. */ + public function holdSeconds(): int + { + return max(1, (int) round($this->config->get('world.season.hold_days', 7) * 86400 / $this->config->speed())); + } + + public function count(): int + { + return (int) $this->config->get('world.season.crowns', 0); + } + + /** More than half of the crowns. */ + public function needed(): int + { + return intdiv($this->count(), 2) + 1; + } + + /** + * Where the crowns should stand: evenly round a ring of `radius` fields about 0|0. + * + * @return list + */ + public function spots(): array + { + $radius = (float) $this->config->get('world.season.radius', 10); + $spots = []; + for ($i = 0; $i < $this->count(); $i++) { + $angle = 2 * M_PI * $i / $this->count() - M_PI / 2; + $spots[] = [(int) round($radius * cos($angle)), (int) round($radius * sin($angle))]; + } + + return $spots; + } + + /** + * The player holding more than half of the crowns, if anyone does. + * + * @param iterable $owners the owner of every crown, null for barbarian + */ + public function holder(iterable $owners): ?int + { + $held = []; + foreach ($owners as $owner) { + if ($owner !== null) { + $held[$owner] = ($held[$owner] ?? 0) + 1; + } + } + arsort($held); + $top = array_key_first($held); + + return $top !== null && $held[$top] >= $this->needed() ? (int) $top : null; + } + + /** "w1" → "w2", "dev" → "dev2", "World 1" → "World 2". */ + public static function next(string $name): string + { + return preg_match('/^(.*?)(\d+)$/', $name, $m) ? $m[1].((int) $m[2] + 1) : $name.'2'; + } +} diff --git a/app/Models/Village.php b/app/Models/Village.php index 7b8ae19..0c42bf6 100644 --- a/app/Models/Village.php +++ b/app/Models/Village.php @@ -26,6 +26,7 @@ class Village extends Model 'starving_since' => 'immutable_datetime', 'loyalty' => 'float', 'loyalty_at' => 'immutable_datetime', + 'crown' => 'boolean', ]; } diff --git a/app/Models/World.php b/app/Models/World.php index 140fb79..6b3dde7 100644 --- a/app/Models/World.php +++ b/app/Models/World.php @@ -2,8 +2,10 @@ namespace App\Models; +use App\Game\GameRuleViolation; use App\Game\WorldConfig; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; class World extends Model @@ -15,7 +17,10 @@ class World extends Model return [ 'config' => 'array', 'started_at' => 'immutable_datetime', + 'crowns_placed_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', ]; } @@ -34,6 +39,24 @@ class World extends Model ], $this->config ?? []); } + /** Changes are refused once the season is over; the world stays to be looked at. */ + public function ensureOpen(): void + { + if ($this->ended_at) { + throw new GameRuleViolation('world_ended', 'This world has ended.'); + } + } + + public function holder(): BelongsTo + { + return $this->belongsTo(Player::class, 'holder_player_id'); + } + + public function winner(): BelongsTo + { + return $this->belongsTo(Player::class, 'winner_player_id'); + } + public function players(): HasMany { return $this->hasMany(Player::class); diff --git a/app/Presenters/SeasonPresenter.php b/app/Presenters/SeasonPresenter.php new file mode 100644 index 0000000..adc21d1 --- /dev/null +++ b/app/Presenters/SeasonPresenter.php @@ -0,0 +1,51 @@ +gameConfig()); + $crowns = $world->crowns_placed_at + ? Village::where('world_id', $world->id)->where('crown', true)->with('player:id,name')->orderBy('id')->get() + : collect(); + + return [ + // When they appear, or appeared. + 'crowns_at' => self::iso($world->crowns_placed_at ?? $season->crownsAt($world->started_at)), + 'count' => $season->count(), + 'needed' => $season->needed(), + 'hold_seconds' => $season->holdSeconds(), + 'crowns' => $crowns->map(fn (Village $v) => [ + 'id' => $v->id, + 'name' => $v->name, + 'x' => $v->x, + 'y' => $v->y, + 'player' => self::player($v->player), + ])->values()->all(), + 'holder' => self::player($world->holder), + // When the holder wins if they keep the crowns. + 'ends_at' => $world->ends_at ? self::iso($world->ends_at) : null, + 'ended_at' => $world->ended_at ? self::iso($world->ended_at) : null, + 'winner' => self::player($world->winner), + ]; + } + + private static function player(?Player $player): ?array + { + return $player ? ['id' => $player->id, 'name' => $player->name] : null; + } + + private static function iso(CarbonImmutable $at): string + { + return $at->utc()->format('Y-m-d\TH:i:s.v\Z'); + } +} diff --git a/app/Presenters/VillagePresenter.php b/app/Presenters/VillagePresenter.php index 021e68e..2e84ef5 100644 --- a/app/Presenters/VillagePresenter.php +++ b/app/Presenters/VillagePresenter.php @@ -79,6 +79,7 @@ final class VillagePresenter 'villages' => Village::where('player_id', $village->player_id)->orderBy('id')->get(['id', 'name', 'x', 'y', 'points']) ->map(fn (Village $v) => ['id' => $v->id, 'name' => $v->name, 'x' => $v->x, 'y' => $v->y, 'points' => $v->points])->all(), 'quests' => Quests::summary($village), + 'season' => SeasonPresenter::present($village->world), 'unread_reports' => Report::where('player_id', $village->player_id)->whereNull('read_at')->count(), 'builders' => $sim->builders(), 'buildings' => $village->buildings->map(function (Building $b) use ($sim, $workforce, $rules) { diff --git a/config/game/world.php b/config/game/world.php index 7cdc3bc..4d56e16 100644 --- a/config/game/world.php +++ b/config/game/world.php @@ -29,6 +29,19 @@ return [ 'start_buildings' => ['headquarters', 'storage', 'farm'], ], + // A world is a season. crowns_after_days (at world speed) after it starts, `crowns` + // crown forts appear on a ring of `radius` fields around 0|0: barbarian villages with + // these building levels and this garrison, which never raid. A player who holds more + // than half of them for hold_days wins; the world ends and the next one opens. + 'season' => [ + 'crowns_after_days' => 30, + 'crowns' => 5, + 'radius' => 10, + 'buildings' => ['headquarters' => 20, 'storage' => 20, 'farm' => 30, 'wall' => 20, 'timber_camp' => 15, 'clay_pit' => 15, 'iron_mine' => 15], + 'garrison' => ['spear' => 300, 'sword' => 300, 'archer' => 150, 'heavy_cavalry' => 50], + 'hold_days' => 7, + ], + 'builders' => [ 'base' => 2, // One more builder from each of these headquarters levels on. diff --git a/database/migrations/2026_10_31_120000_seasons.php b/database/migrations/2026_10_31_120000_seasons.php new file mode 100644 index 0000000..f1f0bde --- /dev/null +++ b/database/migrations/2026_10_31_120000_seasons.php @@ -0,0 +1,35 @@ +boolean('crown')->default(false)->after('player_id'); + }); + Schema::table('worlds', function (Blueprint $table) { + // ends_at (already there) is when the holder wins if they keep their crowns. + $table->dateTime('crowns_placed_at', 3)->nullable()->after('started_at'); + $table->foreignId('holder_player_id')->nullable()->after('crowns_placed_at')->constrained('players')->nullOnDelete(); + $table->foreignId('winner_player_id')->nullable()->after('holder_player_id')->constrained('players')->nullOnDelete(); + $table->dateTime('ended_at', 3)->nullable()->after('ends_at'); + }); + } + + public function down(): void + { + Schema::table('worlds', function (Blueprint $table) { + $table->dropConstrainedForeignId('holder_player_id'); + $table->dropConstrainedForeignId('winner_player_id'); + $table->dropColumn(['crowns_placed_at', 'ended_at']); + }); + Schema::table('villages', function (Blueprint $table) { + $table->dropColumn('crown'); + }); + } +}; diff --git a/docs/architecture.md b/docs/architecture.md index d6c3853..d466311 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -256,6 +256,15 @@ Villages change hands the Die Stämme way (`combat.conquest`, rules in `Conquest - A player who loses the last village joins the world again with a fresh one (`world.join`). - The village payload carries `loyalty`, `conquest: {coins, slots, used, next_slot_coins, coin_cost, max_distance}` and `villages` (the player's villages in the world, for the switcher). +## Seasons + +A world is a season with a winner (`world.season`, rules in `Season`, rows in `Seasons`). + +- `crowns_after_days` (30, at world speed) after `started_at`, `crowns` (5) crown forts appear evenly round a ring of `radius` (10) fields about 0|0, each on the free field nearest its spot (`villages.crown`). They are barbarian villages with the `season.buildings` levels (wall 20, farm 30) and the fixed `season.garrison`, which regroups like any garrison (`Barbarians::full`). They never grow and never raid. +- A crown is taken like any village, by noblemen. Each handover of a crown recounts: the player who holds more than half (3 of 5) becomes the world's `holder_player_id`, and `ends_at` is set `hold_days` (7, at world speed) out. Losing the majority clears both; winning it back starts the clock over. +- The `game:events` worker ticks `Seasons::tick` before every loop: it places due crowns and ends a world whose holder reached `ends_at` (`ended_at` is that moment, `winner_player_id` the holder). The next world opens at once with the same config, its slug and name counted up (`w1` → `w2`). An ended world stays readable, but every change, join and raid there is refused (`world_ended`). +- The village payload carries `season` (`SeasonPresenter`): when the crowns come, the crowns with their owners, the holder, `ends_at`, and the winner. `world.index` carries `ended_at` and `winner`, `map.view` a `crown` flag. + ## Ranking `ranking.index {world_id, kind, page?}` (`Ranking`) lists a world like Die Stämme's ranking, 25 rows a page; without a page it opens on the page with the user's own row (`own: {rank, page}`). Ties go to the older player or village. diff --git a/tests/Feature/JoinWorldTest.php b/tests/Feature/JoinWorldTest.php index 5d4e6a6..ea312cf 100644 --- a/tests/Feature/JoinWorldTest.php +++ b/tests/Feature/JoinWorldTest.php @@ -71,8 +71,8 @@ it('lists worlds with their speed and the player village', function () { $dev = World::where('slug', 'dev')->first(); expect(app(ListWorlds::class)(owner($village)))->toBe([ - ['id' => $village->world_id, 'name' => 'World 1', 'slug' => 'w1', 'speed' => 1.0, 'village_id' => $village->id], - ['id' => $dev->id, 'name' => 'Dev world', 'slug' => 'dev', 'speed' => 100.0, 'village_id' => null], + ['id' => $village->world_id, 'name' => 'World 1', 'slug' => 'w1', 'speed' => 1.0, 'village_id' => $village->id, 'ended_at' => null, 'winner' => null], + ['id' => $dev->id, 'name' => 'Dev world', 'slug' => 'dev', 'speed' => 100.0, 'village_id' => null, 'ended_at' => null, 'winner' => null], ]); }); diff --git a/tests/Feature/SeasonTest.php b/tests/Feature/SeasonTest.php new file mode 100644 index 0000000..96b94b6 --- /dev/null +++ b/tests/Feature/SeasonTest.php @@ -0,0 +1,97 @@ + $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00'))); + +/** The world's crown forts, in id order. */ +function crowns(World $world) +{ + return Village::where('world_id', $world->id)->where('crown', true)->orderBy('id')->get(); +} + +/** A conquest of a crown, the way the engine hands a village over. */ +function takeCrown(Village $crown, int $playerId): void +{ + $crown = $crown->fresh(); + Nobility::of($crown)->handOver($crown, $playerId, now()->toImmutable()); + $crown->save(); +} + +it('places the crown forts round 0|0 once the season is far enough along', function () { + $village = startVillage(); + $world = $village->world; + $this->travel(29)->days(); + $this->artisan('game:events --once')->assertSuccessful(); + expect(crowns($world))->toHaveCount(0) + ->and(shown($village)['season'])->toMatchArray(['count' => 5, 'needed' => 3, 'crowns' => [], 'holder' => null, 'ended_at' => null]); + + $this->travel(2)->days(); + $this->artisan('game:events --once')->assertSuccessful(); + $crowns = crowns($world); + expect($crowns)->toHaveCount(5) + ->and($crowns->every(fn (Village $c) => $c->player_id === null && hypot($c->x, $c->y) <= 12))->toBeTrue() + ->and(Barbarians::of($crowns[0])->current())->toEqual(['archer' => 150, 'heavy_cavalry' => 50, 'spear' => 300, 'sword' => 300]) + ->and($crowns[0]->buildings()->where('type', 'wall')->value('level'))->toBe(20) + ->and(shown($village)['season']['crowns'])->toHaveCount(5); + + // Only once, and crowns never grow. + Seasons::tick(now()->toImmutable()); + expect(crowns($world))->toHaveCount(5) + ->and(GameEvent::where('type', 'barbarian.grows')->whereIn('village_id', $crowns->pluck('id'))->exists())->toBeFalse(); +}); + +it('lets a player who holds three crowns for a week win, and opens the next world', function () { + $village = startVillage(); + $world = $village->world; + $rival = startVillage(); + Seasons::placeCrowns($world->id, now()->toImmutable()); + [$a, $b, $c, $d] = crowns($world); + + takeCrown($a, $village->player_id); + takeCrown($b, $village->player_id); + expect($world->fresh()->holder_player_id)->toBeNull(); + + takeCrown($c, $village->player_id); + expect($world->fresh())->holder_player_id->toBe($village->player_id) + ->and($world->fresh()->ends_at->toDateTimeString())->toBe('2026-11-05 12:00:00') + ->and(shown($village)['season']['holder'])->toBe(['id' => $village->player_id, 'name' => $village->player->name]); + + // The rival takes one back: the clock stops; three again starts it over. + $this->travel(3)->days(); + takeCrown($c, $rival->player_id); + expect($world->fresh()->holder_player_id)->toBeNull()->and($world->fresh()->ends_at)->toBeNull(); + takeCrown($d, $village->player_id); + expect($world->fresh()->ends_at->toDateTimeString())->toBe('2026-11-08 12:00:00'); + + $this->travel(7)->days(); + $this->artisan('game:events --once')->assertSuccessful(); + $ended = $world->fresh(); + expect($ended->ended_at->toDateTimeString())->toBe('2026-11-08 12:00:00') + ->and($ended->winner_player_id)->toBe($village->player_id) + ->and(World::where('slug', 'w2')->first())->name->toBe('World 2') + ->and(shown($village)['season']['winner']['id'])->toBe($village->player_id) + ->and(rule(fn () => app(QueueBuild::class)(owner($village), $village->id, 'timber_camp')))->toBe('world_ended') + ->and(rule(fn () => app(JoinWorld::class)(User::factory()->create(), $world->id)))->toBe('world_ended'); +}); + +it('keeps crowns out of raiding', function () { + config(['game.raids.enabled' => true]); + $village = startVillage(); + Seasons::placeCrowns($village->world_id, now()->toImmutable()); + $village->update(['x' => 0, 'y' => -8]); + + $this->travel(3)->days(); + $this->artisan('game:events --once')->assertSuccessful(); + expect(Movement::count())->toBe(0); +}); diff --git a/tests/Unit/Game/ConfigLintTest.php b/tests/Unit/Game/ConfigLintTest.php index fa9240a..82d9dc5 100644 --- a/tests/Unit/Game/ConfigLintTest.php +++ b/tests/Unit/Game/ConfigLintTest.php @@ -93,3 +93,14 @@ it('reports roles that share buildings or can never be reached', function () { ->toContain('[timber_camp] counts for two roles, [resources] and [military].') ->toContain('[specialisation.min_space] is more than a village has room for.'); }); +it('reports crown forts that would starve or stand on levels that do not exist', function () { + $config = gameConfig(['world' => ['season' => [ + 'buildings' => ['farm' => 2, 'wall' => 99], + 'garrison' => ['dragon' => 1], + ]]]); + + expect(ConfigLint::check($config)) + ->toContain('Crown forts have [wall] at level 99, which can\'t stand.') + ->toContain('Crown forts field unknown unit [dragon].') + ->toContain('A crown fort\'s garrison eats more than its farms leave over, so it would starve.'); +}); diff --git a/tests/Unit/Game/SeasonTest.php b/tests/Unit/Game/SeasonTest.php new file mode 100644 index 0000000..1799ce5 --- /dev/null +++ b/tests/Unit/Game/SeasonTest.php @@ -0,0 +1,31 @@ +crownsAt($start)->toDateTimeString())->toBe('2026-12-01 00:00:00') + ->and((new Season(gameConfig(['world' => ['speed' => 100]])))->crownsAt($start)->toDateTimeString())->toBe('2026-11-01 07:12:00') + ->and((new Season(gameConfig()))->holdSeconds())->toBe(7 * 86400); +}); + +it('places five crowns evenly round 0|0', function () { + expect((new Season(gameConfig()))->spots())->toBe([[0, -10], [10, -3], [6, 8], [-6, 8], [-10, -3]]); +}); + +it('needs more than half of the crowns to hold them', function () { + $season = new Season(gameConfig()); + + expect($season->needed())->toBe(3) + ->and($season->holder([4, 4, 4, null, 9]))->toBe(4) + ->and($season->holder([4, 4, 9, 9, null]))->toBeNull() + ->and($season->holder([null, null, null, null, null]))->toBeNull(); +}); + +it('names the next world', function () { + expect(Season::next('w1'))->toBe('w2') + ->and(Season::next('World 9'))->toBe('World 10') + ->and(Season::next('dev'))->toBe('dev2'); +});