A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Cabinet: candidates follow End turn's queue (Refs #2743) (#2745)
Eyal Golan5bcf62d55994
diff --git a/changelog.d/2743-cabinet-preview.md b/changelog.d/2743-cabinet-preview.mdnew file mode 100644index 000000000..543885092--- /dev/null+++ b/changelog.d/2743-cabinet-preview.md@@ -0,0 +1,4 @@+### Fixed++- The Cabinet screen no longer offers an appointment that this turn's queued appointments make End turn refuse, such as+ a minister's post for the person just appointed Chief of Staff (Refs #2743).diff --git a/unity/Assets/Scripts/UI/CabinetPresenter.cs b/unity/Assets/Scripts/UI/CabinetPresenter.csindex fbad1a853..485439639 100644--- a/unity/Assets/Scripts/UI/CabinetPresenter.cs+++ b/unity/Assets/Scripts/UI/CabinetPresenter.cs@@ -308,16 +308,63 @@ namespace Statecraft.Game.UIvar common = screen.Q<Label>("cabinet-pick-reason");common.text = shared == null ? "" : ReasonText(c, shared);common.style.display = shared == null ? DisplayStyle.None : DisplayStyle.Flex;+ // #2743: only a queued appointment changes who can hold an office this turn (Cabinet.cs; Scenario.cs is dated, not+ // queued), so the exact previews, one per candidate, run only while one is queued.+ var current = bridge.Queued.Any(x => x is Appoint)+ ? Simulation.Preview(c, bridge.TurnStart, bridge.Session.Committed.Concat(bridge.Queued).ToList()) : null;foreach (var (person, reason) in list){if (!rows.TryGetValue(person.Id, out var r)) continue;+ (Rejection rejection, PreviewResult preview)? refused = null;+ CabinetReason? held = null;+ if (reason == null && current != null)+ {+ var press = new Appoint(Selected, person.Id);+ if (bridge.CanPay(press)) refused = PreviewRefusal(c, press, current);+ // Who holds which office once the queue is applied does not depend on Attention, so a person a queued+ // appointment puts in another office is disabled even when the press could not be paid for (#2743).+ else held = HeldAfterQueue(c, current, person.Id);+ }+ var previewReason = refused == null ? null : PreviewReason(c, refused.Value.rejection, refused.Value.preview);r.appoint.text = Describe(person);- r.appoint.SetEnabled(reason == null);- r.reason.text = shared == null && reason != null ? ReasonText(c, reason) : "";- r.reason.style.display = reason == null || shared != null ? DisplayStyle.None : DisplayStyle.Flex;+ r.appoint.SetEnabled(reason == null && refused == null && held == null);+ r.reason.text = shared != null ? "" : reason != null ? ReasonText(c, reason) : previewReason ?? (held != null ? ReasonText(c, held) : "");+ r.reason.style.display = shared == null && (reason != null || refused != null || held != null) ? DisplayStyle.Flex : DisplayStyle.None;}}+ /// <summary>The refusal the exact queue left by <paramref name="press"/> would introduce: the press itself, or an+ /// existing queued order that the current queue accepts. Queue objects are compared by reference so sim-made orders+ /// never count, and a same-key appointment keeps its existing slot exactly as <see cref="SimBridge.Queue"/> does.</summary>+ (Rejection rejection, PreviewResult preview)? PreviewRefusal(Content c, Appoint press, PreviewResult current)+ {+ var queue = bridge.Queued.ToList();+ var old = bridge.QueuedLike(press);+ if (old == null) queue.Add(press);+ else queue[queue.FindIndex(x => ReferenceEquals(x, old))] = press;+ var next = Simulation.Preview(c, bridge.TurnStart, bridge.Session.Committed.Concat(queue).ToList());+ var rejection = next.Rejected.FirstOrDefault(x => ReferenceEquals(x.Command, press))+ ?? next.Rejected.FirstOrDefault(x => bridge.Queued.Any(q => ReferenceEquals(q, x.Command))+ && !current.Rejected.Any(r => ReferenceEquals(r.Command, x.Command)));+ return rejection == null ? null : (rejection, next);+ }++ /// <summary>The reasons a queued appointment can create for <paramref name="person"/>: holding another office once the+ /// queue is applied (Cabinet.CheckReason on the preview's state). Date-bound reasons (a death, an office's dates) are+ /// left out: the preview's state is a turn later than the appointment.</summary>+ static readonly string[] HolderKinds = { "is_president", "is_chief_of_staff", "already_holds" };++ CabinetReason? HeldAfterQueue(Content c, PreviewResult current, string person) =>+ Cabinet.CheckReason(c, current.State, Selected!, person) is CabinetReason r && Array.IndexOf(HolderKinds, r.Kind) >= 0 ? r : null;++ string PreviewReason(Content c, Rejection rejection, PreviewResult preview)+ {+ if (rejection.Command is Appoint a && Cabinet.CheckReason(c, preview.State, a.Office, a.Person) is CabinetReason reason+ && reason.Text == rejection.Reason)+ return ReasonText(c, reason);+ return SimBridge.ReasonText(text, rejection.Reason, c, bridge.TownNamesHe);+ }+string ReasonText(Content c, CabinetReason reason){bool he = text["ui.lang"] == UiLanguage.Hebrew;diff --git a/unity/Assets/Tests/EditMode/CabinetPreviewShots.cs b/unity/Assets/Tests/EditMode/CabinetPreviewShots.csnew file mode 100644index 000000000..cc148308f--- /dev/null+++ b/unity/Assets/Tests/EditMode/CabinetPreviewShots.cs@@ -0,0 +1,181 @@+#nullable enable+using System;+using System.Collections;+using System.IO;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map;+using Statecraft.Game.UI;+using Statecraft.Sim;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;+using UnityEngine.UIElements;+using Object = UnityEngine.Object;++/// <summary>Writes the before and after stills for #2745 (refs #2743 item 1), in English and Hebrew, to+/// `.superpowers/shots-2745/<tag>/` (local, not committed): Assets/Map.unity, its UI drawn through a copy of its+/// PanelSettings into a transparent 1280x720 texture and laid over the main camera's own 1280x720 frame, as CivMovementShots+/// does, so the map shows under the UI. Each state is the one the PR's own tests build+/// (CabinetScreenTests.In1950: the historical game on the golden seed, played by HistoricalAI to 1 February 1950), which the+/// root goes on with (GameRoot.Begin keep:); the Cabinet opens from the top bar's Cabinet button, and the office is picked with+/// CabinetPresenter.Select, as the tests do. The candidate row is scrolled into view.+///+/// Shots (`{lang}` is `en` or `he`):+/// - `maklef-finance-after-cos-queued-{lang}`: Appoint(chief_of_staff, maklef) queued, Minister of Finance selected+/// (AQueuedChiefOfStaffAppointmentDisablesThatPersonsMinisterButton). After: Maklef's button off, with End turn's reason in+/// the row. Before: the button on, no reason.+/// - `maklef-cos-replacing-dayan-{lang}`: Dayan queued as Chief of Staff and Maklef for Finance, Chief of Staff selected+/// (ReplacingAChiefOfStaffOrderCannotNewlyBreakALaterAppointment). After: Maklef's button off, with the reason the later+/// Finance order would be refused. Before: the button on, no reason.+///+/// Run (Unity closed on the project; the same file, unchanged, on both trees, at the same resolution):+/// AFTER, with the PR head checked out:+/// SHOTS_TAG=after <Unity> -batchmode -projectPath unity -runTests -testPlatform EditMode -testFilter CabinetPreviewShots -testResults /tmp/shots-2745-after.xml+/// BEFORE, with this file and its .meta copied onto main:+/// SHOTS_TAG=before <Unity> -batchmode -projectPath unity -runTests -testPlatform EditMode -testFilter CabinetPreviewShots -testResults /tmp/shots-2745-before.xml+/// Uses only APIs that exist on main as well (checked against origin/main when written). Explicit, so CI never runs it.</summary>+[Explicit("writes stills for a pull request, not a check")]+public class CabinetPreviewShots+{+ const int Width = 1280, Height = 720;+ string saveDir = "";+ string shotDir = "";+ RenderTexture? rt; PanelSettings? ps;+ VisualElement ui = null!;+ GameRoot root = null!;++ [SetUp]+ public void TempSaves()+ {+ saveDir = Path.Combine(Path.GetTempPath(), "statecraft-shots-" + Guid.NewGuid().ToString("N"));+ var tag = Environment.GetEnvironmentVariable("SHOTS_TAG");+ shotDir = Path.Combine(Directory.GetCurrentDirectory(), ".superpowers", "shots-2745", string.IsNullOrEmpty(tag) ? "untagged" : tag);+ Directory.CreateDirectory(shotDir);+ }++ [TearDown]+ public void DiscardScene()+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ if (ps != null) Object.DestroyImmediate(ps);+ if (rt != null) { rt.Release(); Object.DestroyImmediate(rt); }+ if (Directory.Exists(saveDir)) Directory.Delete(saveDir, true);+ }++ SimBridge Bridge => root.Bridge!;+ static Content C => MapFocusTests.Inputs.Content;+ static UiText Text(bool he) => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(he ? UiPaths.StringsHebrew : UiPaths.Strings).text);++ IEnumerator Frames(int n) { for (int i = 0; i < n; i++) yield return null; }++ /// <summary>CabinetScreenTests.In1950's game, drawn by the root.</summary>+ IEnumerator Boot(bool hebrew)+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var doc = Object.FindFirstObjectByType<UIDocument>();+ // The UI goes into a transparent texture and Shot puts it over the map camera's frame, as CivMovementShots does.+ rt = new RenderTexture(Width, Height, 24, RenderTextureFormat.ARGB32);+ ps = Object.Instantiate(doc.panelSettings);+ ps.targetTexture = rt; ps.clearColor = true; ps.colorClearValue = Color.clear;+ doc.panelSettings = ps;+ Object.FindFirstObjectByType<MapScene>().Build(MapFocusTests.Inputs.Map);+ root = Object.FindFirstObjectByType<GameRoot>();+ root.Store = new SaveStore(saveDir);+ if (hebrew) root.Language = UiLanguage.Hebrew;+ var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);+ while (g.State.Date < new DateTime(1950, 2, 1)) g.Step(HistoricalAI.Commands(C, g.State));+ root.Begin(MapFocusTests.Inputs, 0, keep: new SimBridge(g, Text(hebrew)));+ ui = doc.rootVisualElement;+ for (int i = 0; i < 30 && !(ui.Q("top-bar").worldBound.height > 0); i++) yield return null;+ yield return Frames(5);+ // Any waiting event card is put away, as its Hide button does, so the Cabinet can open over the map.+ var hide = ui.Q<Button>("event-hide");+ if (hide != null && hide.resolvedStyle.display != DisplayStyle.None && hide.enabledInHierarchy) UiTestKit.Press(hide);+ root.Card?.Collapse(takeFocus: false);+ if (root.Advisor != null && root.Advisor.IsOpen) UiTestKit.Press(ui.Q<Button>("advisor-close")); // as CivMovementShots.Boot+ yield return Frames(3);+ }++ CabinetPresenter CabinetScreen()+ {+ var field = typeof(GameRoot).GetField("cabinet", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);+ return (CabinetPresenter)field!.GetValue(root)!;+ }++ IEnumerator OpenAt(string office, string person)+ {+ UiTestKit.Press(ui.Q<Button>("nav-cabinet"));+ yield return Frames(5);+ CabinetScreen().Select(office);+ yield return Frames(5);+ var row = ui.Q("cand-" + person);+ if (row != null) ui.Q<ScrollView>("cabinet-candidates")?.ScrollTo(row);+ yield return Frames(5);+ }++ static Color[] Read(RenderTexture from)+ {+ var prev = RenderTexture.active;+ RenderTexture.active = from;+ var tex = new Texture2D(from.width, from.height, TextureFormat.RGBA32, false);+ tex.ReadPixels(new Rect(0, 0, from.width, from.height), 0, 0);+ tex.Apply();+ RenderTexture.active = prev;+ var px = tex.GetPixels();+ Object.DestroyImmediate(tex);+ return px;+ }++ /// <summary>The map camera's frame with the UI texture over it (the UI's pixels are premultiplied by their alpha), copied+ /// from CivMovementShots.Shot, which writes to its own folder.</summary>+ void Shot(string name, string person)+ {+ var cam = Camera.main;+ var frame = new RenderTexture(Width, Height, 24, RenderTextureFormat.ARGB32);+ var before = cam.targetTexture;+ cam.targetTexture = frame; cam.Render(); cam.targetTexture = before;+ var map = Read(frame); var over = Read(rt!);+ frame.Release(); Object.DestroyImmediate(frame);+ var outPx = new Color[map.Length];+ for (int i = 0; i < map.Length; i++)+ {+ var u = over[i]; var m = map[i];+ outPx[i] = new Color(u.r + m.r * (1f - u.a), u.g + m.g * (1f - u.a), u.b + m.b * (1f - u.a), 1f);+ }+ var tex = new Texture2D(Width, Height, TextureFormat.RGB24, false);+ tex.SetPixels(outPx); tex.Apply();+ File.WriteAllBytes(Path.Combine(shotDir, name + ".png"), tex.EncodeToPNG());+ Object.DestroyImmediate(tex);+ var button = ui.Q<Button>("appoint-" + person);+ Debug.Log($"SHOT {name} -> {shotDir}: appoint-{person} enabled={button?.enabledSelf}, reason \"{ui.Q<Label>("cand-" + person + "-reason")?.text}\"");+ }++ IEnumerator FinanceAfterChiefOfStaff(bool hebrew)+ {+ var lang = hebrew ? "he" : "en";+ yield return Boot(hebrew);+ Debug.Log($"SHOT queue chief_of_staff maklef -> {Bridge.Queue(new Appoint("chief_of_staff", "maklef")) ?? "queued"}");+ yield return OpenAt("finance_minister", "maklef");+ Shot($"maklef-finance-after-cos-queued-{lang}", "maklef");+ }++ IEnumerator ChiefOfStaffReplacingDayan(bool hebrew)+ {+ var lang = hebrew ? "he" : "en";+ yield return Boot(hebrew);+ // The 1950 game pays for one appointment (1.5 Attention left after it, 2.5 for the next), and this state needs two+ // queued, as CabinetScreenTests.ReplacingAChiefOfStaffOrderCannotNewlyBreakALaterAppointment gives itself.+ Bridge.TurnStart.Attention += 5;+ Debug.Log($"SHOT queue chief_of_staff dayan -> {Bridge.Queue(new Appoint("chief_of_staff", "dayan")) ?? "queued"}");+ Debug.Log($"SHOT queue finance_minister maklef -> {Bridge.Queue(new Appoint("finance_minister", "maklef")) ?? "queued"}");+ yield return OpenAt("chief_of_staff", "maklef");+ Shot($"maklef-cos-replacing-dayan-{lang}", "maklef");+ }++ [UnityTest] public IEnumerator FinanceEnglish() { yield return FinanceAfterChiefOfStaff(false); }+ [UnityTest] public IEnumerator FinanceHebrew() { yield return FinanceAfterChiefOfStaff(true); }+ [UnityTest] public IEnumerator ChiefOfStaffEnglish() { yield return ChiefOfStaffReplacingDayan(false); }+ [UnityTest] public IEnumerator ChiefOfStaffHebrew() { yield return ChiefOfStaffReplacingDayan(true); }+}diff --git a/unity/Assets/Tests/EditMode/CabinetPreviewShots.cs.meta b/unity/Assets/Tests/EditMode/CabinetPreviewShots.cs.metanew file mode 100644index 000000000..6ed6e17c9--- /dev/null+++ b/unity/Assets/Tests/EditMode/CabinetPreviewShots.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 9e226fb90f7b83376e55cc0f63ca19b8\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/CabinetScreenTests.cs b/unity/Assets/Tests/EditMode/CabinetScreenTests.csindex 849bc7fc3..f239b51fe 100644--- a/unity/Assets/Tests/EditMode/CabinetScreenTests.cs+++ b/unity/Assets/Tests/EditMode/CabinetScreenTests.cs@@ -219,6 +219,29 @@ public class CabinetScreenTests}}+ // #2743 review: with an appointment queued the preview path runs, but a candidate the player can't pay for is never+ // disabled for it; pressing gives the queue-time Attention refusal, as before (ARefusalAtQueueTimeIsShown).+ [Test]+ public void WithAnAppointmentQueuedACandidateIsNotDisabledForLackOfAttention()+ {+ using var ui = Shown();+ var bridge = In1950();+ new ToastPresenter(ui.Root, bridge, Text);+ var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);+ Assert.IsNull(bridge.Queue(new Appoint("chief_of_staff", "maklef")), "precondition: an appointment is queued");+ var refused = false;+ foreach (var p in C.Policies)+ if (bridge.Queue(new SetPolicy(p.Id, 0.5)) != null) { refused = true; break; }+ Assert.IsTrue(refused, "precondition: Attention runs out");+ Assert.IsFalse(bridge.CanPay(new Appoint("finance_minister", "golda_meir")), "precondition: the appointment can't be paid for");+ var queued = bridge.Queued.Count;+ cabinet.Select("finance_minister");+ Assert.IsTrue(ui.Q<Button>("appoint-golda_meir").enabledSelf, "not disabled for Attention");+ UiTestKit.Press(ui.Q<Button>("appoint-golda_meir"));+ StringAssert.StartsWith("Not done: Not enough attention", ui.Q<Label>("toast").text);+ Assert.AreEqual(queued, bridge.Queued.Count, "nothing more is queued");+ }+[Test]public void ARefusalAtQueueTimeIsShown(){@@ -234,6 +257,48 @@ public class CabinetScreenTestsAssert.AreEqual(2, bridge.Queued.Count);}+ [Test]+ public void AQueuedChiefOfStaffAppointmentDisablesThatPersonsMinisterButton()+ {+ // Red-first prediction at ae4bfdaab: the button stays enabled because the candidate list ignores queued appointments.+ using var ui = Shown();+ var bridge = In1950();+ using var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);+ Assert.IsNull(bridge.Queue(new Appoint("chief_of_staff", "maklef")));++ cabinet.Select("finance_minister");++ Assert.IsFalse(ui.Q<Button>("appoint-maklef").enabledSelf);+ var preview = Simulation.Preview(C, bridge.TurnStart, bridge.Session.Committed.Concat(bridge.Queued).ToList());+ Assert.AreEqual(Cabinet.Check(C, preview.State, "finance_minister", "maklef"), ui.Q<Label>("cand-maklef-reason").text);+ }++ [Test]+ public void ReplacingAChiefOfStaffOrderCannotNewlyBreakALaterAppointment()+ {+ // Red-first prediction at ae4bfdaab: the button stays enabled because the replacement's effect on the later order is ignored.+ using var ui = Shown();+ var bridge = In1950();+ // In1950's Attention pays for one appointment (1.5 left after it, 2.5 for the next), and this test needs two queued;+ // Attention is not what it checks (WithAnAppointmentQueuedACandidateIsNotDisabledForLackOfAttention does that).+ bridge.TurnStart.Attention += 5;+ using var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);+ Assert.IsNull(bridge.Queue(new Appoint("chief_of_staff", "dayan")));+ Assert.IsNull(bridge.Queue(new Appoint("finance_minister", "maklef")));+ var later = bridge.Queued[1];+ var current = Simulation.Preview(C, bridge.TurnStart, bridge.Session.Committed.Concat(bridge.Queued).ToList());+ Assert.IsFalse(current.Rejected.Any(x => ReferenceEquals(x.Command, later)), "the current queue accepts the later appointment");++ cabinet.Select("chief_of_staff");++ Assert.IsFalse(ui.Q<Button>("appoint-maklef").enabledSelf);+ var replacement = new Appoint("chief_of_staff", "maklef");+ var hypothetical = Simulation.Preview(C, bridge.TurnStart,+ bridge.Session.Committed.Concat(new Command[] { replacement, later }).ToList());+ var rejection = hypothetical.Rejected.Single(x => ReferenceEquals(x.Command, later));+ Assert.AreEqual(rejection.Reason, ui.Q<Label>("cand-maklef-reason").text);+ }+[Test]public void SelectingNothingClosesTheListAndADisposedScreenHearsNothing(){