Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

36.5 KB
Raw Blame
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace Statecraft.Sim
{
    /// <summary>Combat in the GDD v0.1 loop (Phase 5 PR 8; docs/rules/mvp.md R-COMBAT-001 to R-COMBAT-006). A unit given
    /// UnitOrder(unit, attack, q, r) makes a player's unit attack the hex at once; enemy attacks remain standing orders
    /// resolved in step 2. Each player attack is one engagement with that unit alone; it draws once and reads rules.yaml mvp.combat_table
    /// (Q-COMBAT-1). Combat changes the units and the Arms only (R-COMBAT-005): no resident, city, locality or score is ever
    /// a target or an outcome (Q-CIV-2, impact plan section 4.3).</summary>
    public static class Combat
    {
        public const string Attack = "attack";

        /// <summary>The unit_types.yaml class whose units support attacks from range (R-COMBAT-007; Q-ARTY-1).</summary>
        public const string ArtilleryClass = "artillery";

        /// <summary>RNG values each engagement draws, whatever its outcome (docs/determinism.md, "Combat draws").</summary>
        public const int DrawsPerEngagement = 1;

        /// <summary>The player's team: Israel's units and the halutzim (no side). Every other side is the enemy, and the Arab
        /// sides fight on one team (Movement's reading of "the enemy").</summary>
        static bool Player(Unit u) => u.Side == "" || u.Side == Movement.PlayerSide;

        /// <summary>Only military units fight (R-UNIT-001): a halutz is never a target or an attacker.</summary>
        static bool Military(Unit u) => u.Side != "";

        static string Hex(int q, int r) => string.Format(CultureInfo.InvariantCulture, "{0},{1}", q, r);

        static bool Adjacent(Unit u, int q, int r) => Movement.Neighbours.Any(d => u.Q + d.Q == q && u.R + d.R == r);

        static UnitType? TypeOf(Content c, Unit u) => c.UnitTypes.FirstOrDefault(t => t.Id == u.Type);

        /// <summary>R-COMBAT-007: a unit of the artillery class (Q-ARTY-1).</summary>
        static bool Guns(Content c, Unit u) => TypeOf(c, u)?.Class == ArtilleryClass;

        /// <summary>R-COMBAT-007: artillery reaches an enemy hex within its type's range; every other unit only the hex next
        /// to it (Q-COMBAT-2).</summary>
        static bool InReach(Content c, Unit u, int q, int r)
        {
            if (!Guns(c, u)) return Adjacent(u, q, r);
            var d = MapActions.Distance(u.Q, u.R, q, r);
            return d >= 1 && d <= TypeOf(c, u)!.Range!.Value;   // the loader requires a range on an artillery type
        }

        /// <summary>R-COMBAT-004, R-COMBAT-007: whether the player's attacks and artillery fire spend Arms. True for legacy and
        /// gdd-0.1, false under gdd-0.3 (#1706). The Arms stock and every other Arms cost stay; enemy units never pay.</summary>
        public static bool SpendsArms(Content c) => c.Ruleset != SaveGame.Gdd03Ruleset;

        /// <summary>The Arms the player's unit spends when it joins an engagement: its type's arms_per_fire for artillery
        /// (R-COMBAT-007), else mvp.arms_per_attack (R-COMBAT-004).</summary>
        static int Need(Content c, MvpRules mvp, Unit u) => Guns(c, u) ? TypeOf(c, u)!.ArmsPerFire!.Value : mvp.ArmsPerAttack!.Value;

        /// <summary>R-COMBAT-007, R-COMBAT-008: the percent of its strength a unit fights at, its type's combat_percent or 100.</summary>
        static long Factor(Content c, Unit u) => TypeOf(c, u)?.CombatPercent ?? 100;

        /// <summary>R-COMBAT-009: the truce cards and the ends of their windows, half-open like R-ENEMY-006's (Q-WAR-3;
        /// owner, 22 October 2026, #750): from accepting first_truce to 8 July 1948, and from accepting second_truce to
        /// 15 October 1948, the sourced dates of first_truce.yaml, ten_days.yaml, second_truce.yaml and
        /// operation_yoav.yaml. The player's side is bound from accepting the card, not by date alone: a refused or
        /// defied card binds nothing.</summary>
        internal static readonly (string Event, string Option, DateTime Until)[] PlayerTruces =
        {
            ("first_truce", "accept", new DateTime(1948, 7, 8)),
            ("second_truce", "comply", new DateTime(1948, 10, 15)),
        };

        /// <summary>R-COMBAT-009: whether a truce the player accepted is in force on <see cref="GameState.Date"/> (the
        /// turn's first day, the date the HUD shows): until the turn that covers the window's end, so a complying
        /// player attacks again from the 15 October 1948 turn (owner ruling 1, 22 October 2026, #750).</summary>
        internal static bool TruceInForce(GameState s) => TruceUntil(s) != null;

        /// <summary>R-COMBAT-009: the end of the window of the truce in force (<see cref="TruceInForce"/>), else null. The
        /// Defence screen's truce line reads it (#755), so the UI holds no truce rule.</summary>
        public static DateTime? TruceUntil(GameState s) =>
            PlayerTruces.Where(t => s.Date < t.Until && s.ChosenOptions.TryGetValue(t.Event, out var o) && o == t.Option)
                .Select(t => (DateTime?)t.Until).FirstOrDefault();

        /// <summary>The enemy military units on (q, r), seen from <paramref name="attacker"/>'s team, in id order.</summary>
        static List<Unit> Defenders(GameState s, Unit attacker, int q, int r) =>
            s.Units.Values.Where(x => x.Q == q && x.R == r && Military(x) && Player(x) != Player(attacker)).ToList();

        /// <summary><see cref="Check"/>'s own refusals (#2072); the unit, side and existing-order ones are Orders.Refused*. The UI
        /// maps each to its own string (SimBridge.ReasonText). The English is the reason a turn's Rejected list and a save carry,
        /// so it does not change; <see cref="RefusedArms"/> is a format, its values filled in invariantly.</summary>
        public const string RefusedNoHex = "An attack names a hex";
        public const string RefusedTruce = "A truce is in force";
        public const string RefusedOutOfRange = "That hex is beyond the unit's range";
        public const string RefusedNotAdjacent = "That hex is not next to the unit";
        public const string RefusedNoEnemy = "There is no enemy unit on that hex";
        public const string RefusedNoPoints = "That unit has no movement points left this turn";
        public const string RefusedArms = "An attack needs {0} Arms and the stock has {1}";

        /// <summary>R-COMBAT-001's refusals: null when the player may strike (q, r), else the reason shown to the player.
        /// Changes nothing: the unit card asks it for each enemy hex before it offers that hex (#754). Refused for an unknown
        /// unit, a halutz, an enemy unit, no hex, a hex not next to it (artillery: beyond its range), a hex with no enemy unit,
        /// a truce the player accepted (R-COMBAT-009), no movement points left or fewer Arms than the attack takes. With
        /// <paramref name="enemy"/> the enemy AI orders its own unit through the same checks, the sides swapped, with its
        /// existing-order check and no Arms cost (R-ENEMY-001; Q-ENEMY-4).</summary>
        public static string? Check(Content c, GameState s, int unitId, int? q, int? r, bool enemy = false,
                                    IReadOnlyDictionary<int, int>? spent = null)
        {
            if (!s.Units.TryGetValue(unitId, out var u)) return Orders.RefusedNoUnit;
            if (!Military(u)) return Orders.RefusedNotMilitary;
            if (Player(u) == enemy) return Orders.RefusedNotYours;
            if (q == null || r == null) return RefusedNoHex;
            if (!enemy && TruceInForce(s)) return RefusedTruce;   // R-COMBAT-009
            var target = Hex(q.Value, r.Value);
            if (enemy && u.Order == Attack && u.OrderTarget == target) return Orders.RefusedAlready;
            if (!InReach(c, u, q.Value, r.Value)) return Guns(c, u) ? RefusedOutOfRange : RefusedNotAdjacent;
            if (Defenders(s, u, q.Value, r.Value).Count == 0) return RefusedNoEnemy;
            if (!enemy && spent != null && Movement.PointsLeft(c, s, unitId, spent) == 0) return RefusedNoPoints;
            if (enemy || !SpendsArms(c)) return null; // before Need, so gdd-0.3 never reads a price
            var mvp = c.RulesAt(s.Date).Mvp!;
            var need = Need(c, mvp, u);
            return s.Arms < need ? string.Format(CultureInfo.InvariantCulture, RefusedArms, need, s.Arms) : null;
        }

        /// <summary>R-ENEMY-001: gives the enemy AI's military unit a standing attack on (q, r) for resolver step 2, replacing
        /// its order. Refused, state untouched, with <see cref="Check"/>'s reason. The player's attacks are fought at once by
        /// <see cref="Strike"/> and never stand.</summary>
        internal static string? Give(Content c, GameState s, int unitId, int? q, int? r, List<Cause> why, bool enemy)
        {
            var refused = Check(c, s, unitId, q, r, enemy);
            if (refused != null) return refused;
            var u = s.Units[unitId]; var target = Hex(q!.Value, r!.Value);
            s.Units[unitId] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, Attack, target, u.HomeCity, u.Full, u.CombatXp, u.Records);
            var line = UnitLines.Line(WhyKeys.AttackOrdered, $"Unit {unitId} will attack hex {target}", new[] { u }, target);
            // #2534: the enemy's attack order names itself for the turn report's enemy-orders row, as an engagement's does (#1297).
            // UnitLines.Line's system is always "map" (UnitLines.cs); name it as a literal so the Why-screen scan sees it.
            why.Add(enemy
                ? new Cause("map", line.Target, line.Delta, line.Message, enemyOrder: Attack, enemyAttackers: new[] { unitId },
                    key: line.Key, units: line.Units, args: line.Args)
                : line);
            return null;
        }

        /// <summary>R-COMBAT-001 (owner, 23 October 2026, "Instant, like Civ"): the player's unit attacks (q, r) at once:
        /// refused, the state untouched, with <see cref="Check"/>'s reason; else it pays its Arms (R-COMBAT-004; not under gdd-0.3), loses its
        /// order and the rest of its movement points, and fights one engagement alone (OQ-1), drawing once.</summary>
        internal static string? Strike(Content c, GameState s, int unitId, int? q, int? r, Dictionary<int, int> spent,
                                       Dictionary<int, AttackRecord> attacked, List<Cause> why)
        {
            var refused = Check(c, s, unitId, q, r, spent: spent);
            if (refused != null) return refused;
            var mvp = c.RulesAt(s.Date).Mvp!;
            var u = s.Units[unitId];
            if (SpendsArms(c)) s.Arms -= Need(c, mvp, u);
            var attacker = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, "", "", u.HomeCity, u.Full, u.CombatXp, u.Records);
            s.Units[unitId] = attacker;
            if (u.Order == Orders.Fortify)
                why.Add(UnitLines.Line(WhyKeys.FortifyLost,
                    $"Unit {unitId} left hex {u.OrderTarget} and is no longer fortified", new[] { u }, u.OrderTarget));
            spent[unitId] = Movement.Points(c, attacker);
            var defenders = Defenders(s, attacker, q!.Value, r!.Value);
            var target = defenders.Where(e => Prisoners.FrontOf.ContainsKey(e.Side)).OrderBy(e => e.Id).FirstOrDefault();
            attacked[unitId] = new AttackRecord(q.Value, r.Value, target?.Id,
                target == null ? null : Prisoners.FrontOf[target.Side]);
            Engage(c, s, mvp, new List<Unit> { attacker }, defenders, q.Value, r.Value, why);
            return null;
        }

        /// <summary>The player attack preview (spec section 4.1; Q-UI-1): the ratio, in percent and rounded down, of unit
        /// <paramref name="unitId"/>'s strength alone, at its combat factor, against the enemy units there after fortify and
        /// terrain, and the combat_table row it falls in. Null when (q, r) is out of reach, holds no enemy unit, or the unit is
        /// unknown or not military. The unit card shows it with <see cref="Outcomes"/> (#754).</summary>
        public static (int RatioPercent, int Row)? Preview(Content c, GameState s, int unitId, int q, int r)
        {
            if (!s.Units.TryGetValue(unitId, out var u) || !Military(u) || !InReach(c, u, q, r)) return null;
            var defenders = Defenders(s, u, q, r);
            if (defenders.Count == 0) return null;
            var attackers = new List<Unit> { u };
            var mvp = c.RulesAt(s.Date).Mvp!;
            var ratio = Ratio(c, mvp, attackers, defenders, q, r);
            return (ratio, Row(mvp, ratio));
        }

        /// <summary>R-ENEMY-003: the enemy AI's attack preview. Unlike the player's <see cref="Preview"/>, it counts the
        /// unit plus every other unit on its team that already has a standing attack on this hex and can still reach it, as
        /// resolver step 2 groups them into the same engagement (the preview before #1454).</summary>
        internal static (int RatioPercent, int Row)? EnemyPreview(Content c, GameState s, int unitId, int q, int r)
        {
            if (!s.Units.TryGetValue(unitId, out var u) || !Military(u) || Player(u) || !InReach(c, u, q, r)) return null;
            var defenders = Defenders(s, u, q, r);
            if (defenders.Count == 0) return null;
            var target = Hex(q, r);
            var attackers = new List<Unit> { u };
            attackers.AddRange(s.Units.Values
                .Where(x => x.Id != unitId && x.Order == Attack && x.OrderTarget == target &&
                    Player(x) == Player(u) && Military(x) && InReach(c, x, q, r))
                .OrderBy(x => x.Id));
            var mvp = c.RulesAt(s.Date).Mvp!;
            var ratio = Ratio(c, mvp, attackers, defenders, q, r);
            return (ratio, Row(mvp, ratio));
        }

        /// <summary>The outcome bands of combat_table row <paramref name="row"/> (Q-UI-1: the card shows them beside Preview's
        /// ratio): the row's faces with the same outcome taken together, in the order each first appears, each with how many
        /// faces of <c>Of</c> give it, the people the attackers and the defenders lose (population units times
        /// mvp.people_per_unit, as the engagement's report counts them) and whether the defenders retreat. When <paramref name="unitId"/>
        /// names an artillery unit its attackers lose nothing (R-COMBAT-007, as <c>Engage</c> counts it: #2040). When it also
        /// names the hex (<paramref name="q"/>, <paramref name="r"/>) and enemy units stand there, each face's losses are the
        /// ones <see cref="Take"/> can make (#2553): the attacker's at most its strength, the defenders' at most their summed
        /// strength, and no retreat when the defenders are all lost; faces equal after that share a band.</summary>
        public static IReadOnlyList<(int Faces, int Of, int AttackersLose, int DefendersLose, bool Retreat)> Outcomes(Content c, GameState s, int row, int? unitId = null, int? q = null, int? r = null)
        {
            PopulationLedger.RefuseUnlessHistorical(s);   // #1725 PR 7 (#1706): on a Historical ledger it reads the units' strength, as Fight does
            var mvp = c.RulesAt(s.Date).Mvp!;
            var t = mvp.CombatTable[row];
            var attacker = unitId is int id && s.Units.TryGetValue(id, out var u) ? u : null;
            var guns = attacker != null && Guns(c, attacker);
            // Fight's pools: the attackers that take losses (not the guns) and the defenders on the hex. Uncapped without a hex.
            var defenders = attacker != null && q is int dq && r is int dr ? Defenders(s, attacker, dq, dr) : new List<Unit>();
            long attackPool = guns ? 0 : defenders.Count > 0 ? attacker!.Strength : long.MaxValue;
            long defencePool = defenders.Count > 0 ? defenders.Sum(x => (long)x.Strength) : long.MaxValue;
            var bands = new List<(int Faces, int Of, int AttackersLose, int DefendersLose, bool Retreat)>();
            for (int i = 0; i < t.AttackerLoss.Count; i++)
            {
                int attackersLost = Taken(attackPool, t.AttackerLoss[i]), defendersLost = Taken(defencePool, t.DefenderLoss[i]);
                var face = (attackersLost * mvp.PeoplePerUnit, defendersLost * mvp.PeoplePerUnit, t.DefenderRetreats[i] == 1 && defendersLost < defencePool);
                var k = bands.FindIndex(b => (b.AttackersLose, b.DefendersLose, b.Retreat) == face);
                if (k >= 0) bands[k] = (bands[k].Faces + 1, bands[k].Of, bands[k].AttackersLose, bands[k].DefendersLose, bands[k].Retreat);
                else bands.Add((1, t.AttackerLoss.Count, face.Item1, face.Item2, face.Item3));
            }
            return bands;
        }

        /// <summary>R-COMBAT-002: the attackers' summed strength over the defenders' summed strength, each unit's strength times
        /// its type's combat factor (R-COMBAT-007, R-COMBAT-008) and each defender's also times its order's defence percent
        /// (Orders.DefencePercent) and its hex's biome percent, in whole percent rounded down. Integer arithmetic only, so it
        /// is the same on every runtime.</summary>
        static int Ratio(Content c, MvpRules mvp, List<Unit> attackers, List<Unit> defenders, int q, int r)
        {
            long attack = attackers.Sum(x => x.Strength * Factor(c, x));   // in 1/100 of a strength unit
            if (Gdd03Military.Applies(c))
            {
                var biomeBonus = Gdd03Military.Defence(c, c.HexAt(q, r)!.Biome);
                var fortBonus = c.HasPermanentFort(q, r) ? Gdd03Military.Scalar(c, "military.fort_bonus", false) : 0;
                long total = defenders.Sum(x => (long)x.Strength * Factor(c, x) *
                    (100L + biomeBonus + fortBonus + (x.Order == Orders.Fortify && x.OrderTarget == Hex(x.Q, x.R)
                        ? Gdd03Military.Scalar(c, "military.fortify_bonus", false) : 0)));
                return total == 0 ? int.MaxValue : (int)Math.Min(int.MaxValue, attack * 10_000 / total);
            }
            var terrain = mvp.CombatTerrainPercent[c.HexAt(q, r)!.Biome];   // a unit stands on land, and the loader requires every land biome
            long defence = defenders.Sum(x => x.Strength * Factor(c, x) * Orders.DefencePercent(mvp, x) * terrain);   // in 1/1,000,000 of a strength unit
            return defence == 0 ? int.MaxValue : (int)Math.Min(int.MaxValue, attack * 1_000_000 / defence);   // 0: no real unit has no strength
        }

        /// <summary>The last combat_table row whose min_ratio_percent the ratio reaches (the first row starts at 0).</summary>
        static int Row(MvpRules mvp, int ratio)
        {
            var row = 0;
            for (int i = 1; i < mvp.CombatTable.Count; i++) if (ratio >= mvp.CombatTable[i].MinRatioPercent) row = i;
            return row;
        }

        /// <summary>Resolver step 2 (R-COMBAT-002 to R-COMBAT-006): enemy units keep standing attacks. In ascending attacker id, each unit with an attack order not
        /// yet in an engagement this turn leads one, with every unit of its team attacking the same hex. A unit no longer next
        /// to its hex (artillery: within its range), or whose hex holds no enemy unit, ends its attack. Enemy units pay
        /// nothing (Q-ENEMY-4: no supply). Enemy artillery joins after the other attackers and only beside one of them: alone it
        /// holds its fire, pays nothing and keeps its order (R-COMBAT-007). An engagement with an attacker left draws once.
        /// Afterwards every attack whose hex is now empty ends.</summary>
        public static void Resolve(Content c, GameState s, List<Cause> why)
        {
            PopulationLedger.RefuseUnlessHistorical(s);   // #1725 PR 7 (#1706): on a Historical ledger each own loss is a record (Fight)
            var mvp = c.RulesAt(s.Date).Mvp!;
            var done = new HashSet<int>();
            foreach (var id in s.Units.Keys.ToList())   // Units is a SortedList: ascending id
            {
                if (done.Contains(id) || !s.Units.TryGetValue(id, out var lead) || lead.Order != Attack) continue;
                var (q, r) = Target(lead);
                // The guns last (a stable sort keeps id order on each side of it): they fire only beside another attacker.
                var group = s.Units.Values.Where(x => !done.Contains(x.Id) && x.Order == Attack && x.OrderTarget == lead.OrderTarget && Player(x) == Player(lead))
                    .OrderBy(x => Guns(c, x) ? 1 : 0).ToList();
                var defenders = Defenders(s, lead, q, r);
                var attackers = new List<Unit>();
                foreach (var x in group)
                {
                    done.Add(x.Id);
                    if (defenders.Count == 0 || !InReach(c, x, q, r))
                    {
                        End(s, x, WhyKeys.AttackEnded,
                            $"Unit {x.Id}'s attack on hex {x.OrderTarget} ends: no enemy unit is there", why, x.OrderTarget);
                        continue;
                    }
                    if (Guns(c, x) && attackers.Count == 0)
                    {
                        why.Add(UnitLines.Line(WhyKeys.HoldsFire,
                            $"Unit {x.Id} holds its fire: no attack on hex {x.OrderTarget} to support", new[] { x }, x.OrderTarget));
                        continue;
                    }
                    attackers.Add(x);
                }
                if (attackers.Count > 0) Engage(c, s, mvp, attackers, defenders, q, r, why);
            }
            foreach (var u in s.Units.Values.ToList())
                if (u.Order == Attack)
                {
                    var (q, r) = Target(u);
                    if (Defenders(s, u, q, r).Count == 0 || !InReach(c, u, q, r))
                        End(s, u, WhyKeys.AttackEnded,
                            $"Unit {u.Id}'s attack on hex {u.OrderTarget} ends: no enemy unit is there", why, u.OrderTarget);
                }
        }

        static (int Q, int R) Target(Unit u)
        {
            var parts = u.OrderTarget.Split(',');
            return (int.Parse(parts[0], CultureInfo.InvariantCulture), int.Parse(parts[1], CultureInfo.InvariantCulture));
        }

        static void End(GameState s, Unit u, string key, string line, List<Cause> why, params string[] args)
        {
            s.Units[u.Id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, "", "", u.HomeCity, u.Full, u.CombatXp, u.Records);
            why.Add(UnitLines.Line(key, line, new[] { u }, args));
        }

        /// <summary>One engagement (<see cref="Fight"/>), then, under exact gdd-0.3, its survivors' combat experience
        /// (R-UNIT-011) and its fronts' quiet-turn counts broken (R-WAR-005). Every engagement, the player's instant attack and
        /// step 2's alike, runs through here.</summary>
        static void Engage(Content c, GameState s, MvpRules mvp, List<Unit> attackers, List<Unit> defenders, int q, int r, List<Cause> why)
        {
            Fight(c, s, mvp, attackers, defenders, q, r, why);
            if (Gdd03Military.Applies(c)) Experience(c, s, attackers, defenders, why);
            Armistice.Engaged(c, s, attackers.Concat(defenders));   // R-WAR-005: gdd-0.3 only
        }

        /// <summary>R-UNIT-011 (owner, 1 November 2026, #1668 Q14 to Q16): after the engagement's one draw, its losses, retreats
        /// and surrenders, each attacker and defender still in the state, in ascending id, gains military.combat_xp_gain combat
        /// experience, up to military.combat_xp_full. A destroyed or surrendered unit has left the state and gains nothing; a
        /// veteran_soldier is a veteran already and gains none. A recruit that reaches the full count becomes a veteran_soldier
        /// (R-UNIT-004's promotion), so it fought this engagement as a recruit. Draws nothing.</summary>
        static void Experience(Content c, GameState s, List<Unit> attackers, List<Unit> defenders, List<Cause> why)
        {
            var gain = Gdd03Military.Scalar(c, "military.combat_xp_gain");
            var full = Gdd03Military.Scalar(c, "military.combat_xp_full");
            foreach (var id in attackers.Concat(defenders).Select(x => x.Id).OrderBy(x => x))
            {
                if (!s.Units.TryGetValue(id, out var u) || u.Type == Statecraft.Sim.Military.VeteranSoldier) continue;
                var xp = (int)Math.Min(full, (long)u.CombatXp + gain);
                var gained = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, xp, u.Records);
                s.Units[id] = xp == full && Statecraft.Sim.Military.Promotes(u) ? Statecraft.Sim.Military.Promote(gained, why) : gained;
            }
        }

        /// <summary>R-COMBAT-002, R-COMBAT-003, R-COMBAT-006: one engagement. The face is the one draw; its row's losses fall on
        /// each side one population unit at a time on its strongest unit (a tie on the lower id), a unit at 0 leaves the state,
        /// and when the row says so each defender left retreats one hex, in id order, or surrenders when it has nowhere to go.
        /// The attackers stay where they are (no advance, Q-COMBAT-3).</summary>
        static void Fight(Content c, GameState s, MvpRules mvp, List<Unit> attackers, List<Unit> defenders, int q, int r, List<Cause> why)
        {
            var ratio = Ratio(c, mvp, attackers, defenders, q, r);
            var row = mvp.CombatTable[Row(mvp, ratio)];
            var rng = new Rng(s.RngState);
            var face = (int)(rng.NextDouble() * row.AttackerLoss.Count);   // DrawsPerEngagement
            s.RngState = rng.State;
            var target = Hex(q, r);
            var ppu = mvp.PeoplePerUnit;
            var removed = new List<Unit>();
            var source = FormattableString.Invariant($"combat/{s.Date:yyyy-MM-dd}/{target}");   // "Date + battle hex (Recommended)"
            // R-COMBAT-007: the guns fire from behind the line, so the attackers' losses fall on the others only.
            var attackersLost = Take(c, s, attackers.Where(x => !Guns(c, x)).Select(x => x.Id).ToList(), row.AttackerLoss[face], removed, source);
            var defendersLost = Take(c, s, defenders.Select(x => x.Id).ToList(), row.DefenderLoss[face], removed, source);
            var named = attackers.OrderBy(x => x.Id).Concat(defenders.OrderBy(x => x.Id)).Select(x => new UnitRef(x)).ToList();
            why.Add(new Cause("map", target, 0, FormattableString.Invariant(
                $"The attack on hex {target} ({Ids(attackers)} against {Ids(defenders)}, strength ratio {ratio}%): the attackers lost {attackersLost * ppu:N0} people and the defenders lost {defendersLost * ppu:N0} people"),
                // #1297: the turn report names an enemy attack on every turn it engages, a standing one too (R-ENEMY-003)
                enemyOrder: Player(attackers[0]) ? "" : Attack,
                enemyAttackers: Player(attackers[0]) ? null : attackers.Select(x => x.Id).OrderBy(x => x).ToList(),
                key: WhyKeys.Engagement, units: named, args: new[] { target, ratio.ToString(CultureInfo.InvariantCulture),
                    (attackersLost * ppu).ToString(CultureInfo.InvariantCulture), (defendersLost * ppu).ToString(CultureInfo.InvariantCulture),
                    attackers.Count.ToString(CultureInfo.InvariantCulture) }));
            foreach (var u in removed)
                why.Add(UnitLines.Line(WhyKeys.Destroyed, $"Unit {u.Id} was destroyed", new[] { u }));
            if (row.DefenderRetreats[face] != 1) return;
            foreach (var d in defenders)
            {
                if (!s.Units.TryGetValue(d.Id, out var u)) continue;
                if (Retreat(c, s, mvp, u) is (int, int) to)
                {
                    s.Units[u.Id] = new Unit(u.Id, u.Type, to.Item1, to.Item2, u.Service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);
                    var hex = Hex(to.Item1, to.Item2);
                    why.Add(UnitLines.Line(WhyKeys.Retreated, $"Unit {u.Id} retreated to hex {hex}", new[] { u }, hex));
                }
                else
                {
                    // The only way a unit is captured (impact plan section 4.3 item 1; R-POW-001). Its captor is the
                    // engagement's lowest-id attacker (not attackers[0]: the guns are listed last, R-COMBAT-007), whose
                    // side holds the player's soldiers (R-POW-005). Take runs before the unit is removed (#1710). On a
                    // Historical ledger game it may refuse, before it writes anything: InvalidOperationException for a held
                    // count that disagrees with the Captured records, and ArgumentException from PopulationLedger.Capture
                    // for an unbound captor or a record that is not an active soldier (a synthetic or Open ledger is
                    // NotSupportedException). A trained formation and a strength its records do not number are not refused
                    // (owner, 9 November 2026: "Yes, in #1706 (Recommended)" and "Go ahead on strength (Recommended)"):
                    // Take captures the records on the formation's target, at most its strength of them, the lowest ids
                    // first, and SoldiersHeld grows by that number. A formation's leftover records, beyond its strength,
                    // leave service as Send home's do (owner, 9 November 2026: "Sent home (Recommended)"; R-UNIT-005,
                    // Demobilization.RecordsHome), in the capture's own ledger commit. After the surrender line come Send
                    // home's own lines, in its order: the people sent home ("Yes, reuse Send home's (Recommended)"), then,
                    // only when Arms go back, the Arms line. On a ledger the surrender line states the records captured in
                    // people, not the strength (owner, 9 November 2026: "Records captured (Recommended)"); Take's Held is
                    // the strength without one, so the aggregate line is unchanged. This engagement's draw and losses, and
                    // any earlier write to s (an earlier engagement, or the Strike's own), stay on s. In the game s is
                    // always a clone: Strike's caller (Simulation.cs:268) and Resolve's (TurnResolver.cs:20) run inside
                    // Simulation.Step on its clone (Simulation.cs:51; Preview and DelegatedTo clone too), so the whole
                    // command's or turn's result is discarded and the caller's state is unchanged. Today Step refuses a
                    // ledger game (Simulation.cs:48). On a Historical ledger the losses above already removed this
                    // formation's lost records (LoseRecord, #1706: "Prisoners #1710 first (Recommended)"), so for a
                    // formation whose records matched its strength Take finds the records left numbering its strength.
                    var taken = Prisoners.Take(c, s, u, attackers.OrderBy(x => x.Id).First());
                    s.Units.Remove(u.Id);
                    why.Add(UnitLines.Line(u.Side == Movement.PlayerSide ? WhyKeys.SurrenderedHeld : WhyKeys.SurrenderedPrisoners,   // Prisoners.Take's two cases
                        FormattableString.Invariant($"Unit {u.Id} surrendered with {taken.Held * ppu:N0} people: it had no hex to retreat to. {taken.Text}"),
                        new[] { u }, (taken.Held * ppu).ToString(CultureInfo.InvariantCulture)));
                    if (taken.Home != null)   // leftover records went home: Send home's two lines, in its order ("Yes, reuse Send home's (Recommended)")
                    {
                        why.Add(Demobilization.SentHomeLine(c, s, u, taken.Sent, taken.Home));
                        if (taken.ArmsBack > 0) why.Add(Demobilization.ArmsReturnedLine(c, taken.Home, u.Id, taken.ArmsBack));
                    }
                }
            }
        }

        // Sorted for the text: step 2 puts the guns last (R-COMBAT-007), but the line names the units in id order.
        static string Ids(List<Unit> units) => (units.Count == 1 ? "unit " : "units ") + string.Join(", ", units.Select(x => x.Id).OrderBy(x => x).Select(x => x.ToString(CultureInfo.InvariantCulture)));

        /// <summary>Takes up to <paramref name="loss"/> population units from <paramref name="ids"/>, one at a time from the
        /// strongest unit left (a tie on the lower id; the list is in id order), removing each that reaches 0 (its id is never
        /// reused: NextId is not touched) and adding it to <paramref name="removed"/>. Each one an own formation loses on a
        /// Historical ledger also removes one of its serving records (<see cref="LoseRecord"/>). Returns the units taken.</summary>
        static int Take(Content c, GameState s, List<int> ids, int loss, List<Unit> removed, string source)
        {
            int taken = 0;
            for (; taken < loss; taken++)
            {
                Unit? top = null;
                foreach (var id in ids)
                    if (s.Units.TryGetValue(id, out var x) && (top == null || x.Strength > top.Strength)) top = x;
                if (top == null) break;
                LoseRecord(c, s, top, source);
                if (top.Strength <= 1) { s.Units.Remove(top.Id); removed.Add(top); }
                else s.Units[top.Id] = Lose(top);
            }
            return taken;
        }

        /// <summary>R-COMBAT-003 and R-POP-001 on a Historical ledger (#1706, #1725 PR 7; owner, 8 November 2026, #1725): the
        /// own formation <paramref name="u"/> loses one population unit, so one of its serving soldier records (the active
        /// soldiers on its target, <see cref="Training.FormationTarget"/>: "Yes, after #2964 (Recommended)") leaves the ledger
        /// as a combat loss, with <paramref name="source"/>, combat/date/hex, as its provenance ("Date + battle hex
        /// (Recommended)"). "Lowest id first (Recommended)": the lowest id goes. "No, losses are deaths (Recommended)": nothing
        /// else is written. "Go ahead on strength": the engagement is fought on the unit's strength, and a record goes only
        /// while one is left. Enemy formations are not own population (R-POP-004) and lose none; any other game has no
        /// Historical ledger and writes none. Draws nothing.</summary>
        static void LoseRecord(Content c, GameState s, Unit u, string source)
        {
            if (!s.PopulationLedger.IsHistorical || u.Side != Movement.PlayerSide) return;
            var target = Training.FormationTarget(c, u.Id);
            var lowest = s.PopulationLedger.Units.Where(p => p.Status == PopulationStatus.ActiveSoldier
                && string.Equals(p.Assignment.Target, target, StringComparison.Ordinal)).OrderBy(p => p.Id).FirstOrDefault();
            if (lowest != null) s.PopulationLedger.RegisterCombatLoss(lowest.Id, source);
        }

        /// <summary>What <see cref="Take"/> returns for <paramref name="loss"/> on units of <paramref name="pool"/> summed
        /// strength: it takes one population unit a time until the loss is met or no unit is left, so the smaller of the two.
        /// Outcomes reads it so the card's bands are Fight's (#2553).</summary>
        static int Taken(long pool, int loss) => (int)Math.Min(loss, pool);

        /// <summary>R-COMBAT-003 with R-TRAIN-004: the unit one population unit weaker. A player's unit's first loss stores the
        /// strength it had as its Full, the most replacements refill it to; no rule reads an enemy's, so it stores none.</summary>
        internal static Unit Lose(Unit u) =>
            new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength - 1, u.Order, u.OrderTarget, u.HomeCity,
                u.Full == 0 && u.Side == Movement.PlayerSide ? u.Strength : u.Full, u.CombatXp, u.Records);

        /// <summary>R-COMBAT-003: the first neighbour of the unit's hex, in the fixed order (R-MOVE-002), that is land, holds no
        /// unit of the other team, has room under mvp.stack_limit for the unit's side (R-MOVE-003) and, for the player's unit,
        /// is not an enemy-held locality (R-MOVE-005), and for an enemy unit is not a player's locality (R-ENEMY-001,
        /// #2932); null when there is none.</summary>
        static (int, int)? Retreat(Content c, GameState s, MvpRules mvp, Unit u)
        {
            var noEntry = Movement.NoEntry(c, s, enemy: !Player(u));
            foreach (var (dq, dr) in Movement.Neighbours)
            {
                int q = u.Q + dq, r = u.R + dr;
                if (!(c.HexAt(q, r) is MapHex hex) || !hex.Land || noEntry.Contains((q, r))) continue;
                var here = s.Units.Values.Where(x => x.Q == q && x.R == r).ToList();
                if (here.Any(x => Player(x) != Player(u)) || here.Count(x => x.Side == u.Side) >= Movement.StackLimit(c, s)) continue;
                return (q, r);
            }
            return null;
        }
    }
}