feat: world generation like Die Stämme: start at 0|0, grow ring by ring, barbarians come with each player

The map's coordinates now run from -500 to 499 around 0|0, with DS continent names
counted from the top-left (K55 at 0|0). New villages settle on a frontier whose
radius follows all villages at DS density (0.29 per field), at a random angle in
the direction the player picked; they avoid touching other players, not barbarians.
Each join brings 1.3 barbarian villages on average within a few fields. The
one-time barbarian square around the centre is gone, and game:reset-world wipes a
world back to empty while keeping user accounts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-29 01:51:37 +01:00
parent dfe5f50ac6
commit 8cd0aafb88
23 changed files with 506 additions and 276 deletions

View File

@ -4,32 +4,42 @@ namespace App\Actions;
use App\Engine\VillageFactory;
use App\Game\GameRuleViolation;
use App\Game\Map\Frontier;
use App\Models\Player;
use App\Models\User;
use App\Models\Village;
use App\Models\World;
use Illuminate\Support\Facades\DB;
/** Join a world (or come back to it): a player and a start village with HQ, storage and farm at 0. */
/**
* Join a world (or come back to it): a player and a start village with HQ, storage and
* farm at level 1 on the frontier, in the direction the player picked, with the
* barbarian villages that come with every new player around it.
*/
final class JoinWorld
{
public function __construct(private readonly VillageFactory $villages) {}
public function __construct(private readonly VillageFactory $villages, private readonly SpawnBarbarians $barbarians) {}
public function __invoke(User $user, int $worldId): Village
public function __invoke(User $user, int $worldId, string $direction = 'random'): Village
{
$world = World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.');
if (! in_array($direction, Frontier::DIRECTIONS, true)) {
throw new GameRuleViolation('direction', "Unknown direction [$direction].");
}
return DB::transaction(function () use ($user, $world) {
return DB::transaction(function () use ($user, $world, $direction) {
$player = Player::firstOrCreate(['user_id' => $user->id, 'world_id' => $world->id], ['name' => $user->name]);
if ($village = $player->villages()->orderBy('id')->first()) {
return $village;
}
$taken = VillageFactory::takenSpots($world);
[$x, $y] = VillageFactory::spawnSpot($world, $taken);
[$x, $y] = VillageFactory::spawnSpot($world, $taken, $direction);
$levels = array_fill_keys($world->gameConfig()->get('world.village.start_buildings'), 1);
$village = $this->villages->create($world, $player, "{$user->name}'s village", $x, $y, $levels);
$this->barbarians->around($world, $village, $taken);
return $this->villages->create($world, $player, "{$user->name}'s village", $x, $y, $levels);
return $village;
});
}
}

View File

@ -1,78 +0,0 @@
<?php
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;
/**
* Scatters barbarian villages around the map centre, once per world. The RNG is
* seeded from the world's slug, so a world always gets the same layout.
*/
final class SeedBarbarians
{
private const BUILDINGS = ['headquarters', 'storage', 'farm', 'timber_camp', 'clay_pit', 'iron_mine'];
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
{
if ($world->villages()->whereNull('player_id')->exists()) {
return 0;
}
$config = $world->gameConfig()->get('world.map.barbarians');
$centre = intdiv($world->gameConfig()->get('world.map.size', 1000), 2);
mt_srand(crc32($world->slug));
return DB::transaction(function () use ($world, $config, $centre) {
$taken = VillageFactory::takenSpots($world);
$created = 0;
for ($tries = 0; $created < $config['count'] && $tries < $config['count'] * 20; $tries++) {
$x = $centre + mt_rand(-$config['radius'], $config['radius']);
$y = $centre + mt_rand(-$config['radius'], $config['radius']);
// Leave the centre ring free for player spawns (even coordinates near the middle).
if (isset($taken["$x|$y"]) || (abs($x - $centre) < 6 && abs($y - $centre) < 6)) {
continue;
}
$taken["$x|$y"] = true;
$levels = [];
foreach (self::BUILDINGS as $type) {
$levels[$type] = mt_rand(1, $config['max_level']);
}
$this->villages->create($world, null, 'Barbarian village', $x, $y, $levels);
$created++;
}
return $created;
});
}
}

View File

@ -4,6 +4,7 @@ namespace App\Actions;
use App\Game\GameRuleViolation;
use App\Game\Map\Continent;
use App\Game\Map\MapBounds;
use App\Models\Player;
use App\Models\User;
use App\Models\Village;
@ -12,6 +13,7 @@ use App\Models\World;
/**
* The villages in a w × h window of a world's map, centred on (x, y) the way the
* Die Stämme map is. Without a centre it opens on the player's first village there.
* Coordinates run from −size/2 to size/2 − 1; the world starts at 0|0.
*/
final class ShowMap
{
@ -19,7 +21,8 @@ final class ShowMap
{
$world = World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.');
$config = $world->gameConfig();
$size = $config->get('world.map.size', 1000);
$bounds = MapBounds::of($config);
$size = $bounds->size;
$max = $config->get('world.map.max_view', 41);
$w = max(1, min($max, $w));
$h = max(1, min($max, $h));
@ -27,13 +30,13 @@ final class ShowMap
if ($x === null || $y === null) {
$home = Village::whereIn('player_id', Player::where('user_id', $user->id)->where('world_id', $world->id)->select('id'))
->orderBy('id')->first();
$x = $home->x ?? intdiv($size, 2);
$y = $home->y ?? intdiv($size, 2);
$x = $home->x ?? 0;
$y = $home->y ?? 0;
}
$x = max(0, min($size - 1, $x));
$y = max(0, min($size - 1, $y));
$left = max(0, min($size - $w, $x - intdiv($w, 2)));
$top = max(0, min($size - $h, $y - intdiv($h, 2)));
$x = $bounds->clamp($x);
$y = $bounds->clamp($y);
$left = max($bounds->min(), min($bounds->max() - $w + 1, $x - intdiv($w, 2)));
$top = max($bounds->min(), min($bounds->max() - $h + 1, $y - intdiv($h, 2)));
$villages = Village::where('world_id', $world->id)
->whereBetween('x', [$left, $left + $w - 1])
@ -46,7 +49,7 @@ final class ShowMap
'y' => $v->y,
'name' => $v->name,
'points' => $v->points,
'continent' => Continent::of($v->x, $v->y),
'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,
])->values()->all();
@ -54,6 +57,8 @@ final class ShowMap
return [
'world_id' => $world->id,
'size' => $size,
// Lowest coordinate on both axes; the highest is min + size − 1.
'min' => $bounds->min(),
'center' => ['x' => $x, 'y' => $y],
'x' => $left,
'y' => $top,

View File

@ -0,0 +1,82 @@
<?php
namespace App\Actions;
use App\Engine\VillageFactory;
use App\Game\Map\BarbarianGrowth;
use App\Game\Map\Frontier;
use App\Models\GameEvent;
use App\Models\Village;
use App\Models\World;
/**
* Barbarian villages come with the players, as in Die Stämme: each joining player brings
* `barbarians.per_join` of them on average, here placed within a few fields of the new
* village so even a small world has something to loot from the start. They then grow
* by themselves (BarbarianGrowth).
*/
final class SpawnBarbarians
{
private const BUILDINGS = ['headquarters', 'storage', 'farm', 'timber_camp', 'clay_pit', 'iron_mine'];
public function __construct(private readonly VillageFactory $villages) {}
/**
* Barbarian villages around a new player's village, each with its first growth step.
*
* @param array<string, bool> $taken updated with the new villages
* @return list<Village>
*/
public function around(World $world, Village $village, array &$taken): array
{
$config = $world->gameConfig();
$frontier = new Frontier($config);
$maxLevel = $config->get('world.map.barbarians.max_level', 3);
$created = [];
for ($n = $frontier->barbariansPerJoin(VillageFactory::random(...)); $n > 0; $n--) {
$spot = $frontier->near($village->x, $village->y, $taken, VillageFactory::random(...));
if (! $spot) {
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);
$this->scheduleFirstGrowth($world, $barbarian);
$created[] = $barbarian;
}
return $created;
}
/**
* 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
{
$waiting = GameEvent::where('type', GameEvent::BARBARIAN_GROWS)->whereNull('processed_at')->select('village_id');
$villages = $world->villages()->whereNull('player_id')->whereNotIn('id', $waiting)->get();
foreach ($villages as $village) {
$this->scheduleFirstGrowth($world, $village);
}
return $villages->count();
}
/** The first growth step lands 0.5–1.5 intervals out, so villages don't grow in step. */
private function scheduleFirstGrowth(World $world, Village $village): void
{
$interval = (new BarbarianGrowth($world->gameConfig()))->interval();
GameEvent::create([
'world_id' => $world->id,
'village_id' => $village->id,
'type' => GameEvent::BARBARIAN_GROWS,
'fire_at' => now()->toImmutable()->addSeconds((int) round($interval * (0.5 + VillageFactory::random()))),
]);
}
}

View File

@ -0,0 +1,49 @@
<?php
namespace App\Console\Commands;
use App\Models\GameEvent;
use App\Models\Movement;
use App\Models\Player;
use App\Models\Village;
use App\Models\World;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* Start a world over: every village, player, movement, report and pending event of it
* goes; user accounts and the world's config stay. Players join again from scratch.
*/
class ResetWorld extends Command
{
protected $signature = 'game:reset-world {slug : The world to reset} {--force : Skip the confirmation}';
protected $description = 'Wipe a world back to empty, keeping user accounts and its config';
public function handle(): int
{
$world = World::where('slug', $this->argument('slug'))->first();
if (! $world) {
$this->error("No world [{$this->argument('slug')}].");
return self::FAILURE;
}
$villages = $world->villages()->count();
$players = $world->players()->count();
if (! $this->option('force') && ! $this->confirm("Reset {$world->name}: delete $villages villages and $players players?")) {
return self::FAILURE;
}
DB::transaction(function () use ($world) {
// Children first; the rest (buildings, troops, orders, reports) cascade.
GameEvent::where('world_id', $world->id)->delete();
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()]);
});
$this->info("{$world->name} is empty again: $villages villages and $players players removed.");
return self::SUCCESS;
}
}

View File

@ -3,7 +3,8 @@
namespace App\Engine;
use App\Game\GameRuleViolation;
use App\Game\Map\SpawnRing;
use App\Game\Map\Frontier;
use App\Game\Map\MapBounds;
use App\Models\Player;
use App\Models\Village;
use App\Models\World;
@ -39,47 +40,35 @@ final class VillageFactory
}
/**
* 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.
* Where a new player starts: on the frontier, which moves outward as the world fills,
* in the direction they picked. Falls back to the nearest free field if it has no room.
*
* @param array<string, true> $taken "x|y" => true, updated with the result
* @param array<string, bool> $taken "x|y" => whether a player owns it, updated with the result
* @return array{0: int, 1: int}
*/
public static function spawnSpot(World $world, array &$taken): array
public static function spawnSpot(World $world, array &$taken, string $direction = 'random'): 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);
}
$frontier = new Frontier($world->gameConfig());
$spot = $frontier->pick(count($taken), $taken, $direction, self::random(...)) ?? 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.
* First free field on square rings around 0|0.
*
* @param array<string, true> $taken "x|y" => true, updated with the result
* @param array<string, bool> $taken
* @return array{0: int, 1: int}
*/
public static function freeSpot(World $world, array &$taken): array
public static function freeSpot(World $world, array $taken): array
{
$size = $world->gameConfig()->get('world.map.size', 1000);
$centre = intdiv($size, 2);
for ($r = 0; $r <= $centre / 2; $r++) {
$bounds = MapBounds::of($world->gameConfig());
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) {
continue;
}
$x = $centre + $dx * 2;
$y = $centre + $dy * 2;
if (! isset($taken["$x|$y"])) {
$taken["$x|$y"] = true;
return [$x, $y];
if (max(abs($dx), abs($dy)) === $r && ! isset($taken["$dx|$dy"]) && $bounds->contains($dx, $dy)) {
return [$dx, $dy];
}
}
}
@ -88,9 +77,17 @@ final class VillageFactory
throw new GameRuleViolation('world_full', 'This world is full.');
}
/** @return array<string, true> */
/** @return array<string, bool> "x|y" => whether a player owns the village there */
public static function takenSpots(World $world): array
{
return $world->villages()->get(['x', 'y'])->mapWithKeys(fn (Village $v) => ["{$v->x}|{$v->y}" => true])->all();
return $world->villages()->get(['x', 'y', 'player_id'])
->mapWithKeys(fn (Village $v) => ["{$v->x}|{$v->y}" => $v->player_id !== null])
->all();
}
/** Uniform in [0, 1). */
public static function random(): float
{
return mt_rand() / (mt_getrandmax() + 1);
}
}

