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.

Move the scenario runner and MvpGolden into Statecraft.Sim (refs #394) (#420)

Eyal Golanf9c6d97a7e87
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e125bcbf2..be8b49ce6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -196,6 +196,8 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
+0.9 ms at the gameplay zoom), not yet on an idle one.
### Changed
+- The scenario runner (`Scenario`) and the `mvp-slice` golden's player (`MvpGolden`) move from the tests into `Statecraft.Sim`,
+ next to `GoldenRun`, so Unity can play those goldens too (step 1 of #394). Same code, same hashes; no golden moves.
- Sea round 2 (refs #388). The sea has texture at the gameplay and overview zooms, where it used to read as a flat
surface: slow wind streaks, ripples from the waves' slope towards the camera (faded out as a pixel grows towards a
wave's size), and sparse whitecaps on the streaks' bright side, close up only. All three sit behind a new `seatexture`
diff --git a/docs/determinism.md b/docs/determinism.md
index fd2d45718..a92ff7b4e 100644
--- a/docs/determinism.md
+++ b/docs/determinism.md
@@ -59,7 +59,7 @@ The carry-over check (play era N into N+1 and compare with a fresh N+1 on each c
and on `EraSystem.Cross`.
**Scenario goldens.** The two hash goldens follow `HistoricalAI`, the path history took. A scenario is a path a player might take
-instead: `sim/Statecraft.Sim.Tests/scenarios/<name>.yaml` lists commands by date (`on:`), the runner (`Scenario`, in the tests) plays
+instead: `sim/Statecraft.Sim.Tests/scenarios/<name>.yaml` lists commands by date (`on:`), the runner (`Scenario`, in the sim library) plays
them from a seed (default 1948) in Historical mode until `until:`, and `ScenarioTests` checks the final hash against the manifest line
`scenario-<name>` and the snapshot `golden/scenario-<name>.txt`. The file's header comment lists the command kinds. A turn with no
scripted command passes. A command the sim rejects fails the test with the date, the order and the reason, and a step that never runs
@@ -75,6 +75,10 @@ snapshot `golden/mvp-slice.txt`, and the update command re-pins it like the othe
`tools/web_check.py`, because the players run only the legacy goldens until cutover. A Phase 1 PR that adds a GDD rule the slice
exercises moves it, re-pins it and says why; the legacy goldens never move for it.
+`Scenario` and `MvpGolden` live in `Statecraft.Sim` next to `GoldenRun`, so Unity, which gets only `Statecraft.Sim.dll` and
+`YamlDotNet.dll` from `tools/build_sim_for_unity.sh`, can play the same runs (#394). The scenario files, the manifest and the
+snapshots stay with the tests and are not shipped to the player.
+
**Invariants.** A hash says something changed; `sim/Statecraft.Sim.Tests/golden/invariants.yaml` says whether it is
still plausible. Each entry names a golden run (`1950` or `1952`), a value (an indicator id, or `treasury`, `debt`,
`fx`, `population`, `stability`), when it is read (`end`, `always`, or a date: the first state on or after it), a `min`
diff --git a/sim/Statecraft.Sim.Tests/GoldenManifestTests.cs b/sim/Statecraft.Sim.Tests/GoldenManifestTests.cs
index 9486e8984..b0483ea17 100644
--- a/sim/Statecraft.Sim.Tests/GoldenManifestTests.cs
+++ b/sim/Statecraft.Sim.Tests/GoldenManifestTests.cs
@@ -14,7 +14,7 @@ public class GoldenManifestTests
public void TheManifestHoldsExactlyTheKnownGoldens()
{
var m = GoldenManifest.Read();
- var scenarios = System.IO.Directory.GetFiles(Scenario.Dir(), "*.yaml").Select(f => "scenario-" + System.IO.Path.GetFileNameWithoutExtension(f));
+ var scenarios = System.IO.Directory.GetFiles(ScenarioTests.Dir(), "*.yaml").Select(f => "scenario-" + System.IO.Path.GetFileNameWithoutExtension(f));
var known = new[] { "hash1950", "hash1952", "smoke5", "mvp-slice" }.Concat(scenarios).OrderBy(k => k, StringComparer.Ordinal).ToArray(); // one line per scenario file (#296)
Assert.Equal(known, m.Keys.OrderBy(k => k, StringComparer.Ordinal).ToArray());
Assert.All(m.Values, h => Assert.Matches("^[0-9a-f]{64}$", h));
@@ -23,7 +23,7 @@ public class GoldenManifestTests
[Fact]
public void EveryScenarioSnapshotHasItsScenarioFile()
{
- var names = System.IO.Directory.GetFiles(Scenario.Dir(), "*.yaml").Select(f => System.IO.Path.GetFileNameWithoutExtension(f)).ToHashSet();
+ var names = System.IO.Directory.GetFiles(ScenarioTests.Dir(), "*.yaml").Select(f => System.IO.Path.GetFileNameWithoutExtension(f)).ToHashSet();
var snapshots = System.IO.Directory.GetFiles(System.IO.Path.Combine(Repo, "sim", "Statecraft.Sim.Tests", "golden"), "scenario-*.txt");
Assert.NotEmpty(snapshots);
foreach (var f in snapshots)
diff --git a/sim/Statecraft.Sim.Tests/MvpGolden.cs b/sim/Statecraft.Sim.Tests/MvpGolden.cs
deleted file mode 100644
index 09f313c0d..000000000
--- a/sim/Statecraft.Sim.Tests/MvpGolden.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using System;
-using Statecraft.Sim;
-
-/// <summary>The GDD slice's golden (spec 2026-10-12 section 3; docs/determinism.md, "MVP goldens"): MvpSlice (the real content
-/// with the loop switch on and monthly turns), the golden seed, Historical mode and HistoricalAI, until Until. It covers only
-/// what is built: no GDD order is issued, so it needs no reference player (decision D-A7, with the owner) and no resolution
-/// order (D-A6).</summary>
-public static class MvpGolden
-{
- /// <summary>Eight monthly turns from 15 May 1948. A test choice, not a balance value.</summary>
- public static readonly DateTime Until = new DateTime(1949, 1, 15);
-
- public static GameState Play(Content c)
- {
- var s = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);
- for (int turn = 0; turn < 1000 && s.Date < Until && s.GameOver == null; turn++)
- s = Simulation.Step(c, s, HistoricalAI.Commands(c, s)).State;
- return s;
- }
-}
diff --git a/sim/Statecraft.Sim.Tests/Scenario.cs b/sim/Statecraft.Sim.Tests/Scenario.cs
deleted file mode 100644
index 9e8a0648f..000000000
--- a/sim/Statecraft.Sim.Tests/Scenario.cs
+++ /dev/null
@@ -1,136 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using Statecraft.Sim;
-using YamlDotNet.Serialization;
-using YamlDotNet.Serialization.NamingConventions;
-
-/// <summary>A golden playthrough with scripted player choices (#296). The two hash goldens use HistoricalAI, so they cover
-/// the path history took; a scenario covers a path a player might take instead. File: sim/Statecraft.Sim.Tests/scenarios/&lt;name&gt;.yaml.
-/// <code>
-/// name: reckless
-/// seed: 1948 # optional, default GoldenRun.Seed
-/// until: 1949-01-01 # the run stops when the date reaches it
-/// steps:
-/// - on: 1948-05-15 # the commands go in on the first turn that starts on or after this date, once
-/// commands:
-/// - { kind: set_policy, policy: rationing, level: 1.0 }
-/// </code>
-/// Kinds: set_policy (policy, level), allocate_budget (shares: {office: share}), choose_event_option (event, option),
-/// set_mobilization (level), security_order (delta), appoint (office, person), map_action (action, q, r). A turn with no
-/// scripted command passes; events nobody answered are delegated, as in the game. A command the sim rejects fails the run.</summary>
-public sealed class Scenario
-{
- public string Name { get; set; } = "";
- public ulong? Seed { get; set; }
- public string Until { get; set; } = "";
- public List<ScenarioStep> Steps { get; set; } = new List<ScenarioStep>();
-
- public static string Dir() =>
- Path.Combine(Directory.GetParent(RealContentTests.ContentRoot())!.FullName, "sim", "Statecraft.Sim.Tests", "scenarios");
-
- public static Scenario Parse(string yaml)
- {
- var d = new DeserializerBuilder().WithNamingConvention(UnderscoredNamingConvention.Instance).Build();
- var s = d.Deserialize<Scenario>(yaml) ?? throw new InvalidDataException("the scenario file is empty");
- if (string.IsNullOrWhiteSpace(s.Name)) throw new InvalidDataException("a scenario needs a name");
- s.UntilDate = Date(s.Until, "until");
- foreach (var step in s.Steps)
- {
- step.OnDate = Date(step.On, "on");
- foreach (var c in step.Commands) step.Built.Add(Build(c));
- }
- return s;
- }
-
- [YamlIgnore] public DateTime UntilDate { get; private set; }
-
- static DateTime Date(string text, string field) =>
- DateTime.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var d) ? d
- : throw new InvalidDataException($"'{field}' must be yyyy-MM-dd, got '{text}'");
-
- static string Str(Dictionary<string, object> c, string key) =>
- c.TryGetValue(key, out var v) && v != null ? Convert.ToString(v, CultureInfo.InvariantCulture)! : throw new InvalidDataException($"command '{c["kind"]}' needs '{key}'");
- static double Num(Dictionary<string, object> c, string key) =>
- double.TryParse(Str(c, key), NumberStyles.Float, CultureInfo.InvariantCulture, out var d) ? d : throw new InvalidDataException($"command '{c["kind"]}': '{key}' must be a number");
-
- /// <summary>The command kinds a scenario can script, with their fields (CommandGuardTests checks every kind is here).</summary>
- static readonly Dictionary<string, string[]> Allowed = new Dictionary<string, string[]>
- {
- ["set_policy"] = new[] { "policy", "level" }, ["allocate_budget"] = new[] { "shares" },
- ["choose_event_option"] = new[] { "event", "option" }, ["set_mobilization"] = new[] { "level" },
- ["security_order"] = new[] { "delta" }, ["appoint"] = new[] { "office", "person" },
- ["map_action"] = new[] { "action", "q", "r" },
- };
-
- public static IReadOnlyCollection<string> Kinds => Allowed.Keys;
- internal static IReadOnlyList<string> FieldsOf(string kind) => Allowed[kind];
-
- internal static Command Build(Dictionary<string, object> c)
- {
- if (!c.ContainsKey("kind")) throw new InvalidDataException("a command needs 'kind'");
- var kind = Str(c, "kind");
- var allowed = Allowed;
- if (!allowed.TryGetValue(kind, out var keys)) throw new InvalidDataException($"unknown command kind '{kind}' (known: {string.Join(", ", allowed.Keys)})");
- var extra = c.Keys.Where(k => k != "kind" && !keys.Contains(k)).ToList();
- if (extra.Count > 0) throw new InvalidDataException($"command '{kind}' has unknown field '{extra[0]}'");
- switch (kind)
- {
- case "set_policy": return new SetPolicy(Str(c, "policy"), Num(c, "level"));
- case "allocate_budget":
- if (!(c.TryGetValue("shares", out var sh) && sh is Dictionary<object, object> map)) throw new InvalidDataException("allocate_budget needs 'shares' as a map");
- return new AllocateBudget(map.ToDictionary(kv => Convert.ToString(kv.Key, CultureInfo.InvariantCulture)!, kv => double.Parse(Convert.ToString(kv.Value, CultureInfo.InvariantCulture)!, CultureInfo.InvariantCulture)));
- case "choose_event_option": return new ChooseEventOption(Str(c, "event"), Str(c, "option"));
- case "set_mobilization": return new SetMobilization(Num(c, "level"));
- case "security_order": return new SecurityOrder(Whole(c, "delta"));
- case "appoint": return new Appoint(Str(c, "office"), Str(c, "person"));
- case "map_action": return new MapAction(Str(c, "action"), Whole(c, "q"), Whole(c, "r"));
- default: throw new InvalidDataException($"command kind '{kind}' has no builder");
- }
- }
-
- /// <summary>A whole number: 1.5 is refused instead of silently becoming 1.</summary>
- static int Whole(Dictionary<string, object> c, string key)
- {
- var v = Num(c, key);
- if (v != Math.Floor(v)) throw new InvalidDataException($"'{key}' must be a whole number, got {v.ToString(CultureInfo.InvariantCulture)}");
- return (int)v;
- }
-
- /// <summary>Plays the scenario and returns the final state. Fails with the date, the order and the sim's reason when a command is rejected.</summary>
- public GameState Play(Content c)
- {
- var s = Simulation.NewGame(c, Seed ?? GoldenRun.Seed, Mode.Historical);
- var pending = Steps.OrderBy(x => x.OnDate).ToList();
- for (int turn = 0; turn < 1000 && s.Date < UntilDate && s.GameOver == null; turn++)
- {
- var now = new List<Command>();
- while (pending.Count > 0 && pending[0].OnDate <= s.Date) { now.AddRange(pending[0].Built); pending.RemoveAt(0); }
- var r = Simulation.Step(c, s, now);
- if (r.Rejected.Count > 0)
- {
- var x = r.Rejected[0];
- throw new InvalidOperationException($"scenario '{Name}': on {s.Date:yyyy-MM-dd} the sim rejected {x.Command.Kind} ({Describe(x.Command)}): {x.Reason}");
- }
- s = r.State;
- }
- if (pending.Count > 0) throw new InvalidOperationException($"scenario '{Name}': the step on {pending[0].On} never ran (the run ends {s.Date:yyyy-MM-dd})");
- return s;
- }
-
- static string Describe(Command c) => c switch
- {
- SetPolicy p => $"{p.Policy} {p.Level}", ChooseEventOption e => $"{e.EventId}/{e.OptionId}", SetMobilization m => m.Level.ToString(CultureInfo.InvariantCulture),
- SecurityOrder o => o.Delta.ToString(CultureInfo.InvariantCulture), Appoint a => $"{a.Office} {a.Person}", MapAction m => $"{m.Action} {m.Q},{m.R}", _ => c.Kind,
- };
-}
-
-public sealed class ScenarioStep
-{
- public string On { get; set; } = "";
- public List<Dictionary<string, object>> Commands { get; set; } = new List<Dictionary<string, object>>();
- [YamlIgnore] public DateTime OnDate { get; set; }
- [YamlIgnore] public List<Command> Built { get; } = new List<Command>();
-}
diff --git a/sim/Statecraft.Sim.Tests/ScenarioTests.cs b/sim/Statecraft.Sim.Tests/ScenarioTests.cs
index b45b95dd7..7497b4e1f 100644
--- a/sim/Statecraft.Sim.Tests/ScenarioTests.cs
+++ b/sim/Statecraft.Sim.Tests/ScenarioTests.cs
@@ -9,14 +9,18 @@ public class ScenarioTests
{
static readonly Content C = ContentLoader.Load(RealContentTests.ContentRoot());
+ /// <summary>sim/Statecraft.Sim.Tests/scenarios, where the scenario files live (the runner, Scenario, is in the sim library).</summary>
+ public static string Dir() =>
+ Path.Combine(Directory.GetParent(RealContentTests.ContentRoot())!.FullName, "sim", "Statecraft.Sim.Tests", "scenarios");
+
public static System.Collections.Generic.IEnumerable<object[]> Files() =>
- Directory.GetFiles(Scenario.Dir(), "*.yaml").OrderBy(f => f, StringComparer.Ordinal).Select(f => new object[] { Path.GetFileNameWithoutExtension(f) });
+ Directory.GetFiles(Dir(), "*.yaml").OrderBy(f => f, StringComparer.Ordinal).Select(f => new object[] { Path.GetFileNameWithoutExtension(f) });
[Theory]
[MemberData(nameof(Files))]
public void ScenarioMatchesItsGolden(string file)
{
- var sc = Scenario.Parse(File.ReadAllText(Path.Combine(Scenario.Dir(), file + ".yaml")));
+ var sc = Scenario.Parse(File.ReadAllText(Path.Combine(Dir(), file + ".yaml")));
Assert.Equal(file, sc.Name);
var s = sc.Play(C);
var name = "scenario-" + sc.Name;
@@ -28,7 +32,7 @@ public class ScenarioTests
[Fact]
public void EachScenarioEndsElsewhereThanTheSameRunWithoutItsChoicesAndThanEveryOtherScenario()
{
- var scenarios = Directory.GetFiles(Scenario.Dir(), "*.yaml").OrderBy(f => f, StringComparer.Ordinal).Select(f => Scenario.Parse(File.ReadAllText(f))).ToList();
+ var scenarios = Directory.GetFiles(Dir(), "*.yaml").OrderBy(f => f, StringComparer.Ordinal).Select(f => Scenario.Parse(File.ReadAllText(f))).ToList();
Assert.True(scenarios.Count >= 2);
var hashes = scenarios.Select(sc => sc.Play(C).Hash()).ToList();
Assert.Equal(hashes.Count, hashes.Distinct().Count());
diff --git a/sim/Statecraft.Sim/MvpGolden.cs b/sim/Statecraft.Sim/MvpGolden.cs
new file mode 100644
index 000000000..0461e3be9
--- /dev/null
+++ b/sim/Statecraft.Sim/MvpGolden.cs
@@ -0,0 +1,22 @@
+using System;
+
+namespace Statecraft.Sim
+{
+ /// <summary>The GDD slice's golden (spec 2026-10-12 section 3; docs/determinism.md, "MVP goldens"): MvpSlice (the real content
+ /// with the loop switch on and monthly turns), the golden seed, Historical mode and HistoricalAI, until Until. It covers only
+ /// what is built: no GDD order is issued, so it needs no reference player (decision D-A7, with the owner) and no resolution
+ /// order (D-A6).</summary>
+ public static class MvpGolden
+ {
+ /// <summary>Eight monthly turns from 15 May 1948. A test choice, not a balance value.</summary>
+ public static readonly DateTime Until = new DateTime(1949, 1, 15);
+
+ public static GameState Play(Content c)
+ {
+ var s = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);
+ for (int turn = 0; turn < 1000 && s.Date < Until && s.GameOver == null; turn++)
+ s = Simulation.Step(c, s, HistoricalAI.Commands(c, s)).State;
+ return s;
+ }
+ }
+}
diff --git a/sim/Statecraft.Sim/Scenario.cs b/sim/Statecraft.Sim/Scenario.cs
new file mode 100644
index 000000000..563631bdf
--- /dev/null
+++ b/sim/Statecraft.Sim/Scenario.cs
@@ -0,0 +1,135 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using YamlDotNet.Serialization;
+using YamlDotNet.Serialization.NamingConventions;
+
+namespace Statecraft.Sim
+{
+ /// <summary>A golden playthrough with scripted player choices (#296). The two hash goldens use HistoricalAI, so they cover
+ /// the path history took; a scenario covers a path a player might take instead. File: sim/Statecraft.Sim.Tests/scenarios/&lt;name&gt;.yaml.
+ /// <code>
+ /// name: reckless
+ /// seed: 1948 # optional, default GoldenRun.Seed
+ /// until: 1949-01-01 # the run stops when the date reaches it
+ /// steps:
+ /// - on: 1948-05-15 # the commands go in on the first turn that starts on or after this date, once
+ /// commands:
+ /// - { kind: set_policy, policy: rationing, level: 1.0 }
+ /// </code>
+ /// Kinds: set_policy (policy, level), allocate_budget (shares: {office: share}), choose_event_option (event, option),
+ /// set_mobilization (level), security_order (delta), appoint (office, person), map_action (action, q, r). A turn with no
+ /// scripted command passes; events nobody answered are delegated, as in the game. A command the sim rejects fails the run.</summary>
+ public sealed class Scenario
+ {
+ public string Name { get; set; } = "";
+ public ulong? Seed { get; set; }
+ public string Until { get; set; } = "";
+ public List<ScenarioStep> Steps { get; set; } = new List<ScenarioStep>();
+
+ public static Scenario Parse(string yaml)
+ {
+ var d = new DeserializerBuilder().WithNamingConvention(UnderscoredNamingConvention.Instance).Build();
+ var s = d.Deserialize<Scenario>(yaml) ?? throw new InvalidDataException("the scenario file is empty");
+ if (string.IsNullOrWhiteSpace(s.Name)) throw new InvalidDataException("a scenario needs a name");
+ s.UntilDate = Date(s.Until, "until");
+ foreach (var step in s.Steps)
+ {
+ step.OnDate = Date(step.On, "on");
+ foreach (var c in step.Commands) step.Built.Add(Build(c));
+ }
+ return s;
+ }
+
+ [YamlIgnore] public DateTime UntilDate { get; private set; }
+
+ static DateTime Date(string text, string field) =>
+ DateTime.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var d) ? d
+ : throw new InvalidDataException($"'{field}' must be yyyy-MM-dd, got '{text}'");
+
+ static string Str(Dictionary<string, object> c, string key) =>
+ c.TryGetValue(key, out var v) && v != null ? Convert.ToString(v, CultureInfo.InvariantCulture)! : throw new InvalidDataException($"command '{c["kind"]}' needs '{key}'");
+ static double Num(Dictionary<string, object> c, string key) =>
+ double.TryParse(Str(c, key), NumberStyles.Float, CultureInfo.InvariantCulture, out var d) ? d : throw new InvalidDataException($"command '{c["kind"]}': '{key}' must be a number");
+
+ /// <summary>The command kinds a scenario can script, with their fields (CommandGuardTests checks every kind is here).</summary>
+ static readonly Dictionary<string, string[]> Allowed = new Dictionary<string, string[]>
+ {
+ ["set_policy"] = new[] { "policy", "level" }, ["allocate_budget"] = new[] { "shares" },
+ ["choose_event_option"] = new[] { "event", "option" }, ["set_mobilization"] = new[] { "level" },
+ ["security_order"] = new[] { "delta" }, ["appoint"] = new[] { "office", "person" },
+ ["map_action"] = new[] { "action", "q", "r" },
+ };
+
+ public static IReadOnlyCollection<string> Kinds => Allowed.Keys;
+ internal static IReadOnlyList<string> FieldsOf(string kind) => Allowed[kind];
+
+ internal static Command Build(Dictionary<string, object> c)
+ {
+ if (!c.ContainsKey("kind")) throw new InvalidDataException("a command needs 'kind'");
+ var kind = Str(c, "kind");
+ var allowed = Allowed;
+ if (!allowed.TryGetValue(kind, out var keys)) throw new InvalidDataException($"unknown command kind '{kind}' (known: {string.Join(", ", allowed.Keys)})");
+ var extra = c.Keys.Where(k => k != "kind" && !keys.Contains(k)).ToList();
+ if (extra.Count > 0) throw new InvalidDataException($"command '{kind}' has unknown field '{extra[0]}'");
+ switch (kind)
+ {
+ case "set_policy": return new SetPolicy(Str(c, "policy"), Num(c, "level"));
+ case "allocate_budget":
+ if (!(c.TryGetValue("shares", out var sh) && sh is Dictionary<object, object> map)) throw new InvalidDataException("allocate_budget needs 'shares' as a map");
+ return new AllocateBudget(map.ToDictionary(kv => Convert.ToString(kv.Key, CultureInfo.InvariantCulture)!, kv => double.Parse(Convert.ToString(kv.Value, CultureInfo.InvariantCulture)!, CultureInfo.InvariantCulture)));
+ case "choose_event_option": return new ChooseEventOption(Str(c, "event"), Str(c, "option"));
+ case "set_mobilization": return new SetMobilization(Num(c, "level"));
+ case "security_order": return new SecurityOrder(Whole(c, "delta"));
+ case "appoint": return new Appoint(Str(c, "office"), Str(c, "person"));
+ case "map_action": return new MapAction(Str(c, "action"), Whole(c, "q"), Whole(c, "r"));
+ default: throw new InvalidDataException($"command kind '{kind}' has no builder");
+ }
+ }
+
+ /// <summary>A whole number: 1.5 is refused instead of silently becoming 1.</summary>
+ static int Whole(Dictionary<string, object> c, string key)
+ {
+ var v = Num(c, key);
+ if (v != Math.Floor(v)) throw new InvalidDataException($"'{key}' must be a whole number, got {v.ToString(CultureInfo.InvariantCulture)}");
+ return (int)v;
+ }
+
+ /// <summary>Plays the scenario and returns the final state. Fails with the date, the order and the sim's reason when a command is rejected.</summary>
+ public GameState Play(Content c)
+ {
+ var s = Simulation.NewGame(c, Seed ?? GoldenRun.Seed, Mode.Historical);
+ var pending = Steps.OrderBy(x => x.OnDate).ToList();
+ for (int turn = 0; turn < 1000 && s.Date < UntilDate && s.GameOver == null; turn++)
+ {
+ var now = new List<Command>();
+ while (pending.Count > 0 && pending[0].OnDate <= s.Date) { now.AddRange(pending[0].Built); pending.RemoveAt(0); }
+ var r = Simulation.Step(c, s, now);
+ if (r.Rejected.Count > 0)
+ {
+ var x = r.Rejected[0];
+ throw new InvalidOperationException($"scenario '{Name}': on {s.Date:yyyy-MM-dd} the sim rejected {x.Command.Kind} ({Describe(x.Command)}): {x.Reason}");
+ }
+ s = r.State;
+ }
+ if (pending.Count > 0) throw new InvalidOperationException($"scenario '{Name}': the step on {pending[0].On} never ran (the run ends {s.Date:yyyy-MM-dd})");
+ return s;
+ }
+
+ static string Describe(Command c) => c switch
+ {
+ SetPolicy p => $"{p.Policy} {p.Level}", ChooseEventOption e => $"{e.EventId}/{e.OptionId}", SetMobilization m => m.Level.ToString(CultureInfo.InvariantCulture),
+ SecurityOrder o => o.Delta.ToString(CultureInfo.InvariantCulture), Appoint a => $"{a.Office} {a.Person}", MapAction m => $"{m.Action} {m.Q},{m.R}", _ => c.Kind,
+ };
+ }
+
+ public sealed class ScenarioStep
+ {
+ public string On { get; set; } = "";
+ public List<Dictionary<string, object>> Commands { get; set; } = new List<Dictionary<string, object>>();
+ [YamlIgnore] public DateTime OnDate { get; set; }
+ [YamlIgnore] public List<Command> Built { get; } = new List<Command>();
+ }
+}
diff --git a/sim/Statecraft.Sim/Statecraft.Sim.csproj b/sim/Statecraft.Sim/Statecraft.Sim.csproj
index f6a70c4e2..abdff5fcd 100644
--- a/sim/Statecraft.Sim/Statecraft.Sim.csproj
+++ b/sim/Statecraft.Sim/Statecraft.Sim.csproj
@@ -7,4 +7,8 @@
<ItemGroup>
<PackageReference Include="YamlDotNet" Version="18.1.0" />
</ItemGroup>
+ <ItemGroup>
+ <!-- Scenario.Build and Scenario.FieldsOf stay internal; CommandGuardTests reads them. -->
+ <InternalsVisibleTo Include="Statecraft.Sim.Tests" />
+ </ItemGroup>
</Project>