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.

feat(sim): turn lengths, deterministic RNG, state hash

eyalgoland24023380e96
diff --git a/sim/Statecraft.Sim.Tests/CoreTests.cs b/sim/Statecraft.Sim.Tests/CoreTests.cs
new file mode 100644
index 000000000..24551987e
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/CoreTests.cs
@@ -0,0 +1,49 @@
+using System;
+using Statecraft.Sim;
+
+public class CoreTests
+{
+ [Theory]
+ [InlineData(TurnLength.Quarter, "1948-08-15")]
+ [InlineData(TurnLength.Month, "1948-06-15")]
+ [InlineData(TurnLength.Week, "1948-05-22")]
+ public void AdvanceMovesDateByTurnLength(TurnLength len, string expected)
+ {
+ var start = new DateTime(1948, 5, 15);
+ Assert.Equal(DateTime.Parse(expected), SimTime.Advance(start, len));
+ }
+
+ [Fact]
+ public void TurnFractionOfYear()
+ {
+ Assert.Equal(0.25, SimTime.YearFraction(TurnLength.Quarter));
+ Assert.Equal(1.0 / 12, SimTime.YearFraction(TurnLength.Month), 10);
+ Assert.Equal(7.0 / 365, SimTime.YearFraction(TurnLength.Week), 10);
+ }
+
+ [Fact]
+ public void RngIsDeterministicForSameSeed()
+ {
+ var a = new Rng(42); var b = new Rng(42);
+ for (int i = 0; i < 100; i++) Assert.Equal(a.NextDouble(), b.NextDouble());
+ }
+
+ [Fact]
+ public void RngValuesAreInUnitInterval()
+ {
+ var r = new Rng(7);
+ for (int i = 0; i < 1000; i++) { var v = r.NextDouble(); Assert.True(v >= 0.0 && v < 1.0, $"NextDouble out of [0,1): {v}"); }
+ }
+
+ [Fact]
+ public void HashIsStableAndSensitiveToState()
+ {
+ var s1 = new GameState { Date = new DateTime(1948, 5, 15), RngState = 1 };
+ s1.Indicators["morale"] = 0.5;
+ var s2 = s1.Clone();
+ Assert.Equal(s1.Hash(), s2.Hash());
+ s2.Indicators["morale"] = 0.6;
+ Assert.NotEqual(s1.Hash(), s2.Hash());
+ Assert.Equal(0.5, s1.Indicators["morale"]); // clone is deep
+ }
+}
diff --git a/sim/Statecraft.Sim/GameState.cs b/sim/Statecraft.Sim/GameState.cs
new file mode 100644
index 000000000..f7f2d2cb3
--- /dev/null
+++ b/sim/Statecraft.Sim/GameState.cs
@@ -0,0 +1,80 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace Statecraft.Sim
+{
+ public enum Mode { Historical, Open }
+
+ /// <summary>All mutable game data. Systems never share references between states: Step works on Clone().</summary>
+ public sealed class GameState
+ {
+ public DateTime Date;
+ public ulong RngState;
+ public Mode Mode;
+ public int Turn;
+ public Dictionary<string, double> Indicators = new Dictionary<string, double>();
+ public Dictionary<string, double> Policies = new Dictionary<string, double>();
+ public Dictionary<string, double> EffectContributions = new Dictionary<string, double>();
+ public SortedSet<string> ActiveSituations = new SortedSet<string>(StringComparer.Ordinal);
+ public Dictionary<string, double> Budget = new Dictionary<string, double>();
+ public double Treasury;
+ public double Debt;
+ public double FxReserves;
+ public Dictionary<string, double> Population = new Dictionary<string, double>();
+ public int Rung = 1;
+ public int CeasefireWeeksLeft;
+ public double Mobilization;
+ public double CoalitionStability = 1.0;
+ public double Attention;
+ public SortedSet<string> FiredEvents = new SortedSet<string>(StringComparer.Ordinal);
+ public List<string> PendingEvents = new List<string>();
+ public string? GameOver;
+
+ public double TotalPopulation => Population.Values.Sum();
+
+ public GameState Clone()
+ {
+ var c = (GameState)MemberwiseClone();
+ c.Indicators = new Dictionary<string, double>(Indicators);
+ c.Policies = new Dictionary<string, double>(Policies);
+ c.EffectContributions = new Dictionary<string, double>(EffectContributions);
+ c.ActiveSituations = new SortedSet<string>(ActiveSituations, StringComparer.Ordinal);
+ c.Budget = new Dictionary<string, double>(Budget);
+ c.Population = new Dictionary<string, double>(Population);
+ c.FiredEvents = new SortedSet<string>(FiredEvents, StringComparer.Ordinal);
+ c.PendingEvents = new List<string>(PendingEvents);
+ return c;
+ }
+
+ /// <summary>SHA-256 over a canonical text form (ordinal-sorted keys, round-trip doubles).</summary>
+ public string Hash()
+ {
+ var sb = new StringBuilder();
+ void Num(string k, double v) => sb.Append(k).Append('=').Append(v.ToString("R", CultureInfo.InvariantCulture)).Append(';');
+ void Map(string name, Dictionary<string, double> m)
+ {
+ sb.Append(name).Append('{');
+ foreach (var kv in m.OrderBy(k => k.Key, StringComparer.Ordinal)) Num(kv.Key, kv.Value);
+ sb.Append('}');
+ }
+ sb.Append(Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).Append(';')
+ .Append(RngState).Append(';').Append(Mode).Append(';').Append(Turn).Append(';');
+ Map("ind", Indicators); Map("pol", Policies); Map("eff", EffectContributions);
+ Map("bud", Budget); Map("pop", Population);
+ sb.Append("sit[").Append(string.Join(",", ActiveSituations)).Append(']');
+ Num("treasury", Treasury); Num("debt", Debt); Num("fx", FxReserves);
+ sb.Append("rung=").Append(Rung).Append(";cf=").Append(CeasefireWeeksLeft).Append(';');
+ Num("mob", Mobilization); Num("stab", CoalitionStability); Num("att", Attention);
+ sb.Append("fired[").Append(string.Join(",", FiredEvents)).Append(']');
+ sb.Append("pending[").Append(string.Join(",", PendingEvents)).Append(']');
+ sb.Append("over=").Append(GameOver ?? "");
+ using var sha = SHA256.Create();
+ var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString()));
+ return string.Concat(bytes.Select(b => b.ToString("x2")));
+ }
+ }
+}
diff --git a/sim/Statecraft.Sim/Rng.cs b/sim/Statecraft.Sim/Rng.cs
new file mode 100644
index 000000000..67ad46112
--- /dev/null
+++ b/sim/Statecraft.Sim/Rng.cs
@@ -0,0 +1,20 @@
+namespace Statecraft.Sim
+{
+ /// <summary>SplitMix64. The whole generator state is one ulong, stored in GameState.</summary>
+ public struct Rng
+ {
+ public ulong State;
+ public Rng(ulong state) { State = state; }
+
+ public ulong NextULong()
+ {
+ ulong z = State += 0x9E3779B97F4A7C15UL;
+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
+ return z ^ (z >> 31);
+ }
+
+ /// <summary>Uniform in [0, 1).</summary>
+ public double NextDouble() => (NextULong() >> 11) * (1.0 / 9007199254740992.0);
+ }
+}
diff --git a/sim/Statecraft.Sim/SimTime.cs b/sim/Statecraft.Sim/SimTime.cs
new file mode 100644
index 000000000..85a773398
--- /dev/null
+++ b/sim/Statecraft.Sim/SimTime.cs
@@ -0,0 +1,24 @@
+using System;
+
+namespace Statecraft.Sim
+{
+ public enum TurnLength { Quarter, Month, Week }
+
+ public static class SimTime
+ {
+ public static DateTime Advance(DateTime date, TurnLength len) => len switch
+ {
+ TurnLength.Quarter => date.AddMonths(3),
+ TurnLength.Month => date.AddMonths(1),
+ _ => date.AddDays(7),
+ };
+
+ /// <summary>Share of a year one turn represents (used to scale yearly rates).</summary>
+ public static double YearFraction(TurnLength len) => len switch
+ {
+ TurnLength.Quarter => 0.25,
+ TurnLength.Month => 1.0 / 12,
+ _ => 7.0 / 365,
+ };
+ }
+}