2026-10-28 18:17:34 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Actions;
|
|
|
|
|
|
2026-10-29 15:07:54 +00:00
|
|
|
use App\Engine\Raiders;
|
2026-10-28 18:45:02 +00:00
|
|
|
use App\Engine\VillageFactory;
|
2026-10-28 18:17:34 +00:00
|
|
|
use App\Game\GameRuleViolation;
|
2026-10-29 00:51:37 +00:00
|
|
|
use App\Game\Map\Frontier;
|
2026-10-28 18:17:34 +00:00
|
|
|
use App\Models\Player;
|
|
|
|
|
use App\Models\User;
|
|
|
|
|
use App\Models\Village;
|
|
|
|
|
use App\Models\World;
|
|
|
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
|
|
2026-10-29 00:51:37 +00:00
|
|
|
/**
|
|
|
|
|
* 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.
|
|
|
|
|
*/
|
2026-10-28 18:17:34 +00:00
|
|
|
final class JoinWorld
|
|
|
|
|
{
|
2026-10-29 00:51:37 +00:00
|
|
|
public function __construct(private readonly VillageFactory $villages, private readonly SpawnBarbarians $barbarians) {}
|
2026-10-28 18:45:02 +00:00
|
|
|
|
2026-10-29 00:51:37 +00:00
|
|
|
public function __invoke(User $user, int $worldId, string $direction = 'random'): Village
|
2026-10-28 18:17:34 +00:00
|
|
|
{
|
|
|
|
|
$world = World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.');
|
2026-10-29 00:51:37 +00:00
|
|
|
if (! in_array($direction, Frontier::DIRECTIONS, true)) {
|
|
|
|
|
throw new GameRuleViolation('direction', "Unknown direction [$direction].");
|
|
|
|
|
}
|
2026-10-28 18:17:34 +00:00
|
|
|
|
2026-10-29 00:51:37 +00:00
|
|
|
return DB::transaction(function () use ($user, $world, $direction) {
|
2026-10-28 18:17:34 +00:00
|
|
|
$player = Player::firstOrCreate(['user_id' => $user->id, 'world_id' => $world->id], ['name' => $user->name]);
|
|
|
|
|
if ($village = $player->villages()->orderBy('id')->first()) {
|
|
|
|
|
return $village;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-28 18:45:02 +00:00
|
|
|
$taken = VillageFactory::takenSpots($world);
|
2026-10-29 00:51:37 +00:00
|
|
|
[$x, $y] = VillageFactory::spawnSpot($world, $taken, $direction);
|
2026-10-28 21:26:25 +00:00
|
|
|
$levels = array_fill_keys($world->gameConfig()->get('world.village.start_buildings'), 1);
|
2026-10-29 00:51:37 +00:00
|
|
|
$village = $this->villages->create($world, $player, "{$user->name}'s village", $x, $y, $levels);
|
|
|
|
|
$this->barbarians->around($world, $village, $taken);
|
2026-10-29 15:07:54 +00:00
|
|
|
Raiders::of($village)->ensurePlanned(now()->toImmutable());
|
2026-10-28 18:17:34 +00:00
|
|
|
|
2026-10-29 00:51:37 +00:00
|
|
|
return $village;
|
2026-10-28 18:17:34 +00:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|