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.

unity: the queue takes the GDD orders (AssignWorkers, Train, CancelTraining), with a reflection guard (refs #380) (#579)

Eyal Golana20680475ae5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f95ece28d..50eddcb09 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,9 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
## [Unreleased]
### Added
+- GDD v0.1 Phase 1, the Unity queue takes the GDD orders (refs #380): `AssignWorkers`, `Train` and `CancelTraining`
+ now queue in the slice, one per city, per city and track, and per cohort; an unknown city, training track or cohort is
+ refused before End Turn. A reflection test fails for any command type that reaches the queue's default branch.
- Sourced Hebrew names in content (refs #558, #193), data only (no screen shows them yet): `title_he` for 30 of 31
offices, plus `title_he_f` where a woman held the office (Labour, Foreign Affairs), `name_he` for 25 of 26 parties,
the 8 governments and the 25 game settlements, `body_he` for the 4 legislatures, each with its own `*_he_sources`
diff --git a/unity/Assets/Scripts/UI/SimBridge.cs b/unity/Assets/Scripts/UI/SimBridge.cs
index 60cbc9643..bb9eac099 100644
--- a/unity/Assets/Scripts/UI/SimBridge.cs
+++ b/unity/Assets/Scripts/UI/SimBridge.cs
@@ -9,7 +9,8 @@ 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, one pioneer order per unit).</summary>
+ /// per office, one policy level per policy, one build per hex, one work order per city, one training order per city and
+ /// track, one cancel per cohort, one pioneer order per unit).</summary>
public sealed class SimBridge
{
readonly List<Command> queue = new List<Command>();
@@ -45,12 +46,17 @@ namespace Statecraft.Game.UI
this.text = text ?? throw new ArgumentNullException(nameof(text));
}
- static string Key(Command c) => c switch
+ /// <summary>The order's slot in the queue: a later order with the same key replaces the earlier one. Internal for
+ /// SimBridgeGuardTests, which checks that every command type is listed here or is one per turn by design.</summary>
+ internal 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}"),
+ AssignWorkers w => "work:" + w.City,
+ Train t => "train:" + t.City + ":" + t.Track,
+ CancelTraining x => FormattableString.Invariant($"untrain:{x.Cohort}"),
PioneerWork w => FormattableString.Invariant($"unit:{w.Unit}"),
StopWork w => FormattableString.Invariant($"unit:{w.Unit}"),
_ => c.Kind,
@@ -84,6 +90,14 @@ namespace Statecraft.Game.UI
foreach (var k in b.Shares.Keys) { var r = Unknown("budget line", k, Content.Rules.BudgetStart.Keys); if (r != null) return r; }
return null;
case SetMobilization _: case SecurityOrder _: return null;
+ // The GDD orders (#380): ids only. Roles, counts and limits are the sim's, which refuses them with its own
+ // reason and refunds the Attention. The legacy content has no cities, so it queues none of these.
+ case AssignWorkers w: return Unknown("city", w.City, Content.Cities.Select(x => x.Id));
+ case Train t:
+ return Unknown("city", t.City, Content.Cities.Select(x => x.Id))
+ ?? Unknown("training", t.Track, Content.UnitTypes.Where(x => !string.IsNullOrEmpty(x.Facility)).Select(x => x.Id));
+ case CancelTraining x:
+ return Unknown("cohort", x.Cohort.ToString(System.Globalization.CultureInfo.InvariantCulture), State.Cohorts.Keys.Select(k => k.ToString(System.Globalization.CultureInfo.InvariantCulture)));
// Pioneer work (#378): ids only; the sim refuses a busy unit, a built site or a short Treasury with its own reason.
case PioneerWork w:
return Unknown("unit", w.Unit.ToString(System.Globalization.CultureInfo.InvariantCulture), State.Units.Keys.Select(k => k.ToString(System.Globalization.CultureInfo.InvariantCulture)))
diff --git a/unity/Assets/Tests/EditMode/SimBridgeGddTests.cs b/unity/Assets/Tests/EditMode/SimBridgeGddTests.cs
new file mode 100644
index 000000000..6415f4755
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/SimBridgeGddTests.cs
@@ -0,0 +1,112 @@
+#nullable enable
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEngine;
+
+/// <summary>The GDD orders through the UI's queue (#380): AssignWorkers, Train and CancelTraining queue in the slice
+/// (MvpSlice), an id the content or state does not have is refused before End Turn, an order replaces an earlier one
+/// with the same key, and the legacy loop's content queues none of them.</summary>
+public class SimBridgeGddTests
+{
+ static readonly Content Slice = MvpSlice.Load(Paths.Content);
+ static readonly Content Legacy = ContentLoader.Load(Paths.Content);
+ static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ static SimBridge Bridge(Content c) => new SimBridge(GameSession.New(c, GoldenRun.Seed, Mode.Historical), Text);
+
+ /// <summary>A slice bridge after one turn that opened a halutz cohort, and that cohort's id.</summary>
+ static (SimBridge bridge, int cohort) WithACohort()
+ {
+ var b = Bridge(Slice);
+ Assert.IsNull(b.Queue(new Train("tel_aviv", "halutz", 1)));
+ b.EndTurn();
+ Assert.AreEqual(1, b.State.Cohorts.Count, "the turn opened one cohort");
+ return (b, b.State.Cohorts.Keys.First());
+ }
+
+ [Test]
+ public void EachGddOrderQueuesInTheSlice()
+ {
+ var b = Bridge(Slice);
+ Assert.IsNull(b.Queue(new AssignWorkers("tel_aviv", "job", 90)));
+ Assert.IsNull(b.Queue(new Train("tel_aviv", "recruit", 1)));
+ Assert.AreEqual(2, b.Queued.Count);
+
+ var (withCohort, id) = WithACohort();
+ Assert.IsNull(withCohort.Queue(new CancelTraining(id)));
+ Assert.AreEqual(1, withCohort.Queued.Count);
+ }
+
+ [Test]
+ public void AnUnknownIdIsRefusedAndNothingIsQueued()
+ {
+ var t = Text;
+ var b = Bridge(Slice);
+ Assert.AreEqual(t.Format("order.unknown", "city", "haifa"), b.Queue(new AssignWorkers("haifa", "job", 1)));
+ Assert.AreEqual(t.Format("order.unknown", "city", "haifa"), b.Queue(new Train("haifa", "halutz", 1)));
+ Assert.AreEqual(t.Format("order.unknown", "training", "pilot"), b.Queue(new Train("tel_aviv", "pilot", 1)));
+ // civilian is a unit type, but nobody trains to it: it has no facility.
+ Assert.AreEqual(t.Format("order.unknown", "training", "civilian"), b.Queue(new Train("tel_aviv", "civilian", 1)));
+ Assert.AreEqual(t.Format("order.unknown", "cohort", "7"), b.Queue(new CancelTraining(7)));
+ Assert.AreEqual(0, b.Queued.Count);
+ }
+
+ [Test]
+ public void AnOrderWithTheSameKeyReplacesTheEarlierOne()
+ {
+ var b = Bridge(Slice);
+ b.Queue(new AssignWorkers("tel_aviv", "job", 10));
+ b.Queue(new AssignWorkers("tel_aviv", "job", 20));
+ Assert.AreEqual(1, b.Queued.Count);
+ Assert.AreEqual(20, ((AssignWorkers)b.Queued[0]).Count);
+
+ // A fresh bridge, so the Attention the work order took cannot refuse a training order.
+ var t = Bridge(Slice);
+ Assert.IsNull(t.Queue(new Train("tel_aviv", "halutz", 1)));
+ Assert.IsNull(t.Queue(new Train("tel_aviv", "halutz", 2)));
+ Assert.AreEqual(1, t.Queued.Count);
+ Assert.AreEqual(2, ((Train)t.Queued[0]).Count);
+ Assert.IsNull(t.QueuedLike(new Train("tel_aviv", "recruit", 1)), "another track is its own order");
+ Assert.IsNull(t.QueuedLike(new AssignWorkers("tel_aviv", "job", 1)), "work and training orders do not share a key");
+
+ var (withCohort, id) = WithACohort();
+ withCohort.Queue(new CancelTraining(id));
+ withCohort.Queue(new CancelTraining(id));
+ Assert.AreEqual(1, withCohort.Queued.Count);
+ }
+
+ /// <summary>The work key names the city: another city's order is its own, not a replacement. (QueuedLike checks keys
+ /// only, so a city the slice does not have is enough.) One per city is right while "job" is the only role; craftsmen
+ /// (Phase 3, D-D4) will need the role in the key.</summary>
+ [Test]
+ public void AnotherCitysWorkOrderIsItsOwn()
+ {
+ var b = Bridge(Slice);
+ Assert.IsNull(b.Queue(new AssignWorkers("tel_aviv", "job", 10)));
+ Assert.IsNull(b.QueuedLike(new AssignWorkers("jerusalem", "job", 1)), "another city is its own order");
+ }
+
+ /// <summary>The cancel key names the cohort: cancelling two cohorts in one turn keeps both orders.</summary>
+ [Test]
+ public void AnotherCohortsCancelIsItsOwn()
+ {
+ var (b, id) = WithACohort();
+ Assert.IsNull(b.Queue(new CancelTraining(id)));
+ Assert.IsNull(b.QueuedLike(new CancelTraining(id + 1)), "another cohort is its own order");
+ }
+
+ [Test]
+ public void TheLegacyLoopQueuesNoGddOrder()
+ {
+ var t = Text;
+ var b = Bridge(Legacy);
+ Assert.IsFalse(Legacy.IsGdd);
+ Assert.AreEqual(t.Format("order.unknown", "city", "tel_aviv"), b.Queue(new AssignWorkers("tel_aviv", "job", 1)));
+ Assert.AreEqual(t.Format("order.unknown", "city", "tel_aviv"), b.Queue(new Train("tel_aviv", "halutz", 1)));
+ Assert.AreEqual(t.Format("order.unknown", "cohort", "1"), b.Queue(new CancelTraining(1)));
+ Assert.AreEqual(0, b.Queued.Count);
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/SimBridgeGddTests.cs.meta b/unity/Assets/Tests/EditMode/SimBridgeGddTests.cs.meta
new file mode 100644
index 000000000..e818cca1d
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/SimBridgeGddTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 68620c1a99a84de9a675936eb47e87cc
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/SimBridgeGuardTests.cs b/unity/Assets/Tests/EditMode/SimBridgeGuardTests.cs
new file mode 100644
index 000000000..a0812e1af
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/SimBridgeGuardTests.cs
@@ -0,0 +1,76 @@
+#nullable enable
+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;
+
+/// <summary>Every concrete command type in the sim assembly has a real branch in SimBridge.Validate, so the queue never
+/// refuses a valid order with the default "That order is not valid" (#380). A new command type fails here until it has a
+/// sample below and its branch in SimBridge. The samples mirror the sim's CommandGuardTests.Samples.</summary>
+public class SimBridgeGuardTests
+{
+ static readonly Content Slice = MvpSlice.Load(Paths.Content);
+ static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+
+ static readonly Dictionary<Type, Command> Samples = new Dictionary<Type, Command>
+ {
+ [typeof(SetPolicy)] = new SetPolicy("rationing", 0.5),
+ [typeof(AllocateBudget)] = new AllocateBudget(new Dictionary<string, double> { ["finance_minister"] = 1.0 }),
+ [typeof(ChooseEventOption)] = new ChooseEventOption("drought", "a"),
+ [typeof(SetMobilization)] = new SetMobilization(0.5),
+ [typeof(SecurityOrder)] = new SecurityOrder(1),
+ [typeof(Appoint)] = new Appoint("prime_minister", "pm_one"),
+ [typeof(MapAction)] = new MapAction("housing", 1, 2),
+ [typeof(AssignWorkers)] = new AssignWorkers("tel_aviv", "job", 1),
+ [typeof(Train)] = new Train("tel_aviv", "halutz", 1),
+ [typeof(CancelTraining)] = new CancelTraining(1),
+ [typeof(PioneerWork)] = new PioneerWork(1, "build_yishuv", "mefalsim"),
+ [typeof(StopWork)] = new StopWork(1),
+ };
+
+ static IEnumerable<Type> CommandTypes() =>
+ typeof(Command).Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(Command)) && !t.IsAbstract);
+
+ [Test]
+ public void EveryCommandTypeHasASample()
+ {
+ var missing = CommandTypes().Where(t => !Samples.ContainsKey(t)).Select(t => t.Name).ToList();
+ Assert.IsEmpty(missing, "add a sample here, then a branch in SimBridge.Validate and SimBridge.Key");
+ // Not vacuous: the reflection finds exactly the sampled types (an empty scan would pass every check in this class).
+ CollectionAssert.AreEquivalent(Samples.Keys, CommandTypes().ToList());
+ }
+
+ /// <summary>The command types whose order is one per turn by design, so their key is their kind (SimBridge.Key's
+ /// default): one budget, one call-up level, one security order.</summary>
+ static readonly HashSet<Type> OnePerTurn = new HashSet<Type> { typeof(AllocateBudget), typeof(SetMobilization), typeof(SecurityOrder) };
+
+ /// <summary>Every other command type has its own branch in SimBridge.Key, so its orders are not one per turn by accident
+ /// (a new type with a Validate branch and no Key branch would silently keep only the last order of the turn).</summary>
+ [Test]
+ public void EveryCommandTypeHasAKeyBranchOrIsOnePerTurn()
+ {
+ foreach (var t in CommandTypes().Where(Samples.ContainsKey))
+ {
+ var key = SimBridge.Key(Samples[t]);
+ if (OnePerTurn.Contains(t)) Assert.AreEqual(Samples[t].Kind, key, t.Name);
+ else Assert.AreNotEqual(Samples[t].Kind, key, t.Name + " has no branch in SimBridge.Key: add one, or list it in OnePerTurn");
+ }
+ }
+
+ [Test]
+ public void NoCommandTypeFallsToTheDefaultBranch()
+ {
+ var text = Text;
+ foreach (var t in CommandTypes().Where(Samples.ContainsKey))
+ {
+ var bridge = new SimBridge(GameSession.New(Slice, GoldenRun.Seed, Mode.Historical), text);
+ var reason = bridge.Queue(Samples[t]);
+ Assert.AreNotEqual(text["order.invalid"], reason, t.Name + " reaches SimBridge.Validate's default branch");
+ }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/SimBridgeGuardTests.cs.meta b/unity/Assets/Tests/EditMode/SimBridgeGuardTests.cs.meta
new file mode 100644
index 000000000..d605f1dac
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/SimBridgeGuardTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 051ee119cd844c39a729ae2cb51509cb
\ No newline at end of file