2026-10-28 18:17:34 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Actions;
|
|
|
|
|
|
2026-10-28 18:45:02 +00:00
|
|
|
use App\Engine\VillageFactory;
|
2026-10-28 18:17:34 +00:00
|
|
|
use App\Game\GameRuleViolation;
|
|
|
|
|
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
|
|
|
|
|
{
|
2026-10-28 18:45:02 +00:00
|
|
|
public function __construct(private readonly VillageFactory $villages) {}
|
|
|
|
|
|
2026-10-28 18:17:34 +00:00
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-28 18:45:02 +00:00
|
|
|
$taken = VillageFactory::takenSpots($world);
|
2026-10-28 20:32:09 +00:00
|
|
|
[$x, $y] = VillageFactory::spawnSpot($world, $taken);
|
2026-10-28 18:45:02 +00:00
|
|
|
$levels = array_fill_keys($world->gameConfig()->get('world.village.start_buildings'), 0);
|
2026-10-28 18:17:34 +00:00
|
|
|
|
2026-10-28 18:45:02 +00:00
|
|
|
return $this->villages->create($world, $player, "{$user->name}'s village", $x, $y, $levels);
|
2026-10-28 18:17:34 +00:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|