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

72 lines
3.1 KiB
PHP

<?php
namespace App\Actions;
use App\Game\Combat\CombatResolver;
use App\Game\GameRuleViolation;
use App\Game\Military\UnitRules;
use App\Models\World;
/**
* The rally point's battle simulator: the world's CombatResolver on any units, wall,
* morale, luck and night, plus what surviving catapults would do. Changes nothing.
*/
final class SimulateBattle
{
private const MAX_UNITS = 10_000_000;
/**
* @param array<string, mixed> $attack
* @param array<string, mixed> $defense may include `militia`
*/
public function __invoke(int $worldId, array $attack, array $defense, int $wall, float $morale, float $luck, bool $night, int $building): array
{
$config = (World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.'))->gameConfig();
$units = new UnitRules($config);
$combat = new CombatResolver($config);
$attack = $this->counts($attack, fn (string $u) => $units->exists($u));
$defense = $this->counts($defense, fn (string $u) => $units->exists($u) || $u === 'militia');
$wall = max(0, min($wall, (int) $config->get('buildings.wall.max_level', 20)));
$morale = max((float) $config->get('combat.morale.floor', 0.3), min(1.0, $morale / 100));
$maxLuck = (float) $config->get('combat.luck', 0);
$luck = max(-$maxLuck, min($maxLuck, $luck / 100));
$nightFactor = $night ? (float) $config->get('combat.night.factor', 2.0) : 1.0;
$battle = $combat->fight($attack, $defense, $wall, $morale, $luck, $nightFactor);
$attackLost = $battle->attackDead($attack);
$defenseLost = $battle->defenseDead($defense);
$catapults = ($attack['catapult'] ?? 0) - ($attackLost['catapult'] ?? 0);
$hit = $building > 0 && $catapults > 0 && $battle->attackerWon
? ['before' => $building, 'after' => $combat->siege('catapult', $building, $catapults)]
: null;
return [
'won' => $battle->attackerWon,
'attacker' => ['units' => (object) $attack, 'lost' => (object) $attackLost],
'defender' => ['units' => (object) $defense, 'lost' => (object) $defenseLost],
// Of the lost, the ones the other side's volley killed before the melee.
'volley' => $battle->volleyed() ? ['attacker' => (object) $battle->attackVolleyDead($attack), 'defender' => (object) $battle->defenseVolleyDead($defense)] : null,
'wall' => $wall > 0 ? ['before' => $battle->wallBefore, 'after' => $battle->wallAfter] : null,
'building' => $hit,
'power' => ['attack' => round($battle->attackPower, 1), 'defense' => round($battle->defensePower, 1)],
];
}
/**
* @param array<string, mixed> $units
* @return array<string, int>
*/
private function counts(array $units, \Closure $known): array
{
$counts = [];
foreach ($units as $unit => $count) {
$count = max(0, min(self::MAX_UNITS, (int) $count));
if ($count > 0 && $known((string) $unit)) {
$counts[(string) $unit] = $count;
}
}
return $counts;
}
}