$user->id, 'world_id' => $world->id], ['name' => $user->name]); if ($village = $player->villages()->orderBy('id')->first()) { return $village; } $config = $world->gameConfig(); [$x, $y] = $this->spawnPoint($world, $config); [$w, $h] = $config->get('world.village.grid'); $village = Village::create([ 'world_id' => $world->id, 'player_id' => $player->id, 'name' => "{$user->name}'s village", 'x' => $x, 'y' => $y, 'grid_w' => $w, 'grid_h' => $h, ...$config->get('world.village.start_resources'), 'resources_at' => now()->toImmutable(), ]); $rules = new BuildingRules($config); $grid = new VillageGrid($w, $h); foreach ($config->get('world.village.start_buildings') as $type) { [$fw, $fh] = $rules->footprint($type); $at = $grid->freeSlot($fw, $fh); $grid->take($at['x'], $at['y'], $fw, $fh); $village->buildings()->create(['type' => $type, 'level' => 0, 'x' => $at['x'], 'y' => $at['y']]); } return $village; }); } /** * First free coordinate on rings around the map centre. Stand-in until M2's * spawn ring that moves outward as the world fills. * * @return array{0: int, 1: int} */ private function spawnPoint(World $world, WorldConfig $config): array { $centre = intdiv($config->get('world.map.size', 1000), 2); $taken = $world->villages()->get(['x', 'y'])->mapWithKeys(fn ($v) => ["{$v->x}|{$v->y}" => true])->all(); for ($r = 0; $r <= $centre; $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"])) { return [$x, $y]; } } } } throw new GameRuleViolation('world_full', 'This world is full.'); } }