A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Combat preview: cap each outcome's losses at the units' strength (#2563)
Eyal Golanc1b4f2d3cc50
diff --git a/changelog.d/2553-combat-preview-cap.md b/changelog.d/2553-combat-preview-cap.mdnew file mode 100644index 000000000..561062cd1--- /dev/null+++ b/changelog.d/2553-combat-preview-cap.md@@ -0,0 +1,6 @@+### Fixed++- The unit card's attack preview no longer shows losses a unit cannot suffer: each outcome's losses now stop at the+ attacking unit's remaining strength and at the defenders' combined strength, as the attack itself does, and an outcome+ that wipes out the defenders no longer says they retreat. Outcomes that become the same after this are shown together+ (Fixes #2553).diff --git a/sim/Statecraft.Sim.Tests/CombatTests.cs b/sim/Statecraft.Sim.Tests/CombatTests.csindex 46d405885..dec0cef1e 100644--- a/sim/Statecraft.Sim.Tests/CombatTests.cs+++ b/sim/Statecraft.Sim.Tests/CombatTests.cs@@ -285,6 +285,77 @@ public class CombatTestsAssert.Equal(new[] { (2, 2, 0, 10, true) }, Combat.Outcomes(c, s, 1));}+ /// <summary>#2553: a five-face table whose losses outrun a weak unit's strength, so the caps show: the row's faces lose+ /// 2, 1, 0, 0 and 0 attackers and 0, 0, 3, 2 and 1 defenders, the last three with a retreat. Both rows alike, so the+ /// ratio does not matter.</summary>+ static Content LoadDeepTable()+ {+ const string row = "attacker_loss: [2, 1, 0, 0, 0], defender_loss: [0, 0, 3, 2, 1], defender_retreats: [0, 0, 1, 1, 1] }";+ var files = Fixture.Gdd(new Dictionary<string, string>+ {+ ["unit_types.yaml"] = Types, ["map/hexes.json"] = MovementTests.Board(), ["corridors.yaml"] = "corridors: []\n"+ });+ files["rules.yaml"] = files["rules.yaml"]+ .Replace("{ min_ratio_percent: 0, attacker_loss: [1, 1], defender_loss: [1, 1], defender_retreats: [0, 0] }", "{ min_ratio_percent: 0, " + row)+ .Replace("{ min_ratio_percent: 200, attacker_loss: [0, 0], defender_loss: [1, 1], defender_retreats: [1, 1] }", "{ min_ratio_percent: 200, " + row);+ return ContentLoader.Load(Fixture.Write(files));+ }++ /// <summary>The state for one #2553 engagement: unit 1 (a <paramref name="type"/>) of <paramref name="attacker"/> strength+ /// in reach of hex (3, 1), which holds enemy units of the <paramref name="defenders"/> strengths (ids 2, 3, ...).</summary>+ static GameState Engagement(Content c, string type, int attacker, int[] defenders)+ {+ var units = new List<Unit> { new Unit(1, type, type == "gun" ? 1 : 2, 1, side: "israel", strength: attacker) };+ for (int i = 0; i < defenders.Length; i++) units.Add(Enemy(2 + i, 3, 1, defenders[i]));+ return With(c, units.ToArray());+ }++ // #2553 (R-COMBAT-003, R-COMBAT-007): the card's bands are what Strike does. For each face of the row, Strike is fought on a+ // fresh state whose RNG draws that face; its report's losses and whether any defender retreated or surrendered, taken+ // together the way Outcomes takes them, are the preview's bands. A damaged attacker loses at most its strength, weak+ // defenders at most theirs (pooled over the hex), a wiped-out hex has no retreat, and faces equal after the cap share a band.+ [Theory]+ [InlineData("soldier", 1, new[] { 2 })] // damaged attacker, weak defender+ [InlineData("soldier", 1, new[] { 1, 1 })] // two weak defenders: the losses pool over the hex+ [InlineData("soldier", 5, new[] { 5 })] // nobody capped: the row as it is+ [InlineData("soldier", 3, new[] { 1 })] // one defender of 1: every face with a defender loss wipes it out+ [InlineData("gun", 1, new[] { 2 })] // R-COMBAT-007: the guns lose nothing+ public void TheOutcomesAreWhatStrikeDoesFaceByFace(string type, int attacker, int[] defenders)+ {+ var c = LoadDeepTable();+ var ppu = c.RulesAt(With(c).Date).Mvp!.PeoplePerUnit;+ var p = Combat.Preview(c, Engagement(c, type, attacker, defenders), 1, 3, 1)!.Value;+ var faces = c.RulesAt(With(c).Date).Mvp!.CombatTable[p.Row].AttackerLoss.Count;+ var real = new List<(int A, int D, bool Retreat)>();+ for (int face = 0; face < faces; face++)+ {+ var s = Engagement(c, type, attacker, defenders);+ ulong seed = 0;+ while ((int)(new Rng(seed).NextDouble() * faces) != face) seed++;+ s.RngState = seed;+ var why = new List<Cause>();+ Assert.Null(Combat.Strike(c, s, 1, 3, 1, new Dictionary<int, int>(), new Dictionary<int, (int Q, int R)>(), why));+ var fight = why.Single(w => w.Key == WhyKeys.Engagement);+ real.Add((int.Parse(fight.Args[2]), int.Parse(fight.Args[3]),+ why.Any(w => w.Key == WhyKeys.Retreated || w.Key == WhyKeys.SurrenderedPrisoners || w.Key == WhyKeys.SurrenderedHeld)));+ }+ var expected = real.Distinct().Select(o => (real.Count(x => x == o), faces, o.A, o.D, o.Retreat)).ToList();+ var bands = Combat.Outcomes(c, Engagement(c, type, attacker, defenders), p.Row, 1, 3, 1);+ Assert.Equal(expected, bands);+ Assert.All(bands, b => Assert.True(b.AttackersLose <= (type == "gun" ? 0 : attacker * ppu) && b.DefendersLose <= defenders.Sum() * ppu));+ }++ // #2553: without the hex (or with one holding no enemy) the bands are the row's, uncapped, as before.+ [Fact]+ public void WithoutAHexTheOutcomesAreTheRowsUncapped()+ {+ var c = LoadDeepTable();+ var s = Engagement(c, "soldier", 1, new[] { 2 });+ var row = new[] { (1, 5, 20, 0, false), (1, 5, 10, 0, false), (1, 5, 0, 30, true), (1, 5, 0, 20, true), (1, 5, 0, 10, true) };+ Assert.Equal(row, Combat.Outcomes(c, s, 0, 1));+ Assert.Equal(row, Combat.Outcomes(c, s, 0, 1, 0, 0)); // no enemy on (0, 0)+ }+// R-COMBAT-007 (#2040): the guns fire from behind the line, so a strike by an artillery unit costs it nothing and its// bands say 0 attackers lose; an infantry unit's bands are the row's as before.[Fact]diff --git a/sim/Statecraft.Sim/Combat.cs b/sim/Statecraft.Sim/Combat.csindex 7e7d6f591..779c0d97a 100644--- a/sim/Statecraft.Sim/Combat.cs+++ b/sim/Statecraft.Sim/Combat.cs@@ -172,17 +172,26 @@ namespace Statecraft.Sim/// 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).</summary>- public static IReadOnlyList<(int Faces, int Of, int AttackersLose, int DefendersLose, bool Retreat)> Outcomes(Content c, GameState s, int row, int? unitId = null)+ /// 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.RefuseAggregate(s);var mvp = c.RulesAt(s.Date).Mvp!;var t = mvp.CombatTable[row];- var guns = unitId is int id && s.Units.TryGetValue(id, out var u) && Guns(c, u);+ 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++){- var face = ((guns ? 0 : t.AttackerLoss[i]) * mvp.PeoplePerUnit, t.DefenderLoss[i] * mvp.PeoplePerUnit, t.DefenderRetreats[i] == 1);+ 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));@@ -381,6 +390,11 @@ namespace Statecraft.Simreturn taken;}+ /// <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) =>diff --git a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs b/unity/Assets/Scripts/UI/InfoPanelPresenter.csindex 44fbc2499..fbaea0142 100644--- a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs+++ b/unity/Assets/Scripts/UI/InfoPanelPresenter.cs@@ -363,7 +363,7 @@ namespace Statecraft.Game.UI}/// <summary>Q-UI-1's preview of the shown unit's attack on (q, r), for the card: the defenders' names and the sim's- /// strength ratio (Combat.Preview), then its combat_table row's outcome bands (Combat.Outcomes); empty where Preview+ /// strength ratio (Combat.Preview), then its combat_table row's outcome bands (Combat.Outcomes, capped at what the units can lose: #2553); empty where Preview/// has none. Every number is the sim's, read on the state after the turn's committed orders.</summary>string Odds(int unit, int q, int r){@@ -372,7 +372,7 @@ namespace Statecraft.Game.UI// The enemy units there (Combat's defenders: a side, not Israel's; Check has made sure there is one).var names = s.Units.Values.Where(u => u.Q == q && u.R == r && u.Side != "" && u.Side != Movement.PlayerSide).Select(u => unitName?.Invoke(u.Id)).Where(n => !string.IsNullOrEmpty(n)).ToList();var who = names.Count > 0 ? string.Join(", ", names) : string.Format(CultureInfo.InvariantCulture, "{0},{1}", q, r);- var bands = Combat.Outcomes(c, s, p.Row, unit).Select(b => text.Format(b.Retreat ? "unit.attack_band_retreat" : "unit.attack_band",+ var bands = Combat.Outcomes(c, s, p.Row, unit, q, r).Select(b => text.Format(b.Retreat ? "unit.attack_band_retreat" : "unit.attack_band",b.Faces, b.Of, b.AttackersLose, b.DefendersLose));return text.Format("unit.attack_odds", who, p.RatioPercent) + "\n" + string.Join("\n", bands); // one band a line}diff --git a/unity/Assets/Tests/EditMode/UnitOrdersTests.cs b/unity/Assets/Tests/EditMode/UnitOrdersTests.csindex e6973c2de..971311697 100644--- a/unity/Assets/Tests/EditMode/UnitOrdersTests.cs+++ b/unity/Assets/Tests/EditMode/UnitOrdersTests.cs@@ -586,7 +586,7 @@ public class UnitOrdersTestsstring Odds(int q, int r){var p = Combat.Preview(C, bridge.State, id, q, r)!.Value;- var bands = Combat.Outcomes(C, bridge.State, p.Row).Select(b => Text.Format(b.Retreat ? "unit.attack_band_retreat" : "unit.attack_band",+ var bands = Combat.Outcomes(C, bridge.State, p.Row, id, q, r).Select(b => Text.Format(b.Retreat ? "unit.attack_band_retreat" : "unit.attack_band",b.Faces, b.Of, b.AttackersLose, b.DefendersLose));var names = string.Join(", ", bridge.State.Units.Values.Where(u => (u.Q, u.R) == (q, r)).Where(u => u.Side != "" && u.Side != Movement.PlayerSide).Select(u => "Unit-" + u.Id));return Text.Format("unit.attack_odds", names, p.RatioPercent) + "\n" + string.Join("\n", bands); // one band a line