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): Budget screen with shares that always sum to one
eyalgoland6eeaa902ad7
diff --git a/sim/Statecraft.Sim.Tests/TreasuryFlowsTests.cs b/sim/Statecraft.Sim.Tests/TreasuryFlowsTests.csnew file mode 100644index 000000000..1600313e7--- /dev/null+++ b/sim/Statecraft.Sim.Tests/TreasuryFlowsTests.cs@@ -0,0 +1,21 @@+using System;+using System.Collections.Generic;+using Statecraft.Sim;++public class TreasuryFlowsTests+{+ static readonly Content C = ContentLoader.Load(Fixture.Write());++ [Fact]+ public void FlowsMatchWhatATurnAdds()+ {+ var s = new GameState { Date = new DateTime(1948, 6, 1) };+ EconomySystem.Init(C, s);+ s.Population["veterans"] = 1000; s.Mobilization = 0.5;+ var before = s.Treasury;+ var f = EconomySystem.Flows(C, s, 0.25);+ EconomySystem.Apply(C, s, 0.25, new List<Cause>());+ Assert.Equal(before + f.Tax - f.Spending - f.Mobilization, s.Treasury, 12);+ Assert.Equal(C.Rules.TaxPerCapitaPerYear * 1000, EconomySystem.Flows(C, s, 1.0).Tax, 12);+ }+}diff --git a/sim/Statecraft.Sim/EconomySystem.cs b/sim/Statecraft.Sim/EconomySystem.csindex 9c98e7d01..0212e4a5c 100644--- a/sim/Statecraft.Sim/EconomySystem.cs+++ b/sim/Statecraft.Sim/EconomySystem.cs@@ -15,12 +15,26 @@ namespace Statecraft.Sims.Budget = new Dictionary<string, double>(c.Rules.BudgetStart);}+ /// <summary>The treasury's money in and out over <paramref name="yearFraction"/> of a year (1.0 = a year): tax,+ /// spending and the cost of the reserve call-up. Apply uses it, and the Budget screen shows it.</summary>+ public readonly struct TreasuryFlows+ {+ public readonly double Tax, Spending, Mobilization;+ public TreasuryFlows(double tax, double spending, double mobilization) { Tax = tax; Spending = spending; Mobilization = mobilization; }+ }++ public static TreasuryFlows Flows(Content c, GameState s, double yearFraction)+ {+ var r = c.Rules; var pop = s.TotalPopulation;+ return new TreasuryFlows(r.TaxPerCapitaPerYear * pop * yearFraction, r.SpendingPerCapitaPerYear * pop * yearFraction,+ r.MobilizationCostPerYear * s.Mobilization * yearFraction);+ }+public static void Apply(Content c, GameState s, double yearFraction, List<Cause> why){var r = c.Rules; var pop = s.TotalPopulation;- var revenue = r.TaxPerCapitaPerYear * pop * yearFraction;- var spending = r.SpendingPerCapitaPerYear * pop * yearFraction;- var mobilization = r.MobilizationCostPerYear * s.Mobilization * yearFraction;+ var flows = Flows(c, s, yearFraction);+ var revenue = flows.Tax; var spending = flows.Spending; var mobilization = flows.Mobilization;s.Treasury += revenue - spending - mobilization;why.Add(new Cause("economy", "treasury", revenue - spending - mobilization,FormattableString.Invariant($"treasury {revenue - spending - mobilization:+0.00;-0.00;+0.00} (tax {revenue:0.00}, spending {spending:0.00}, reserve call-up {mobilization:0.00})")));diff --git a/unity/Assets/Scripts/UI/BudgetPresenter.cs b/unity/Assets/Scripts/UI/BudgetPresenter.csnew file mode 100644index 000000000..0a7a5a51c--- /dev/null+++ b/unity/Assets/Scripts/UI/BudgetPresenter.cs@@ -0,0 +1,111 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Linq;+using Statecraft.Sim;+using UnityEngine.UIElements;++namespace Statecraft.Game.UI+{+ /// <summary>The Budget screen: each budgeted ministry's share of spending, its minister and the effect multiplier the+ /// share gives (the sim's own EffectsSystem.BudgetFactor), the money position, and whether the legislature must approve. +/- moves+ /// a ministry by 5 points and rescales the others so shares always sum to 1. Submit queues AllocateBudget.</summary>+ public sealed class BudgetPresenter : IDisposable+ {+ public const double Step = 0.05;+ readonly VisualElement screen; readonly SimBridge bridge; readonly UiText text;+ readonly Button reset, submit;+ Dictionary<string, double> draft = new Dictionary<string, double>();++ 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;+ draft = Current();+ bridge.Changed += OnChanged;+ Render();+ }++ /// <summary>Unsubscribes from the bridge and the buttons and removes the rows (the owner calls this when disabled).</summary>+ public void Dispose()+ {+ bridge.Changed -= OnChanged;+ reset.clicked -= Reset; submit.clicked -= Submit;+ screen.Q<ScrollView>("budget-rows")?.Clear();+ }++ void Reset() { draft = Current(); Render(); }++ // A new game, a loaded save or a finished turn replaces the draft unless the player has unsaved edits.+ void OnChanged()+ {+ if (bridge.QueuedLike(new AllocateBudget(new Dictionary<string, double>())) == null && !Dirty) draft = Current();+ Render();+ }++ /// <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);++ /// <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)+ {+ 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]);+ var result = new Dictionary<string, double> { [office] = target };+ foreach (var k in others) result[k] = rest > 0 ? shares[k] / rest * (1 - target) : (1 - target) / others.Count;+ 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);+ }+ return result;+ }++ public void Change(string office, double delta) { draft = Adjust(draft, office, delta); Render(); }++ void Submit()+ {+ // 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)));+ }++ public void Render()+ {+ var c = bridge.Content; var s = bridge.State;+ var rows = screen.Q<ScrollView>("budget-rows");+ rows.Clear();+ foreach (var office in c.Rules.BudgetStart.Keys)+ {+ var o = c.Offices.First(x => x.Id == office);+ var share = draft.TryGetValue(office, out var v) ? v : 0;+ var row = new VisualElement { name = "budget-" + office };+ row.AddToClassList("row");+ row.Add(new Label(text.Format("budget.office", o.Title, Cabinet.Holder(c, s, office)?.Name ?? "-")) { name = "budget-" + office + "-name" });+ row[0].AddToClassList("grow");+ row.Add(new Button(() => Change(office, -Step)) { name = "budget-" + office + "-down", text = "-" });+ row.Add(new Label(text.Format("budget.share", share * 100)) { name = "budget-" + office + "-share" });+ row.Add(new Button(() => Change(office, +Step)) { name = "budget-" + office + "-up", text = "+" });+ var factor = EffectsSystem.BudgetFactor(draft, office);+ row.Add(new Label(text.Format("budget.factor", factor)) { name = "budget-" + office + "-factor" });+ row[4].AddToClassList("muted");+ rows.Add(row);+ }+ var leg = Offices.Legislature(c, s.Date);+ var (seats, size) = PoliticsSystem.CoalitionSeats(c, s.Date);+ screen.Q<Label>("budget-vote").text = leg == null ? "" : leg.BudgetApproval+ ? text.Format("budget.vote_needed", leg.Body, seats, size) : text.Format("budget.no_vote", leg.Body);+ 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"] : "";+ }+ }+}diff --git a/unity/Assets/Scripts/UI/BudgetPresenter.cs.meta b/unity/Assets/Scripts/UI/BudgetPresenter.cs.metanew file mode 100644index 000000000..a6aa2c21d--- /dev/null+++ b/unity/Assets/Scripts/UI/BudgetPresenter.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 0a94f8e0c43e4477daa5abca29208197\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/BudgetScreenTests.cs b/unity/Assets/Tests/EditMode/BudgetScreenTests.csnew file mode 100644index 000000000..9f9b781d3--- /dev/null+++ b/unity/Assets/Tests/EditMode/BudgetScreenTests.cs@@ -0,0 +1,117 @@+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.UIElements;++public class BudgetScreenTests+{+ static readonly Content C = ContentLoader.Load(Paths.Content);+ static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);++ [Test]+ public void AdjustKeepsTheTotalAtExactlyOne()+ {+ var shares = new Dictionary<string, double> { ["a"] = 0.45, ["b"] = 0.35, ["c"] = 0.2 };+ var up = BudgetPresenter.Adjust(shares, "c", 0.05);+ Assert.AreEqual(0.25, up["c"], 1e-12);+ Assert.AreEqual(1.0, up.Values.Sum(), 1e-12);+ Assert.Greater(up["a"] / up["b"], 1.28); // the others keep their proportions+ var floor = BudgetPresenter.Adjust(shares, "c", -0.5);+ Assert.AreEqual(0.0, floor["c"]);+ Assert.AreEqual(1.0, floor.Values.Sum(), 1e-12);+ }++ [Test]+ public void TheScreenListsTheMinistriesAndSubmitsTheDraft()+ {+ using var ui = new UiTestKit();+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ var budget = new BudgetPresenter(ui.Root, bridge, Text);+ Assert.AreEqual("45%", ui.Q<Label>("budget-defense_minister-share").text);+ Assert.AreEqual("Minister of Defense (David Ben-Gurion)", ui.Q<Label>("budget-defense_minister-name").text);+ Assert.AreEqual("effect x1.50", ui.Q<Label>("budget-defense_minister-factor").text); // capped at 1.5+ Assert.AreEqual("The Provisional State Council does not vote on the budget", ui.Q<Label>("budget-vote").text);+ Assert.AreEqual("Treasury 20.0m · debt 0.0m · foreign currency $40.0m", ui.Q<Label>("budget-money").text);+ UiTestKit.Press(ui.Q<Button>("budget-education_minister-up"));+ Assert.AreEqual("11%", ui.Q<Label>("budget-education_minister-share").text);+ Assert.AreEqual("Changed: submit to put it to the vote", ui.Q<Label>("budget-status").text);+ ui.Press("budget-submit");+ var queued = (AllocateBudget)bridge.Queued.Single();+ Assert.AreEqual(1.0, queued.Shares.Values.Sum(), 1e-9);+ Assert.AreEqual("Submitted: takes effect at End Turn", ui.Q<Label>("budget-status").text);+ bridge.EndTurn();+ Assert.AreEqual(budget.Draft["education_minister"], bridge.State.Budget["education_minister"], 1e-12);+ Assert.IsEmpty(bridge.Session.Last!.Rejected);+ }++ [Test]+ public void AdjustHandlesEdges()+ {+ var one = BudgetPresenter.Adjust(new Dictionary<string, double> { ["a"] = 1.0, ["b"] = 0.0 }, "a", -0.05);+ Assert.AreEqual(0.95, one["a"], 1e-12); Assert.AreEqual(0.05, one["b"], 1e-12); // nothing to rescale: split evenly+ var cap = BudgetPresenter.Adjust(new Dictionary<string, double> { ["a"] = 0.9, ["b"] = 0.1 }, "a", 0.5);+ Assert.AreEqual(1.0, cap["a"]); Assert.AreEqual(0.0, cap["b"], 1e-12);+ var lone = BudgetPresenter.Adjust(new Dictionary<string, double> { ["a"] = 1.0 }, "a", -0.5);+ Assert.AreEqual(0.5, lone["a"], 1e-12); // a single line cannot leave 1: the sim would refuse a sum of 0.5+ }++ [Test]+ public void FactorsAndFlowsComeFromTheSim()+ {+ using var ui = new UiTestKit();+ 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);+ 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);+ 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);+ }++ [Test]+ public void TheDraftSurvivesOtherChangesAndResetsToTheBudget()+ {+ using var ui = new UiTestKit();+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ var budget = new BudgetPresenter(ui.Root, bridge, Text);+ UiTestKit.Press(ui.Q<Button>("budget-education_minister-up"));+ bridge.Queue(new SecurityOrder(-1)); // another order changes the bridge; the draft stays+ Assert.AreEqual("11%", ui.Q<Label>("budget-education_minister-share").text);+ ui.Press("budget-reset");+ Assert.AreEqual("6%", ui.Q<Label>("budget-education_minister-share").text);+ Assert.AreEqual("", ui.Q<Label>("budget-status").text);+ }++ [Test]+ public void ALegislatureThatMustApproveIsNamed()+ {+ using var ui = new UiTestKit();+ var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);+ while (!(Offices.Legislature(C, g.State.Date)?.BudgetApproval ?? false)) g.Step(new Command[0]);+ var bridge = new SimBridge(g, Text);+ 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);+ }++ [Test]+ public void ADisposedScreenHearsNothing()+ {+ using var ui = new UiTestKit();+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ var budget = new BudgetPresenter(ui.Root, bridge, Text);+ budget.Dispose();+ ui.Q<Label>("budget-money").text = "untouched";+ ui.Press("budget-submit");+ Assert.AreEqual(0, bridge.Queued.Count);+ bridge.EndTurn();+ Assert.AreEqual("untouched", ui.Q<Label>("budget-money").text);+ }+}diff --git a/unity/Assets/Tests/EditMode/BudgetScreenTests.cs.meta b/unity/Assets/Tests/EditMode/BudgetScreenTests.cs.metanew file mode 100644index 000000000..21d358640--- /dev/null+++ b/unity/Assets/Tests/EditMode/BudgetScreenTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: e933ffab8e08d4afba09c11c5f5175b0\ No newline at end of filediff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxmlindex 446b6d5cf..65860879a 100644--- a/unity/Assets/UI/Game.uxml+++ b/unity/Assets/UI/Game.uxml@@ -57,7 +57,17 @@<ui:VisualElement name="info-panel" class="panel info-panel" /><ui:VisualElement name="minimap" class="panel minimap" /><ui:VisualElement name="screen-cabinet" class="panel screen" />- <ui:VisualElement name="screen-budget" class="panel screen" />+ <ui:VisualElement name="screen-budget" class="panel screen">+ <ui:VisualElement class="screen-header"><ui:Label text="Budget" class="title" /><ui:Label name="budget-vote" class="muted" /></ui:VisualElement>+ <ui:Label name="budget-money" />+ <ui:Label name="budget-flow" class="muted" />+ <ui:ScrollView name="budget-rows" class="grow" />+ <ui:VisualElement class="row">+ <ui:Button name="budget-reset" text="Reset" />+ <ui:Button name="budget-submit" text="Submit the budget" />+ <ui:Label name="budget-status" class="muted grow" />+ </ui:VisualElement>+ </ui:VisualElement><ui:VisualElement name="screen-defence" class="panel screen"><ui:VisualElement class="screen-header"><ui:Label text="Defence" class="title" /><ui:Label name="defence-command" class="muted" /></ui:VisualElement><ui:Label text="Security level" class="meter-name" />diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yamlindex e80b643cd..71694c80c 100644--- a/unity/Assets/UI/strings.en.yaml+++ b/unity/Assets/UI/strings.en.yaml@@ -34,3 +34,12 @@ defence.mob: "{0:0}% of reserves called up (level {1} needs at least {2:0}%)"defence.mob_cost: "Costs {0:0.0}m a year in pay and lost work"defence.ceasefire_stops: "The UN ceasefire clock stops if the level is lowered"defence.ceasefire_starts: "UN ceasefire: {0} weeks once level 5 is reached"+budget.share: "{0:0}%"+budget.office: "{0} ({1})"+budget.factor: "effect x{0:0.00}"+budget.vote_needed: "The {0} must approve it: the coalition holds {1} of {2} seats"+budget.no_vote: "The {0} does not vote on the budget"+budget.money: "Treasury {0:0.0}m · debt {1:0.0}m · foreign currency ${2:0.0}m"+budget.flow: "Taxes {0:0.0}m, spending {1:0.0}m and reserve call-up {2:0.0}m a year"+budget.queued: "Submitted: takes effect at End Turn"+budget.unsaved: "Changed: submit to put it to the vote"