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) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-29 16:31:34 +01:00
parent 594ce4dcdc
commit 99d70ef10e
26 changed files with 554 additions and 10 deletions

View File

@ -24,6 +24,7 @@ final class JoinWorld
public function __invoke(User $user, int $worldId, string $direction = 'random'): Village public function __invoke(User $user, int $worldId, string $direction = 'random'): Village
{ {
$world = World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.'); $world = World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.');
$world->ensureOpen();
if (! in_array($direction, Frontier::DIRECTIONS, true)) { if (! in_array($direction, Frontier::DIRECTIONS, true)) {
throw new GameRuleViolation('direction', "Unknown direction [$direction]."); throw new GameRuleViolation('direction', "Unknown direction [$direction].");
} }

View File

@ -8,18 +8,20 @@ use App\Models\World;
final class ListWorlds final class ListWorlds
{ {
/** @return list<array{id: int, name: string, slug: string, speed: float, village_id: int|null}> */ /** @return list<array{id: int, name: string, slug: string, speed: float, village_id: int|null, ended_at: string|null, winner: array{id: int, name: string}|null}> */
public function __invoke(User $user): array public function __invoke(User $user): array
{ {
$villageIds = Player::where('user_id', $user->id)->with('villages:id,player_id')->get() $villageIds = Player::where('user_id', $user->id)->with('villages:id,player_id')->get()
->mapWithKeys(fn (Player $p) => [$p->world_id => $p->villages->min('id')]); ->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, 'id' => $world->id,
'name' => $world->name, 'name' => $world->name,
'slug' => $world->slug, 'slug' => $world->slug,
'speed' => $world->gameConfig()->speed(), 'speed' => $world->gameConfig()->speed(),
'village_id' => $villageIds[$world->id] ?? null, '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(); ])->all();
} }
} }

View File

@ -45,7 +45,7 @@ final class ShowMap
->whereBetween('x', [$left, $left + $w - 1]) ->whereBetween('x', [$left, $left + $w - 1])
->whereBetween('y', [$top, $top + $h - 1]) ->whereBetween('y', [$top, $top + $h - 1])
->with('player:id,user_id,name') ->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) => [ ->map(fn (Village $v) => [
'id' => $v->id, 'id' => $v->id,
'x' => $v->x, 'x' => $v->x,
@ -55,6 +55,7 @@ final class ShowMap
'continent' => Continent::of($v->x, $v->y, $size), 'continent' => Continent::of($v->x, $v->y, $size),
'player' => $v->player ? ['id' => $v->player->id, 'name' => $v->player->name] : null, 'player' => $v->player ? ['id' => $v->player->id, 'name' => $v->player->name] : null,
'own' => $v->player?->user_id === $user->id, 'own' => $v->player?->user_id === $user->id,
'crown' => $v->crown,
])->values()->all(); ])->values()->all();
return [ return [

View File

@ -12,4 +12,9 @@ final class ShowVillage extends VillageAction
{ {
return $this->mutate($user, $villageId, fn () => null); return $this->mutate($user, $villageId, fn () => null);
} }
protected function readOnly(): bool
{
return true;
}
} }

View File

