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.

fix(ui): budget draft follows the session, status matches the queue, no-op submit spends nothing

eyalgolan53019dbce450
diff --git a/unity/Assets/Scripts/UI/BudgetPresenter.cs b/unity/Assets/Scripts/UI/BudgetPresenter.cs
index 0a7a5a51c..fe17dd884 100644
--- a/unity/Assets/Scripts/UI/BudgetPresenter.cs
+++ b/unity/Assets/Scripts/UI/BudgetPresenter.cs
@@ -16,12 +16,14 @@ namespace Statecraft.Game.UI
readonly VisualElement screen; readonly SimBridge bridge; readonly UiText text;
readonly Button reset, submit;
Dictionary<string, double> draft = new Dictionary<string, double>();
+ GameSession session;
public BudgetPresenter(VisualElement root, SimBridge bridge, UiText text)
{
screen = root.Q<VisualElement>("screen-budget"); this.bridge = bridge; this.text = text;
reset = screen.Q<Button>("budget-reset"); submit = screen.Q<Button>("budget-submit");
reset.clicked += Reset; submit.clicked += Submit;
+ session = bridge.Session;
draft = Current();
bridge.Changed += OnChanged;
Render();
@@ -37,24 +39,34 @@ namespace Statecraft.Game.UI
void Reset() { draft = Current(); Render(); }
- // A new game, a loaded save or a finished turn replaces the draft unless the player has unsaved edits.
+ // A different session (a new game or a loaded save) always replaces the draft. Within a session, a draft the player
+ // has edited survives End Turn (it was never submitted, so it is never applied; the status still says "Changed");
+ // an untouched one follows the budget.
void OnChanged()
{
- if (bridge.QueuedLike(new AllocateBudget(new Dictionary<string, double>())) == null && !Dirty) draft = Current();
+ if (bridge.Session != session) { session = bridge.Session; draft = Current(); }
+ else if (!Dirty && QueuedShares == null) draft = Current();
Render();
}
+ IReadOnlyDictionary<string, double>? QueuedShares => (bridge.QueuedLike(new AllocateBudget(new Dictionary<string, double>())) as AllocateBudget)?.Shares;
+
+ static bool Same(IReadOnlyDictionary<string, double> a, IReadOnlyDictionary<string, double> b) =>
+ a.Keys.Union(b.Keys).All(k => Math.Abs((a.TryGetValue(k, out var x) ? x : 0) - (b.TryGetValue(k, out var y) ? y : 0)) <= 1e-9);
+
/// <summary>The shares the screen proposes.</summary>
public IReadOnlyDictionary<string, double> Draft => draft;
Dictionary<string, double> Current() => new Dictionary<string, double>(bridge.State.Budget);
- bool Dirty => draft.Any(kv => Math.Abs(kv.Value - (bridge.State.Budget.TryGetValue(kv.Key, out var v) ? v : 0)) > 1e-9);
+ // Compares the union of the draft's and the budget's offices.
+ bool Dirty => !Same(draft, bridge.State.Budget);
/// <summary>Moves <paramref name="office"/> by <paramref name="delta"/> (clamped to [0, 1]) and rescales the other
/// shares proportionally; the largest other share absorbs rounding so the total is exactly 1.</summary>
public static Dictionary<string, double> Adjust(IReadOnlyDictionary<string, double> shares, string office, double delta)
{
+ if (!shares.ContainsKey(office)) return new Dictionary<string, double>(shares); // not a budget line: nothing to move
var target = Math.Max(0, Math.Min(1, shares[office] + delta));
var others = shares.Keys.Where(k => k != office).OrderBy(k => k, StringComparer.Ordinal).ToList();
var rest = others.Sum(k => shares[k]);
@@ -63,15 +75,27 @@ namespace Statecraft.Game.UI
if (others.Count > 0)
{
var largest = others.OrderByDescending(k => result[k]).ThenBy(k => k, StringComparer.Ordinal).First();
- result[largest] = 1 - result.Where(kv => kv.Key != largest).Sum(kv => kv.Value);
+ result[largest] = Math.Max(0, 1 - result.Where(kv => kv.Key != largest).Sum(kv => kv.Value));
}
return result;
}
- public void Change(string office, double delta) { draft = Adjust(draft, office, delta); Render(); }
+ public void Change(string office, double delta)
+ {
+ if (!draft.ContainsKey(office)) draft = Current(); // a draft without this line is stale: start again from the budget
+ draft = Adjust(draft, office, delta);
+ Render();
+ }
void Submit()
{
+ var queued = QueuedShares;
+ if (!Dirty)
+ {
+ // Same as today's budget: nothing to put to the vote and no attention to spend; an earlier submission is withdrawn.
+ if (queued != null) bridge.Withdraw(bridge.QueuedLike(new AllocateBudget(new Dictionary<string, double>()))!);
+ return;
+ }
// The bridge copies the shares and reports a refusal itself; the sim checks coverage and the sum.
bridge.Queue(new AllocateBudget(new Dictionary<string, double>(draft)));
}
@@ -104,8 +128,11 @@ namespace Statecraft.Game.UI
screen.Q<Label>("budget-money").text = text.Format("budget.money", s.Treasury, s.Debt, s.FxReserves);
var flows = EconomySystem.Flows(c, s, 1.0); // the sim's own arithmetic, for a year
screen.Q<Label>("budget-flow").text = text.Format("budget.flow", flows.Tax, flows.Spending, flows.Mobilization);
- var queued = bridge.QueuedLike(new AllocateBudget(new Dictionary<string, double>())) != null;
- screen.Q<Label>("budget-status").text = queued ? text["budget.queued"] : Dirty ? text["budget.unsaved"] : "";
+ var queuedShares = QueuedShares;
+ // The status says what is actually queued: edits after Submit are "Changed" again.
+ screen.Q<Label>("budget-status").text = queuedShares != null ? (Same(draft, queuedShares) ? text["budget.queued"] : text["budget.unsaved"])
+ : Dirty ? text["budget.unsaved"] : "";
+ submit.SetEnabled(Dirty || queuedShares != null);
}
}
}
diff --git a/unity/Assets/Tests/EditMode/BudgetScreenTests.cs b/unity/Assets/Tests/EditMode/BudgetScreenTests.cs
index 9f9b781d3..5f10dc5c2 100644
--- a/unity/Assets/Tests/EditMode/BudgetScreenTests.cs
+++ b/unity/Assets/Tests/EditMode/BudgetScreenTests.cs
@@ -67,11 +67,11 @@ public class BudgetScreenTests
var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);
var budget = new BudgetPresenter(ui.Root, bridge, Text);
foreach (var office in C.Rules.BudgetStart.Keys)
- Assert.AreEqual($"effect x{EffectsSystem.BudgetFactor(budget.Draft, office):0.00}", ui.Q<Label>($"budget-{office}-factor").text, office);
+ Assert.AreEqual(System.FormattableString.Invariant($"effect x{EffectsSystem.BudgetFactor(budget.Draft, office):0.00}"), ui.Q<Label>($"budget-{office}-factor").text, office);
var f = EconomySystem.Flows(C, bridge.State, 1.0);
- Assert.AreEqual($"Taxes {f.Tax:0.0}m, spending {f.Spending:0.0}m and reserve call-up {f.Mobilization:0.0}m a year", ui.Q<Label>("budget-flow").text);
+ Assert.AreEqual(System.FormattableString.Invariant($"Taxes {f.Tax:0.0}m, spending {f.Spending:0.0}m and reserve call-up {f.Mobilization:0.0}m a year"), ui.Q<Label>("budget-flow").text);
UiTestKit.Press(ui.Q<Button>("budget-education_minister-up"));
- Assert.AreEqual($"effect x{EffectsSystem.BudgetFactor(budget.Draft, "education_minister"):0.00}", ui.Q<Label>("budget-education_minister-factor").text);
+ Assert.AreEqual(System.FormattableString.Invariant($"effect x{EffectsSystem.BudgetFactor(budget.Draft, "education_minister"):0.00}"), ui.Q<Label>("budget-education_minister-factor").text);
}
[Test]
@@ -98,7 +98,7 @@ public class BudgetScreenTests
new BudgetPresenter(ui.Root, bridge, Text);
var leg = Offices.Legislature(C, g.State.Date)!;
var (seats, size) = PoliticsSystem.CoalitionSeats(C, g.State.Date);
- Assert.AreEqual($"The {leg.Body} must approve it: the coalition holds {seats} of {size} seats", ui.Q<Label>("budget-vote").text);
+ Assert.AreEqual(System.FormattableString.Invariant($"The {leg.Body} must approve it: the coalition holds {seats} of {size} seats"), ui.Q<Label>("budget-vote").text);
}
[Test]
@@ -114,4 +114,94 @@ public class BudgetScreenTests
bridge.EndTurn();
Assert.AreEqual("untouched", ui.Q<Label>("budget-money").text);
}
+
+ static (UiTestKit ui, SimBridge bridge, BudgetPresenter budget) Open()
+ {
+ var ui = new UiTestKit();
+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);
+ return (ui, bridge, new BudgetPresenter(ui.Root, bridge, Text));
+ }
+
+ [Test]
+ public void ALoadedGameNeverInheritsADirtyDraft()
+ {
+ var (ui, bridge, budget) = Open();
+ using (ui)
+ {
+ UiTestKit.Press(ui.Q<Button>("budget-education_minister-up"));
+ var other = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+ bridge.Replace(other);
+ foreach (var kv in other.State.Budget) Assert.AreEqual(kv.Value, budget.Draft[kv.Key], 1e-12, kv.Key);
+ Assert.AreEqual("", ui.Q<Label>("budget-status").text);
+ Assert.AreEqual("6%", ui.Q<Label>("budget-education_minister-share").text);
+ }
+ }
+
+ [Test]
+ public void AnUnsubmittedDraftSurvivesEndTurnAndIsNeverAppliedSilently()
+ {
+ var (ui, bridge, budget) = Open();
+ using (ui)
+ {
+ var before = bridge.State.Budget["education_minister"];
+ UiTestKit.Press(ui.Q<Button>("budget-education_minister-up"));
+ bridge.EndTurn();
+ Assert.AreEqual(before, bridge.State.Budget["education_minister"], 1e-12, "never submitted, so never applied");
+ Assert.AreEqual(before + 0.05, budget.Draft["education_minister"], 1e-9, "the draft is kept");
+ Assert.AreEqual("Changed: submit to put it to the vote", ui.Q<Label>("budget-status").text);
+ }
+ }
+
+ [Test]
+ public void TheStatusFollowsWhatIsActuallyQueued()
+ {
+ var (ui, bridge, budget) = Open();
+ using (ui)
+ {
+ UiTestKit.Press(ui.Q<Button>("budget-education_minister-up"));
+ ui.Press("budget-submit");
+ Assert.AreEqual("Submitted: takes effect at End Turn", ui.Q<Label>("budget-status").text);
+ UiTestKit.Press(ui.Q<Button>("budget-education_minister-up"));
+ Assert.AreEqual("Changed: submit to put it to the vote", ui.Q<Label>("budget-status").text);
+ ui.Press("budget-submit");
+ Assert.AreEqual("Submitted: takes effect at End Turn", ui.Q<Label>("budget-status").text);
+ var queued = (AllocateBudget)bridge.Queued.Single();
+ foreach (var kv in budget.Draft) Assert.AreEqual(kv.Value, queued.Shares[kv.Key], 1e-12);
+ }
+ }
+
+ [Test]
+ public void SubmittingAnUnchangedBudgetSpendsNothing()
+ {
+ var (ui, bridge, _) = Open();
+ using (ui)
+ {
+ ui.Press("budget-submit");
+ Assert.AreEqual(0, bridge.Queued.Count);
+ Assert.AreEqual(bridge.State.Attention, bridge.AttentionLeft, 1e-12);
+ Assert.IsFalse(ui.Q<Button>("budget-submit").enabledSelf);
+ UiTestKit.Press(ui.Q<Button>("budget-education_minister-up"));
+ Assert.IsTrue(ui.Q<Button>("budget-submit").enabledSelf);
+ ui.Press("budget-submit");
+ ui.Press("budget-reset"); // back to today's budget: submitting now withdraws the order
+ Assert.IsTrue(ui.Q<Button>("budget-submit").enabledSelf);
+ ui.Press("budget-submit");
+ Assert.AreEqual(0, bridge.Queued.Count);
+ }
+ }
+
+ [Test]
+ public void AdjustAndChangeSurviveAMissingOffice()
+ {
+ var shares = new Dictionary<string, double> { ["a"] = 0.5, ["b"] = 0.5 };
+ var same = BudgetPresenter.Adjust(shares, "zzz", 0.05);
+ Assert.AreEqual(0.5, same["a"]); Assert.IsFalse(same.ContainsKey("zzz"));
+ foreach (var v in BudgetPresenter.Adjust(new Dictionary<string, double> { ["a"] = 0.3, ["b"] = 0.3, ["c"] = 0.4 }, "a", 0.7).Values) Assert.GreaterOrEqual(v, 0);
+ var (ui, bridge, budget) = Open();
+ using (ui)
+ {
+ Assert.DoesNotThrow(() => budget.Change("zzz", 0.05));
+ foreach (var kv in bridge.State.Budget) Assert.AreEqual(kv.Value, budget.Draft[kv.Key], 1e-12);
+ }
+ }
}