View File

@ -3,15 +3,18 @@
namespace App\Game\Map;
/**
* Continents are 100 × 100 blocks named by their y and x hundreds, as in Die Stämme:
* 500|500 lies in K55, 123|456 in K41.
* Continents are 100 × 100 blocks named by their row and column counted from the map's
* top-left corner, as in Die Stämme. The world starts at 0|0, the corner of K44, K45,
* K54 and K55; on a 1000-field map −500|−500 lies in K00 and 499|499 in K99.
*/
final class Continent
{
public const SIZE = 100;
public static function of(int $x, int $y): string
public static function of(int $x, int $y, int $mapSize = 1000): string
{
return 'K'.intdiv($y, self::SIZE).intdiv($x, self::SIZE);
$offset = intdiv($mapSize, 2);
return 'K'.intdiv($y + $offset, self::SIZE).intdiv($x + $offset, self::SIZE);
}
}

123
app/Game/Map/Frontier.php Normal file
View File

@ -0,0 +1,123 @@
<?php
namespace App\Game\Map;
use App\Game\WorldConfig;
use Closure;
/**
* Where the world grows, the way Die Stämme does it: villages settle on a ring around
* 0|0 whose radius follows the number of all villages (players and barbarians), so the
* settled disc keeps an even density and spreads outward as players join. A new player
* lands at a random angle on that ring, inside the quarter they chose.
*/
final class Frontier
{
/** Start directions a joining player can pick. */
public const DIRECTIONS = ['random', 'nw', 'ne', 'sw', 'se'];
/** Degrees per direction, with 0° pointing east and y growing south. */
private const SECTORS = ['random' => [0, 360], 'se' => [0, 90], 'sw' => [90, 180], 'nw' => [180, 270], 'ne' => [270, 360]];
/** Tries that keep clear of other players before any free field will do. */
private const CLEAR_TRIES = 200;
private const TRIES = 400;
public function __construct(private readonly WorldConfig $config) {}
/** Radius in fields of the settled disc when the world has this many villages. */
public function radius(int $villages): float
{
$spawn = $this->config->get('world.map.spawn');
return $spawn['start_radius'] + sqrt($villages / (M_PI * $spawn['density']));
}
/**
* A free field near the ring for a new player, in the given direction. The first tries
* want no player village on the 8 fields around it; barbarians may stand right next
* to it, as in Die Stämme. Each failed try widens the band around the ring a little.
*
* @param array<string, bool> $taken "x|y" => whether a player owns the village there
* @param Closure(): float $random uniform in [0, 1)
* @return array{0: int, 1: int}|null
*/
public function pick(int $villages, array $taken, string $direction, Closure $random): ?array
{
$bounds = MapBounds::of($this->config);
[$from, $to] = self::SECTORS[$direction] ?? self::SECTORS['random'];
$radius = $this->radius($villages);
$band = $this->config->get('world.map.spawn.band', 3);
for ($try = 0; $try < self::TRIES; $try++) {
$angle = deg2rad($from + $random() * ($to - $from));
$distance = max(0, $radius + ($random() * 2 - 1) * ($band + $try / 30));
$x = (int) round(cos($angle) * $distance);
$y = (int) round(sin($angle) * $distance);
if (! $bounds->contains($x, $y) || isset($taken["$x|$y"])) {
continue;
}
if ($try < self::CLEAR_TRIES && self::nextToPlayer($x, $y, $taken)) {
continue;
}
return [$x, $y];
}
return null;
}
/**
* A free field for a barbarian village close to a new player's village: between 1.5
* fields and `barbarians.near` fields away, at a random angle.
*
* @param array<string, bool> $taken
* @param Closure(): float $random
* @return array{0: int, 1: int}|null
*/
public function near(int $x, int $y, array $taken, Closure $random): ?array
{
$bounds = MapBounds::of($this->config);
$reach = (float) $this->config->get('world.map.barbarians.near', 4);
for ($try = 0; $try < self::TRIES; $try++) {
$angle = $random() * 2 * M_PI;
$distance = 1.5 + $random() * max(0, $reach - 1.5) + $try / 100;
$bx = $x + (int) round(cos($angle) * $distance);
$by = $y + (int) round(sin($angle) * $distance);
if ($bounds->contains($bx, $by) && ! isset($taken["$bx|$by"])) {
return [$bx, $by];
}
}
return null;
}
/**
* How many barbarian villages come with a joining player: `per_join` on average,
* e.g. 1.3 is one, plus a second with a 30% chance.
*
* @param Closure(): float $random
*/
public function barbariansPerJoin(Closure $random): int
{
$average = (float) $this->config->get('world.map.barbarians.per_join', 0);
return (int) floor($average) + ($random() < $average - floor($average) ? 1 : 0);
}
/** @param array<string, bool> $taken */
private static function nextToPlayer(int $x, int $y, array $taken): bool
{
for ($dy = -1; $dy <= 1; $dy++) {
for ($dx = -1; $dx <= 1; $dx++) {
if (($taken[($x + $dx).'|'.($y + $dy)] ?? false) === true) {
return true;
}
}
}
return false;
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace App\Game\Map;
use App\Game\WorldConfig;
/**
* The map's coordinates: the world starts at 0|0 and runs from −size/2 to size/2 − 1 on
* both axes, so a 1000-field map spans −500 to 499.
*/
final class MapBounds
{
public function __construct(public readonly int $size) {}
public static function of(WorldConfig $config): self
{
return new self((int) $config->get('world.map.size', 1000));
}
public function min(): int
{
return -intdiv($this->size, 2);
}
public function max(): int
{
return $this->min() + $this->size - 1;
}
public function contains(int $x, int $y): bool
{
return $x >= $this->min() && $x <= $this->max() && $y >= $this->min() && $y <= $this->max();
}
public function clamp(int $value): int
{
return max($this->min(), min($this->max(), $value));
}
}

View File

@ -1,67 +0,0 @@
<?php
namespace App\Game\Map;
use App\Game\WorldConfig;
use Closure;
/**
* Where new players start: on a ring around the map centre whose radius grows with the
* number of player villages, so the settled area spreads outward as the world fills.
*/
final class SpawnRing
{
public function __construct(private readonly WorldConfig $config) {}
/** Ring radius in fields for a world that already has this many player villages. */
public function radius(int $playerVillages): float
{
$spawn = $this->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<string, true> $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<string, true> $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;
}
}

View File

@ -36,7 +36,7 @@ final class VillagePresenter
'name' => $village->name,
'x' => $village->x,
'y' => $village->y,
'continent' => Continent::of($village->x, $village->y),
'continent' => Continent::of($village->x, $village->y, (int) $sim->config()->get('world.map.size', 1000)),
'points' => $village->points,
'space' => ['used' => $sim->spaceUsed(), 'max' => $sim->spaceMax()],
'resources' => array_map(fn (float $n) => round($n, 4), $village->resources()),

View File

@ -6,7 +6,7 @@ use App\Actions\JoinWorld;
use App\Actions\ListWorlds;
use App\Websocket\GameController;
/** world.index, world.join */
/** world.index, world.join {world_id, direction: random|nw|ne|sw|se} */
class WorldController extends GameController
{
public function index()
@ -17,7 +17,7 @@ class WorldController extends GameController
public function join()
{
return $this->play(fn () => [
'village_id' => app(JoinWorld::class)(auth()->user(), (int) request('world_id'))->id,
'village_id' => app(JoinWorld::class)(auth()->user(), (int) request('world_id'), (string) (request('direction') ?: 'random'))->id,
]);
}
}

View File

@ -23,19 +23,24 @@ return [
],
'map' => [
// Fields per side. The world starts at 0|0; coordinates run from −size/2 to size/2 − 1.
'size' => 1000,
// 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.
// Every few hours (at world speed) one building of each grows a level, up to growth.max_level.
// Like Die Stämme, villages settle on a frontier around 0|0 that grows with all
// villages (players and barbarians): start_radius + sqrt(villages / (π·density)),
// ± band fields. 0.29 is DS's density: about one village in 3.4 fields. A new
// player avoids the fields right next to other players for as long as it can.
'spawn' => ['start_radius' => 0, 'density' => 0.29, 'band' => 3],
// Barbarian villages come with the players: per_join on average for each joining
// player (1.3 = one, and a second with 30% chance, as in DS), within near fields of
// the new village, buildings at random levels up to max_level. Every few hours (at
// world speed) one building of each grows a level, up to growth.max_level.
'barbarians' => [
'count' => 120,
'radius' => 25,
'per_join' => 1.3,
'near' => 4,
'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],
],
];

View File

@ -2,11 +2,14 @@
namespace Database\Seeders;
use App\Actions\SeedBarbarians;
use App\Actions\SpawnBarbarians;
use App\Models\World;
use Illuminate\Database\Seeder;
/** The default world and a fast dev world, with their barbarians. Safe to run on every deploy. */
/**
* 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.
*/
class WorldSeeder extends Seeder
{
public function run(): void
@ -19,10 +22,9 @@ class WorldSeeder extends Seeder
'started_at' => now(),
]),
];
$barbarians = app(SeedBarbarians::class);
// Barbarian villages that lost their growth event get it back.
foreach ($worlds as $world) {
$barbarians($world);
$barbarians->scheduleGrowth($world);
app(SpawnBarbarians::class)->scheduleGrowth($world);
}
}
}

