feat: volley before the melee: archers and catapults shoot first, from the wall or at it, and kill by what their targets eat; reports and the simulator show the volley's dead

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-31 10:59:32 +01:00
parent d55850cec1
commit c344eb3a39
11 changed files with 293 additions and 18 deletions

View File

@ -2,7 +2,6 @@
namespace App\Actions; namespace App\Actions;
use App\Game\Combat\Battle;
use App\Game\Combat\CombatResolver; use App\Game\Combat\CombatResolver;
use App\Game\GameRuleViolation; use App\Game\GameRuleViolation;
use App\Game\Military\UnitRules; use App\Game\Military\UnitRules;
@ -34,8 +33,8 @@ final class SimulateBattle
$nightFactor = $night ? (float) $config->get('combat.night.factor', 2.0) : 1.0; $nightFactor = $night ? (float) $config->get('combat.night.factor', 2.0) : 1.0;
$battle = $combat->fight($attack, $defense, $wall, $morale, $luck, $nightFactor); $battle = $combat->fight($attack, $defense, $wall, $morale, $luck, $nightFactor);
$attackLost = Battle::dead($attack, $battle->attackLoss); $attackLost = $battle->attackDead($attack);
$defenseLost = Battle::dead($defense, $battle->defenseLoss); $defenseLost = $battle->defenseDead($defense);
$catapults = ($attack['catapult'] ?? 0) - ($attackLost['catapult'] ?? 0); $catapults = ($attack['catapult'] ?? 0) - ($attackLost['catapult'] ?? 0);
$hit = $building > 0 && $catapults > 0 && $battle->attackerWon $hit = $building > 0 && $catapults > 0 && $battle->attackerWon
? ['before' => $building, 'after' => $combat->siege('catapult', $building, $catapults)] ? ['before' => $building, 'after' => $combat->siege('catapult', $building, $catapults)]
@ -45,6 +44,8 @@ final class SimulateBattle
'won' => $battle->attackerWon, 'won' => $battle->attackerWon,
'attacker' => ['units' => (object) $attack, 'lost' => (object) $attackLost], 'attacker' => ['units' => (object) $attack, 'lost' => (object) $attackLost],
'defender' => ['units' => (object) $defense, 'lost' => (object) $defenseLost], '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, 'wall' => $wall > 0 ? ['before' => $battle->wallBefore, 'after' => $battle->wallAfter] : null,
'building' => $hit, 'building' => $hit,
'power' => ['attack' => round($battle->attackPower, 1), 'defense' => round($battle->defensePower, 1)], 'power' => ['attack' => round($battle->attackPower, 1), 'defense' => round($battle->defensePower, 1)],

View File

