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

52 lines
2.0 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Actions;
use App\Engine\Quests;
use App\Engine\Rally;
use App\Engine\Simulation;
use App\Game\GameRuleViolation;
use App\Models\Movement;
use App\Models\User;
use App\Models\Village;
use Carbon\CarbonImmutable;
/** Send an attack or support from the rally point to the village at x|y. */
final class SendTroops extends VillageAction
{
/** @param array<string, mixed> $units */
public function __invoke(User $user, int $villageId, string $type, int $x, int $y, array $units, ?string $mode, ?string $catapultTarget): Village
{
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($type, $x, $y, $units, $mode, $catapultTarget) {
$target = Village::where('world_id', $village->world_id)->where('x', $x)->where('y', $y)->first()
?? throw new GameRuleViolation('not_found', 'No village there.');
$rally = Rally::of($village, $sim);
$movement = $rally->send($type, $target, $units, $mode ?: $rally->travel()->defaultMode(), $catapultTarget ?: null, $now);
$this->count($village, $target, $movement);
});
}
/** Counters for the quest book: attacks (on barbarians), support, scouting. */
private function count(Village $village, Village $target, Movement $movement): void
{
if ($movement->type === Movement::SUPPORT) {
Quests::bump($village->player_id, 'support.sent');
return;
}
Quests::bump($village->player_id, 'attacks.sent');
if ($target->player_id === null) {
Quests::bump($village->player_id, 'attacks.barbarian');
}
if (array_intersect(array_keys($movement->units), $this->scoutUnits($village))) {
Quests::bump($village->player_id, 'scouts.sent');
}
}
/** @return list<string> */
private function scoutUnits(Village $village): array
{
return array_keys(array_filter($village->world->gameConfig()->get('units', []), fn (array $u) => $u['scout'] ?? false));
}
}