A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
feat(sim): turn pipeline, commands, historical AI, determinism
eyalgolanf484f104ab9e
diff --git a/sim/Statecraft.Sim.Tests/SimTests.cs b/sim/Statecraft.Sim.Tests/SimTests.csnew file mode 100644index 000000000..fadc969a6--- /dev/null+++ b/sim/Statecraft.Sim.Tests/SimTests.cs@@ -0,0 +1,248 @@+using System;+using System.Collections.Generic;+using System.Linq;+using Statecraft.Sim;++public class SimTests+{+ static readonly Content C = ContentLoader.Load(Fixture.Write());+ static readonly IReadOnlyList<Command> None = new Command[0];++ [Fact]+ public void NewGameStartsAtRulesStartAtWar()+ {+ var s = Simulation.NewGame(C, 42, Mode.Historical);+ Assert.Equal(new DateTime(1948, 5, 15), s.Date);+ Assert.Equal(5, s.Rung);+ Assert.Equal(3, s.Attention);+ Assert.Equal(1000, s.TotalPopulation);+ }++ [Fact]+ public void OpenModeIsNotAvailableYet() =>+ Assert.Throws<NotSupportedException>(() => Simulation.NewGame(C, 1, Mode.Open));++ [Fact]+ public void StepAdvancesByRungTurnLengthAndExplainsItself()+ {+ var s0 = Simulation.NewGame(C, 42, Mode.Historical);+ var r = Simulation.Step(C, s0, None);+ Assert.Equal(new DateTime(1948, 5, 22), r.State.Date); // rung 5 = weekly+ Assert.Equal(1, r.State.Turn);+ Assert.Contains(r.Why, w => w.System == "population");+ Assert.Contains(r.Why, w => w.System == "economy");+ }++ [Fact]+ public void StepDoesNotMutateItsInput()+ {+ var s0 = Simulation.NewGame(C, 42, Mode.Historical);+ var before = s0.Hash();+ Simulation.Step(C, s0, new Command[] { new SetMobilization(1.0) });+ Assert.Equal(before, s0.Hash());+ }++ [Fact]+ public void InvalidCommandsAreRejectedWithReasonsAndAttentionRefunded()+ {+ var s0 = Simulation.NewGame(C, 42, Mode.Historical);+ var r = Simulation.Step(C, s0, new Command[] { new SetPolicy("curfew", 1), new SetMobilization(2) });+ Assert.Equal(new[] { "Unknown policy 'curfew'", "Mobilization must be between 0 and 1" }, r.Rejected.Select(x => x.Reason));+ }++ [Fact]+ public void AttentionLimitsCommandsPerTurn()+ {+ var s0 = Simulation.NewGame(C, 42, Mode.Historical); // attention 3, rung 5 -> each command costs 2+ var r = Simulation.Step(C, s0, new Command[] { new SetMobilization(0.9), new SetMobilization(1.0) });+ Assert.Single(r.Rejected);+ Assert.StartsWith("Not enough attention", r.Rejected[0].Reason);+ }++ [Fact]+ public void SecurityOrderChangesRung()+ {+ var s0 = Simulation.NewGame(C, 42, Mode.Historical);+ var r = Simulation.Step(C, s0, new Command[] { new SecurityOrder(-2) });+ Assert.Equal(3, r.State.Rung);+ Assert.Equal(new DateTime(1948, 8, 15), r.State.Date); // now quarterly+ }++ [Fact]+ public void GameOverRejectsEverything()+ {+ var s0 = Simulation.NewGame(C, 42, Mode.Historical); s0.GameOver = "coalition_collapse";+ var r = Simulation.Step(C, s0, new Command[] { new SecurityOrder(-1) });+ Assert.Equal("The game is over: coalition_collapse", r.Rejected[0].Reason);+ Assert.Equal(s0.Hash(), r.State.Hash());+ }++ [Fact]+ public void SameSeedAndCommandsGiveIdenticalHashes()+ {+ string Play(ulong seed)+ {+ var s = Simulation.NewGame(C, seed, Mode.Historical);+ for (int i = 0; i < 20; i++)+ s = Simulation.Step(C, s, i == 3 ? new Command[] { new SecurityOrder(-3) } : HistoricalAI.Commands(C, s)).State;+ return s.Hash();+ }+ Assert.Equal(Play(7), Play(7));+ Assert.NotEqual(Play(7), Play(8));+ }++ // ---- Beyond the brief: post-H1 rules and robustness ----++ const string Shortage = @"+id: shortage+title: Bread lines+text: '{finance_minister} reports shortages.'+office: finance_minister+from: 1948-05-15+options:+ - id: ration+ text: Ration food+ recommended: true+ effects:+ - target: food_supply+ delta: 0.2+ - id: import+ text: Buy abroad+ historical: true+ effects:+ - target: fx_reserves+ delta: -10+";++ const string Raid = @"+id: raid+title: Border raid+text: 'A raid on the border.'+office: defense_minister+from: 1948-05-15+options:+ - id: hold+ text: Hold the line+ effects:+ - target: morale+ delta: -0.05+ - id: strike+ text: Strike back+ effects:+ - target: morale+ delta: 0.05+";++ static Content WithEvents() =>+ ContentLoader.Load(Fixture.Write(events: new Dictionary<string, string> { ["shortage.yaml"] = Shortage, ["raid.yaml"] = Raid }));++ sealed class Bogus : Command { public override string Kind => "bogus"; }++ [Fact]+ public void UnknownCommandKindIsRejectedNotThrown()+ {+ var s0 = Simulation.NewGame(C, 42, Mode.Historical);+ var r = Simulation.Step(C, s0, new Command[] { new Bogus(), new SetMobilization(1.0) });+ Assert.Equal(new[] { "Unknown command 'bogus'" }, r.Rejected.Select(x => x.Reason));+ Assert.Equal(1.0, r.State.Mobilization); // the bogus command cost no attention+ }++ [Fact]+ public void PolicyLevelMustBeFinite()+ {+ var s0 = Simulation.NewGame(C, 42, Mode.Historical);+ var r = Simulation.Step(C, s0, new Command[] { new SetPolicy("rationing", double.NaN) });+ Assert.Equal("Policy level must be between 0 and 1", r.Rejected.Single().Reason);+ Assert.Equal(0.0, r.State.Policies["rationing"]);+ }++ [Fact]+ public void PolicyPassesWithAMajority()+ {+ var s0 = Simulation.NewGame(C, 42, Mode.Historical); // council: alpha holds 3 of 5+ var r = Simulation.Step(C, s0, new Command[] { new SetPolicy("rationing", 0.5) });+ Assert.Empty(r.Rejected);+ Assert.Equal(0.5, r.State.Policies["rationing"]);+ Assert.Contains(r.Why, w => w.System == "policy" && w.Message == "rationing set to 0.50");+ }++ [Fact]+ public void PartialBudgetIsRejectedWithEconomyReason()+ {+ var s0 = Simulation.NewGame(C, 42, Mode.Historical);+ var r = Simulation.Step(C, s0, new Command[] { new AllocateBudget(new Dictionary<string, double> { ["defense_minister"] = 1.0 }) });+ Assert.Equal("Budget shares must cover exactly: finance_minister", r.Rejected.Single().Reason);+ Assert.Equal(1.0, r.State.Budget["finance_minister"]);+ }++ [Fact]+ public void MalformedBudgetIsRejectedBeforeAnyVoteIsCast()+ {+ var s0 = Simulation.NewGame(C, 42, Mode.Historical);+ s0.Date = new DateTime(1949, 4, 1); // House needs to approve budgets; gov2 holds 10/10+ s0.CoalitionStability = 0.3; // so a vote would draw from the RNG+ var r = Simulation.Step(C, s0, new Command[] { new AllocateBudget(new Dictionary<string, double> { ["finance_minister"] = 0.7 }) });+ Assert.Equal("Budget shares must sum to 1", r.Rejected.Single().Reason);+ Assert.Equal(s0.RngState, r.State.RngState);+ }++ [Fact]+ public void BudgetVoteFailsWithoutAMajority()+ {+ var s0 = Simulation.NewGame(C, 42, Mode.Historical);+ s0.Date = new DateTime(1949, 3, 1); // House sits, gov1 (alpha, 4 of 10) has no majority+ var r = Simulation.Step(C, s0, new Command[] { new AllocateBudget(new Dictionary<string, double> { ["finance_minister"] = 1.0 }) });+ Assert.Equal("House voted the budget down", r.Rejected.Single().Reason);+ }++ [Fact]+ public void SecurityOrderDoesNotOverflow()+ {+ var s0 = Simulation.NewGame(C, 42, Mode.Historical);+ var r = Simulation.Step(C, s0, new Command[] { new SecurityOrder(int.MaxValue) });+ Assert.Empty(r.Rejected);+ Assert.Equal(5, r.State.Rung);+ }++ [Fact]+ public void HistoricalAIChoosesTheHistoricalOption()+ {+ var c = WithEvents();+ var s = Simulation.NewGame(c, 42, Mode.Historical);+ Assert.Equal(new[] { "raid", "shortage" }, s.PendingEvents);+ var cmds = HistoricalAI.Commands(c, s).Cast<ChooseEventOption>().ToList();+ Assert.Equal(new[] { ("raid", "hold"), ("shortage", "import") }, cmds.Select(x => (x.EventId, x.OptionId)));+ }++ [Fact]+ public void UnaffordableEventChoicesAreDelegated()+ {+ var c = WithEvents();+ var s0 = Simulation.NewGame(c, 42, Mode.Historical);+ var r = Simulation.Step(c, s0, HistoricalAI.Commands(c, s0)); // 3 attention, each choice costs 2+ Assert.StartsWith("Not enough attention", r.Rejected.Single().Reason);+ Assert.Empty(r.State.PendingEvents);+ Assert.Contains(r.Why, w => w.System == "events" && w.Message.StartsWith("chosen: "));+ Assert.Contains(r.Why, w => w.System == "events" && w.Message.StartsWith("delegated to Def Two"));+ }++ [Fact]+ public void DeterministicWithEventsAndDelegation()+ {+ var c = WithEvents();+ (string hash, string why) Play(ulong seed)+ {+ var s = Simulation.NewGame(c, seed, Mode.Historical);+ var lines = new List<string>();+ for (int i = 0; i < 20; i++)+ {+ var r = Simulation.Step(c, s, i % 2 == 0 ? None : HistoricalAI.Commands(c, s));+ lines.AddRange(r.Why.Select(w => w.ToString()));+ s = r.State;+ }+ return (s.Hash(), string.Join("\n", lines));+ }+ Assert.Equal(Play(11), Play(11));+ Assert.NotEqual(Play(11).hash, Play(12).hash);+ }+}diff --git a/sim/Statecraft.Sim/Commands.cs b/sim/Statecraft.Sim/Commands.csnew file mode 100644index 000000000..6caacd7ac--- /dev/null+++ b/sim/Statecraft.Sim/Commands.cs@@ -0,0 +1,57 @@+using System.Collections.Generic;++namespace Statecraft.Sim+{+ /// <summary>A player (or AI) order for one turn. Kind keys rules.yaml attention_cost (see AttentionSystem.CommandKinds).</summary>+ public abstract class Command { public abstract string Kind { get; } }++ public sealed class SetPolicy : Command+ {+ public override string Kind => "set_policy";+ public string Policy { get; } public double Level { get; }+ public SetPolicy(string policy, double level) { Policy = policy; Level = level; }+ }++ /// <summary>Shares must cover exactly the offices in rules.yaml budget_start and sum to 1.</summary>+ public sealed class AllocateBudget : Command+ {+ public override string Kind => "allocate_budget";+ public Dictionary<string, double> Shares { get; }+ public AllocateBudget(Dictionary<string, double> shares) { Shares = shares; }+ }++ public sealed class ChooseEventOption : Command+ {+ public override string Kind => "choose_event_option";+ public string EventId { get; } public string OptionId { get; }+ public ChooseEventOption(string eventId, string optionId) { EventId = eventId; OptionId = optionId; }+ }++ public sealed class SetMobilization : Command+ {+ public override string Kind => "set_mobilization";+ public double Level { get; }+ public SetMobilization(double level) { Level = level; }+ }++ public sealed class SecurityOrder : Command+ {+ public override string Kind => "security_order";+ public int Delta { get; }+ public SecurityOrder(int delta) { Delta = delta; }+ }++ public sealed class Rejection+ {+ public Command Command { get; } public string Reason { get; }+ public Rejection(Command command, string reason) { Command = command; Reason = reason; }+ }++ public sealed class StepResult+ {+ public GameState State { get; }+ public IReadOnlyList<Cause> Why { get; }+ public IReadOnlyList<Rejection> Rejected { get; }+ public StepResult(GameState state, IReadOnlyList<Cause> why, IReadOnlyList<Rejection> rejected) { State = state; Why = why; Rejected = rejected; }+ }+}diff --git a/sim/Statecraft.Sim/HistoricalAI.cs b/sim/Statecraft.Sim/HistoricalAI.csnew file mode 100644index 000000000..4cd893b8e--- /dev/null+++ b/sim/Statecraft.Sim/HistoricalAI.cs@@ -0,0 +1,16 @@+using System.Collections.Generic;+using System.Linq;++namespace Statecraft.Sim+{+ /// <summary>Plays what really happened: picks each pending event's historical option (else its first).+ /// It sends no budget allocation, so the budget stays at rules.yaml budget_start.</summary>+ public static class HistoricalAI+ {+ public static IReadOnlyList<Command> Commands(Content c, GameState s) =>+ s.PendingEvents+ .Select(id => c.Events.First(e => e.Id == id))+ .Select(e => (Command)new ChooseEventOption(e.Id, (e.Options.FirstOrDefault(o => o.Historical) ?? e.Options[0]).Id))+ .ToList();+ }+}diff --git a/sim/Statecraft.Sim/Simulation.cs b/sim/Statecraft.Sim/Simulation.csnew file mode 100644index 000000000..c55eb76f5--- /dev/null+++ b/sim/Statecraft.Sim/Simulation.cs@@ -0,0 +1,115 @@+using System;+using System.Collections.Generic;+using System.Linq;++namespace Statecraft.Sim+{+ /// <summary>The public entry point the Unity layer calls: start a game, then step it one turn at a time.</summary>+ public static class Simulation+ {+ public static GameState NewGame(Content c, ulong seed, Mode mode)+ {+ if (c == null) throw new ArgumentNullException(nameof(c));+ if (mode == Mode.Open) throw new NotSupportedException("Open mode arrives with milestone M4.");+ var s = new GameState { Date = c.Rules.Start, RngState = seed, Mode = mode };+ var why = new List<Cause>();+ EffectsSystem.Init(c, s);+ EconomySystem.Init(c, s);+ PopulationSystem.Init(c, s);+ SecuritySystem.Init(c, s, why);+ AttentionSystem.Refill(c, s);+ EventSystem.Trigger(c, s, why);+ return s;+ }++ /// <summary>Applies commands in order (each pays attention first; a rejected command is refunded and carries a+ /// reason), delegates unanswered events, then advances one turn. Never mutates <paramref name="state"/>.</summary>+ public static StepResult Step(Content c, GameState state, IReadOnlyList<Command> commands)+ {+ if (c == null) throw new ArgumentNullException(nameof(c));+ if (state == null) throw new ArgumentNullException(nameof(state));+ if (commands == null) throw new ArgumentNullException(nameof(commands));+ if (commands.Any(x => x == null)) throw new ArgumentException("Commands cannot contain null.", nameof(commands));++ var s = state.Clone();+ var why = new List<Cause>();+ var rejected = new List<Rejection>();+ if (s.GameOver != null)+ {+ foreach (var cmd in commands) rejected.Add(new Rejection(cmd, $"The game is over: {s.GameOver}"));+ return new StepResult(s, why, rejected);+ }++ foreach (var cmd in commands)+ {+ if (!AttentionSystem.IsCommandKind(cmd.Kind)) { rejected.Add(new Rejection(cmd, $"Unknown command '{cmd.Kind}'")); continue; }+ var before = s.Attention;+ var error = AttentionSystem.TrySpend(c, s, cmd.Kind) ?? Execute(c, s, cmd, why);+ if (error != null) { s.Attention = before; rejected.Add(new Rejection(cmd, error)); }+ }+ EventSystem.Delegate(c, s, why);++ var len = SecuritySystem.TurnLengthFor(s.Rung);+ var next = SimTime.Advance(s.Date, len);+ var yf = SimTime.YearFraction(len);+ EffectsSystem.Apply(c, s, why);+ PopulationSystem.Apply(c, s, next, yf, why);+ EconomySystem.Apply(c, s, yf, why);+ PoliticsSystem.UpdateStability(c, s, yf, why);+ SecuritySystem.Apply(c, s, len, why);+ PoliticsSystem.ReportChanges(c, s.Date, next, why);+ s.Date = next;+ s.Turn++;+ AttentionSystem.Refill(c, s);+ EventSystem.Trigger(c, s, why);+ return new StepResult(s, why, rejected);+ }++ /// <summary>Returns null on success, or the reason the command was rejected. A rejected command leaves the+ /// state as it found it (attention is refunded by the caller).</summary>+ static string? Execute(Content c, GameState s, Command cmd, List<Cause> why)+ {+ switch (cmd)+ {+ case SetPolicy p:+ if (c.Policies.All(x => x.Id != p.Policy)) return $"Unknown policy '{p.Policy}'";+ if (!(p.Level >= 0 && p.Level <= 1)) return "Policy level must be between 0 and 1";+ if (!PassVote(c, s)) return $"{Offices.Legislature(c, s.Date)?.Body ?? "The legislature"} voted it down";+ s.Policies[p.Policy] = p.Level;+ why.Add(new Cause("policy", p.Policy, p.Level, FormattableString.Invariant($"{p.Policy} set to {p.Level:0.00}")));+ return null;+ case AllocateBudget b:+ {+ // Validate before voting, so a malformed allocation neither draws from the RNG nor blames the legislature.+ var old = s.Budget;+ var invalid = EconomySystem.Allocate(c, s, b.Shares);+ if (invalid != null) return invalid;+ if (PoliticsSystem.BudgetNeedsVote(c, s.Date) && !PassVote(c, s))+ {+ s.Budget = old;+ return $"{Offices.Legislature(c, s.Date)!.Body} voted the budget down";+ }+ return null;+ }+ case ChooseEventOption e:+ return EventSystem.Choose(c, s, e.EventId, e.OptionId, why);+ case SetMobilization m:+ return SecuritySystem.SetMobilization(c, s, m.Level, why);+ case SecurityOrder o:+ // long arithmetic: an extreme delta clamps to the ladder's end instead of wrapping around.+ SecuritySystem.SetRung(c, s, (int)Math.Max(1L, Math.Min(5L, (long)s.Rung + o.Delta)), why);+ return null;+ default:+ return $"Unknown command '{cmd.Kind}'";+ }+ }++ static bool PassVote(Content c, GameState s)+ {+ var rng = new Rng(s.RngState);+ var passed = PoliticsSystem.Vote(c, s, ref rng);+ s.RngState = rng.State;+ return passed;+ }+ }+}