feat: battle simulator: rally.simulate runs the world's combat rules on any setup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-29 00:08:43 +01:00
parent e75a755e48
commit 28ee28120b
3 changed files with 116 additions and 1 deletions

View File

@ -0,0 +1,70 @@
<?php
namespace App\Actions;
use App\Game\Combat\Battle;
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::dead($attack, $battle->attackLoss);
$defenseLost = Battle::dead($defense, $battle->defenseLoss);
$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],
'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;
}
}

View File

@ -6,12 +6,13 @@ use App\Actions\CancelMovement;
use App\Actions\PlanMarch;
use App\Actions\SendSupportHome;
use App\Actions\SendTroops;
use App\Actions\SimulateBattle;
use App\Actions\WithdrawSupport;
use App\Presenters\VillagePresenter;
use App\Websocket\GameController;
/**
* rally.preview {village_id, x, y, units, mode}: target, distance and travel time.
* rally.preview {village_id, x, y, units, mode}: target, distance and travel time; rally.simulate: a battle on paper.
* rally.send {village_id, type, x, y, units, mode, catapult_target}, rally.cancel {village_id, movement_id},
* rally.sendHome {village_id, home_village_id}, rally.withdraw {village_id, host_village_id}:
* each answers with the fresh village state.
@ -30,6 +31,21 @@ class RallyController extends GameController
));
}
/** rally.simulate {world_id, attack, defense, wall, morale, luck, night, building}: a battle on paper. */
public function simulate()
{
return $this->play(fn () => app(SimulateBattle::class)(
(int) request('world_id'),
(array) request('attack', []),
(array) request('defense', []),
(int) request('wall', 0),
(float) (request('morale') ?? 100),
(float) request('luck', 0),
(bool) request('night', false),
(int) request('building', 0),
));
}
public function send()
{
return $this->village(fn () => app(SendTroops::class)(

View File

@ -0,0 +1,29 @@
<?php
use App\Actions\SimulateBattle;
use App\Models\World;
use Database\Seeders\WorldSeeder;
it('simulates a battle with the world\'s rules and changes nothing', function () {
(new WorldSeeder)->run();
$world = World::where('slug', 'w1')->value('id');
$result = app(SimulateBattle::class)($world, ['light_cavalry' => 100, 'catapult' => 20, 'axe' => 5], ['spear' => 50, 'militia' => 10], 0, 100, 0, false, 20);
expect($result['won'])->toBeTrue()
->and((array) $result['attacker']['units'])->toBe(['light_cavalry' => 100, 'catapult' => 20])
->and((array) $result['defender']['lost'])->toBe(['spear' => 50, 'militia' => 10])
// One of 20 catapults falls; 19 take the building down one level, 20 would take two.
->and($result['building'])->toBe(['before' => 20, 'after' => 19])
->and($result['wall'])->toBeNull();
});
it('keeps morale and luck within the world\'s limits', function () {
(new WorldSeeder)->run();
$world = World::where('slug', 'w1')->value('id');
$low = app(SimulateBattle::class)($world, ['spear' => 100], [], 0, 0, -90, false, 0);
// Morale never below 30%, luck never below −25%.
expect($low['power']['attack'])->toBe(round(1000 * 0.3 * 0.75, 1));
});