@ -310,16 +310,20 @@ final class Rally
$standing[$this->village->id] = ($standing[$this->village->id] ?? 0) + $defeated->weight(['militia' => $defense['militia']]); $standing[$this->village->id] = ($standing[$this->village->id] ?? 0) + $defeated->weight(['militia' => $defense['militia']]);
} }
// Defenders fall in every stack alike, support included. // Defenders fall in every stack alike, support included: the volley's share, then
// the melee's share of the rest, rounded per stack.
$defenseLost = []; $defenseLost = [];
$defenseShot = [];
$ownLost = []; $ownLost = [];
$supporters = []; $supporters = [];
foreach ($stacks as $stack) { foreach ($stacks as $stack) {
if ($stack->home_village_id !== $this->village->id) { if ($stack->home_village_id !== $this->village->id) {
$supporters[$stack->home_village_id] = true; $supporters[$stack->home_village_id] = true;
} }
$dead = Battle::dead([$stack->unit => $stack->count], $battle?->defenseLoss ?? 0.0)[$stack->unit]; $group = [$stack->unit => $stack->count];
$dead = $battle ? $battle->defenseDead($group)[$stack->unit] : 0;
$defenseLost[$stack->unit] = ($defenseLost[$stack->unit] ?? 0) + $dead; $defenseLost[$stack->unit] = ($defenseLost[$stack->unit] ?? 0) + $dead;
$defenseShot[$stack->unit] = ($defenseShot[$stack->unit] ?? 0) + ($battle ? $battle->defenseVolleyDead($group)[$stack->unit] : 0);
if ($stack->home_village_id === $this->village->id && $dead > 0) { if ($stack->home_village_id === $this->village->id && $dead > 0) {
$ownLost[$stack->unit] = $dead; $ownLost[$stack->unit] = $dead;
} }
@ -328,7 +332,8 @@ final class Rally
} }
$this->village->setRelation('troops', $this->village->troops->filter(fn (UnitStack $s) => $s->count > 0)->values()); $this->village->setRelation('troops', $this->village->troops->filter(fn (UnitStack $s) => $s->count > 0)->values());
if (isset($defense['militia'])) { if (isset($defense['militia'])) {
$defenseLost['militia'] = Battle::dead(['militia' => $defense['militia']], $battle?->defenseLoss ?? 0.0)['militia']; $defenseLost['militia'] = $battle ? $battle->defenseDead(['militia' => $defense['militia']])['militia'] : 0;
$defenseShot['militia'] = $battle ? $battle->defenseVolleyDead(['militia' => $defense['militia']])['militia'] : 0;
$this->village->militia -= $defenseLost['militia']; $this->village->militia -= $defenseLost['militia'];
if ($this->village->militia <= 0) { if ($this->village->militia <= 0) {
Military::of($this->village, $this->sim)->endLevy($at); Military::of($this->village, $this->sim)->endLevy($at);
@ -341,7 +346,7 @@ final class Rally
$damaged = true; $damaged = true;
} }
$attackLost = [ $attackLost = [
...($battle ? Battle::dead($army, $battle->attackLoss) : []), ...($battle ? $battle->attackDead($army) : []),
...Battle::dead($scouts, $scouts ? $scoutsLost / array_sum($scouts) : 0.0), ...Battle::dead($scouts, $scouts ? $scoutsLost / array_sum($scouts) : 0.0),
]; ];
Quests::bump($movement->player_id, 'defeated.attack', $defeated->points($defenseLost)); Quests::bump($movement->player_id, 'defeated.attack', $defeated->points($defenseLost));
@ -421,6 +426,8 @@ final class Rally
'night' => $night > 1, 'night' => $night > 1,
'attacker' => ['village' => self::summary($origin), 'units' => $movement->units, 'lost' => $attackLost], 'attacker' => ['village' => self::summary($origin), 'units' => $movement->units, 'lost' => $attackLost],
'defender' => ['village' => self::summary($this->village), 'units' => $defense, 'lost' => $defenseLost], 'defender' => ['village' => self::summary($this->village), 'units' => $defense, 'lost' => $defenseLost],
// Of the lost, the ones the other side's volley killed before the melee.
'volley' => $battle?->volleyed() ? ['attacker' => $battle->attackVolleyDead($movement->units), 'defender' => $defenseShot] : null,
// Of the lost, the ones in the defender's hospital, and when they stand again. // Of the lost, the ones in the defender's hospital, and when they stand again.
'wounded' => $wounded ? ['units' => $wounded->units, 'heals_at' => $wounded->heals_at->utc()->format('Y-m-d\TH:i:s.v\Z')] : null, 'wounded' => $wounded ? ['units' => $wounded->units, 'heals_at' => $wounded->heals_at->utc()->format('Y-m-d\TH:i:s.v\Z')] : null,
'wall' => $wall && $battle ? ['before' => $battle->wallBefore, 'after' => $wall->level] : null, 'wall' => $wall && $battle ? ['before' => $battle->wallBefore, 'after' => $wall->level] : null,
@ -442,6 +449,9 @@ final class Rally
// An attacker learns about the defence from survivors of the battle or scouts that got through. // An attacker learns about the defence from survivors of the battle or scouts that got through.
$informed = ($battle && array_diff_key($survivors, $scouts)) || $scouted; $informed = ($battle && array_diff_key($survivors, $scouts)) || $scouted;
$seen = $informed ? $report : ['defender' => ['village' => $report['defender']['village'], 'units' => null, 'lost' => null], 'wall' => null] + $report; $seen = $informed ? $report : ['defender' => ['village' => $report['defender']['village'], 'units' => null, 'lost' => null], 'wall' => null] + $report;
if (! $informed && $seen['volley']) {
$seen['volley']['defender'] = null;
}
// The hospital stays the defender's business. // The hospital stays the defender's business.
$seen['wounded'] = null; $seen['wounded'] = null;
Report::write($movement->player_id, Report::ATTACK, $seen, $at); Report::write($movement->player_id, Report::ATTACK, $seen, $at);

View File

@ -2,12 +2,19 @@
namespace App\Game\Combat; namespace App\Game\Combat;
/** The outcome of one battle, from CombatResolver. */ /**
* The outcome of one battle, from CombatResolver. The volley kills first; the melee
* share then applies to who is left. Every group of a side, each stack of support
* included, falls alike: the volley share of each unit, then the melee share of the
* rest, rounded per group and unit type. attackDead() and defenseDead() give that total.
*/
final readonly class Battle final readonly class Battle
{ {
/** /**
* @param float $attackLoss share of every attacking unit that died, 0..1 * @param float $attackLoss share of every attacking unit left after the volley that died in the melee, 0..1
* @param float $defenseLoss share of every defending unit that died, 0..1 * @param float $defenseLoss share of every defending unit left after the volley that died in the melee, 0..1
* @param array<string, float> $attackVolley unit => share of it the defenders' volley killed; units missing were not hit
* @param array<string, float> $defenseVolley unit => share of it the attackers' volley killed
*/ */
public function __construct( public function __construct(
public bool $attackerWon, public bool $attackerWon,
@ -17,8 +24,60 @@ final readonly class Battle
public int $wallAfter, public int $wallAfter,
public float $attackPower, public float $attackPower,
public float $defensePower, public float $defensePower,
public array $attackVolley = [],
public array $defenseVolley = [],
) {} ) {}
/** Whether anybody shot before the melee. */
public function volleyed(): bool
{
return $this->attackVolley !== [] || $this->defenseVolley !== [];
}
/**
* Attackers the defenders' volley killed.
*
* @param array<string, int> $units
* @return array<string, int>
*/
public function attackVolleyDead(array $units): array
{
return self::shot($units, $this->attackVolley);
}
/**
* Defenders the attackers' volley killed, for one group or the whole defence.
*
* @param array<string, int> $units
* @return array<string, int>
*/
public function defenseVolleyDead(array $units): array
{
return self::shot($units, $this->defenseVolley);
}
/**
* Every attacker who fell: the volley's dead, then the melee share of the rest.
*
* @param array<string, int> $units
* @return array<string, int>
*/
public function attackDead(array $units): array
{
return self::fallen($units, $this->attackVolley, $this->attackLoss);
}
/**
* Every defender who fell, for one group (a stack, the militia) or the whole defence.
*
* @param array<string, int> $units
* @return array<string, int>
*/
public function defenseDead(array $units): array
{
return self::fallen($units, $this->defenseVolley, $this->defenseLoss);
}
/** /**
* Dead units of a group at a loss share, rounded per unit type. * Dead units of a group at a loss share, rounded per unit type.
* *
@ -29,4 +88,37 @@ final readonly class Battle
{ {
return array_map(fn (int $n) => min($n, (int) round($n * $loss)), $units); return array_map(fn (int $n) => min($n, (int) round($n * $loss)), $units);
} }
/**
* Units a volley killed at these shares, rounded per unit type like dead().
*
* @param array<string, int> $units
* @param array<string, float> $shares unit => share; units missing were not hit
* @return array<string, int>
*/
public static function shot(array $units, array $shares): array
{
$dead = [];
foreach ($units as $unit => $n) {
$dead[$unit] = self::dead([$unit => $n], $shares[$unit] ?? 0.0)[$unit];
}
return $dead;
}
/**
* @param array<string, int> $units
* @param array<string, float> $volley
* @return array<string, int>
*/
private static function fallen(array $units, array $volley, float $melee): array
{
$shot = self::shot($units, $volley);
$dead = [];
foreach ($units as $unit => $n) {
$dead[$unit] = $shot[$unit] + self::dead([$unit => $n - $shot[$unit]], $melee)[$unit];
}
return $dead;
}
} }

View File

@ -25,21 +25,63 @@ final class CombatResolver
*/ */
public function fight(array $attack, array $defense, int $wall, float $morale, float $luck, float $night = 1.0): Battle public function fight(array $attack, array $defense, int $wall, float $morale, float $luck, float $night = 1.0): Battle
{ {
// Both sides shoot at once, from their numbers at the start. The defenders shoot
// from the wall, and it covers them from the attackers' volley.
$cover = $this->config->get('combat.wall.factor', 1.0) ** $wall;
$attackVolley = $this->volley($defense, $attack, $cover);
$defenseVolley = $this->volley($attack, $defense, 1 / $cover);
$attack = self::left($attack, $attackVolley);
$defense = self::left($defense, $defenseVolley);
// The melee runs with who is left. An attack shot to pieces has nobody to fight.
$wallAfter = $this->siege('ram', $wall, $attack['ram'] ?? 0); $wallAfter = $this->siege('ram', $wall, $attack['ram'] ?? 0);
$byClass = $this->attackByClass($attack); $byClass = $this->attackByClass($attack);
$total = array_sum($byClass); $total = array_sum($byClass);
if ($total <= 0) { if ($total <= 0) {
return new Battle(false, 1.0, 0.0, $wall, $wall, 0.0, 0.0); return new Battle(false, 1.0, 0.0, $wall, $wall, 0.0, 0.0, $attackVolley, $defenseVolley);
} }
$attackPower = $total * $morale * (1 + $luck); $attackPower = $total * $morale * (1 + $luck);
$defensePower = $this->defense($defense, $byClass, $total, $wallAfter) * $night; $defensePower = $this->defense($defense, $byClass, $total, $wallAfter) * $night;
if ($attackPower > $defensePower) { if ($attackPower > $defensePower) {
return new Battle(true, $this->winnerLoss($defensePower / $attackPower), 1.0, $wall, $wallAfter, $attackPower, $defensePower); return new Battle(true, $this->winnerLoss($defensePower / $attackPower), 1.0, $wall, $wallAfter, $attackPower, $defensePower, $attackVolley, $defenseVolley);
} }
return new Battle(false, 1.0, $this->winnerLoss($attackPower / $defensePower), $wall, $wallAfter, $attackPower, $defensePower); return new Battle(false, 1.0, $this->winnerLoss($attackPower / $defensePower), $wall, $wallAfter, $attackPower, $defensePower, $attackVolley, $defenseVolley);
}
/**
* The volley before the melee: the shooters' summed `volley` × $factor, soaked by the
* other side's food upkeep (a levied villager's for militia). It kills that share of
* every unit it hits, all of them at most. Scouts neither shoot nor get hit.
*
* @param array<string, int> $shooters
* @param array<string, int> $targets
* @return array<string, float> unit => share killed; empty when nobody shoots or nobody is there
*/
public function volley(array $shooters, array $targets, float $factor = 1.0): array
{
$volley = 0.0;
foreach ($shooters as $unit => $count) {
if ($unit !== 'militia' && ! $this->isScout($unit)) {
$volley += $count * (float) $this->config->get("units.$unit.volley", 0);
}
}
$soak = 0.0;
$hit = [];
foreach ($targets as $unit => $count) {
if ($unit === 'militia' || ! $this->isScout($unit)) {
$soak += $count * ($unit === 'militia' ? (float) $this->config->get('economy.upkeep.villager', 1) : (float) $this->config->get("units.$unit.upkeep"));
$hit[] = $unit;
}
}
$volley *= $factor;
if ($volley <= 0 || $soak <= 0) {
return [];
}
return array_fill_keys($hit, min(1.0, $volley / $soak));
} }
/** /**
@ -130,6 +172,28 @@ final class CombatResolver
return $inside ? (float) $night['factor'] : 1.0; return $inside ? (float) $night['factor'] : 1.0;
} }
private function isScout(string $unit): bool
{
return (bool) $this->config->get("units.$unit.scout", false);
}
/**
* Who is left of a side after the volley, rounded per unit type like Battle::dead.
*
* @param array<string, int> $units
* @param array<string, float> $shares
* @return array<string, int>
*/
private static function left(array $units, array $shares): array
{
$shot = Battle::shot($units, $shares);
foreach ($units as $unit => $n) {
$units[$unit] = $n - $shot[$unit];
}
return $units;
}
/** /**
* @param array<string, int> $units * @param array<string, int> $units
* @return array<string, float> class => attack strength * @return array<string, float> class => attack strength

View File

@ -156,7 +156,10 @@ final class ConfigLint
return $problems; return $problems;
} }
/** Battle shares stay shares: the winner's loss threshold below 1, so the loss curve has room to rise. */ /**
* Battle shares stay shares: the winner's loss threshold below 1, so the loss curve
* has room to rise, and no volley below 0, which would raise the dead.
*/
private static function battlesSettle(WorldConfig $config): array private static function battlesSettle(WorldConfig $config): array
{ {
$problems = []; $problems = [];
@ -164,6 +167,11 @@ final class ConfigLint
if ($threshold < 0 || $threshold >= 1) { if ($threshold < 0 || $threshold >= 1) {
$problems[] = '[combat.loss_threshold] must be at least 0 and below 1.'; $problems[] = '[combat.loss_threshold] must be at least 0 and below 1.';
} }
foreach ((new UnitRules($config))->units() as $unit) {
if ($config->get("units.$unit.volley", 0) < 0) {
$problems[] = "[units.$unit.volley] cannot be negative.";
}
}
return $problems; return $problems;
} }

View File

@ -17,6 +17,9 @@ return [
'loss_threshold' => 0.1, 'loss_threshold' => 0.1,
// Wall at level L: defenders get basic_defense × L extra, then everything × factor^L. // Wall at level L: defenders get basic_defense × L extra, then everything × factor^L.
// Before the melee both sides shoot at once (units.*.volley): the defenders' volley
// × factor^L, the attackers' ÷ factor^L. A volley kills min(1, volley / the other side's
// food upkeep) of every unit but scouts; the melee runs with who is left.
'wall' => ['basic_defense' => 20, 'factor' => 1.037], 'wall' => ['basic_defense' => 20, 'factor' => 1.037],
// Rams hit the wall before the battle, surviving catapults the chosen building after // Rams hit the wall before the battle, surviving catapults the chosen building after

View File

@ -3,7 +3,8 @@
// Units, with Die Stämme-like stats. A unit is trained from one villager at its building // Units, with Die Stämme-like stats. A unit is trained from one villager at its building
// type; while queued and after, it eats `upkeep` food per hour instead of that villager. // type; while queued and after, it eats `upkeep` food per hour instead of that villager.
// build_time is seconds per unit at world speed 1, building level 1 and full staffing. // build_time is seconds per unit at world speed 1, building level 1 and full staffing.
// speed is minutes per field (M4), carry is loot per unit (M4). // speed is minutes per field (M4), carry is loot per unit (M4). volley is what one unit
// shoots before the melee, in food upkeep of the enemy it kills (0 when missing; see combat.php).
return [ return [
'spear' => [ 'spear' => [
@ -38,6 +39,7 @@ return [
'attack' => 15, 'attack' => 15,
'defense' => ['infantry' => 50, 'cavalry' => 40, 'archer' => 5], 'defense' => ['infantry' => 50, 'cavalry' => 40, 'archer' => 5],
'class' => 'archer', 'class' => 'archer',
'volley' => 0.1,
'speed' => 18, 'speed' => 18,
'carry' => 10, 'carry' => 10,
'requires' => ['barracks' => 3], 'requires' => ['barracks' => 3],
@ -101,6 +103,7 @@ return [
'attack' => 100, 'attack' => 100,
'defense' => ['infantry' => 100, 'cavalry' => 50, 'archer' => 100], 'defense' => ['infantry' => 100, 'cavalry' => 50, 'archer' => 100],
'class' => 'infantry', 'class' => 'infantry',
'volley' => 0.5,
'speed' => 30, 'speed' => 30,
'carry' => 0, 'carry' => 0,
'requires' => ['workshop' => 2], 'requires' => ['workshop' => 2],

View File

@ -9,6 +9,7 @@ use App\Models\Village;
use App\Models\World; use App\Models\World;
use App\Models\Wounded; use App\Models\Wounded;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
beforeEach(fn () => $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00'))); beforeEach(fn () => $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00')));
@ -101,6 +102,26 @@ it('takes in only the own fallen, not the support', function () {
->and($defense['wounded']['units'])->toBe(['sword' => 6]); ->and($defense['wounded']['units'])->toBe(['sword' => 6]);
}); });
it('counts the volley\'s dead with the fallen: in the reports, the hospital and the ranking', function () {
[$attacker, $defender] = wardVillages();
$attacker->troops()->create(['home_village_id' => $attacker->id, 'unit' => 'archer', 'count' => 30]);
app(SendTroops::class)(owner($attacker), $attacker->id, 'attack', $defender->x, $defender->y, ['archer' => 30], null, null);
$this->travelTo(Movement::where('target_id', $defender->id)->sole()->arrives_at);
$this->artisan('game:events --once')->assertSuccessful();
// 30 archers shoot 3 food at the swordsmen's 20 before the melee: 3 fall. The 17 left
// hold 680 against 450 and lose ((450 / 680 − 0.1) / 0.9)^1.5 of themselves: 8 more.
$defense = Report::where('player_id', $defender->player_id)->sole()->payload;
expect($defense['volley'])->toBe(['attacker' => ['archer' => 0], 'defender' => ['sword' => 3]])
->and($defense['defender']['lost'])->toBe(['sword' => 11])
->and($defense['wounded']['units'])->toBe(['sword' => 5])
->and((array) shown($defender)['troops'])->toBe(['sword' => 9])
// No archer came back, so the attacker learns nothing of the defence, its volley neither.
->and(Report::where('player_id', $attacker->player_id)->sole()->payload['volley'])->toBe(['attacker' => ['archer' => 0], 'defender' => null])
->and(DB::table('player_counters')->where('player_id', $attacker->player_id)->where('key', 'defeated.attack')->value('value'))->toBe(11)
->and(DB::table('player_counters')->where('player_id', $defender->player_id)->where('key', 'defeated.defense')->value('value'))->toBe(30);
});
it('loses its wounded when the village turns barbarian', function () { it('loses its wounded when the village turns barbarian', function () {
[$attacker, $defender] = wardVillages(); [$attacker, $defender] = wardVillages();
strike($attacker, $defender, 60); strike($attacker, $defender, 60);

View File

@ -13,6 +13,9 @@ it('simulates a battle with the world\'s rules and changes nothing', function ()
expect($result['won'])->toBeTrue() expect($result['won'])->toBeTrue()
->and((array) $result['attacker']['units'])->toBe(['light_cavalry' => 100, 'catapult' => 20]) ->and((array) $result['attacker']['units'])->toBe(['light_cavalry' => 100, 'catapult' => 20])
->and((array) $result['defender']['lost'])->toBe(['spear' => 50, 'militia' => 10]) ->and((array) $result['defender']['lost'])->toBe(['spear' => 50, 'militia' => 10])
// 20 catapults shoot 10 food at 60 before the melee: a sixth of each falls.
->and((array) $result['volley']['defender'])->toBe(['spear' => 8, 'militia' => 2])
->and((array) $result['volley']['attacker'])->toBe(['light_cavalry' => 0, 'catapult' => 0])
// 2100 defence against 15000 attack: under 1% falls, no catapult, so 20 take the building down two levels. // 2100 defence against 15000 attack: under 1% falls, no catapult, so 20 take the building down two levels.
->and($result['building'])->toBe(['before' => 20, 'after' => 18]) ->and($result['building'])->toBe(['before' => 20, 'after' => 18])
->and($result['wall'])->toBeNull(); ->and($result['wall'])->toBeNull();
@ -25,5 +28,6 @@ it('keeps morale and luck within the world\'s limits', function () {
$low = app(SimulateBattle::class)($world, ['spear' => 100], [], 0, 0, -90, false, 0); $low = app(SimulateBattle::class)($world, ['spear' => 100], [], 0, 0, -90, false, 0);
// Morale never below 30%, luck never below −25%. // Morale never below 30%, luck never below −25%.
expect($low['power']['attack'])->toBe(round(1000 * 0.3 * 0.75, 1)); expect($low['power']['attack'])->toBe(round(1000 * 0.3 * 0.75, 1))
->and($low['volley'])->toBeNull();
}); });

View File

@ -112,3 +112,72 @@ it('lets scouts through when they outnumber the defending ones', function () {
->and($combat->scout(5, 5))->toBe([false, 5]) ->and($combat->scout(5, 5))->toBe([false, 5])
->and($combat->scout(0, 3))->toBe([false, 0]); ->and($combat->scout(0, 3))->toBe([false, 0]);
}); });
it('lets archers shoot the attackers down before they reach the defence', function () {
$battle = (new CombatResolver(gameConfig()))->fight(['spear' => 50], ['spear' => 2000, 'archer' => 2000], 0, 1.0, 0.0);
// 2000 archers shoot 200 food of enemies, the 50 spears eat 50: all of them fall
// before the melee, so there is none and the defence loses nobody.
expect($battle->attackerWon)->toBeFalse()
->and($battle->attackVolley)->toBe(['spear' => 1.0])
->and($battle->defenseVolley)->toBe([])
->and($battle->attackDead(['spear' => 50]))->toBe(['spear' => 50])
->and($battle->defenseDead(['spear' => 2000, 'archer' => 2000]))->toBe(['spear' => 0, 'archer' => 0]);
});
it('beats a raid band without a loss when the defence has archers and catapults', function () {
// A live raid: the defenders lost 8 spears and 8 archers every time before the volley.
$band = ['spear' => 136, 'sword' => 58, 'ram' => 2];
$defense = ['spear' => 502, 'archer' => 470, 'catapult' => 23, 'sword' => 28, 'light_cavalry' => 2, 'nobleman' => 1];
$battle = (new CombatResolver(gameConfig()))->fight($band, $defense, 2, 1.0, 0.25);
// (470 × 0.1 + 23 × 0.5) × 1.037² = 62.9 against 136 + 58 + 2 × 4 = 202 food: 31% fall.
expect($battle->attackerWon)->toBeFalse()
->and($battle->attackVolleyDead($band))->toBe(['spear' => 42, 'sword' => 18, 'ram' => 1])
->and($battle->attackDead($band))->toBe($band)
->and(array_sum($battle->defenseDead($defense)))->toBe(0);
});
it('shoots from the wall and through it', function () {
$combat = new CombatResolver(gameConfig());
$open = $combat->fight(['archer' => 100], ['spear' => 100, 'archer' => 100], 0, 1.0, 0.0);
$walled = $combat->fight(['archer' => 100], ['spear' => 100, 'archer' => 100], 10, 1.0, 0.0);
// Each side shoots 10 food of 200: 5% of every unit. Behind wall 10 the defenders
// shoot 1.037^10 more, the attackers 1.037^10 less.
expect($open->attackVolley)->toEqualWithDelta(['archer' => 0.1], 1e-9)
->and($open->defenseVolley)->toEqualWithDelta(['spear' => 0.05, 'archer' => 0.05], 1e-9)
->and($walled->attackVolley['archer'])->toEqualWithDelta(0.1 * 1.037 ** 10, 1e-9)
->and($walled->defenseVolley['spear'])->toEqualWithDelta(0.05 / 1.037 ** 10, 1e-9)
->and($walled->defenseVolleyDead(['spear' => 100, 'archer' => 100]))->toBe(['spear' => 3, 'archer' => 3]);
});
it('weighs a volley by what its targets eat; militia soak a villager each and scouts stay out of it', function () {
$combat = new CombatResolver(gameConfig());
// 10 catapults shoot 5 food: 10 spears and 10 militia soak 20, a heavy rider 4.
expect($combat->volley(['catapult' => 10], ['spear' => 10, 'militia' => 10, 'scout' => 50]))->toBe(['spear' => 0.25, 'militia' => 0.25])
->and($combat->volley(['catapult' => 10], ['heavy_cavalry' => 1]))->toBe(['heavy_cavalry' => 1.0])
->and($combat->volley(['spear' => 100, 'scout' => 100, 'militia' => 5], ['spear' => 10]))->toBe([])
->and($combat->volley(['archer' => 10], ['scout' => 10]))->toBe([]);
});
it('wins outright when the volley leaves no defender standing', function () {
$battle = (new CombatResolver(gameConfig()))->fight(['archer' => 100], ['spear' => 5, 'scout' => 3], 0, 1.0, 0.0);
// 10 food shot at 5 spears: none left, the scouts fall with the village.
expect($battle->attackerWon)->toBeTrue()
->and($battle->attackLoss)->toBe(0.0)
->and($battle->defenseDead(['spear' => 5, 'scout' => 3]))->toBe(['spear' => 5, 'scout' => 3])
->and($battle->defenseVolleyDead(['spear' => 5, 'scout' => 3]))->toBe(['spear' => 5, 'scout' => 0]);
});
it('kills the volley share first and the melee share of the rest, per group', function () {
$battle = new Battle(false, 1.0, 0.5, 0, 0, 1.0, 2.0, [], ['spear' => 0.25]);
// 10 spears: 3 shot (2.5 rounded), half of the 7 left in the melee (3.5 → 4).
expect($battle->defenseVolleyDead(['spear' => 10, 'sword' => 10]))->toBe(['spear' => 3, 'sword' => 0])
->and($battle->defenseDead(['spear' => 10, 'sword' => 10]))->toBe(['spear' => 7, 'sword' => 5])
->and($battle->volleyed())->toBeTrue()
->and((new Battle(true, 0.0, 1.0, 0, 0, 2.0, 1.0))->volleyed())->toBeFalse();
});

View File

@ -93,8 +93,8 @@ it('reports raids that never pause or that a beaten camp still sends', function
->toContain('[raids.mode] is not a travel mode.'); ->toContain('[raids.mode] is not a travel mode.');
}); });
it('reports battle shares out of range', function () { it('reports battle shares out of range', function () {
expect(ConfigLint::check(gameConfig(['combat' => ['loss_threshold' => 1.0]]))) expect(ConfigLint::check(gameConfig(['combat' => ['loss_threshold' => 1.0], 'units' => ['archer' => ['volley' => -0.1]]])))
->toBe(['[combat.loss_threshold] must be at least 0 and below 1.']); ->toBe(['[combat.loss_threshold] must be at least 0 and below 1.', '[units.archer.volley] cannot be negative.']);
}); });
it('reports roles that share buildings or can never be reached', function () { it('reports roles that share buildings or can never be reached', function () {
$config = gameConfig(['world' => ['village' => ['specialisation' => [ $config = gameConfig(['world' => ['village' => ['specialisation' => [