@ -64,7 +64,7 @@ final class SpawnBarbarians
public function scheduleGrowth(World $world): int public function scheduleGrowth(World $world): int
{ {
$waiting = GameEvent::where('type', GameEvent::BARBARIAN_GROWS)->whereNull('processed_at')->select('village_id'); $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) { foreach ($villages as $village) {
$this->scheduleFirstGrowth($world, $village); $this->scheduleFirstGrowth($world, $village);
} }

View File

@ -40,6 +40,9 @@ abstract class VillageAction
if (! $village || $village->player?->user_id !== $user->id) { if (! $village || $village->player?->user_id !== $user->id) {
throw new GameRuleViolation('not_found', 'Village not found.'); throw new GameRuleViolation('not_found', 'Village not found.');
} }
if (! $this->readOnly()) {
$village->world->ensureOpen();
}
$sim = Simulation::of($village); $sim = Simulation::of($village);
$sim->settle($now); $sim->settle($now);
Military::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 protected function building(Village $village, int $buildingId): Building
{ {
return $village->buildings->firstWhere('id', $buildingId) return $village->buildings->firstWhere('id', $buildingId)

View File

@ -24,6 +24,7 @@ final class WithdrawSupport
if (! $home || $home->player?->user_id !== $user->id) { if (! $home || $home->player?->user_id !== $user->id) {
throw new GameRuleViolation('not_found', 'Village not found.'); throw new GameRuleViolation('not_found', 'Village not found.');
} }
$home->world->ensureOpen();
$now = now()->toImmutable(); $now = now()->toImmutable();
// Support that should have arrived by now has. // Support that should have arrived by now has.
$this->engine->catchUpAround($villageId, $now); $this->engine->catchUpAround($villageId, $now);

View File

@ -4,6 +4,7 @@ namespace App\Console\Commands;
use App\Engine\Engine; use App\Engine\Engine;
use App\Engine\Push; use App\Engine\Push;
use App\Engine\Seasons;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Throwable; use Throwable;
@ -22,6 +23,8 @@ class ProcessGameEvents extends Command
{ {
do { do {
$now = now()->toImmutable(); $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)) { while ($villageId = $engine->nextDueVillage($now)) {
try { try {
$engine->catchUp($villageId, $now); $engine->catchUp($villageId, $now);

View File

@ -40,7 +40,7 @@ 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()]); $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."); $this->info("{$world->name} is empty again: $villages villages and $players players removed.");

View File

@ -40,6 +40,11 @@ final class Barbarians
/** @return array<string, int> full strength now, from the village's points and food */ /** @return array<string, int> full strength now, from the village's points and food */
public function full(): array 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); return $this->garrison->full($this->profile(), (int) $this->village->points, $this->sim->workforce()->foodBudget);
} }

View File

@ -112,6 +112,9 @@ final class Nobility
$village->loyalty_at = $at; $village->loyalty_at = $at;
// Raiders come for the new owner's village too. // Raiders come for the new owner's village too.
Raiders::of($village)->ensurePlanned($at); Raiders::of($village)->ensurePlanned($at);
if ($village->crown) {
Seasons::recount($village, $at);
}
return array_values(array_unique($touched)); return array_values(array_unique($touched));
} }

View File

@ -51,7 +51,7 @@ final class Raiders
public function plan(GameEvent $event): void public function plan(GameEvent $event): void
{ {
$at = $event->fire_at; $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; return;
} }
$protected = Rally::of($this->village, $this->sim)->protectedUntil($this->village->player); $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()); 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 private function camp(): ?Village
{ {
$range = $this->raids->range(); $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('x', [$this->village->x - $range, $this->village->x + $range])
->whereBetween('y', [$this->village->y - $range, $this->village->y + $range]) ->whereBetween('y', [$this->village->y - $range, $this->village->y + $range])
->get(['id', 'x', 'y']); ->get(['id', 'x', 'y']);

119
app/Engine/Seasons.php Normal file
View File

@ -0,0 +1,119 @@
<?php
namespace App\Engine;
use App\Game\Map\MapBounds;
use App\Game\Map\Season;
use App\Models\Village;
use App\Models\World;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Throwable;
/**
* Worlds as seasons (architecture.md, "Seasons"). The game:events worker ticks every
* loop: crowns appear when they are due, and a holder who kept them long enough wins.
* A conquest of a crown recounts who holds them.
*/
final class Seasons
{
public const CROWN_NAME = 'Crown fort';
/** Place crowns and end worlds that are due by $now. */
public static function tick(CarbonImmutable $now): void
{
foreach (World::whereNull('ended_at')->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<string, bool> $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];
}
}

View File

@ -28,6 +28,7 @@ final class ConfigLint
...self::garrisonsRegroup($config), ...self::garrisonsRegroup($config),
...self::raidsPause($config), ...self::raidsPause($config),
...self::rolesReachable($config), ...self::rolesReachable($config),
...self::crownsHold($config),
]; ];
} }
@ -167,6 +168,48 @@ final class ConfigLint
return $problems; 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. */ /** 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 private static function timersRun(WorldConfig $config): array
{ {

80
app/Game/Map/Season.php Normal file
View File

@ -0,0 +1,80 @@
<?php
namespace App\Game\Map;
use App\Game\WorldConfig;
use Carbon\CarbonImmutable;
/**
* A world as a season (world.season): when the crown forts appear, where they stand, who
* holds them, when a holder wins, and what the next world is called.
*/
final class Season
{
public function __construct(private readonly WorldConfig $config) {}
/** When the crowns appear: crowns_after_days after the start, at world speed. */
public function crownsAt(CarbonImmutable $startedAt): CarbonImmutable
{
return $startedAt->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<array{0: int, 1: int}>
*/
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<?int> $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';
}
}

View File

