75 lines
2.7 KiB
PHP
75 lines
2.7 KiB
PHP
<?php
|
||
|
||
namespace App\Actions;
|
||
|
||
use App\Engine\Quests;
|
||
use App\Game\GameRuleViolation;
|
||
use App\Game\Map\Continent;
|
||
use App\Game\Map\MapBounds;
|
||
use App\Models\Player;
|
||
use App\Models\User;
|
||
use App\Models\Village;
|
||
use App\Models\World;
|
||
|
||
/**
|
||
* The villages in a w × h window of a world's map, centred on (x, y) the way the
|
||
* Die Stämme map is. Without a centre it opens on the player's first village there.
|
||
* Coordinates run from −size/2 to size/2 − 1; the world starts at 0|0.
|
||
*/
|
||
final class ShowMap
|
||
{
|
||
public function __invoke(User $user, int $worldId, ?int $x, ?int $y, int $w, int $h): array
|
||
{
|
||
$world = World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.');
|
||
$config = $world->gameConfig();
|
||
$bounds = MapBounds::of($config);
|
||
$size = $bounds->size;
|
||
$max = $config->get('world.map.max_view', 41);
|
||
$w = max(1, min($max, $w));
|
||
$h = max(1, min($max, $h));
|
||
|
||
Quests::mark(Player::where('user_id', $user->id)->where('world_id', $world->id)->value('id'), 'map.viewed');
|
||
|
||
if ($x === null || $y === null) {
|
||
$home = Village::whereIn('player_id', Player::where('user_id', $user->id)->where('world_id', $world->id)->select('id'))
|
||
->orderBy('id')->first();
|
||
$x = $home->x ?? 0;
|
||
$y = $home->y ?? 0;
|
||
}
|
||
$x = $bounds->clamp($x);
|
||
$y = $bounds->clamp($y);
|
||
$left = max($bounds->min(), min($bounds->max() - $w + 1, $x - intdiv($w, 2)));
|
||
$top = max($bounds->min(), min($bounds->max() - $h + 1, $y - intdiv($h, 2)));
|
||
|
||
$villages = Village::where('world_id', $world->id)
|
||
->whereBetween('x', [$left, $left + $w - 1])
|
||
->whereBetween('y', [$top, $top + $h - 1])
|
||
->with('player:id,user_id,name')
|
||
->get(['id', 'player_id', 'crown', 'name', 'x', 'y', 'points'])
|
||
->map(fn (Village $v) => [
|
||
'id' => $v->id,
|
||
'x' => $v->x,
|
||
'y' => $v->y,
|
||
'name' => $v->name,
|
||
'points' => $v->points,
|
||
'continent' => Continent::of($v->x, $v->y, $size),
|
||
'player' => $v->player ? ['id' => $v->player->id, 'name' => $v->player->name] : null,
|
||
'own' => $v->player?->user_id === $user->id,
|
||
'crown' => $v->crown,
|
||
])->values()->all();
|
||
|
||
return [
|
||
'world_id' => $world->id,
|
||
'size' => $size,
|
||
// Lowest coordinate on both axes; the highest is min + size − 1.
|
||
'min' => $bounds->min(),
|
||
'center' => ['x' => $x, 'y' => $y],
|
||
'x' => $left,
|
||
'y' => $top,
|
||
'w' => $w,
|
||
'h' => $h,
|
||
'villages' => $villages,
|
||
];
|
||
}
|
||
}
|