level, one instance each), * start resources and the matching points. * * @param array $levels */ public function create(World $world, ?Player $player, string $name, int $x, int $y, array $levels): Village { $config = $world->gameConfig(); $village = Village::create([ 'world_id' => $world->id, 'player_id' => $player?->id, 'name' => $name, 'x' => $x, 'y' => $y, 'space' => $config->get('world.village.space'), ...$config->get('world.village.start_resources'), 'resources_at' => now()->toImmutable(), ]); foreach ($levels as $type => $level) { $village->buildings()->create(['type' => $type, 'level' => $level]); } $village->update(['points' => Simulation::of($village)->points()]); return $village; } /** * 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" => whether a player owns it, updated with the result * @return array{0: int, 1: int} */ public static function spawnSpot(World $world, array &$taken, string $direction = 'random'): array { $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 field on square rings around 0|0. * * @param array $taken * @return array{0: int, 1: int} */ public static function freeSpot(World $world, array $taken): array { $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 && ! isset($taken["$dx|$dy"]) && $bounds->contains($dx, $dy)) { return [$dx, $dy]; } } } } throw new GameRuleViolation('world_full', 'This world is full.'); } /** @return array "x|y" => whether a player owns the village there */ public static function takenSpots(World $world): array { 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); } }