Skip to content

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

feat(ui): SimBridge, top bar with changes since last turn, refusal messages, screen navigation

eyalgolaneeb8e8808ce7
diff --git a/unity/Assets/Scripts/UI/HudModel.cs b/unity/Assets/Scripts/UI/HudModel.cs
new file mode 100644
index 000000000..56c77f4df
--- /dev/null
+++ b/unity/Assets/Scripts/UI/HudModel.cs
@@ -0,0 +1,53 @@
+#nullable enable
+using System;
+using System.Linq;
+using Statecraft.Sim;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>One top-bar indicator: its value and the change since the last turn (empty when there is none).</summary>
+ public readonly struct Meter
+ {
+ public readonly string Value, Delta;
+ /// <summary>+1 up, -1 down, 0 unchanged or unknown.</summary>
+ public readonly int Sign;
+ public Meter(string value, string delta, int sign) { Value = value; Delta = delta; Sign = sign; }
+ }
+
+ /// <summary>What the top bar shows, computed from simulation state only (no UI types), so it is testable on its own.
+ /// Indicators (0..1) show as 0-100; Treasury is the net position (cash minus debt, IL millions); Immigration is the
+ /// number of immigrants who arrived during the last turn.</summary>
+ public sealed class HudModel
+ {
+ public string Year = "", Turn = "", Date = "", Attention = "", SecurityLevel = "";
+ public Meter Treasury, Immigration, Security, Support, Standing, Fx;
+
+ static double Arrivals(StepResult? r) => r == null ? 0 : r.Why.Where(w => w.System == "population").Sum(w => w.Delta);
+
+ public static HudModel From(SimBridge b, UiText t)
+ {
+ var c = b.Content; var s = b.State; var prev = b.Session.Previous;
+ Meter M(double now, double? before, string valueKey, string deltaKey)
+ {
+ if (before == null) return new Meter(t.Format(valueKey, now), "", 0);
+ var d = Math.Round(now - before.Value, deltaKey == "hud.delta_money" ? 1 : 0);
+ return d == 0 ? new Meter(t.Format(valueKey, now), "", 0) : new Meter(t.Format(valueKey, now), t.Format(deltaKey, d), Math.Sign(d));
+ }
+ double Pct(GameState x, string id) => Math.Round(x.Indicators[id] * 100);
+ return new HudModel
+ {
+ Year = s.Date.Year.ToString(System.Globalization.CultureInfo.InvariantCulture),
+ Turn = t.Format("hud.turn", s.Turn),
+ Date = t.Format("hud.date", s.Date),
+ Attention = t.Format("hud.attention", b.AttentionLeft, c.Rules.AttentionPerTurn),
+ SecurityLevel = t.Format("hud.level", s.Rung),
+ Treasury = M(s.Treasury - s.Debt, prev == null ? (double?)null : prev.Treasury - prev.Debt, "hud.money", "hud.delta_money"),
+ Immigration = M(Arrivals(b.Session.Last), b.BeforeLast == null ? (double?)null : Arrivals(b.BeforeLast), "hud.people", "hud.delta"),
+ Security = M(Pct(s, "security"), prev == null ? (double?)null : Pct(prev, "security"), "hud.percent", "hud.delta"),
+ Support = M(Math.Round(EffectsSystem.Approval(c, s) * 100), prev == null ? (double?)null : Math.Round(EffectsSystem.Approval(c, prev) * 100), "hud.percent", "hud.delta"),
+ Standing = M(Pct(s, "intl_standing"), prev == null ? (double?)null : Pct(prev, "intl_standing"), "hud.percent", "hud.delta"),
+ Fx = M(s.FxReserves, prev?.FxReserves, "hud.fx", "hud.delta_money"),
+ };
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/HudModel.cs.meta b/unity/Assets/Scripts/UI/HudModel.cs.meta
new file mode 100644
index 000000000..f3521c5ac
--- /dev/null
+++ b/unity/Assets/Scripts/UI/HudModel.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: bc3599a3c19eb4eacb0cdf3bb82e7fd3
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/HudPresenter.cs b/unity/Assets/Scripts/UI/HudPresenter.cs
new file mode 100644
index 000000000..a1e217173
--- /dev/null
+++ b/unity/Assets/Scripts/UI/HudPresenter.cs
@@ -0,0 +1,40 @@
+#nullable enable
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>Fills the top bar from HudModel and runs End Turn.</summary>
+ public sealed class HudPresenter
+ {
+ readonly VisualElement root; readonly SimBridge bridge; readonly UiText text;
+
+ public HudPresenter(VisualElement root, SimBridge bridge, UiText text)
+ {
+ this.root = root; this.bridge = bridge; this.text = text;
+ root.Q<Button>("end-turn").clicked += () => bridge.EndTurn();
+ bridge.Changed += Render;
+ Render();
+ }
+
+ void Set(string name, string value) => root.Q<Label>(name).text = value;
+
+ void Set(string meter, Meter m)
+ {
+ Set(meter + "-value", m.Value);
+ var delta = root.Q<Label>(meter + "-delta");
+ delta.text = m.Delta;
+ delta.EnableInClassList("delta-up", m.Sign > 0);
+ delta.EnableInClassList("delta-down", m.Sign < 0);
+ }
+
+ public void Render()
+ {
+ var m = HudModel.From(bridge, text);
+ Set("year", m.Year); Set("turn", m.Turn); Set("date", m.Date); Set("attention", m.Attention);
+ Set("security-level", m.SecurityLevel);
+ Set("treasury", m.Treasury); Set("immigration", m.Immigration); Set("security", m.Security);
+ Set("support", m.Support); Set("standing", m.Standing); Set("fx", m.Fx);
+ root.Q<Button>("end-turn").SetEnabled(bridge.State.GameOver == null);
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/HudPresenter.cs.meta b/unity/Assets/Scripts/UI/HudPresenter.cs.meta
new file mode 100644
index 000000000..ad0409dac
--- /dev/null
+++ b/unity/Assets/Scripts/UI/HudPresenter.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 273bb851ce5264830849c2cee371e00d
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/ScreenNav.cs b/unity/Assets/Scripts/UI/ScreenNav.cs
new file mode 100644
index 000000000..3840e58fb
--- /dev/null
+++ b/unity/Assets/Scripts/UI/ScreenNav.cs
@@ -0,0 +1,36 @@
+#nullable enable
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>The top-bar buttons open the Cabinet, Budget, Defence and Why screens, one at a time; pressing the open
+ /// screen's button again closes it.</summary>
+ public sealed class ScreenNav
+ {
+ public static readonly string[] Screens = { "cabinet", "budget", "defence", "why" };
+ readonly VisualElement root;
+
+ public ScreenNav(VisualElement root)
+ {
+ this.root = root;
+ foreach (var s in Screens)
+ {
+ var screen = s;
+ root.Q<Button>("nav-" + screen).clicked += () => Toggle(screen);
+ }
+ Open(null);
+ }
+
+ /// <summary>The open screen's name, or null.</summary>
+ public string? Current { get; private set; }
+
+ public void Toggle(string screen) => Open(Current == screen ? null : screen);
+
+ public void Open(string? screen)
+ {
+ Current = screen;
+ foreach (var s in Screens)
+ root.Q<VisualElement>("screen-" + s).style.display = s == screen ? DisplayStyle.Flex : DisplayStyle.None;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/ScreenNav.cs.meta b/unity/Assets/Scripts/UI/ScreenNav.cs.meta
new file mode 100644
index 000000000..0db82857c
--- /dev/null
+++ b/unity/Assets/Scripts/UI/ScreenNav.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 9d03a7326021a4f58b1b642715ad2184
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/SimBridge.cs b/unity/Assets/Scripts/UI/SimBridge.cs
new file mode 100644
index 000000000..80cb75d3d
--- /dev/null
+++ b/unity/Assets/Scripts/UI/SimBridge.cs
@@ -0,0 +1,87 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Sim;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>The UI's only door into the simulation (spec section 6). Holds the GameSession, collects this turn's
+ /// orders, runs End Turn and tells the screens to refresh. Orders take effect at End Turn, in the order given; each
+ /// order replaces an earlier one with the same key (one choice per event, one call-up level, one budget, one appointee
+ /// per office, one policy level per policy, one build per hex).</summary>
+ public sealed class SimBridge
+ {
+ readonly List<Command> queue = new List<Command>();
+
+ public GameSession Session { get; private set; }
+ public Content Content => Session.Content;
+ public GameState State => Session.State;
+ public IReadOnlyList<Command> Queued => queue;
+ /// <summary>The step before Session.Last (null until two turns have run), for "change since last turn".</summary>
+ public StepResult? BeforeLast { get; private set; }
+ /// <summary>Raised after every change the screens show: an order queued or withdrawn, a turn, a load.</summary>
+ public event Action? Changed;
+ /// <summary>Raised after End Turn with the orders the simulation refused (possibly none).</summary>
+ public event Action<IReadOnlyList<Rejection>>? TurnEnded;
+
+ public SimBridge(GameSession session) { Session = session ?? throw new ArgumentNullException(nameof(session)); }
+
+ static string Key(Command c) => c switch
+ {
+ ChooseEventOption e => "event:" + e.EventId,
+ SetPolicy p => "policy:" + p.Policy,
+ Appoint a => "appoint:" + a.Office,
+ MapAction m => FormattableString.Invariant($"map:{m.Q},{m.R}"),
+ _ => c.Kind,
+ };
+
+ double Price(Command c) => AttentionSystem.IsCommandKind(c.Kind) ? AttentionSystem.Cost(Content, State, c.Kind) : 0;
+
+ /// <summary>Attention left after paying for the queued orders at this turn's prices.</summary>
+ public double AttentionLeft => State.Attention - queue.Sum(Price);
+
+ /// <summary>The queued order with this key, or null.</summary>
+ public Command? QueuedLike(Command c) => queue.FirstOrDefault(q => Key(q) == Key(c));
+
+ /// <summary>Queues an order (replacing one with the same key). Returns null, or why it was refused here:
+ /// the game is over, or the order costs more attention than is left.</summary>
+ public string? Queue(Command c)
+ {
+ if (c == null) throw new ArgumentNullException(nameof(c));
+ if (State.GameOver != null) return "The game is over";
+ var old = QueuedLike(c);
+ var left = AttentionLeft + (old != null ? Price(old) : 0);
+ if (Price(c) > left + 1e-9)
+ return FormattableString.Invariant($"Not enough attention (need {Price(c):0.0}, have {left:0.0})");
+ if (old != null) queue[queue.IndexOf(old)] = c; else queue.Add(c);
+ Changed?.Invoke();
+ return null;
+ }
+
+ public void Withdraw(Command c)
+ {
+ if (queue.Remove(c)) Changed?.Invoke();
+ }
+
+ /// <summary>Runs the turn with the queued orders, clears the queue, and notifies.</summary>
+ public StepResult EndTurn()
+ {
+ BeforeLast = Session.Last;
+ var r = Session.Step(queue.ToList());
+ queue.Clear();
+ Changed?.Invoke();
+ TurnEnded?.Invoke(r.Rejected);
+ return r;
+ }
+
+ /// <summary>Switches to another session (a loaded save), dropping queued orders.</summary>
+ public void Replace(GameSession session)
+ {
+ Session = session ?? throw new ArgumentNullException(nameof(session));
+ BeforeLast = null;
+ queue.Clear();
+ Changed?.Invoke();
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/SimBridge.cs.meta b/unity/Assets/Scripts/UI/SimBridge.cs.meta
new file mode 100644
index 000000000..05056f728
--- /dev/null
+++ b/unity/Assets/Scripts/UI/SimBridge.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: f9473e2400977468691aeba794fb0896
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/ToastPresenter.cs b/unity/Assets/Scripts/UI/ToastPresenter.cs
new file mode 100644
index 000000000..2d2d878de
--- /dev/null
+++ b/unity/Assets/Scripts/UI/ToastPresenter.cs
@@ -0,0 +1,36 @@
+#nullable enable
+using System.Collections.Generic;
+using System.Linq;
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>A short message under the top bar: why orders were refused (spec section 7: the UI shows the stated
+ /// reason), or a note such as a save warning. Hidden when there is nothing to say; cleared by the next order.</summary>
+ public sealed class ToastPresenter
+ {
+ readonly Label label; readonly UiText text;
+
+ public ToastPresenter(VisualElement root, SimBridge bridge, UiText text)
+ {
+ label = root.Q<Label>("toast"); this.text = text;
+ bridge.TurnEnded += r => Show(r.Select(x => text.Format("toast.refused", x.Reason)));
+ Clear();
+ }
+
+ /// <summary>Shows the lines as they are (none = hide).</summary>
+ public void Show(IEnumerable<string> lines)
+ {
+ var list = lines.ToList();
+ label.text = string.Join("\n", list);
+ label.style.display = list.Count > 0 ? DisplayStyle.Flex : DisplayStyle.None;
+ }
+
+ public void Show(string line) => Show(new[] { line });
+
+ /// <summary>Shows why an order was refused ("Not done: ...").</summary>
+ public void Refuse(string reason) => Show(text.Format("toast.refused", reason));
+
+ public void Clear() => Show(new string[0]);
+ }
+}
diff --git a/unity/Assets/Scripts/UI/ToastPresenter.cs.meta b/unity/Assets/Scripts/UI/ToastPresenter.cs.meta
new file mode 100644
index 000000000..093408fd7
--- /dev/null
+++ b/unity/Assets/Scripts/UI/ToastPresenter.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 3fae532c673fa463595d16a2087aefb7
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/HudTests.cs b/unity/Assets/Tests/EditMode/HudTests.cs
new file mode 100644
index 000000000..51f7616b8
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/HudTests.cs
@@ -0,0 +1,109 @@
+using System.Collections;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.TestTools;
+using UnityEngine.UIElements;
+
+public class HudTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+ static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ static SimBridge NewBridge() => new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical));
+
+ [Test]
+ public void TheTopBarShowsTheOpeningOfTheGame()
+ {
+ var m = HudModel.From(NewBridge(), Text);
+ Assert.AreEqual("1948", m.Year);
+ Assert.AreEqual("Turn 0", m.Turn);
+ Assert.AreEqual("15 May 1948", m.Date);
+ Assert.AreEqual("20.0m", m.Treasury.Value);
+ Assert.AreEqual("$40.0m", m.Fx.Value);
+ Assert.AreEqual("Level 5 of 5", m.SecurityLevel);
+ Assert.AreEqual("Attention 4.0 of 4.0", m.Attention);
+ Assert.AreEqual("", m.Treasury.Delta); // no previous turn yet
+ }
+
+ [Test]
+ public void EndTurnAdvancesTheGameAndShowsChanges()
+ {
+ using var ui = new UiTestKit();
+ var bridge = NewBridge();
+ new HudPresenter(ui.Root, bridge, Text);
+ ui.Press("end-turn");
+ Assert.AreEqual(1, bridge.State.Turn);
+ Assert.AreEqual("Turn 1", ui.Q<Label>("turn").text);
+ Assert.AreEqual("22 May 1948", ui.Q<Label>("date").text);
+ var arrivals = bridge.Session.Last!.Why.Where(w => w.System == "population").Sum(w => w.Delta);
+ Assert.AreEqual(arrivals.ToString("N0", System.Globalization.CultureInfo.InvariantCulture), ui.Q<Label>("immigration-value").text);
+ Assert.AreEqual("-1.4", ui.Q<Label>("treasury-delta").text); // a week of war: taxes, spending and the call-up
+ Assert.IsTrue(ui.Q<Label>("treasury-delta").ClassListContains("delta-down"));
+ }
+
+ [Test]
+ public void QueuedOrdersSpendAttentionUpFront()
+ {
+ var bridge = NewBridge();
+ Assert.IsNull(bridge.Queue(new SetMobilization(1.0))); // at war each order costs 2
+ Assert.AreEqual(2.0, bridge.AttentionLeft, 1e-9);
+ Assert.IsNull(bridge.Queue(new SetMobilization(0.9))); // replaces the first: still one order
+ Assert.AreEqual(1, bridge.Queued.Count);
+ Assert.IsNull(bridge.Queue(new SecurityOrder(-1)));
+ Assert.AreEqual("Not enough attention (need 2.0, have 0.0)", bridge.Queue(new SetPolicy("rationing", 1)));
+ }
+
+ [Test]
+ public void RefusedOrdersAreShownWithTheirReason()
+ {
+ using var ui = new UiTestKit();
+ var bridge = NewBridge();
+ var text = Text;
+ new HudPresenter(ui.Root, bridge, text);
+ new ToastPresenter(ui.Root, bridge, text);
+ Assert.AreEqual(DisplayStyle.None, ui.Q<Label>("toast").style.display.value);
+ bridge.Queue(new SetPolicy("curfew", 1));
+ ui.Press("end-turn");
+ Assert.AreEqual("Not done: Unknown policy 'curfew'", ui.Q<Label>("toast").text);
+ Assert.AreEqual(DisplayStyle.Flex, ui.Q<Label>("toast").style.display.value);
+ }
+
+ [Test]
+ public void NavigationOpensOneScreenAtATime()
+ {
+ using var ui = new UiTestKit();
+ var nav = new ScreenNav(ui.Root);
+ Assert.IsNull(nav.Current);
+ ui.Press("nav-budget");
+ Assert.AreEqual("budget", nav.Current);
+ Assert.AreEqual(DisplayStyle.Flex, ui.Q<VisualElement>("screen-budget").style.display.value);
+ Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>("screen-cabinet").style.display.value);
+ ui.Press("nav-cabinet");
+ Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>("screen-budget").style.display.value);
+ ui.Press("nav-cabinet");
+ Assert.IsNull(nav.Current);
+ }
+
+ [UnityTest]
+ public IEnumerator AtStartNoScreenIsShownAndTheMiddleOfTheScreenIsNotUi()
+ {
+ using var ui = new UiTestKit();
+ var bridge = NewBridge();
+ new ScreenNav(ui.Root);
+ new ToastPresenter(ui.Root, bridge, Text);
+ foreach (var name in new[] { "screen-cabinet", "screen-budget", "screen-defence", "screen-why", "toast" })
+ Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>(name).style.display.value, name);
+ for (int i = 0; i < 10 && float.IsNaN(ui.Root.worldBound.width); i++) yield return null;
+ var panel = ui.Root.panel;
+ var middle = ui.Root.worldBound.center;
+ Assert.IsNull(panel.Pick(middle), "the middle of the screen must reach the map");
+ // screen coordinates are y-up; UiPointer flips them
+ var screenH = (float)Screen.height;
+ var asScreen = new Vector2(middle.x, screenH - middle.y);
+ Assert.IsFalse(UiPointer.IsOverUi(panel, asScreen, screenH));
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/HudTests.cs.meta b/unity/Assets/Tests/EditMode/HudTests.cs.meta
new file mode 100644
index 000000000..000372b1c
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/HudTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: d2b286bda17b04915a6f06d5c79eab32
\ No newline at end of file