View File

@ -29,6 +29,8 @@ app/Game/ pure rules: no Eloquent, no now(), fully unit tested
Buildings/BuildingRules.php cost, time, workers, output, space, points per level
Buildings/BuildQueue.php builders, next unblocked order
Map/Continent.php K-names of the 100 × 100 continents
Map/MapBounds.php coordinates from −size/2 to size/2 − 1 around 0|0
Map/Frontier.php where new villages settle as the world grows
Travel/TravelTime.php
Combat/CombatResolver.php
Combat/LootCalculator.php
@ -160,11 +162,17 @@ Handlers are idempotent per event row: the transaction plus `processed_at` guard
## Map
The map is square (`map.size`, default 1000 × 1000) and split into TW-style continents of 100 × 100 for orientation (K55). New players spawn on a ring that moves outward from the center as the world fills. Barbarian villages fill the gaps, grow slowly (world config), and a village whose player has been inactive for too long turns barbarian.
The map is square (`map.size`, default 1000 × 1000) with the world's start at **0|0**: coordinates run from −size/2 to size/2 − 1 (−500 to 499), negative included (`MapBounds`). Continents are 100 × 100 blocks named by row and column counted from the top-left corner, as in Die Stämme, so 0|0 is the corner of K44, K45, K54 and K55, −500|−500 lies in K00 and 499|499 in K99.
`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.
The world grows the way Die Stämme's does (measured on de261, see the research repo): a disc around 0|0 that spreads outward ring by ring as players join, at an even density, with barbarian villages arriving alongside the players. A world starts empty.
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`.
- **Frontier** (`Frontier`): a new player's village lands at a random angle on a ring of radius `start_radius + sqrt(villages / (π · density))`, ± `band` fields, where `villages` counts every village of the world, barbarians included. `density` is DS's 0.29 villages per field (about one in 3.4 fields). The first tries keep clear of the 8 fields around other players; barbarians may stand right next to a new village. If the ring has no room, the nearest free field around 0|0 is taken.
- **Direction**: when joining (`world.join {world_id, direction}`) a player picks random, nw, ne, sw or se, and the angle stays inside that quarter.
- **Barbarians come with players** (`SpawnBarbarians`): each join brings `barbarians.per_join` of them on average (1.3: one, and a second with 30% chance, as in DS), placed within `barbarians.near` fields of the new village so a small world has something to loot from the start (DS scatters them on the frontier instead; with thousands of players that ends up the same). Their buildings start at random levels up to `max_level`, and each has a `barbarian.grows` event: every `growth.every_hours` (at world speed) one building goes up a level, up to `growth.max_level`. Bonus villages (DS adds 0.4 per join) come later.
- A village whose player has been inactive for too long turns barbarian (M6).
- `php artisan game:reset-world {slug}` wipes a world back to empty (villages, players, movements, reports, events) and keeps user accounts and the world's config.
`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, plus `size` and `min` (the lowest coordinate); without a centre it opens on the player's first village, else on 0|0. 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.
## Movements and encounters

View File

@ -22,8 +22,8 @@ Each milestone ends with tests green, `ConfigLint` green, and something playable
## M2: Map and barbarian villages
- [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
- [x] Spawn placement, like Die Stämme: the world starts at 0|0 (negative coordinates, DS continent names) and grows ring by ring with all villages at DS density; players pick a direction (random, NW, NE, SW, SE) and never land right next to another player
- [x] Barbarian villages come with the players: 1.3 per join on average, within a few fields of the new village, random levels; `game:reset-world` starts a world over
- [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

View File

@ -6,13 +6,15 @@ use App\Actions\RenameVillage;
use App\Actions\ShowVillage;
use App\Game\Map\Continent;
use App\Models\User;
use App\Models\Village;
use App\Models\World;
use Database\Seeders\WorldSeeder;
it('starts a village with HQ, storage and farm at level 1', function () {
$village = startVillage();
// On the spawn ring: start radius 6 ± 2 around 500|500.
expect(hypot($village->x - 500, $village->y - 500))->toBeBetween(3.0, 9.0)
// The first village of a world lands on the frontier at radius 0 ± 3: right at 0|0.
expect(hypot($village->x, $village->y))->toBeLessThanOrEqual(3 * M_SQRT2 + 0.01)
->and($village->only('space', 'points'))->toBe(['space' => 40, '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([
@ -28,8 +30,8 @@ it('returns the same village when joining again', function () {
expect(app(JoinWorld::class)(owner($village), $village->world_id)->id)->toBe($village->id);
});
it('spawns players on the ring, never next to another village', function () {
$villages = collect(range(1, 6))->map(fn () => startVillage(User::factory()->create()));
it('spawns players on the frontier, never right next to another player', function () {
$villages = collect(range(1, 8))->map(fn () => startVillage(User::factory()->create()));
foreach ($villages as $a) {
foreach ($villages as $b) {
@ -40,6 +42,30 @@ it('spawns players on the ring, never next to another village', function () {
}
});
it('starts a player in the quarter they picked', function () {
(new WorldSeeder)->run();
$world = World::where('slug', 'w1')->value('id');
// A few villages first, so the frontier has moved off 0|0.
collect(range(1, 6))->each(fn () => app(JoinWorld::class)(User::factory()->create(), $world));
$nw = app(JoinWorld::class)(User::factory()->create(), $world, 'nw');
$se = app(JoinWorld::class)(User::factory()->create(), $world, 'se');
expect($nw->x)->toBeLessThanOrEqual(0)->and($nw->y)->toBeLessThanOrEqual(0)
->and($se->x)->toBeGreaterThanOrEqual(0)->and($se->y)->toBeGreaterThanOrEqual(0)
->and(rule(fn () => app(JoinWorld::class)(User::factory()->create(), $world, 'up')))->toBe('direction');
});
it('brings barbarian villages with every new player, close to their village', function () {
config(['game.world.map.barbarians.per_join' => 2]);
$village = startVillage();
$barbarians = Village::where('world_id', $village->world_id)->whereNull('player_id')->get();
expect($barbarians)->toHaveCount(2)
->and($barbarians->every(fn ($b) => hypot($b->x - $village->x, $b->y - $village->y) <= 4 + 1))->toBeTrue()
->and($barbarians->every(fn ($b) => $b->points > 0 && $b->buildings()->count() === 6))->toBeTrue();
});
it('lists worlds with their speed and the player village', function () {
$village = startVillage();
$dev = World::where('slug', 'dev')->first();

View File

@ -1,12 +1,10 @@
<?php
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;
it('opens on the player village and marks it as their own', function () {
$village = startVillage();
@ -33,30 +31,15 @@ it('shows only the window around the given centre, kept inside the map', functio
$village = startVillage();
$far = app(ShowMap::class)(owner($village), $village->world_id, 100, 100, 15, 15);
$edge = app(ShowMap::class)(owner($village), $village->world_id, 2, 998, 15, 999);
$edge = app(ShowMap::class)(owner($village), $village->world_id, -498, 498, 15, 999);
// Coordinates run from −500 to 499.
expect($far['villages'])->toBe([])
->and($edge)->toMatchArray(['x' => 0, 'y' => 939, 'w' => 15, 'h' => 61]);
});
it('seeds barbarian villages once per world, away from the spawn centre', function () {
config(['game.world.map.barbarians' => ['count' => 20, 'radius' => 20, 'max_level' => 3]]);
$village = startVillage();
$world = World::find($village->world_id);
$barbarians = Village::where('world_id', $world->id)->whereNull('player_id')->get();
expect($barbarians)->toHaveCount(20)
->and($barbarians->every(fn ($v) => abs($v->x - 500) <= 20 && abs($v->y - 500) <= 20))->toBeTrue()
->and($barbarians->every(fn ($v) => abs($v->x - 500) >= 6 || abs($v->y - 500) >= 6))->toBeTrue()
->and($barbarians->every(fn ($v) => $v->points > 0 && $v->buildings()->count() === 6))->toBeTrue()
->and(app(SeedBarbarians::class)($world))->toBe(0);
$map = app(ShowMap::class)(owner($village), $world->id, 500, 500, 41, 41);
expect(collect($map['villages'])->whereNull('player'))->toHaveCount(20);
->and($edge)->toMatchArray(['x' => -500, 'y' => 439, 'w' => 15, 'h' => 61, 'min' => -500]);
});
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]]]);
config(['game.world.map.barbarians' => ['per_join' => 3, 'near' => 4, '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();

View File

@ -0,0 +1,25 @@
<?php
use App\Models\GameEvent;
use App\Models\Player;
use App\Models\User;
use App\Models\Village;
use App\Models\World;
it('wipes a world back to empty and keeps the user accounts', function () {
config(['game.world.map.barbarians.per_join' => 2]);
$village = startVillage();
$world = World::find($village->world_id);
$users = User::count();
$user = owner($village);
$this->artisan('game:reset-world', ['slug' => 'w1', '--force' => true])->assertSuccessful();
expect(Village::where('world_id', $world->id)->count())->toBe(0)
->and(Player::where('world_id', $world->id)->count())->toBe(0)
->and(GameEvent::where('world_id', $world->id)->count())->toBe(0)
->and(User::count())->toBe($users);
// Joining again starts a fresh village at the centre.
$again = startVillage($user);
expect(hypot($again->x, $again->y))->toBeLessThanOrEqual(5);
});

View File

@ -13,9 +13,9 @@ use Database\Seeders\WorldSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
// Feature tests start without barbarians unless a test asks for them, to stay fast.
// Feature tests start without barbarians unless a test asks for them, so tests can place their own.
pest()->extend(TestCase::class)->use(RefreshDatabase::class)
->beforeEach(fn () => config(['game.world.map.barbarians.count' => 0]))
->beforeEach(fn () => config(['game.world.map.barbarians.per_join' => 0]))
->in('Feature');
/** The default game config without booting Laravel, so unit tests stay pure. */

View File

@ -2,9 +2,11 @@
use App\Game\Map\Continent;
it('names continents by the hundreds of y, then x', function () {
expect(Continent::of(500, 500))->toBe('K55')
->and(Continent::of(123, 456))->toBe('K41')
->and(Continent::of(0, 0))->toBe('K00')
->and(Continent::of(999, 99))->toBe('K09');
it('names continents by row and column from the top-left, with the world starting at 0|0', function () {
expect(Continent::of(0, 0))->toBe('K55')
->and(Continent::of(-1, -1))->toBe('K44')
->and(Continent::of(-1, 0))->toBe('K54')
->and(Continent::of(-500, -500))->toBe('K00')
->and(Continent::of(499, 499))->toBe('K99')
->and(Continent::of(-377, -44))->toBe('K41');
});

View File

@ -0,0 +1,49 @@
<?php
use App\Game\Map\Frontier;
/** A random source that repeats the given values. */
function sequence(float ...$values): Closure
{
$i = 0;
return function () use ($values, &$i) {
return $values[$i++ % count($values)];
};
}
it('grows the settled disc with all villages, at Die Stämme density', function () {
$frontier = new Frontier(gameConfig());
expect($frontier->radius(0))->toBe(0.0)
->and($frontier->radius(37346))->toEqualWithDelta(202.5, 0.1)
->and($frontier->radius(100))->toEqualWithDelta(sqrt(100 / (M_PI * 0.29)), 1e-9);
});
it('starts the world at 0|0 and keeps new players inside the quarter they picked', function () {
$frontier = new Frontier(gameConfig());
// No offset from the ring: the first village sits on 0|0; with 100 villages the ring is ~10.5 out.
expect($frontier->pick(0, [], 'random', sequence(0.0, 0.5)))->toBe([0, 0])
->and($frontier->pick(100, [], 'random', sequence(0.0, 0.5)))->toBe([10, 0])
->and($frontier->pick(100, [], 'ne', sequence(0.0, 0.5)))->toBe([0, -10])
->and($frontier->pick(100, [], 'sw', sequence(0.5, 0.5)))->toBe([-7, 7]);
});
it('keeps clear of other players for as long as it can, but not of barbarians', function () {
$frontier = new Frontier(gameConfig());
expect($frontier->pick(100, ['11|1' => false], 'random', sequence(0.0, 0.5)))->toBe([10, 0])
// Next to a player every try lands in the same spot, so the clear tries run out first.
->and($frontier->pick(100, ['11|1' => true], 'random', sequence(0.0, 0.5)))->toBe([10, 0])
->and($frontier->pick(100, ['10|0' => false], 'random', sequence(0.0, 0.5)))->toBeNull();
});
it('places barbarians a few fields from the new village and brings 1.3 per join on average', function () {
$frontier = new Frontier(gameConfig());
// Angle 0, distance 1.5 + 0.5 × 2.5 = 2.75: three fields east.
expect($frontier->near(5, 5, [], sequence(0.0, 0.5)))->toBe([8, 5])
->and($frontier->barbariansPerJoin(sequence(0.29)))->toBe(2)
->and($frontier->barbariansPerJoin(sequence(0.31)))->toBe(1);
});

View File

@ -1,33 +0,0 @@
<?php
use App\Game\Map\SpawnRing;
/** A random source that repeats the given values. */
function sequence(float ...$values): Closure
{
$i = 0;
return function () use ($values, &$i) {
return $values[$i++ % count($values)];
};
}
it('grows the ring with the number of player villages', function () {
$ring = new SpawnRing(gameConfig());
expect($ring->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]);
});