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

47 lines
1.7 KiB
PHP
Raw Normal View History

<?php
namespace App\Actions;
use App\Engine\Rally;
use App\Game\GameRuleViolation;
use App\Game\Military\UnitRules;
use App\Game\Travel\TravelTime;
use App\Models\User;
use App\Models\Village;
/**
* What the send form shows before the player commits: the village at x|y, the distance,
* and how long these units would take. Changes nothing.
*/
final class PlanMarch
{
/** @param array<string, mixed> $units */
public function __invoke(User $user, int $villageId, int $x, int $y, array $units, ?string $mode): array
{
$village = Village::with('player')->find($villageId);
if (! $village || $village->player?->user_id !== $user->id) {
throw new GameRuleViolation('not_found', 'Village not found.');
}
$rally = Rally::of($village);
$travel = $rally->travel();
$mode = $mode && $travel->hasMode($mode) ? $mode : $travel->defaultMode();
$known = new UnitRules($village->world->gameConfig());
$picked = array_filter(
array_map('intval', array_filter($units, fn ($n, $unit) => $known->exists((string) $unit), ARRAY_FILTER_USE_BOTH)),
fn (int $n) => $n > 0,
);
$target = Village::with('player')->where('world_id', $village->world_id)->where('x', $x)->where('y', $y)->first();
$distance = TravelTime::distance($village->x, $village->y, $x, $y);
$seconds = $picked && $distance > 0 ? $travel->seconds($picked, $distance, $mode) : null;
return [
'x' => $x,
'y' => $y,
'target' => $target ? Rally::summary($target) : null,
'mode' => $mode,
'distance' => round($distance, 2),
'seconds' => $seconds,
];
}
}