A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Units: attacking figures fire when a combat resolves (supersedes #2078) (#2177)
Eyal Golan4467504b7940
diff --git a/changelog.d/1867-attack-presentation.md b/changelog.d/1867-attack-presentation.mdnew file mode 100644index 000000000..202217998--- /dev/null+++ b/changelog.d/1867-attack-presentation.md@@ -0,0 +1,9 @@+### Added++- Up close, an attacking unit's figures play their fire animation once when a combat resolves: at once for your attack+ order, and at End Turn for the turn's new attacks. Supporting gun units fire with the attackers; the defenders do+ not, and an attack you ordered earlier in the turn does not play again at End Turn. Only figures that have a fire+ animation play it: the Israeli young recruit, veteran fighter and Palmach scout, the Arab Legion soldier and the+ irregular. The Syrian, Iraqi, Egyptian and Lebanese infantry have none yet, so their attacks show no animation.+ Designed by Tal Heuberger (#2078, #1867), using Tal Heuberger's own fire animations; the models and animations are+ unchanged.diff --git a/sim/Statecraft.Sim.Tests/GameSessionTurnTests.cs b/sim/Statecraft.Sim.Tests/GameSessionTurnTests.csindex 7303c46c5..0f939360d 100644--- a/sim/Statecraft.Sim.Tests/GameSessionTurnTests.cs+++ b/sim/Statecraft.Sim.Tests/GameSessionTurnTests.cs@@ -35,6 +35,25 @@ public class GameSessionTurnTestsAssert.Throws<ArgumentException>(() => session.Commit(new UnitOrder(0, Demobilization.SendHome))); // waits for End turn}+ // R-TURN-004: End turn runs the committed orders first, as the open turn showed them, so the step's first causes are+ // the open turn's own, in order. The game plays a combat once when it resolves and skips that prefix at End turn+ // (SimBridge.CombatResolved, #1867): a cause added before the committed orders would replay or hide one.+ [Fact]+ public void EndTurnBeginsWithTheOpenTurnsCausesInOrder()+ {+ var session = Fresh();+ var enemy = session.State.Units[9];+ Assert.NotEqual(Movement.PlayerSide, enemy.Side);+ Assert.Null(session.Commit(new UnitOrder(5, Combat.Attack, enemy.Q, enemy.R))); // unit 5 stands next to unit 9+ Assert.Null(session.Commit(new Move(6, enemy.Q - 2, enemy.R))); // and unit 6 steps up beside it+ var open = session.Now.Why.ToList();+ Assert.Contains(open, x => x.Key == WhyKeys.Engagement);+ var ended = session.EndTurn(new Command[] { new BuyArms(1) });+ Assert.True(ended.Why.Count > open.Count, "the turn adds causes of its own");+ Assert.Equal(open.Select(x => (x.Key, x.Target, x.Message)), ended.Why.Take(open.Count).Select(x => (x.Key, x.Target, x.Message)));+ Assert.Contains(ended.Why.Skip(open.Count), x => x.Key == WhyKeys.Engagement && x.EnemyOrder == Combat.Attack);+ }+// R-TURN-004: deferred orders run after the committed ones, whatever order they were given in.[Fact]public void DeferredOrdersRunAfterCommittedOnes()diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex c520b7388..e44ee84ec 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -424,6 +424,7 @@ namespace Statecraft.Game.UIbridge.Changed += showUnits;owned.Add(new Undo(() => bridge.Changed -= showUnits));showUnits();+ owned.Add(new UnitAttackPresenter(bridge, unitLayer.PlayAttack)); // after showUnits: the map is redrawn firstDiagLog.BootPhase("units layer built");// #1878: the turn report is up, the hexes the turn attacked show the under-attack look; closing it clears them.var underAttack = new Statecraft.Game.Map.UnderAttackLayer(map);diff --git a/unity/Assets/Scripts/UI/SimBridge.cs b/unity/Assets/Scripts/UI/SimBridge.csindex 0475314d7..4d050e77b 100644--- a/unity/Assets/Scripts/UI/SimBridge.cs+++ b/unity/Assets/Scripts/UI/SimBridge.cs@@ -47,6 +47,10 @@ namespace Statecraft.Game.UIpublic event Action<IReadOnlyList<Rejection>>? TurnEnded;/// <summary>Raised after a move or unit order is committed, with the Why lines it added (an attack's result).</summary>public event Action<IReadOnlyList<Cause>>? Committed;+ /// <summary>The engagements the player has just seen resolve, raised after <see cref="Changed"/> has redrawn the map+ /// (UnitAttackPresenter plays them, #1867): an attack order's at once, and at End Turn only the turn's new ones, not+ /// the open turn's attack orders, which the turn runs again first. Never on a load or a refused turn.</summary>+ public event Action<IReadOnlyList<Cause>>? CombatResolved;/// <summary>Raised when Queue refuses an order, with the player-facing reason.</summary>public event Action<string>? Refused;/// <summary>A validated order was refused specifically for Attention; presentation-only advice signal.</summary>@@ -291,6 +295,8 @@ namespace Statecraft.Game.UIstring? Refuse(string reason) { reason = ReasonText(text, reason, Content, TownNamesHe); Refused?.Invoke(reason); return reason; }+ static IReadOnlyList<Cause> Engagements(IEnumerable<Cause> why) => why.Where(x => x.Key == WhyKeys.Engagement).ToList();+static void Notify(Action? handlers){if (handlers == null) return;@@ -323,7 +329,9 @@ namespace Statecraft.Game.UIvar refused = Session.Commit(c);if (refused != null) return Refuse(refused);Notify(Changed);- Notify(Committed, Session.Now.Why.Skip(before).ToList());+ var added = Session.Now.Why.Skip(before).ToList();+ Notify(Committed, added);+ Notify(CombatResolved, Engagements(added));return null;}if (c is AllocateBudget ab) c = new AllocateBudget(new Dictionary<string, double>(ab.Shares)); // a snapshot: later edits to the caller's dictionary must not change the order@@ -353,6 +361,9 @@ namespace Statecraft.Game.UIpublic StepResult EndTurn(){StepResult r;+ // The turn runs the open turn's orders first, as the open turn did (Simulation.Step and Preview share RunOrders),+ // so its first causes are the open turn's, already played when each order was given (#1867).+ int replayed = Session.Now.Why.Count;var batch = Session.Committed.Concat(deferred).ToList();var date = TurnStart.Date;try { r = step(Session, deferred.ToList()); } // a snapshot: the queue is cleared below@@ -372,6 +383,7 @@ namespace Statecraft.Game.UILastBatch = batch; LastBatchDate = date;deferred.Clear(); skipped.Clear();Notify(Changed);+ Notify(CombatResolved, Engagements(r.Why.Skip(replayed)));Notify(TurnEnded, r.Rejected);return r;}diff --git a/unity/Assets/Scripts/UI/UnitAttackPresenter.cs b/unity/Assets/Scripts/UI/UnitAttackPresenter.csnew file mode 100644index 000000000..6ceb9b52f--- /dev/null+++ b/unity/Assets/Scripts/UI/UnitAttackPresenter.cs@@ -0,0 +1,44 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Globalization;+using Statecraft.Sim;++namespace Statecraft.Game.UI+{+ /// <summary>Plays each fresh engagement's attackers' fire take on the map (#1867; design by Tal Heuberger, #2078): the+ /// attacking units' figures, supporting guns included, never the defenders'. Presentation only. A unit whose token cannot+ /// play now (destroyed, hidden, far, or no fire take) is skipped and nothing is kept to play later. GameRoot owns it.</summary>+ public sealed class UnitAttackPresenter : IDisposable+ {+ readonly SimBridge bridge;+ readonly Func<int, bool> play;++ /// <param name="play">Plays a sim unit's attack (UnitLayer.PlayAttack); false when its token cannot.</param>+ public UnitAttackPresenter(SimBridge bridge, Func<int, bool> play)+ {+ this.bridge = bridge ?? throw new ArgumentNullException(nameof(bridge));+ this.play = play ?? throw new ArgumentNullException(nameof(play));+ bridge.CombatResolved += Resolved;+ }++ void Resolved(IReadOnlyList<Cause> engagements)+ {+ foreach (var engagement in engagements)+ foreach (int id in Attackers(engagement)) play(id);+ }++ /// <summary>An engagement's attackers, from its structured line (Combat.Engage): the units are the attackers by id,+ /// supporting guns included, then the defenders, and the fifth argument counts the attackers. Never the report's+ /// text. None for another line or a malformed count.</summary>+ internal static IEnumerable<int> Attackers(Cause engagement)+ {+ if (engagement.Key != WhyKeys.Engagement || engagement.Args.Count < 5+ || !int.TryParse(engagement.Args[4], NumberStyles.None, CultureInfo.InvariantCulture, out int count)+ || count < 1 || count > engagement.Units.Count) yield break;+ for (int i = 0; i < count; i++) yield return engagement.Units[i].Id;+ }++ public void Dispose() => bridge.CombatResolved -= Resolved;+ }+}diff --git a/unity/Assets/Scripts/UI/UnitAttackPresenter.cs.meta b/unity/Assets/Scripts/UI/UnitAttackPresenter.cs.metanew file mode 100644index 000000000..7919c9b02--- /dev/null+++ b/unity/Assets/Scripts/UI/UnitAttackPresenter.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 56bfded9a1b004861a478257b023b887\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/GameSceneTests.cs b/unity/Assets/Tests/EditMode/GameSceneTests.csindex 4fd249d40..e44a6b835 100644--- a/unity/Assets/Tests/EditMode/GameSceneTests.cs+++ b/unity/Assets/Tests/EditMode/GameSceneTests.cs@@ -52,6 +52,21 @@ public class GameSceneTestsstatic VisualElement Ui => Object.FindFirstObjectByType<UIDocument>().rootVisualElement;+ /// <summary>#1867 (design by Tal Heuberger, #2078): the game plays each resolved combat on its units' tokens, through one+ /// UnitAttackPresenter that GameRoot makes over its bridge and its unit layer.</summary>+ [Test]+ public void TheGamePlaysResolvedCombatOnItsUnitLayer()+ {+ var root = Boot();+ var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;+ var resolved = (Delegate?)typeof(SimBridge).GetField(nameof(SimBridge.CombatResolved), flags)!.GetValue(root.Bridge);+ var presenters = (resolved?.GetInvocationList() ?? Array.Empty<Delegate>()).Select(d => d.Target).OfType<UnitAttackPresenter>().ToList();+ Assert.AreEqual(1, presenters.Count, "one presenter listens to the game's combat");+ var play = (Func<int, bool>)typeof(UnitAttackPresenter).GetField("play", flags)!.GetValue(presenters[0])!;+ Assert.AreSame(root.Units, play.Target, "it plays on the game's unit layer");+ Assert.AreEqual(nameof(Statecraft.Game.Map.Units.UnitLayer.PlayAttack), play.Method.Name);+ }+[Test]public void MapUnityIsTheOnlyBuildSceneAndIsFullyWired(){diff --git a/unity/Assets/Tests/EditMode/UnitAttackPresenterTests.cs b/unity/Assets/Tests/EditMode/UnitAttackPresenterTests.csnew file mode 100644index 000000000..609ea4a8f--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnitAttackPresenterTests.cs@@ -0,0 +1,170 @@+using System;+using System.Collections.Generic;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.UI;+using Statecraft.Sim;+using UnityEditor;+using UnityEngine;+using UnityEngine.TestTools;++/// <summary>#1867 (design by Tal Heuberger, #2078): each engagement the player sees resolve plays its attackers' fire+/// take once: an attack order at once, a fresh End Turn engagement after the map is redrawn; never the defenders, never+/// an engagement End Turn only replays, never history on a load.</summary>+public class UnitAttackPresenterTests+{+ static readonly Content C = ContentLoader.Load(Paths.Content);+ static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);+ static GameSession NewSession() => GameSession.New(C, GoldenRun.Seed, Mode.Historical);++ static Cause Line(string key, string attackers) => new Cause("map", "9,9", 0, "Report text is never read",+ key: key, units: new[] { new UnitRef(new Unit(71, "infantry", 0, 0)), new UnitRef(new Unit(72, "guns", 0, 0)),+ new UnitRef(new Unit(73, "infantry", 0, 0)) }, args: new[] { "9,9", "150", "0", "0", attackers });++ /// <summary>The first player unit's attack on an enemy next to it at the start of the game.</summary>+ static UnitOrder AttackNextTo(GameSession session, out int attacker)+ {+ foreach (var u in session.Now.State.Units.Values.Where(u => u.Side == Movement.PlayerSide))+ {+ var enemy = session.Now.State.Units.Values.FirstOrDefault(x => x.Side != Movement.PlayerSide && x.Side != ""+ && MapActions.Distance(x.Q, x.R, u.Q, u.R) == 1);+ if (enemy == null) continue;+ attacker = u.Id;+ return new UnitOrder(u.Id, Combat.Attack, enemy.Q, enemy.R);+ }+ throw new InvalidOperationException("fixture: no player unit stands next to an enemy at the start");+ }++ [Test]+ public void TheAttackersIncludingGunsPlayAndTheDefendersDoNot()+ {+ CollectionAssert.AreEqual(new[] { 71, 72 }, UnitAttackPresenter.Attackers(Line(WhyKeys.Engagement, "2")));+ CollectionAssert.AreEqual(new[] { 71, 72, 73 }, UnitAttackPresenter.Attackers(Line(WhyKeys.Engagement, "3")));+ }++ [TestCase("0")]+ [TestCase("-1")]+ [TestCase("4")]+ [TestCase("two")]+ [TestCase("")]+ public void AMalformedAttackerCountPlaysNothing(string count)+ {+ Assert.IsEmpty(UnitAttackPresenter.Attackers(Line(WhyKeys.Engagement, count)));+ }++ [Test]+ public void OnlyAnEngagementPlays()+ {+ Assert.IsEmpty(UnitAttackPresenter.Attackers(Line(WhyKeys.AttackOrdered, "2")));+ }++ /// <summary>An attack order plays at once, after the map is redrawn for it; End Turn runs it again inside the sim (its+ /// first causes are the open turn's), and that replay does not play it twice.</summary>+ [Test]+ public void AnAttackOrderPlaysOnceAfterTheMapIsRedrawn()+ {+ var session = NewSession();+ var bridge = new SimBridge(session, Text);+ var played = new List<int>();+ bool redrawn = false;+ bridge.Changed += () => redrawn = true;+ using var presenter = new UnitAttackPresenter(bridge, id => { Assert.IsTrue(redrawn, "after Changed"); played.Add(id); return true; });+ Assert.IsNull(bridge.Queue(AttackNextTo(session, out int attacker)));+ CollectionAssert.AreEqual(new[] { attacker }, played);+ redrawn = false;+ var r = bridge.EndTurn();+ Assert.IsTrue(r.Why.Any(x => x.Key == WhyKeys.Engagement && UnitAttackPresenter.Attackers(x).Contains(attacker)),+ "the sim replays the committed attack at End Turn");+ Assert.AreEqual(1, played.Count(id => id == attacker), "and the replay is not played again");+ Assert.IsTrue(redrawn, "End Turn redraws the map");+ }++ /// <summary>The real sim, an attack order then a move in the open turn, then End Turn, where an enemy attacks (review of+ /// #2078): the fresh enemy engagement plays, after the map is redrawn; the committed attack, which End Turn replays+ /// first, does not. If the replayed prefix ever stopped matching the open turn's causes, this fails.</summary>+ [Test]+ public void AFreshEndTurnEngagementPlaysBesideAReplayedOne()+ {+ var session = NewSession();+ var bridge = new SimBridge(session, Text);+ var played = new List<int>();+ bool redrawn = false;+ bridge.Changed += () => redrawn = true;+ using var presenter = new UnitAttackPresenter(bridge, id => { Assert.IsTrue(redrawn, "after Changed"); played.Add(id); return true; });+ // Found by running the sim (1948 seed, Historical, first turn): unit 5 attacks enemy unit 9, unit 6 steps next+ // to unit 9, and at End Turn unit 9 attacks.+ var nine = session.Now.State.Units[9];+ Assert.AreNotEqual(Movement.PlayerSide, nine.Side, "fixture: unit 9 is an enemy");+ Assert.IsNull(bridge.Queue(new UnitOrder(5, Combat.Attack, nine.Q, nine.R)), "fixture: unit 5 can attack unit 9");+ Assert.IsNull(bridge.Queue(new Move(6, nine.Q - 2, nine.R)), "fixture: unit 6 can step next to unit 9");+ CollectionAssert.AreEqual(new[] { 5 }, played, "the attack order played at once");+ int openTurn = session.Now.Why.Count;+ redrawn = false;+ var r = bridge.EndTurn();+ var replayed = r.Why.Take(openTurn).Where(x => x.Key == WhyKeys.Engagement).ToList();+ var fresh = r.Why.Skip(openTurn).Where(x => x.Key == WhyKeys.Engagement).ToList();+ Assert.AreEqual(1, replayed.Count, "End Turn replays the committed attack first");+ CollectionAssert.AreEqual(new[] { 5 }, UnitAttackPresenter.Attackers(replayed[0]));+ Assert.IsTrue(fresh.Any(x => x.EnemyOrder == Combat.Attack && UnitAttackPresenter.Attackers(x).Contains(9)),+ "fixture: unit 9's attack is a fresh engagement of this End Turn");+ CollectionAssert.AreEqual(new[] { 5 }.Concat(fresh.SelectMany(UnitAttackPresenter.Attackers)), played,+ "the fresh engagement plays; the replayed attack does not play again");+ CollectionAssert.Contains(played.Skip(1), 9);+ }++ /// <summary>A mid-turn save loads with its attack order already committed (R-SAVE-003), so the bridge never queued it+ /// (ported from Tal Heuberger's #2078): End Turn runs it again first, and it is not played; it played when it was given.</summary>+ [Test]+ public void ALoadedOpenTurnsAttackIsNotPlayedAtEndTurn()+ {+ var session = NewSession();+ Assert.IsNull(session.Commit(AttackNextTo(session, out int attacker)));+ var bridge = new SimBridge(session, Text);+ var played = new List<int>();+ using var presenter = new UnitAttackPresenter(bridge, id => { played.Add(id); return true; });+ var r = bridge.EndTurn();+ Assert.IsTrue(r.Why.Any(x => x.Key == WhyKeys.Engagement && UnitAttackPresenter.Attackers(x).Contains(attacker)),+ "the sim replays the restored attack at End Turn");+ CollectionAssert.DoesNotContain(played, attacker);+ }++ [Test]+ public void ALoadPlaysNoHistoryAndAMissingTokenIsNotRetried()+ {+ var calls = new List<int>();+ var engagement = Line(WhyKeys.Engagement, "2");+ var bridge = new SimBridge(NewSession(), Text,+ (session, orders) => new StepResult(session.State, session.Now.Why.Append(engagement).ToArray(), Array.Empty<Rejection>()));+ using var presenter = new UnitAttackPresenter(bridge, id => { calls.Add(id); return false; });+ bridge.EndTurn();+ CollectionAssert.AreEqual(new[] { 71, 72 }, calls, "false (no token can play) is not retried");+ bridge.Replace(NewSession());+ CollectionAssert.AreEqual(new[] { 71, 72 }, calls, "a load plays nothing");+ }++ [Test]+ public void ARefusedTurnPlaysNothing()+ {+ var session = NewSession();+ Assert.IsNull(session.Commit(AttackNextTo(session, out _)));+ var bridge = new SimBridge(session, Text, (s, orders) => throw new ArgumentException("refused for the test"));+ var calls = new List<int>();+ using var presenter = new UnitAttackPresenter(bridge, id => { calls.Add(id); return true; });+ LogAssert.Expect(LogType.Warning, "End Turn refused: refused for the test");+ bridge.EndTurn();+ Assert.IsEmpty(calls);+ }++ [Test]+ public void DisposingStopsPlaying()+ {+ var session = NewSession();+ var bridge = new SimBridge(session, Text);+ var calls = new List<int>();+ var presenter = new UnitAttackPresenter(bridge, id => { calls.Add(id); return true; });+ presenter.Dispose(); presenter.Dispose();+ Assert.IsNull(bridge.Queue(AttackNextTo(session, out _)));+ Assert.IsEmpty(calls);+ }+}diff --git a/unity/Assets/Tests/EditMode/UnitAttackPresenterTests.cs.meta b/unity/Assets/Tests/EditMode/UnitAttackPresenterTests.cs.metanew file mode 100644index 000000000..02c2a0128--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnitAttackPresenterTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: dbfd705ef923746feb7012b0d150dab2\ No newline at end of file