game-village-politics-backend/app/Actions/JoinWorld.php

49 lines
1.9 KiB
PHP

<?php
namespace App\Actions;
use App\Engine\Raiders;
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 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, private readonly SpawnBarbarians $barbarians) {}
public function __invoke(User $user, int $worldId, string $direction = 'random'): Village
{
$world = World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.');
$world->ensureOpen();
if (! in_array($direction, Frontier::DIRECTIONS, true)) {
throw new GameRuleViolation('direction', "Unknown direction [$direction].");
}
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, $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);
Raiders::of($village)->ensurePlanned(now()->toImmutable());
return $village;
});
}
}