@ -26,6 +26,7 @@ class Village extends Model
'starving_since' => 'immutable_datetime', 'starving_since' => 'immutable_datetime',
'loyalty' => 'float', 'loyalty' => 'float',
'loyalty_at' => 'immutable_datetime', 'loyalty_at' => 'immutable_datetime',
'crown' => 'boolean',
]; ];
} }

View File

@ -2,8 +2,10 @@
namespace App\Models; namespace App\Models;
use App\Game\GameRuleViolation;
use App\Game\WorldConfig; use App\Game\WorldConfig;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
class World extends Model class World extends Model
@ -15,7 +17,10 @@ class World extends Model
return [ return [
'config' => 'array', 'config' => 'array',
'started_at' => 'immutable_datetime', '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', 'ends_at' => 'immutable_datetime',
'ended_at' => 'immutable_datetime',
]; ];
} }
@ -34,6 +39,24 @@ class World extends Model
], $this->config ?? []); ], $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 public function players(): HasMany
{ {
return $this->hasMany(Player::class); return $this->hasMany(Player::class);

View File

@ -0,0 +1,51 @@
<?php
namespace App\Presenters;
use App\Game\Map\Season;
use App\Models\Player;
use App\Models\Village;
use App\Models\World;
use Carbon\CarbonImmutable;
/** The season part of `village.show`: when the crowns come, who holds them, and the end. */
final class SeasonPresenter
{
public static function present(World $world): array
{
$season = new Season($world->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');
}
}

View File

@ -79,6 +79,7 @@ final class VillagePresenter
'villages' => Village::where('player_id', $village->player_id)->orderBy('id')->get(['id', 'name', 'x', 'y', 'points']) '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(), ->map(fn (Village $v) => ['id' => $v->id, 'name' => $v->name, 'x' => $v->x, 'y' => $v->y, 'points' => $v->points])->all(),
'quests' => Quests::summary($village), 'quests' => Quests::summary($village),
'season' => SeasonPresenter::present($village->world),
'unread_reports' => Report::where('player_id', $village->player_id)->whereNull('read_at')->count(), 'unread_reports' => Report::where('player_id', $village->player_id)->whereNull('read_at')->count(),
'builders' => $sim->builders(), 'builders' => $sim->builders(),
'buildings' => $village->buildings->map(function (Building $b) use ($sim, $workforce, $rules) { 'buildings' => $village->buildings->map(function (Building $b) use ($sim, $workforce, $rules) {

View File

@ -29,6 +29,19 @@ return [
'start_buildings' => ['headquarters', 'storage', 'farm'], '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' => [ 'builders' => [
'base' => 2, 'base' => 2,
// One more builder from each of these headquarters levels on. // One more builder from each of these headquarters levels on.

View File

@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// A world is a season: crown villages appear, a holder wins, the world ends.
return new class extends Migration
{
public function up(): void
{
Schema::table('villages', function (Blueprint $table) {
$table->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');
});
}
};

View File

@ -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`). - 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). - 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
`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. `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.

View File

@ -71,8 +71,8 @@ it('lists worlds with their speed and the player village', function () {
$dev = World::where('slug', 'dev')->first(); $dev = World::where('slug', 'dev')->first();
expect(app(ListWorlds::class)(owner($village)))->toBe([ expect(app(ListWorlds::class)(owner($village)))->toBe([
['id' => $village->world_id, 'name' => 'World 1', 'slug' => 'w1', 'speed' => 1.0, 'village_id' => $village->id], ['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], ['id' => $dev->id, 'name' => 'Dev world', 'slug' => 'dev', 'speed' => 100.0, 'village_id' => null, 'ended_at' => null, 'winner' => null],
]); ]);
}); });

View File

@ -0,0 +1,97 @@
<?php
use App\Actions\JoinWorld;
use App\Actions\QueueBuild;
use App\Engine\Barbarians;
use App\Engine\Nobility;
use App\Engine\Seasons;
use App\Models\GameEvent;
use App\Models\Movement;
use App\Models\User;
use App\Models\Village;
use App\Models\World;
use Carbon\CarbonImmutable;
beforeEach(fn () => $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);
});

View File

@ -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('[timber_camp] counts for two roles, [resources] and [military].')
->toContain('[specialisation.min_space] is more than a village has room for.'); ->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.');
});

View File

@ -0,0 +1,31 @@
<?php
use App\Game\Map\Season;
use Carbon\CarbonImmutable;
it('brings the crowns after 30 days and lets a holder win after 7, at world speed', function () {
$start = CarbonImmutable::parse('2026-11-01 00:00:00');
expect((new Season(gameConfig()))->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');
});