84 lines
3.0 KiB
PHP
84 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Actions;
|
|
|
|
use App\Game\Buildings\BuildingRules;
|
|
use App\Game\Buildings\VillageGrid;
|
|
use App\Game\GameRuleViolation;
|
|
use App\Game\WorldConfig;
|
|
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. */
|
|
final class JoinWorld
|
|
{
|
|
public function __invoke(User $user, int $worldId): Village
|
|
{
|
|
$world = World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.');
|
|
|
|
return DB::transaction(function () use ($user, $world) {
|
|
$player = Player::firstOrCreate(['user_id' => $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.');
|
|
}
|
|
}
|