game-village-politics-backend/app/Game/Map/SpawnRing.php

68 lines
2.1 KiB
PHP
Raw Normal View History

<?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;
}
}