diff --git a/app/Actions/JoinWorld.php b/app/Actions/JoinWorld.php index 02b1bfc..cd4086e 100644 --- a/app/Actions/JoinWorld.php +++ b/app/Actions/JoinWorld.php @@ -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; }); } } diff --git a/app/Actions/SeedBarbarians.php b/app/Actions/SeedBarbarians.php deleted file mode 100644 index 4fff004..0000000 --- a/app/Actions/SeedBarbarians.php +++ /dev/null @@ -1,78 +0,0 @@ -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; - }); - } -} diff --git a/app/Actions/ShowMap.php b/app/Actions/ShowMap.php index 1fb2609..a4b329a 100644 --- a/app/Actions/ShowMap.php +++ b/app/Actions/ShowMap.php @@ -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, diff --git a/app/Actions/SpawnBarbarians.php b/app/Actions/SpawnBarbarians.php new file mode 100644 index 0000000..e045350 --- /dev/null +++ b/app/Actions/SpawnBarbarians.php @@ -0,0 +1,82 @@ + $taken updated with the new villages + * @return list + */ + 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()))), + ]); + } +} diff --git a/app/Console/Commands/ResetWorld.php b/app/Console/Commands/ResetWorld.php new file mode 100644 index 0000000..7c567c1 --- /dev/null +++ b/app/Console/Commands/ResetWorld.php @@ -0,0 +1,49 @@ +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; + } +} diff --git a/app/Engine/VillageFactory.php b/app/Engine/VillageFactory.php index 7e96385..76520ff 100644 --- a/app/Engine/VillageFactory.php +++ b/app/Engine/VillageFactory.php @@ -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 $taken "x|y" => true, updated with the result + * @param array $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 $taken "x|y" => true, updated with the result + * @param array $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 */ + /** @return array "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); } } diff --git a/app/Game/Map/Continent.php b/app/Game/Map/Continent.php index dbd8374..718d5ab 100644 --- a/app/Game/Map/Continent.php +++ b/app/Game/Map/Continent.php @@ -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); } } diff --git a/app/Game/Map/Frontier.php b/app/Game/Map/Frontier.php new file mode 100644 index 0000000..0a7e6ad --- /dev/null +++ b/app/Game/Map/Frontier.php @@ -0,0 +1,123 @@ + [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 $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 $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 $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; + } +} diff --git a/app/Game/Map/MapBounds.php b/app/Game/Map/MapBounds.php new file mode 100644 index 0000000..6522c14 --- /dev/null +++ b/app/Game/Map/MapBounds.php @@ -0,0 +1,39 @@ +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)); + } +} diff --git a/app/Game/Map/SpawnRing.php b/app/Game/Map/SpawnRing.php deleted file mode 100644 index 2e1917d..0000000 --- a/app/Game/Map/SpawnRing.php +++ /dev/null @@ -1,67 +0,0 @@ -config->get('world.map.spawn'); - - return $spawn['start_radius'] + sqrt($playerVillages / (M_PI * $spawn['density'])); - } - - /** - * A free field near the ring with no village on any of its 8 neighbours, or null if - * none turned up. Each failed try widens the band around the ring a little. - * - * @param array $taken "x|y" => true - * @param Closure(): float $random uniform in [0, 1) - * @return array{0: int, 1: int}|null - */ - public function pick(int $playerVillages, array $taken, Closure $random): ?array - { - $size = $this->config->get('world.map.size', 1000); - $centre = $size / 2; - $radius = $this->radius($playerVillages); - $band = $this->config->get('world.map.spawn.band', 2); - - for ($try = 0; $try < 400; $try++) { - $angle = $random() * 2 * M_PI; - $distance = $radius + ($random() * 2 - 1) * ($band + $try / 40); - $x = (int) round($centre + cos($angle) * $distance); - $y = (int) round($centre + sin($angle) * $distance); - if ($x < 0 || $y < 0 || $x >= $size || $y >= $size || ! self::clear($x, $y, $taken)) { - continue; - } - - return [$x, $y]; - } - - return null; - } - - /** @param array $taken */ - private static function clear(int $x, int $y, array $taken): bool - { - for ($dy = -1; $dy <= 1; $dy++) { - for ($dx = -1; $dx <= 1; $dx++) { - if (isset($taken[($x + $dx).'|'.($y + $dy)])) { - return false; - } - } - } - - return true; - } -} diff --git a/app/Presenters/VillagePresenter.php b/app/Presenters/VillagePresenter.php index bf20ce7..6ca7f0f 100644 --- a/app/Presenters/VillagePresenter.php +++ b/app/Presenters/VillagePresenter.php @@ -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()), diff --git a/app/Websocket/Controllers/WorldController.php b/app/Websocket/Controllers/WorldController.php index 26c7bc4..7a0e4d3 100644 --- a/app/Websocket/Controllers/WorldController.php +++ b/app/Websocket/Controllers/WorldController.php @@ -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, ]); } } diff --git a/config/game/world.php b/config/game/world.php index 0c015f0..76aa1c2 100644 --- a/config/game/world.php +++ b/config/game/world.php @@ -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], ], ]; diff --git a/database/seeders/WorldSeeder.php b/database/seeders/WorldSeeder.php index db57b7f..8ca6c07 100644 --- a/database/seeders/WorldSeeder.php +++ b/database/seeders/WorldSeeder.php @@ -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); } } } diff --git a/docs/architecture.md b/docs/architecture.md index fb3a6c6..e071de8 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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 diff --git a/docs/roadmap.md b/docs/roadmap.md index 7f608e6..33f3428 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -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 diff --git a/tests/Feature/JoinWorldTest.php b/tests/Feature/JoinWorldTest.php index 27b3027..5d4e6a6 100644 --- a/tests/Feature/JoinWorldTest.php +++ b/tests/Feature/JoinWorldTest.php @@ -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(); diff --git a/tests/Feature/MapTest.php b/tests/Feature/MapTest.php index 2a7e257..2ad273b 100644 --- a/tests/Feature/MapTest.php +++ b/tests/Feature/MapTest.php @@ -1,12 +1,10 @@ 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(); diff --git a/tests/Feature/ResetWorldTest.php b/tests/Feature/ResetWorldTest.php new file mode 100644 index 0000000..75bb0ff --- /dev/null +++ b/tests/Feature/ResetWorldTest.php @@ -0,0 +1,25 @@ + 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); +}); diff --git a/tests/Pest.php b/tests/Pest.php index 84472b7..bc77dca 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -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. */ diff --git a/tests/Unit/Game/ContinentTest.php b/tests/Unit/Game/ContinentTest.php index b385a62..e9deed7 100644 --- a/tests/Unit/Game/ContinentTest.php +++ b/tests/Unit/Game/ContinentTest.php @@ -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'); }); diff --git a/tests/Unit/Game/FrontierTest.php b/tests/Unit/Game/FrontierTest.php new file mode 100644 index 0000000..682f226 --- /dev/null +++ b/tests/Unit/Game/FrontierTest.php @@ -0,0 +1,49 @@ +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); +}); diff --git a/tests/Unit/Game/SpawnRingTest.php b/tests/Unit/Game/SpawnRingTest.php deleted file mode 100644 index 5f33072..0000000 --- a/tests/Unit/Game/SpawnRingTest.php +++ /dev/null @@ -1,33 +0,0 @@ -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]); -});