A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
UI: the attack order and its odds on the unit card (GDD Phase 5 PR 15 slice 3, refs #754) (#1277)
Beri929769d554b5
diff --git a/changelog.d/unity-gdd-unit-orders-attack-754.md b/changelog.d/unity-gdd-unit-orders-attack-754.mdnew file mode 100644index 000000000..a0e9fc25b--- /dev/null+++ b/changelog.d/unity-gdd-unit-orders-attack-754.md@@ -0,0 +1,6 @@+- GDD Phase 5 PR 15, slice 3: the unit card's Attack order with its odds (refs #754). In the GDD loop a unit's card shows+ Attack (Q-UI-2's name, "Attack" / "התקפה") only where the sim's new `Combat.Check` takes some hex; where it refuses+ an enemy hex in reach, the card shows the sim's reason. Pressing it lights those hexes, and the card gives each the+ sim's strength ratio and the combat table's outcome bands for it (Q-UI-1; `Combat.Preview`, new `Combat.Outcomes`).+ A click on a lit hex queues the sim's attack, and the card says it comes at End turn. `Combat.Give` now runs+ `Combat.Check` first, so the card and the sim refuse the same attacks for the same reasons.diff --git a/docs/units.md b/docs/units.mdindex 380eb2cf3..4dba39b1a 100644--- a/docs/units.md+++ b/docs/units.md@@ -420,7 +420,14 @@ checks every anchor and logs each spot and its distance.the sim's `Orders.Check` takes the order, and where it does not, the card shows the sim's reason as the sim gives it(in English for now, as the End turn toast does). A press queues the sim's `UnitOrder` through `SimBridge` (one standingorder per unit: Hold replaces a queued Fortify, and either replaces a queued attack) and the card says when it takes- effect. Tests: `UnitOrdersTests`,+ effect. Slice 3 adds Attack (Q-UI-2's "Attack" / "התקפה"): the button shows only where the sim's `Combat.Check` takes+ some unit's hex, and the sim's reasons for the enemy hexes in reach it refuses (no Arms, the attack it already has)+ show as the others do. Pressing it lights those hexes; for each the card gives the units there by name, the sim's+ strength ratio (`Combat.Preview`) and its `combat_table` row's outcome bands (`Combat.Outcomes`: how many faces of the+ draw give each outcome, and the people each side loses), as Q-UI-1 decided. A click on a lit hex queues the sim's+ `UnitOrder(unit, attack, q, r)` through `SimBridge`, and the card says the attack comes at End turn, with that hex's+ odds. `Orders.Give` and `Combat.Give` run `Orders.Check` and `Combat.Check` first, so the card and End turn refuse the+ same orders for the same reasons. Tests: `UnitOrdersTests`,`InfoPanelLayoutTests.TheUnitCardWithItsOrdersFitsEveryWindow`.**The Avia S-199** (`UnitModels.AviaS199`; type `avia-s199-101sqn-1948`):diff --git a/sim/Statecraft.Sim.Tests/CombatTests.cs b/sim/Statecraft.Sim.Tests/CombatTests.csindex a9397895d..91fb8354b 100644--- a/sim/Statecraft.Sim.Tests/CombatTests.cs+++ b/sim/Statecraft.Sim.Tests/CombatTests.cs@@ -58,6 +58,9 @@ public class CombatTests{var c = Load();var s = With(c, Soldier(1, 3, 0, 5), Enemy(2, 2, 0, 3), new Unit(3, "halutz", 3, 1));+ var before = s.Hash();+ Assert.Equal(reason, Combat.Check(c, s, unit, q, r)); // the unit card asks before it offers the target (#754)+ Assert.Equal(before, s.Hash());var refused = Step(c, s, new UnitOrder(unit, Combat.Attack, q, r));Assert.Equal(reason, Assert.Single(refused.Rejected).Reason);Assert.Equal(Step(c, s).State.Hash(), refused.State.Hash());@@ -69,13 +72,75 @@ public class CombatTestsvar c = Load();var s = With(c, Soldier(1, 3, 0, 5), Enemy(2, 2, 0, 3));Assert.Equal("An attack names a hex", Assert.Single(Step(c, s, new UnitOrder(1, Combat.Attack)).Rejected).Reason);+ Assert.Equal("An attack names a hex", Combat.Check(c, s, 1, null, null));Assert.Equal("That order names no hex", Assert.Single(Step(c, s, new UnitOrder(1, Orders.Hold, 2, 0)).Rejected).Reason);s.Arms = 1; // the fixture's attack takes 2Assert.Equal("An attack needs 2 Arms and the stock has 1", Assert.Single(Step(c, s, new UnitOrder(1, Combat.Attack, 2, 0)).Rejected).Reason);+ Assert.Equal("An attack needs 2 Arms and the stock has 1", Combat.Check(c, s, 1, 2, 0));s.Arms = 2;var given = Step(c, s, new UnitOrder(1, Combat.Attack, 2, 0)).State; // resolved the same turnAssert.Equal(0, given.Arms);Assert.Equal("That unit already has that order", Assert.Single(Step(c, given, new UnitOrder(1, Combat.Attack, 2, 0)).Rejected).Reason);+ Assert.Equal("That unit already has that order", Combat.Check(c, given, 1, 2, 0));+ }++ // R-COMBAT-001: Check is null exactly where Give takes the attack (the unit card offers the target, #754), changes+ // nothing, and counts the attacks already standing as Give does (Q-COMBAT-4).+ [Fact]+ public void CheckIsNullForAnAttackGiveTakes()+ {+ var c = Load();+ var s = With(c, Soldier(1, 3, 0, 5), Soldier(3, 1, 1, 5), Enemy(2, 2, 0, 3));+ s.Arms = 2; // the fixture's attack takes 2+ var before = s.Hash();+ Assert.Null(Combat.Check(c, s, 1, 2, 0));+ Assert.Null(Combat.Check(c, s, 3, 2, 0));+ Assert.Equal(before, s.Hash());+ Assert.Empty(Step(c, s, new UnitOrder(1, Combat.Attack, 2, 0)).Rejected);+ s.Units[1] = Attacking(s.Units[1], 2, 0);+ Assert.Equal("An attack needs 2 Arms and the stock has 2, of which 2 go to attacks already ordered", Combat.Check(c, s, 3, 2, 0));+ }++ // R-ENEMY-001: with enemy, Check runs the same checks with the sides swapped and asks for no Arms (Q-ENEMY-4), as Give+ // does for the enemy AI.+ [Fact]+ public void CheckForTheEnemySwapsTheSidesAndAsksNoArms()+ {+ var c = Load();+ var s = With(c, Soldier(1, 3, 0, 5), Enemy(2, 2, 0, 3));+ s.Arms = 0;+ Assert.Null(Combat.Check(c, s, 2, 3, 0, enemy: true));+ Assert.Equal("That unit is not yours", Combat.Check(c, s, 1, 2, 0, enemy: true));+ Assert.Equal("An attack needs 2 Arms and the stock has 0", Combat.Check(c, s, 1, 2, 0));+ }++ // Q-UI-1: the preview's outcome bands are its combat_table row's faces, the same outcomes together, in people. The+ // fixture's two faces agree: below 2:1 both sides lose 1 unit (10 people); from 2:1 the defenders lose 1 and retreat.+ [Fact]+ public void TheOutcomesAreTheRowsFacesInPeople()+ {+ var c = Load();+ var s = With(c);+ Assert.Equal(new[] { (2, 2, 10, 10, false) }, Combat.Outcomes(c, s, 0));+ Assert.Equal(new[] { (2, 2, 0, 10, true) }, Combat.Outcomes(c, s, 1));+ }++ // Q-UI-1: on the real table every row's bands cover its faces exactly once, in the order each outcome first appears, and+ // no two bands are the same outcome.+ [Fact]+ public void TheRealTablesOutcomesCoverEachRowsFaces()+ {+ var s = Simulation.NewGame(Real, 1, Mode.Historical);+ var mvp = Real.RulesAt(s.Date).Mvp!;+ for (int row = 0; row < mvp.CombatTable.Count; row++)+ {+ var t = mvp.CombatTable[row];+ var faces = Enumerable.Range(0, t.AttackerLoss.Count)+ .Select(i => (t.AttackerLoss[i] * mvp.PeoplePerUnit, t.DefenderLoss[i] * mvp.PeoplePerUnit, t.DefenderRetreats[i] == 1)).ToList();+ var bands = Combat.Outcomes(Real, s, row);+ Assert.Equal(faces.Distinct(), bands.Select(b => (b.AttackersLose, b.DefendersLose, b.Retreat)));+ Assert.All(bands, b => Assert.Equal((faces.Count(f => f == (b.AttackersLose, b.DefendersLose, b.Retreat)), faces.Count), (b.Faces, b.Of)));+ }}// Q-COMBAT-4: the Arms are paid at resolution, so a new attack counts the attacks already ordered. With the stock fordiff --git a/sim/Statecraft.Sim/Combat.cs b/sim/Statecraft.Sim/Combat.csindex c6df9383c..427472a37 100644--- a/sim/Statecraft.Sim/Combat.cs+++ b/sim/Statecraft.Sim/Combat.cs@@ -57,13 +57,13 @@ namespace Statecraft.Simstatic 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>R-COMBAT-001: gives the player's military unit a standing attack on the adjacent hex (q, r), replacing its- /// order (a fortify is lost). Refused, state untouched, for an unknown unit, a halutz, an enemy unit, no hex, the attack- /// it already has, a hex not next to it or with no enemy unit, or fewer Arms than one attack takes on top of the- /// player's other attacks already ordered (Q-COMBAT-4). It costs no Attention (D-A6) and resolves in this turn's step 2.- /// With <paramref name="enemy"/> the enemy AI orders its own unit through the same checks, the sides swapped, and pays no- /// Arms (R-ENEMY-001; Q-ENEMY-4).</summary>- internal static string? Give(Content c, GameState s, int unitId, int? q, int? r, List<Cause> why, bool enemy = false)+ /// <summary>R-COMBAT-001's refusals: null when <see cref="Give"/> takes the attack on (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, the attack it already has, a hex not next to it (artillery: beyond+ /// its range) or with no enemy unit, or fewer Arms than one attack takes on top of the player's other attacks already+ /// ordered (Q-COMBAT-4). With <paramref name="enemy"/> the enemy AI orders its own unit through the same checks, the+ /// sides swapped, and pays no Arms (R-ENEMY-001; Q-ENEMY-4).</summary>+ public static string? Check(Content c, GameState s, int unitId, int? q, int? r, bool enemy = false){if (!s.Units.TryGetValue(unitId, out var u)) return "There is no such unit";if (!Military(u)) return "Only a military unit takes that order";@@ -78,7 +78,17 @@ namespace Statecraft.Sim// Arms are paid at resolution, so the stock must also cover the player's other standing attacks, this turn's// included; the unit's own attack, which this order replaces, is not counted.var committed = s.Units.Values.Where(x => x.Id != unitId && x.Order == Attack && Military(x) && Player(x)).Sum(x => Need(c, mvp, x));- if (!enemy && s.Arms < need + committed) return Short(need, s.Arms, committed);+ return !enemy && s.Arms < need + committed ? Short(need, s.Arms, committed) : null;+ }++ /// <summary>R-COMBAT-001: gives the player's military unit a standing attack on the adjacent hex (q, r), replacing its+ /// order (a fortify is lost). Refused, state untouched, with <see cref="Check"/>'s reason. It costs no Attention (D-A6)+ /// and resolves in this turn's step 2. With <paramref name="enemy"/>, the enemy AI's own unit (see Check).</summary>+ internal static string? Give(Content c, GameState s, int unitId, int? q, int? r, List<Cause> why, bool enemy = false)+ {+ 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);why.Add(new Cause("map", unitId.ToString(CultureInfo.InvariantCulture), 0, $"Unit {unitId} will attack hex {target}", enemy ? Attack : ""));return null;@@ -93,7 +103,7 @@ namespace Statecraft.Sim/// it (artillery: from within its range), each 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 the unit's reach or holds no enemy unit, or/// the unit is unknown or no military unit. A gun previewed with no other attacker still gets a ratio, though step 2- /// would have it hold its fire (R-COMBAT-007); the UI that shows it is Phase 5 PR 15.</summary>+ /// would have it hold its fire (R-COMBAT-007); 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;@@ -107,6 +117,25 @@ namespace Statecraft.Simreturn (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.</summary>+ public static IReadOnlyList<(int Faces, int Of, int AttackersLose, int DefendersLose, bool Retreat)> Outcomes(Content c, GameState s, int row)+ {+ var mvp = c.RulesAt(s.Date).Mvp!;+ var t = mvp.CombatTable[row];+ 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 = (t.AttackerLoss[i] * mvp.PeoplePerUnit, t.DefenderLoss[i] * mvp.PeoplePerUnit, t.DefenderRetreats[i] == 1);+ 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 itdiff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex e8d3f4321..6c8eaa67c 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -345,7 +345,9 @@ namespace Statecraft.Game.UIregions: regions, localitiesAt: localitiesAt,townHex: InfoPanelPresenter.TownHex(map.SettlementsFor(inputs.Map.SettlementsYaml), map.Hexes),townNamesHe: map.SettlementsFor(inputs.Map.SettlementsYaml).ToDictionary(s => s.Id, s => s.NameHe),- showReachable: map.ShowReachable));+ showReachable: map.ShowReachable,+ unitName: id => unitLayer.Tokens.Where(p => UnitCard.SimUnit(bridge.Content, bridge.State, p.Token.Unit) == id)+ .Select(p => UnitCard.For(p, bridge.State, text, bridge.Content.IsGdd).Title).FirstOrDefault()));// A smoke session never touches the player's save: no autosave, and no New Game (which deletes the autosave).// Leaving New Game out is safer than handing it a throwaway store: no file is ever deleted, no path has to be// right on every platform, and the scripted run never presses it.@@ -549,8 +551,8 @@ namespace Statecraft.Game.UI/// <summary>A map click: on a unit's hex it selects the unit (the ring and its card; the hex outline is cleared, so/// the unit has the promo's one highlight); a second click on it, or a click anywhere else, shows the hex (so a token- /// never hides the hex's map actions). While the card's Move pick is open (#754), a click on a lit hex queues the move- /// and keeps the unit's card; any other click ends the pick first and then selects as usual.</summary>+ /// never hides the hex's map actions). While the card's Move or Attack pick is open (#754), a click on a lit hex queues+ /// the order and keeps the unit's card; any other click ends the pick first and then selects as usual.</summary>internal static void OnHexClicked(MapScene map, Statecraft.Game.Map.Units.UnitLayer units, InfoPanelPresenter info, int q, int r){if (info.Covered)@@ -560,7 +562,7 @@ namespace Statecraft.Game.UIif (info.Selected is (int sq, int sr) && !info.ShowsUnit) map.Select(sq, sr); else map.ClearSelection();return;}- if (info.PickMoveTarget(q, r)) { map.ClearSelection(); return; } // the unit keeps its ring, the one highlight+ if (info.PickTarget(q, r)) { map.ClearSelection(); return; } // the unit keeps its ring, the one highlightvar id = units.UnitToSelectAt(q, r);units.Select(id);if (id != null) { map.ClearSelection(); info.ShowUnit(); }diff --git a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs b/unity/Assets/Scripts/UI/InfoPanelPresenter.csindex f739c81d3..95282a562 100644--- a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs+++ b/unity/Assets/Scripts/UI/InfoPanelPresenter.cs@@ -13,7 +13,7 @@ namespace Statecraft.Game.UI/// built there, and the two map actions (transit camp, housing project) with the reason when one is not possible/// (MapActions.Check). Tile yields are deliberately not shown (owner decision, M3 rulings 2). A selected unit/// (<see cref="ShowUnit"/>) shows its card instead (<see cref="UnitCard"/>), with a button to the Defence screen (owner- /// ruling, 2026-10-11) and, in the GDD loop, the Move, Fortify and Hold orders (GDD Phase 5 PR 15, #754).</summary>+ /// ruling, 2026-10-11) and, in the GDD loop, the Move, Fortify, Hold and Attack orders (GDD Phase 5 PR 15, #754).</summary>public sealed class InfoPanelPresenter : System.IDisposable{/// <summary>The class of a fact row (Game.uxml): a sign, then the fact's line; hidden while the line is empty.</summary>@@ -25,15 +25,19 @@ namespace Statecraft.Game.UIreadonly List<(VisualElement row, Label line)> rows = new List<(VisualElement, Label)>();readonly VisualElement panel; readonly SimBridge bridge; readonly UiText text;- readonly Button campButton, housingButton, defenceButton, moveButton, fortifyButton, holdButton;- readonly System.Action onCamp, onHousing, onDefence, onMove, onFortify, onHold;+ readonly Button campButton, housingButton, defenceButton, moveButton, fortifyButton, holdButton, attackButton;+ readonly System.Action onCamp, onHousing, onDefence, onMove, onFortify, onHold, onAttack;readonly System.Func<PlacedToken?> selectedUnit;bool unitMode;- /// <summary>Lights the hexes the Move pick offers on the map (none: clears them); null: nothing is drawn.</summary>+ /// <summary>Lights the hexes the Move or Attack pick offers on the map (none: clears them); null: nothing is drawn.</summary>readonly System.Action<IReadOnlyCollection<(int q, int r)>>? showReachable;- /// <summary>While the player picks a Move's hex: the unit, the hexes Movement.Reachable gave (the only ones a click- /// takes), and the session and turn they were read on (a turn or a load ends the pick, as the hexes change).</summary>- (int unit, HashSet<(int q, int r)> hexes, GameSession session, int turn)? pick;+ /// <summary>While the player picks a Move's or an Attack's hex: the unit, the hexes the sim gave (Movement.Reachable's,+ /// or those Combat.Check takes: the only ones a click takes), the session and turn they were read on (a turn or a+ /// load ends the pick, as the hexes change), and whether it is the attack's.</summary>+ (int unit, HashSet<(int q, int r)> hexes, GameSession session, int turn, bool attack)? pick;+ /// <summary>A sim unit's name on screen, for the attack's targets (GameRoot: its token's card title); null, or no+ /// name, gives the hex's coordinates.</summary>+ readonly System.Func<int, string?>? unitName;readonly Label title, subtitle, region, settlements, localitiesLabel, placement, reason;readonly System.Func<int, int, IReadOnlyList<Statecraft.Game.Map.Kits.Localities.Place>>? localitiesAt;readonly UiIcon thumb;@@ -60,12 +64,15 @@ namespace Statecraft.Game.UI/// title, the "Settlements" line and that note (#899), or with the English name where it has none (null: English/// names).</param>/// <param name="showReachable">Lights the hexes a Move can go to while the player picks one, and clears them with none- /// (GameRoot: MapScene.ShowReachable; null: the pick still works, with nothing lit).</param>+ /// (GameRoot: MapScene.ShowReachable; null: the pick still works, with nothing lit). The Attack pick lights its hexes+ /// with it too.</param>+ /// <param name="unitName">A sim unit's name on screen, by id (GameRoot: its token's card title), for the Attack pick's+ /// targets (null: the hex's coordinates).</param>public InfoPanelPresenter(VisualElement root, SimBridge bridge, UiText text, IReadOnlyDictionary<string, string> settlementNames,ScreenNav? nav = null, System.Func<PlacedToken?>? selectedUnit = null, MapRegions? regions = null,System.Func<int, int, IReadOnlyList<Statecraft.Game.Map.Kits.Localities.Place>>? localitiesAt = null,System.Func<string, (int q, int r)>? townHex = null, IReadOnlyDictionary<string, string>? townNamesHe = null,- System.Action<IReadOnlyCollection<(int q, int r)>>? showReachable = null)+ System.Action<IReadOnlyCollection<(int q, int r)>>? showReachable = null, System.Func<int, string?>? unitName = null){panel = root.Q<VisualElement>("info-panel"); this.bridge = bridge; this.text = text;this.settlementNames = settlementNames; this.regions = regions; this.localitiesAt = localitiesAt; this.townHex = townHex;@@ -87,13 +94,18 @@ namespace Statecraft.Game.UIdefenceButton.text = text["unit.defence"];this.showReachable = showReachable;moveButton = panel.Q<Button>("info-move");- onMove = ToggleMovePick;+ onMove = () => TogglePick(attack: false);moveButton.clicked += onMove;moveButton.text = text["unit.order.move"];fortifyButton = panel.Q<Button>("info-fortify"); holdButton = panel.Q<Button>("info-hold");onFortify = () => GiveOrder(Orders.Fortify); onHold = () => GiveOrder(Orders.Hold);fortifyButton.clicked += onFortify; holdButton.clicked += onHold;fortifyButton.text = text["unit.order.fortify"]; holdButton.text = text["unit.order.hold"];+ this.unitName = unitName;+ attackButton = panel.Q<Button>("info-attack");+ onAttack = () => TogglePick(attack: true);+ attackButton.clicked += onAttack;+ attackButton.text = text["unit.order.attack"];bridge.Changed += Render;panel.parent?.RegisterCallback<GeometryChangedEvent>(OnHudGeometry);Render();@@ -102,7 +114,7 @@ namespace Statecraft.Game.UIvoid OnHudGeometry(GeometryChangedEvent e) => panel.EnableInClassList(ShortClass, e.newRect.height < ShortBelowPx);/// <summary>Unsubscribes from the bridge and the buttons (the owner calls this when disabled).</summary>- public void Dispose() { bridge.Changed -= Render; panel.parent?.UnregisterCallback<GeometryChangedEvent>(OnHudGeometry); campButton.clicked -= onCamp; housingButton.clicked -= onHousing; defenceButton.clicked -= onDefence; moveButton.clicked -= onMove; fortifyButton.clicked -= onFortify; holdButton.clicked -= onHold; EndPick(); }+ public void Dispose() { bridge.Changed -= Render; panel.parent?.UnregisterCallback<GeometryChangedEvent>(OnHudGeometry); campButton.clicked -= onCamp; housingButton.clicked -= onHousing; defenceButton.clicked -= onDefence; moveButton.clicked -= onMove; fortifyButton.clicked -= onFortify; holdButton.clicked -= onHold; attackButton.clicked -= onAttack; EndPick(); }/// <summary>Below this window height (logical px; 1366x657 is about 998) the panel gets ShortClass, and the city's own/// hex folds its projects behind their toggle as on a stacked bar (GddHexPanel.ToggleName): there the full list ran into@@ -164,17 +176,57 @@ namespace Statecraft.Game.UIreturn reach.Count == 0 ? null : (id, reach);}- /// <summary>Move's button: starts the pick (the reachable hexes lit), or ends it when pressed again.</summary>- void ToggleMovePick()+ /// <summary>The shown unit's sim id, the hexes its attack can name (each unit's hex the sim's Combat.Check takes: the+ /// sim's answer, nothing reckoned here), and the sim's reasons for the hexes it refuses that Combat.Preview gives odds+ /// for (an enemy in the unit's reach: no Arms for it, or the attack it already has). Null when the unit can take no+ /// order (OrderUnit).</summary>+ (int unit, List<(int q, int r)> hexes, List<string> refused)? AttackTargets(){- if (pick != null) { EndPick(); Render(); return; }- if (!(MoveTargets() is { } moves)) return;- var hexes = moves.hexes.Keys.Select(h => (h.Q, h.R)).ToList();- pick = (moves.unit, new HashSet<(int q, int r)>(hexes), bridge.Session, bridge.State.Turn);- showReachable?.Invoke(hexes);+ if (!(OrderUnit() is int id)) return null;+ var c = bridge.Content; var s = bridge.State;+ var hexes = new List<(int q, int r)>(); var refused = new List<string>();+ foreach (var (q, r) in s.Units.Values.Select(u => (u.Q, u.R)).Distinct())+ {+ var why = Combat.Check(c, s, id, q, r);+ if (why == null) hexes.Add((q, r));+ else if (Combat.Preview(c, s, id, q, r) != null && !refused.Contains(why)) refused.Add(why);+ }+ return (id, hexes, refused);+ }++ /// <summary>Move's or Attack's button: starts its pick (the sim's hexes lit), or ends it when pressed again; a press+ /// of the other ends the open pick and starts its own.</summary>+ void TogglePick(bool attack)+ {+ var again = pick?.attack == attack;+ EndPick();+ (int unit, List<(int q, int r)> hexes)? offer = null;+ if (!again && attack && AttackTargets() is { } a && a.hexes.Count > 0) offer = (a.unit, a.hexes);+ if (!again && !attack && MoveTargets() is { } m) offer = (m.unit, m.hexes.Keys.Select(h => (h.Q, h.R)).ToList());+ if (offer is { } o)+ {+ pick = (o.unit, new HashSet<(int q, int r)>(o.hexes), bridge.Session, bridge.State.Turn, attack);+ showReachable?.Invoke(o.hexes);+ }Render();}+ /// <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+ /// has none. Every number is the sim's, read on the state as it is: attacks queued for this turn and not yet stepped+ /// are not in it (as for Fortify and Hold), so End turn can still refuse one with the sim's reason.</summary>+ string Odds(int unit, int q, int r)+ {+ var c = bridge.Content; var s = bridge.State;+ if (!(Combat.Preview(c, s, unit, q, r) is { } p)) return "";+ // 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).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+ }+/// <summary>The shown unit's sim id, or null when it can take no order: no unit card, no sim unit for it, or the game/// is over (the bridge would refuse every order).</summary>int? OrderUnit()@@ -199,15 +251,16 @@ namespace Statecraft.Game.UIshowReachable?.Invoke(System.Array.Empty<(int q, int r)>());}- /// <summary>A map click while the player picks a Move's hex (GameRoot.OnHexClicked asks first): on a lit hex it queues- /// the sim's Move through the bridge and returns true (the click is taken, the card stays); anywhere else it only ends- /// the pick and returns false, so the click selects as usual. False when no pick is open.</summary>- public bool PickMoveTarget(int q, int r)+ /// <summary>A map click while the player picks a Move's or an Attack's hex (GameRoot.OnHexClicked asks first): on a lit+ /// hex it queues the sim's Move, or its UnitOrder(unit, attack, q, r), through the bridge and returns true (the click is+ /// taken, the card stays); anywhere else it only ends the pick and returns false, so the click selects as usual. False+ /// when no pick is open.</summary>+ public bool PickTarget(int q, int r){if (!(pick is { } p)) return false;EndPick();if (!p.hexes.Contains((q, r))) return false;- bridge.Queue(new Move(p.unit, q, r)); // a refusal is raised by the bridge (Refused)+ bridge.Queue(p.attack ? new UnitOrder(p.unit, Combat.Attack, q, r) : (Command)new Move(p.unit, q, r)); // a refusal is raised by the bridge (Refused)Render(); // the card drops the pick line either way: a refused Queue raises no Changedreturn true;}@@ -351,16 +404,23 @@ namespace Statecraft.Game.UIbutton.style.display = orderUnit != null && why == null ? DisplayStyle.Flex : DisplayStyle.None;if (why != null && own && !refusals.Contains(why)) refusals.Add(why);}+ // Attack (#754): offered where the sim's Combat.Check takes some hex; its refusals in reach show as the others'.+ var attacks = AttackTargets();+ attackButton.style.display = attacks is { } at && at.hexes.Count > 0 ? DisplayStyle.Flex : DisplayStyle.None;+ foreach (var why in attacks?.refused ?? new List<string>()) if (own && !refusals.Contains(why)) refusals.Add(why);panel.EnableInClassList(UnitClass, unit != null);if (unit != null){var card = UnitCard.For(unit.Value, s, text, c.IsGdd);panel.EnableInClassList("info-empty", false);- // The orders' state under the card's lines: the pick asks for a hex; a queued Move, Fortify or Hold waits for End turn.- var order = pick != null ? text["unit.move_pick"]+ // The orders' state under the card's lines: the pick asks for a hex (an attack's with each lit hex's odds, Q-UI-1);+ // a queued Move, Fortify, Hold or Attack waits for End turn (an attack's with its hex's odds).+ var order = pick is { attack: true } ap ? string.Join("\n", new[] { text["unit.attack_pick"] }.Concat(ap.hexes.Select(h => Odds(ap.unit, h.q, h.r))).Where(x => x != ""))+ : pick != null ? text["unit.move_pick"]: moves is { } m && bridge.QueuedLike(new Move(m.unit, 0, 0)) != null ? text["unit.move_queued"] : "";var standing = orderUnit is int su && bridge.QueuedLike(new UnitOrder(su, Orders.Hold)) is UnitOrder given- ? given.Order == Orders.Fortify ? text["unit.fortify_queued"] : given.Order == Orders.Hold ? text["unit.hold_queued"] : "" : "";+ ? given.Order == Orders.Fortify ? text["unit.fortify_queued"] : given.Order == Orders.Hold ? text["unit.hold_queued"]+ : given.Order == Combat.Attack && given.Q is int gq && given.R is int gr ? text["unit.attack_queued"] + "\n" + Odds(su, gq, gr) : "" : "";var lines = new[] { card.Body, order, standing }.Where(x => x != "");title.text = card.Title; subtitle.text = card.Subtitle; settlements.text = string.Join("\n", lines);ShowLocalities("");diff --git a/unity/Assets/Scripts/UI/UnitCard.cs b/unity/Assets/Scripts/UI/UnitCard.csindex 06e8c68b7..359f6a09b 100644--- a/unity/Assets/Scripts/UI/UnitCard.cs+++ b/unity/Assets/Scripts/UI/UnitCard.cs@@ -8,7 +8,7 @@ using Statecraft.Sim;namespace Statecraft.Game.UI{- /// <summary>The info panel's text for a selected unit (its orders so far, Move, Fortify and Hold, are the panel's: InfoPanelPresenter; the panel also links to the Defence screen):+ /// <summary>The info panel's text for a selected unit (its orders so far, Move, Fortify, Hold and Attack, are the panel's: InfoPanelPresenter; the panel also links to the Defence screen):/// its name, number and service; where it stands, and since when only from a sourced start (the anchor's `since`,/// never the game's first day: review I1); its formation and first commander where sourced; the sector in the/// source's words; on Israel's units, the national values its token reflects (legacy loop: the reserve call-up sets andiff --git a/unity/Assets/Tests/EditMode/HebrewValuesTests.cs b/unity/Assets/Tests/EditMode/HebrewValuesTests.csindex 9b869f2c6..424a119ee 100644--- a/unity/Assets/Tests/EditMode/HebrewValuesTests.cs+++ b/unity/Assets/Tests/EditMode/HebrewValuesTests.cs@@ -359,4 +359,38 @@ public class HebrewValuesTestsAssert.Greater(dollar, FontSize / 5, $"the leftmost glyph of the line (its last value, '$-4.2m') is the dollar ({dollar}px tall); the minus sits next to the number");Assert.IsTrue(Found(r.Row(1), r.Row(2)), $"\"15 May 1948\" is drawn as one run, as it is on its own: its words {Show(Words(r.Row(2)))}, the line's {Show(Words(r.Row(1)))}");}++ /// <summary>The attack's odds on the unit card (#754), each line read right to left: the strength line has "133%" at its+ /// left end (the sign on the number's right, not "%133"), and a band line has its faces ("1") at its right end and what+ /// the defenders lose ("1,000") at its left end.</summary>+ [UnityTest]+ public IEnumerator InHebrewTheAttackOddsReadRightToLeft()+ {+ using var r = new Rendered(+ He.Format("unit.attack_odds", "10,10", 133),+ He.Format("unit.attack_band", 1, 6, 0, 1000),+ "133%", "1,000", "1");+ yield return r.Draw();+ Assert.AreEqual(LanguageDirection.RTL, r.Labels[0].languageDirection, r.Labels[0].text);+ Assert.AreEqual(LanguageDirection.RTL, r.Labels[1].languageDirection, r.Labels[1].text);+ List<(int Start, int End)> odds = Words(r.Row(0)), band = Words(r.Row(1));+ Assert.IsTrue(DrawsAt(r.Row(0), 0, r.Row(2)), $"the strength line starts on the left with \"133%\": its words {Show(odds)}, \"133%\" {Show(Words(r.Row(2)))}");+ Assert.IsTrue(DrawsAt(r.Row(1), 0, r.Row(3)), $"the band starts on the left with \"1,000\": its words {Show(band)}, \"1,000\" {Show(Words(r.Row(3)))}");+ Assert.IsTrue(DrawsAt(r.Row(1), band.Count - 1, r.Row(4)), $"the band ends on the right with \"1\": its words {Show(band)}");+ }++ /// <summary>Whether <paramref name="line"/>, from its word <paramref name="first"/> (left to right), draws+ /// <paramref name="part"/>'s words: the same widths and gaps to a pixel, and alike ink (a "%" is a word of its own here).</summary>+ static bool DrawsAt(float[,] line, int first, float[,] part)+ {+ var l = Words(line); var p = Words(part);+ if (first < 0 || first + p.Count > l.Count) return false;+ for (int k = 0; k < p.Count; k++)+ {+ int lw = l[first + k].End - l[first + k].Start, pw = p[k].End - p[k].Start;+ if (Math.Abs(lw - pw) > 1 || !Same(line, l[first + k].Start, part, p[k].Start, pw + 1)) return false;+ if (k > 0 && Math.Abs((l[first + k].Start - l[first + k - 1].End) - (p[k].Start - p[k - 1].End)) > 1) return false;+ }+ return true;+ }}diff --git a/unity/Assets/Tests/EditMode/InfoPanelLayoutTests.cs b/unity/Assets/Tests/EditMode/InfoPanelLayoutTests.csindex e60b06cec..e071b3c7c 100644--- a/unity/Assets/Tests/EditMode/InfoPanelLayoutTests.cs+++ b/unity/Assets/Tests/EditMode/InfoPanelLayoutTests.cs@@ -39,7 +39,7 @@ public class InfoPanelLayoutTests/// card and the info panel (with the region lines) on the session given.</summary>static IEnumerator Rendered(int w, int h, GameSession g, System.Action<VisualElement, InfoPanelPresenter> act, System.Action<VisualElement> check,UiText? text = null, bool hebrew = false, System.Action<VisualElement>? settled = null,- System.Func<Statecraft.Game.Map.Units.PlacedToken?>? unit = null)+ System.Func<Statecraft.Game.Map.Units.PlacedToken?>? unit = null, System.Func<int, string?>? unitName = null){var t = text ?? Text;var rt = new RenderTexture(w, h, 0);@@ -57,7 +57,7 @@ public class InfoPanelLayoutTestsvar bridge = new SimBridge(g, t);var hud = new HudPresenter(root, bridge, t);var card = new EventCardPresenter(root, bridge, t, null);- var info = new InfoPanelPresenter(root, bridge, t, Names(), regions: Regions(), selectedUnit: unit);+ var info = new InfoPanelPresenter(root, bridge, t, Names(), regions: Regions(), selectedUnit: unit, unitName: unitName);try{act(root, info);@@ -196,9 +196,10 @@ public class InfoPanelLayoutTestsAssert.IsEmpty(problems, string.Join("\n", problems));}- /// <summary>GDD Phase 5 PR 15, slices 1 and 2 (#754): Golani's card at the start with its Move, Fortify and Hold buttons,- /// as it is, picking a Move's hex (the pick line under the card's lines), with Fortify queued (its line), and on the turn- /// after a Hold (Hold refused, with the sim's reason), at every window size in English and Hebrew: the panel lies in the+ /// <summary>GDD Phase 5 PR 15, slices 1 to 3 (#754): Golani's card at the start with its Move, Fortify and Hold buttons,+ /// as it is, picking a Move's hex (the pick line under the card's lines), with Fortify queued (its line), on the turn+ /// after a Hold (Hold refused, with the sim's reason), and picking an Attack's hex (an enemy put in its reach if none is) (the+ /// pick line, the enemy's name, strength ratio and outcome bands), at every window size in English and Hebrew: the panel lies in the/// window, and every shown label and button lies inside the panel with its text fitting its box.</summary>[UnityTest]public IEnumerator TheUnitCardWithItsOrdersFitsEveryWindow()@@ -208,11 +209,16 @@ public class InfoPanelLayoutTestsvar problems = new List<string>();foreach (var hebrew in new[] { false, true })foreach (var (w, h) in Windows)- foreach (var state in new[] { "", "info-move", "info-fortify", "holding" })+ foreach (var state in new[] { "", "info-move", "info-fortify", "holding", "info-attack" }){var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);var token = Statecraft.Game.Map.Units.UnitRoster.FromState(units, C, g.State, null, (row, a, q, r) => a).Single(x => x.Unit.Id == "golani");if (state == "holding") g.Step(new Command[] { new UnitOrder(UnitCard.SimUnit(C, g.State, token.Unit)!.Value, Orders.Hold) });+ if (state == "info-attack") UnitOrdersTests.EnemyInGolanisReach(g.State);+ var t = hebrew ? he : Text;+ var names = Statecraft.Game.Map.Units.UnitRoster.FromState(units, C, g.State, null, (row, a, q, r) => a)+ .Where(x => UnitCard.SimUnit(C, g.State, x.Unit) != null)+ .ToDictionary(x => UnitCard.SimUnit(C, g.State, x.Unit)!.Value, x => hebrew && x.Unit.NameHe != "" ? x.Unit.NameHe : x.Unit.Name);Statecraft.Game.Map.Units.PlacedToken? golani = new Statecraft.Game.Map.Units.PlacedToken(token, new Statecraft.Game.Map.Units.AnchorSpot(0, 0, 0, 0, false));var pressed = state.StartsWith("info-");var at = $"{(hebrew ? "he" : "en")} {w}x{h} {state}";@@ -222,7 +228,7 @@ public class InfoPanelLayoutTestsvar move = root.Q<Button>("info-move");if (!Shown(move)) { problems.Add($"{at}: precondition: the Move button shows"); return; }var lines = root.Q<Label>("info-settlements").text;- foreach (var (key, when) in new[] { ("unit.move_pick", "info-move"), ("unit.fortify_queued", "info-fortify") })+ foreach (var (key, when) in new[] { ("unit.move_pick", "info-move"), ("unit.fortify_queued", "info-fortify"), ("unit.attack_pick", "info-attack") })if (lines.Contains((hebrew ? he : Text)[key]) != (state == when)) problems.Add($"{at}: {key} shows: {state != when}");if (Shown(root.Q<Button>("info-hold")) == (state == "holding")) problems.Add($"{at}: precondition: Hold shows only while it is not held");if (!Inside(panel.worldBound, window)) problems.Add($"{at}: the panel {panel.worldBound} leaves the window {window}");@@ -231,13 +237,13 @@ public class InfoPanelLayoutTestsif (!Inside(l.worldBound, panel.worldBound)) problems.Add($"{at}: '{l.text}' {l.worldBound} leaves the panel {panel.worldBound}");if (!TextFits(l)) problems.Add($"{at}: '{l.text}' does not fit its box {l.contentRect} ({l.name})");}- }, hebrew ? he : Text, hebrew, root =>+ }, t, hebrew, root =>{if (!pressed) return;var hide = root.Q<Button>("event-hide");if (hide != null && Shown(hide)) UiTestKit.Press(hide); // the turn's decision card disables the panel under itUiTestKit.Press(root.Q<Button>(state));- }, () => golani);+ }, () => golani, id => names.TryGetValue(id, out var n) ? n : null);}Assert.IsEmpty(problems, string.Join("\n", problems));}diff --git a/unity/Assets/Tests/EditMode/UnitOrdersTests.cs b/unity/Assets/Tests/EditMode/UnitOrdersTests.csindex 46b194f1a..4be550db3 100644--- a/unity/Assets/Tests/EditMode/UnitOrdersTests.cs+++ b/unity/Assets/Tests/EditMode/UnitOrdersTests.cs@@ -16,7 +16,9 @@ using UnityEngine.UIElements;/// <summary>GDD Phase 5 PR 15 (#754): the unit card's orders. Slice 1, Move: the card offers Move only when the sim's/// Movement.Reachable has a hex for the unit; pressing it lights exactly those hexes on the map, a click on one queues the/// sim's Move through SimBridge, and a click anywhere else ends the pick and selects as before. Slice 2, Fortify and Hold:-/// each shows only where the sim's Orders.Check takes it, else the sim's reason, and a press queues the sim's UnitOrder.</summary>+/// each shows only where the sim's Orders.Check takes it, else the sim's reason, and a press queues the sim's UnitOrder.+/// Slice 3, Attack: shown only where the sim's Combat.Check takes some hex; pressing it lights those hexes with+/// Combat.Preview's strength ratio and Combat.Outcomes' bands for each (Q-UI-1), and a click on one queues the attack.</summary>public class UnitOrdersTests{static readonly Content C = ContentLoader.Load(Paths.Content);@@ -234,6 +236,144 @@ public class UnitOrdersTestsinfo.Dispose();}+ /// <summary>Gives the state the Arms for an attack and, when Golani has no enemy in reach (the sim's Combat.Check takes no+ /// hex), puts the first enemy sim unit on the first free land hex next to it; returns Golani's sim id.</summary>+ internal static int EnemyInGolanisReach(GameState s)+ {+ var id = C.StartingForces.ToList().FindIndex(f => f.Row == "golani");+ s.Arms = 1000;+ if (Targets(s, id).Count > 0) return id;+ var g = s.Units[id];+ var enemy = s.Units.Values.First(u => u.Side != "" && u.Side != Movement.PlayerSide);+ var at = new[] { (1, 0), (1, -1), (0, -1), (-1, 0), (-1, 1), (0, 1) }.Select(d => (q: g.Q + d.Item1, r: g.R + d.Item2))+ .First(h => C.HexAt(h.q, h.r)?.Land == true && !s.Units.Values.Any(u => (u.Q, u.R) == h));+ s.Units[enemy.Id] = new Unit(enemy.Id, enemy.Type, at.q, at.r, enemy.Service, enemy.Side, enemy.Strength);+ return id;+ }++ /// <summary>The hexes the card offers for an attack: every unit's hex the sim's Combat.Check takes.</summary>+ static List<(int q, int r)> Targets(GameState s, int unit) =>+ s.Units.Values.Select(u => (u.Q, u.R)).Distinct().Where(h => Combat.Check(C, s, unit, h.Item1, h.Item2) == null).ToList();++ /// <summary>Slice 3 (#754): for every unit with a sim unit, Israel's and the enemy's, the card shows Attack only where+ /// the sim's Combat.Check takes some hex, and on Israel's units the sim's reason for each hex in reach it refuses (an+ /// enemy's card gives none, as for Fortify and Hold). With no Arms, Golani+ /// (an enemy in its reach) has no Attack and shows the sim's reason; once the game is over no card has one.</summary>+ [Test]+ public void TheCardOffersAttackOnlyWhereTheSimTakesAHex()+ {+ using var ui = new UiTestKit();+ var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);+ var bridge = new SimBridge(g, Text);+ var id = EnemyInGolanisReach(g.State);+ var tokens = UnitRoster.FromState(Units, C, g.State, _ => true, (row, a, q, r) => a).Where(t => UnitCard.SimUnit(C, g.State, t.Unit) != null).ToList();+ // An enemy with a card next to Golani, so an enemy's card has a hex in reach the sim refuses ("not yours").+ var foe = UnitCard.SimUnit(C, g.State, tokens.First(t => t.Unit.Side != UnitData.Israel).Unit)!.Value;+ var gq = g.State.Units[id].Q; var gr = g.State.Units[id].R;+ var next = new[] { (1, 0), (1, -1), (0, -1), (-1, 0), (-1, 1), (0, 1) }.Select(d => (q: gq + d.Item1, r: gr + d.Item2))+ .First(h => C.HexAt(h.q, h.r)?.Land == true && !g.State.Units.Values.Any(u => (u.Q, u.R) == h));+ var f = g.State.Units[foe];+ g.State.Units[foe] = new Unit(f.Id, f.Type, next.q, next.r, f.Service, f.Side, f.Strength);+ Assert.IsNotNull(Combat.Preview(C, g.State, foe, gq, gr), "precondition: Golani is in an enemy card's reach");+ PlacedToken? shown = null;+ var info = new InfoPanelPresenter(ui.Root, bridge, Text, new Dictionary<string, string>(), selectedUnit: () => shown);+ var attack = ui.Q<Button>("info-attack");+ var offered = new HashSet<bool>();+ foreach (var token in tokens)+ {+ shown = new PlacedToken(token, new AnchorSpot(0, 0, 0, 0, false));+ info.ShowUnit();+ var u = UnitCard.SimUnit(C, g.State, token.Unit)!.Value;+ var has = Targets(g.State, u).Count > 0;+ offered.Add(has);+ Assert.AreEqual(has ? DisplayStyle.Flex : DisplayStyle.None, attack.style.display.value, token.Unit.Id);+ foreach (var h in g.State.Units.Values.Select(x => (x.Q, x.R)).Distinct().Where(h => Combat.Preview(C, g.State, u, h.Item1, h.Item2) != null))+ if (Combat.Check(C, g.State, u, h.Item1, h.Item2) is string why)+ if (token.Unit.Side == UnitData.Israel) StringAssert.Contains(why, ui.Q<Label>("info-reason").text, $"{token.Unit.Id}: the sim's reason");+ else StringAssert.DoesNotContain(why, ui.Q<Label>("info-reason").text, $"{token.Unit.Id}: no reason on an enemy's card");+ }+ CollectionAssert.AreEquivalent(new[] { true, false }, offered, "precondition: some cards offer Attack and some do not");+ shown = new PlacedToken(tokens.Single(t => t.Unit.Id == "golani"), new AnchorSpot(0, 0, 0, 0, false));+ info.ShowUnit();+ Assert.AreEqual("Attack", attack.text, "Q-UI-2's approved name");+ var at = Targets(g.State, id)[0];+ g.State.Arms = 0;+ info.ShowUnit();+ var short_ = Combat.Check(C, g.State, id, at.q, at.r);+ Assert.IsNotNull(short_, "precondition: no Arms");+ Assert.AreEqual(DisplayStyle.None, attack.style.display.value, "no Arms for an attack");+ StringAssert.Contains(short_, ui.Q<Label>("info-reason").text, "the sim's reason");+ g.State.Arms = 1000;+ g.State.GameOver = GameOverCodes.MvpEnded;+ info.ShowUnit();+ Assert.AreEqual(DisplayStyle.None, attack.style.display.value, "no orders once the game is over");+ info.Dispose();+ }++ /// <summary>Attack lights exactly the hexes Combat.Check takes, and the card gives each its units' names with+ /// Combat.Preview's strength ratio and Combat.Outcomes' bands for its row (Q-UI-1). A click on an unlit hex queues+ /// nothing; a click on a lit one queues UnitOrder(unit, attack, q, r) through SimBridge and the card says the attack+ /// waits for End turn, with that hex's odds; the sim takes the queued attack at End turn.</summary>+ [Test]+ public void AttackShowsEachTargetsOddsAndAClickOnOneQueuesTheAttack()+ {+ var map = BuildMap();+ using var ui = new UiTestKit();+ try+ {+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ var id = EnemyInGolanisReach(bridge.State);+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);+ layer.Show(bridge.Content, bridge.State);+ var lit = new List<IReadOnlyCollection<(int q, int r)>>();+ var towns = SettlementPlacer.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", SettlementPlacer.DefaultFileName))).ToDictionary(t => t.Id, t => t.Name);+ var info = new InfoPanelPresenter(ui.Root, bridge, Text, towns,+ selectedUnit: () => layer.Selected is string sel ? layer.Tokens.First(p => p.Token.Unit.Id == sel) : (PlacedToken?)null,+ showReachable: hexes => { lit.Add(hexes.ToList()); map.ShowReachable(hexes); },+ unitName: u => "Unit-" + u);+ var golani = layer.Tokens.Single(p => p.Token.Unit.Id == "golani");+ var attack = ui.Q<Button>("info-attack");+ string Lines() => ui.Q<Label>("info-settlements").text;+ string 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",+ 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+ }+ GameRoot.OnHexClicked(map, layer, info, golani.Q, golani.R);+ UiTestKit.Press(attack);+ var targets = Targets(bridge.State, id);+ Assert.IsNotEmpty(targets, "precondition");+ CollectionAssert.AreEquivalent(targets, lit.Last(), "the lit hexes are the ones Combat.Check takes");+ StringAssert.Contains(Text["unit.attack_pick"], Lines());+ foreach (var (q, r) in targets) StringAssert.Contains(Odds(q, r), Lines());+ StringAssert.Contains("strength ratio", Lines());+ // An unlit hex: nothing queued, the pick ends.+ var tlv = C.SettlementHexes.Single(t => t.Id == "tel_aviv");+ Assert.IsFalse(targets.Contains((tlv.Q, tlv.R)), "precondition");+ GameRoot.OnHexClicked(map, layer, info, tlv.Q, tlv.R);+ Assert.IsEmpty(lit.Last());+ Assert.IsEmpty(bridge.Queued);+ // A lit hex: the sim's attack is queued and the card keeps the unit, with the order's line and its odds.+ GameRoot.OnHexClicked(map, layer, info, golani.Q, golani.R);+ UiTestKit.Press(attack);+ var at = targets[0];+ GameRoot.OnHexClicked(map, layer, info, at.q, at.r);+ var queued = bridge.Queued.OfType<UnitOrder>().Single();+ Assert.AreEqual((id, Combat.Attack, (int?)at.q, (int?)at.r), (queued.Unit, queued.Order, queued.Q, queued.R));+ Assert.IsEmpty(lit.Last());+ Assert.IsTrue(info.ShowsUnit);+ Assert.IsFalse(Lines().Contains(Text["unit.attack_pick"]), Lines());+ StringAssert.Contains(Text["unit.attack_queued"], Lines());+ StringAssert.Contains(Odds(at.q, at.r), Lines());+ Assert.IsEmpty(bridge.EndTurn().Rejected, "the sim takes the attack the card queued");+ info.Dispose();+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }+/// <summary>The overlay draws one band per hex given (two rings of MapBuilder.RingVertices each) and hides when given/// none, or only hexes off the map.</summary>[Test]diff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxmlindex 0ffe46ac1..2a4eb40bc 100644--- a/unity/Assets/UI/Game.uxml+++ b/unity/Assets/UI/Game.uxml@@ -154,6 +154,8 @@<!-- Fortify and Hold (#754): each shown only when the sim's Orders.Check takes it; else its reason shows. --><ui:Button name="info-fortify" /><ui:Button name="info-hold" />+ <!-- Attack (#754): shown only when the sim's Combat.Check takes some hex; the pick shows each hex's odds. -->+ <ui:Button name="info-attack" /></ui:VisualElement><ui:Label name="info-reason" class="reason" /><!-- The hex's city projects (GddHexPanel, #1122): here, not in the GDD column, which a city's own hex fills. -->diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yamlindex 92930dd53..2a6837f32 100644--- a/unity/Assets/UI/strings.en.yaml+++ b/unity/Assets/UI/strings.en.yaml@@ -428,6 +428,15 @@ unit.order.fortify: "Fortify"unit.order.hold: "Hold"unit.fortify_queued: "Fortify ordered: the unit is fortified from the end of the turn"unit.hold_queued: "Hold ordered: the unit holds its hex when you end the turn"+# Attack (#754): the name is Q-UI-2's, approved by the owner (#375). The odds are Q-UI-1's: Combat.Preview's strength ratio+# ({0} the defenders' names, or the hex's coordinates; {1} the percent), then each of Combat.Outcomes' bands ({0} of {1} faces; {2} and {3} people lost).+unit.order.attack: "Attack"+unit.attack_pick: "Choose a lit hex to attack"+# {1}'s format carries the %, as in Hebrew (the two files' format items must match), where it keeps the sign inside UiText.Format's marks.+unit.attack_odds: "{0}: strength ratio {1:0'%'}"+unit.attack_band: "{0} in {1}: you lose {2:N0} people, they lose {3:N0}"+unit.attack_band_retreat: "{0} in {1}: you lose {2:N0} people, they lose {3:N0} and retreat"+unit.attack_queued: "Attack ordered: the unit attacks when you end the turn"newgame.confirm: "Press New game again to abandon this game and start over."newgame.delete_failed: "The old saved game could not be removed; it will be replaced after your next turn."save.unreadable: "Your saved game could not be loaded ({0}). A new game has started."diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yamlindex f303924be..c8fe5a9e3 100644--- a/unity/Assets/UI/strings.he.yaml+++ b/unity/Assets/UI/strings.he.yaml@@ -458,6 +458,19 @@ unit.order.hold: "החזקה"unit.fortify_queued: "ניתנה פקודת ביצור: היחידה תהיה מבוצרת מסוף התור"# Approved by Beri, a native speaker, on #1269 (21 Oct 2026). For the native reviewer (#564)unit.hold_queued: "ניתנה פקודת החזקה: היחידה תחזיק במשושה שלה בסיום התור"+# Attack (#754): the name is Q-UI-2's, approved by the owner (#375).+unit.order.attack: "התקפה"+# Approved by Beri, a native speaker, on #1277 (21 Oct 2026). For the native reviewer (#564)+unit.attack_pick: "בחרו משושה מואר להתקפה"+# Approved by Beri, a native speaker, on #1277 (21 Oct 2026). For the native reviewer (#564)+# The % is in {1}'s format, inside the left-to-right marks UiText.Format puts round the value: a bare % after them is drawn on the number's left (#754).+unit.attack_odds: "{0}: יחס כוחות {1:0'%'}"+# Approved by Beri, a native speaker, on #1277 (21 Oct 2026). For the native reviewer (#564)+unit.attack_band: "{0} מתוך {1}: אתם מאבדים {2:N0} איש, הם מאבדים {3:N0}"+# Approved by Beri, a native speaker, on #1277 (21 Oct 2026). For the native reviewer (#564)+unit.attack_band_retreat: "{0} מתוך {1}: אתם מאבדים {2:N0} איש, הם מאבדים {3:N0} ונסוגים"+# Approved by Beri, a native speaker, on #1277 (21 Oct 2026). For the native reviewer (#564)+unit.attack_queued: "ניתנה פקודת התקפה: היחידה תתקוף בסיום התור"newgame.confirm: "יש ללחוץ שוב על משחק חדש כדי לעזוב את המשחק הזה ולהתחיל מחדש."newgame.delete_failed: "לא ניתן היה להסיר את השמירה הקודמת; היא תוחלף אחרי התור הבא."save.unreadable: "לא ניתן היה לטעון את המשחק השמור ({0}). משחק חדש התחיל."