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.

27.5 KB
Raw Blame
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Statecraft.Sim
{
    /// <summary>The stable codes <see cref="GameState.GameOver"/> can hold (they are in the state hash).</summary>
    public static class GameOverCodes
    {
        /// <summary>The last era's end was reached (eras.yaml).</summary>
        public const string EraEnded = "era_ended";
        /// <summary>The GDD game's last day was reached (rules.yaml mvp.end, R-LOOP-004).</summary>
        public const string MvpEnded = "mvp_ended";
        public const string CoalitionCollapse = "coalition_collapse";
        /// <summary>Money and Food were both exhausted for mvp.defeat_turns turn ends in a row (R-END-002; D-B5).</summary>
        public const string DefeatEconomy = "defeat_economy";
        /// <summary>An enemy military unit holds a GDD city's hex at the turn's end (R-END-003; Q-WAR-5, Q-DEF-3).</summary>
        public const string DefeatWar = "defeat_war";
    }

    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
    {
        /// <summary>Immutable replay identity. Old manually constructed states retain their historical hash layout.</summary>
        public string Ruleset { get; } = SaveGame.LegacyRuleset;
        readonly bool usesAttention = true;
        public bool UsesPopulationLedger => Ruleset == SaveGame.Gdd03Ruleset;
        public PopulationLedger PopulationLedger { get; private set; } = new PopulationLedger(false);
        SortedDictionary<string, PlayerRegionPool> playerRegions = new SortedDictionary<string, PlayerRegionPool>(StringComparer.Ordinal);
        PlayerRegionCatalogue playerGeography = PlayerRegionCatalogue.Empty;
        public IReadOnlyDictionary<string, PlayerRegionPool> PlayerRegions =>
            new System.Collections.ObjectModel.ReadOnlyDictionary<string, PlayerRegionPool>(playerRegions);
        internal void InitializePlayerRegions(PlayerRegionCatalogue geography, SortedDictionary<string, PlayerRegionPool> pools)
        {
            if (!UsesPopulationLedger || !PopulationLedger.IsInitialized || playerRegions.Count != 0)
                throw new InvalidOperationException("Regional state needs an initialized gdd-0.3 fixture ledger.");
            playerGeography = geography;
            playerRegions = new SortedDictionary<string, PlayerRegionPool>(pools, StringComparer.Ordinal);
        }
        public GameState() { }
        internal GameState(Content c)
        {
            Ruleset = c.Ruleset; usesAttention = c.UsesAttention;
            PopulationLedger = new PopulationLedger(UsesPopulationLedger);
        }
        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>();
        /// <summary>Permanent per-indicator offsets from event choices, added on top of base and effects.</summary>
        public Dictionary<string, double> IndicatorShifts = 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>();
        /// <summary>Soft events that were eligible but found no slot, by id (R-EVT-001). They remain here until they fire.</summary>
        public SortedSet<string> CappedEvents = new SortedSet<string>(StringComparer.Ordinal);
        /// <summary>R-ENEMY-007 (owner, 7 November 2026: "Keep the option (Recommended)", "Wait, with a limit (Recommended)"): each
        /// pending operation card a delegation postponed, by id: the option it was postponed with, which later delegations
        /// keep instead of drawing again, and the turn of its first postponement, from which its wait is counted.</summary>
        public SortedDictionary<string, PostponedOperation> PostponedOperations = new SortedDictionary<string, PostponedOperation>(StringComparer.Ordinal);
        /// <summary>The option each resolved event was resolved with (chosen or delegated), for events' `requires`.</summary>
        public Dictionary<string, string> ChosenOptions = new Dictionary<string, string>();
        /// <summary>Player appointments by office id; valid while the government in AppointedUnder is in office (Cabinet).</summary>
        public Dictionary<string, Appointment> Appointments = new Dictionary<string, Appointment>();
        public string AppointedUnder = "";
        /// <summary>Map actions built so far, in order (MapActions).</summary>
        public List<Placement> Placements = new List<Placement>();
        /// <summary>The turn (its date) the map-action counter belongs to, and the actions accepted in it. Counted on
        /// acceptance, so replacing a camp with housing cannot reopen the per-turn cap; a new date starts from zero.</summary>
        public DateTime MapActionsTurnDate;
        public int MapActionsThisTurn;
        /// <summary>R-PROJ-001 under gdd-0.3 only (#1700 slice B): the city projects each city started in the turn of
        /// <see cref="MapActionsTurnDate"/>, by city id (ordinal), counted on acceptance. Read only while that date is the
        /// turn's, and cleared when a start or map action moves it on, as MapActionsThisTurn is reset. Empty under every
        /// other ruleset, and then left out of the hash.</summary>
        public SortedDictionary<string, int> CityStartsThisTurn = new SortedDictionary<string, int>(StringComparer.Ordinal);
        /// <summary>Why the game ended, as one of the <see cref="GameOverCodes"/>; null while it is on. Never display it: use PlayerText.GameOver.</summary>
        public string? GameOver;
        // GDD v0.1 state (spec 2026-10-12 section 2.2). Empty in the legacy loop, and then left out of the hash (R-LOOP-002).
        /// <summary>The cities by id (ordinal).</summary>
        public SortedDictionary<string, City> Cities = new SortedDictionary<string, City>(StringComparer.Ordinal);
        /// <summary>The movable units by id.</summary>
        public SortedList<int, Unit> Units = new SortedList<int, Unit>();
        /// <summary>The groups in training by id (R-TRAIN-001). A cohort leaves when it finishes or is cancelled.</summary>
        public SortedList<int, Cohort> Cohorts = new SortedList<int, Cohort>();
        /// <summary>The designated sites being built or built, by site id (ordinal; R-SITE-001). An available site has no record.</summary>
        public SortedDictionary<string, SiteWork> Sites = new SortedDictionary<string, SiteWork>(StringComparer.Ordinal);
        /// <summary>The city projects being built or built, by id (R-PROJ-001). A cancelled project leaves.</summary>
        public SortedList<int, CityProject> CityProjects = new SortedList<int, CityProject>();
        /// <summary>R-ARMS-005, R-ARMS-006 (gdd-0.3 only): the built arms workshops ever staffed, by their city project's id. A
        /// workshop never staffed has no record; one unstaffed keeps its record, its paid cost and its progress.</summary>
        public SortedList<int, Workshop> Workshops = new SortedList<int, Workshop>();
        /// <summary>The corridors with a segment being built or built, by corridor id (ordinal; R-COR-001). A corridor with no
        /// started segment has no record.</summary>
        public SortedDictionary<string, CorridorWork> Corridors = new SortedDictionary<string, CorridorWork>(StringComparer.Ordinal);
        /// <summary>The locked projects.yaml kinds an event option has unlocked (R-EFX-008), by id (ordinal).</summary>
        public SortedSet<string> UnlockedProjects = new SortedSet<string>(StringComparer.Ordinal);
        /// <summary>The units whose go-to an operation card gave (R-ENEMY-005), by unit id, each with the day the order ends: the
        /// end of the window of the anchor it goes to (the owner's answer 1 on #2087, "Orders expire with the operation").</summary>
        public SortedDictionary<int, DateTime> CardOrders = new SortedDictionary<int, DateTime>();
        /// <summary>The next id a new unit, training cohort or city project takes (they share it). Ids are never reused.</summary>
        public int NextId;
        /// <summary>The date each completed objective was completed, by objective id (ordinal).</summary>
        public SortedDictionary<string, DateTime> Objectives = new SortedDictionary<string, DateTime>(StringComparer.Ordinal);
        /// <summary>Settlement control by target id, ordinal (R-CTRL-002).</summary>
        public SortedDictionary<string, SettlementControl> Settlements = new SortedDictionary<string, SettlementControl>(StringComparer.Ordinal);
        /// <summary>The player's score (GDD "Objectives": bonus points). An int: the point values (D-B6) and the timing bonus (D-B2)
        /// the owner set on 14 October 2026 (#456) are whole numbers (R-OBJ-002).</summary>
        public int Score;
        /// <summary>The parts of <see cref="Score"/> (R-SCORE-001; Q-SCORE-1), each added when it scores, so no reading has to
        /// rebuild them from rules that may have changed since: objective base points (R-OBJ-002, R-OBJ-006), timing bonuses
        /// (R-OBJ-002, R-OBJ-005) and points for prisoners returned (R-POW-004). Their sum is <see cref="Score"/>.</summary>
        public int ScoreObjectivePoints, ScoreTimingBonuses, ScorePrisonerPoints;
        /// <summary>The national Food stock (R-FOOD-001; D-C2): units of Food, one population unit's food for a month. Never below 0.</summary>
        public int Food;
        /// <summary>The Food the nation needed in the last turn (R-FOOD-002): its population in units, set at the start and in step 7.</summary>
        public int FoodNeed;
        /// <summary>The part of <see cref="FoodNeed"/> the stock could not cover in the last turn (R-FOOD-002, Q-POOL-5).</summary>
        public int FoodUnmet;
        /// <summary>Consecutive turn ends with Money and Food both exhausted (R-END-001, R-END-002); 0 when either was not.</summary>
        public int ExhaustedTurns;
        /// <summary>The national Arms stock (R-ARMS-001; D-G6): one Arms is the equipment package for one 1,000-person recruit group. Never below 0.</summary>
        public int Arms;
        /// <summary>The foreign currency converted into Money so far, in US$ millions (R-MONEY-004, #813): never more than
        /// mvp.dollars_total.</summary>
        public int DollarsConverted;
        /// <summary>The enemy prisoners held, in population units, by the side of the unit that surrendered (R-POW-001; impact
        /// plan section 4.3). Only a surrender in combat adds to it; only a front's exchange card takes from it (R-POW-004).</summary>
        public SortedDictionary<string, int> PrisonersHeld = new SortedDictionary<string, int>(StringComparer.Ordinal);
        /// <summary>The prisoners returned so far, in population units, by side (R-POW-004).</summary>
        public SortedDictionary<string, int> PrisonersReturned = new SortedDictionary<string, int>(StringComparer.Ordinal);
        /// <summary>The player's soldiers held by the enemy, in population units, by the side that took them (R-POW-005; Q-POW-4).</summary>
        public SortedDictionary<string, int> SoldiersHeld = new SortedDictionary<string, int>(StringComparer.Ordinal);
        /// <summary>R-WAR-005, under exact gdd-0.3 only: each front's consecutive quiet turns (Q48), set at every turn end;
        /// R-WAR-006 sets a front to 0 on a refused armistice. Empty under every other ruleset.</summary>
        public SortedDictionary<string, int> QuietTurns = new SortedDictionary<string, int>(StringComparer.Ordinal);
        /// <summary>R-WAR-005: the fronts with a unit in an engagement this turn, instant attacks included, and a front whose armistice was refused this turn (R-WAR-006, Q49); cleared at the turn end.</summary>
        public SortedSet<string> EngagedFronts = new SortedSet<string>(StringComparer.Ordinal);
        /// <summary>The places the player has deported, the permanent record of R-CTRL-018 and R-CTRL-019: a count of places,
        /// not people (Q-CAP-2 (b)), with no destination on the board (Q-DEP-3 (a)).</summary>
        public int DisplacedByPlayer;

        public double TotalPopulation => PopulationLedger.IsInitialized
            ? PopulationLedger.TotalPeople
            // R-FOOD-001: in ordinal key order, since .NET does not promise a Dictionary's enumeration order and the sum feeds the economy's per-capita tax and spending (EconomySystem), which is what moves the hashed debt and fx.
            : Population.OrderBy(kv => kv.Key, StringComparer.Ordinal).Sum(kv => kv.Value);

        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.IndicatorShifts = new Dictionary<string, double>(IndicatorShifts);
            c.ActiveSituations = new SortedSet<string>(ActiveSituations, StringComparer.Ordinal);
            c.Budget = new Dictionary<string, double>(Budget);
            c.Population = new Dictionary<string, double>(Population);
            c.PopulationLedger = PopulationLedger.Clone();
            // Pool records, facilities and geography are immutable; only the owning collection needs a copy.
            c.playerRegions = new SortedDictionary<string, PlayerRegionPool>(playerRegions, StringComparer.Ordinal);
            c.FiredEvents = new SortedSet<string>(FiredEvents, StringComparer.Ordinal);
            c.PendingEvents = new List<string>(PendingEvents);
            c.CappedEvents = new SortedSet<string>(CappedEvents, StringComparer.Ordinal);
            c.PostponedOperations = new SortedDictionary<string, PostponedOperation>(PostponedOperations, StringComparer.Ordinal);
            c.ChosenOptions = new Dictionary<string, string>(ChosenOptions);
            c.Appointments = new Dictionary<string, Appointment>(Appointments);
            c.Placements = new List<Placement>(Placements);
            c.Cities = new SortedDictionary<string, City>(Cities, StringComparer.Ordinal);
            c.Units = new SortedList<int, Unit>(Units);
            c.Cohorts = new SortedList<int, Cohort>(Cohorts);
            c.Sites = new SortedDictionary<string, SiteWork>(Sites, StringComparer.Ordinal);
            c.CityProjects = new SortedList<int, CityProject>(CityProjects);
            c.CityStartsThisTurn = new SortedDictionary<string, int>(CityStartsThisTurn, StringComparer.Ordinal);
            c.Workshops = new SortedList<int, Workshop>(Workshops);
            c.Corridors = new SortedDictionary<string, CorridorWork>(Corridors, StringComparer.Ordinal);
            c.UnlockedProjects = new SortedSet<string>(UnlockedProjects, StringComparer.Ordinal);
            c.CardOrders = new SortedDictionary<int, DateTime>(CardOrders);
            c.Objectives = new SortedDictionary<string, DateTime>(Objectives, StringComparer.Ordinal);
            c.Settlements = new SortedDictionary<string, SettlementControl>(Settlements, StringComparer.Ordinal);
            c.PrisonersHeld = new SortedDictionary<string, int>(PrisonersHeld, StringComparer.Ordinal);
            c.PrisonersReturned = new SortedDictionary<string, int>(PrisonersReturned, StringComparer.Ordinal);
            c.SoldiersHeld = new SortedDictionary<string, int>(SoldiersHeld, StringComparer.Ordinal);
            c.QuietTurns = new SortedDictionary<string, int>(QuietTurns, StringComparer.Ordinal);
            c.EngagedFronts = new SortedSet<string>(EngagedFronts, StringComparer.Ordinal);
            return c;
        }

        /// <summary>SHA-256 over a canonical text form (ordinal-sorted keys, doubles as IEEE bit patterns with -0.0
        /// written as 0.0), so hashes match across .NET, Mono and IL2CPP.</summary>
        public string Hash()
        {
            using var sha = SHA256.Create();
            var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(CanonicalText(false)));
            return string.Concat(bytes.Select(b => b.ToString("x2", CultureInfo.InvariantCulture)));
        }

        /// <summary>The state in the order and form <see cref="Hash"/> hashes it, one line per section, with each number
        /// also written as a plain value (`name=1.5 [3FF8000000000000]`). For humans: a golden-hash failure diffs this
        /// (issue #256). It shares one writer with <see cref="Hash"/>, so the two cannot list different fields.</summary>
        public string Describe() => CanonicalText(true);

        string CanonicalText(bool readable)
        {
            // Hash text: one line, ';'-separated, closing brackets. Readable text: a section label per line, each entry
            // on its own indented line, no closing brackets. Both are written by the calls below, in the same order.
            var sb = new StringBuilder();
            if (!usesAttention) sb.Append("ruleset=").Append(Ruleset).Append(';');
            void Nl() { if (readable) sb.Append('\n'); }
            void Entry() { if (readable) sb.Append("\n  "); }
            void Close(char c) { if (!readable) sb.Append(c); }
            void Num(string k, double v, bool inMap = false)
            {
                var bits = BitConverter.DoubleToInt64Bits(v == 0.0 ? 0.0 : v).ToString("X16", CultureInfo.InvariantCulture);
                if (readable) sb.Append(inMap ? "\n  " : "\n").Append(k).Append('=').Append((v == 0.0 ? 0.0 : v).ToString("R", CultureInfo.InvariantCulture)).Append(" [").Append(bits).Append(']');
                else sb.Append(k).Append('=').Append(bits).Append(';');
            }
            void Map(string name, Dictionary<string, double> m)
            {
                Nl(); sb.Append(name).Append('{');
                foreach (var kv in m.OrderBy(k => k.Key, StringComparer.Ordinal)) Num(kv.Key, kv.Value, true);
                Close('}');
            }
            void List(string name, IEnumerable<string> items)
            {
                Nl(); sb.Append(name).Append('[');
                if (readable) foreach (var i in items) { Entry(); sb.Append(i); }
                else sb.Append(string.Join(",", items));
                Close(']');
            }
            void Sep() { if (!readable) sb.Append(';'); }
            sb.Append(Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).Append(';')
              .Append(RngState.ToString(CultureInfo.InvariantCulture)).Append(';').Append(Mode).Append(';').Append(Turn.ToString(CultureInfo.InvariantCulture)).Append(';');
            Map("ind", Indicators); Map("pol", Policies); Map("eff", EffectContributions); Map("shift", IndicatorShifts);
            Map("bud", Budget); Map("pop", Population);
            List("sit", ActiveSituations);
            Num("treasury", Treasury); Num("debt", Debt); Num("fx", FxReserves);
            Nl(); sb.Append("rung=").Append(Rung.ToString(CultureInfo.InvariantCulture)).Append(";cf=").Append(CeasefireWeeksLeft.ToString(CultureInfo.InvariantCulture)).Append(';');
            Num("mob", Mobilization); Num("stab", CoalitionStability); if (usesAttention) Num("att", Attention);
            List("fired", FiredEvents);
            List("pending", PendingEvents);
            // R-EVT-001: absent when no event has waited for the cap, so all existing golden hashes stay byte-for-byte stable.
            if (CappedEvents.Count > 0) Section("capped", '[', ']', CappedEvents);
            // R-ENEMY-007: absent while no operation waits, as `capped`, so a run that postpones none hashes as before.
            if (PostponedOperations.Count > 0)
                Section("postponed", '{', '}', PostponedOperations.Select(kv => kv.Key + "=" + kv.Value.Option + "@" + kv.Value.Turn.ToString(CultureInfo.InvariantCulture)
                    + "@" + kv.Value.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
            Nl(); sb.Append("chosen{");
            foreach (var kv in ChosenOptions.OrderBy(k => k.Key, StringComparer.Ordinal)) { Entry(); sb.Append(kv.Key).Append('=').Append(kv.Value); Sep(); }
            Close('}');
            Nl(); sb.Append("appt{");
            foreach (var kv in Appointments.OrderBy(k => k.Key, StringComparer.Ordinal))
            {
                Entry(); sb.Append(kv.Key).Append('=').Append(kv.Value.Person).Append('@').Append(kv.Value.From.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); Sep();
            }
            Close('}');
            Nl(); sb.Append("under=").Append(AppointedUnder).Append(';');
            Nl(); sb.Append("map[");
            foreach (var p in Placements)
            {
                Entry(); sb.Append(p.Action).Append('@').Append(p.Q.ToString(CultureInfo.InvariantCulture)).Append(',').Append(p.R.ToString(CultureInfo.InvariantCulture)).Append('@').Append(p.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); Sep();
            }
            Close(']');
            Nl(); sb.Append("mapturn=").Append(MapActionsTurnDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).Append(':').Append(MapActionsThisTurn.ToString(CultureInfo.InvariantCulture)).Append(';');
            Nl(); sb.Append("over=").Append(GameOver ?? "");
            // GDD v0.1 sections (spec 2026-10-12 section 2.4): each written only when set, so with the legacy loop the text
            // above is the whole text, byte for byte. The over= line has no separator after it, so each section adds one.
            // R-LOOP-002.
            void Section(string name, char open, char close, IEnumerable<string> items)
            {
                Sep(); Nl(); sb.Append(name).Append(open);
                foreach (var i in items) { Entry(); sb.Append(i); Sep(); }
                Close(close);
            }
            if (Cities.Count > 0) Section("city", '{', '}', Cities.Values.Select(x => x.Canonical(readable)));
            if (Units.Count > 0) Section("units", '[', ']', Units.Values.Select(x => x.Canonical()));
            if (Cohorts.Count > 0) Section("train", '[', ']', Cohorts.Values.Select(x => x.Canonical()));
            if (Sites.Count > 0) Section("site", '{', '}', Sites.Values.Select(x => x.Canonical()));
            if (CityProjects.Count > 0) Section("cproj", '[', ']', CityProjects.Values.Select(x => x.Canonical()));
            if (CityStartsThisTurn.Count > 0)   // R-PROJ-001, gdd-0.3 only
                Section("cstart", '{', '}', CityStartsThisTurn.Select(kv => kv.Key + "=" + kv.Value.ToString(CultureInfo.InvariantCulture)));
            if (Workshops.Count > 0) Section("wshop", '[', ']', Workshops.Values.Select(x => x.Canonical()));   // R-ARMS-005, gdd-0.3 only
            if (Corridors.Count > 0) Section("corr", '{', '}', Corridors.Values.Select(x => x.Canonical()));
            if (UnlockedProjects.Count > 0) Section("unlocked", '[', ']', UnlockedProjects);
            if (CardOrders.Count > 0)   // R-ENEMY-005: only while a card's order stands, so a game with none hashes as before
                Section("cardorders", '{', '}', CardOrders.Select(kv => kv.Key.ToString(CultureInfo.InvariantCulture) + "=" + kv.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
            if (NextId != 0) { Sep(); Nl(); sb.Append("next=").Append(NextId.ToString(CultureInfo.InvariantCulture)); }
            if (Objectives.Count > 0)
                Section("obj", '{', '}', Objectives.Select(kv => kv.Key + "=" + kv.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
            if (Settlements.Count > 0)
                Section("ctrl", '{', '}', Settlements.Select(kv => kv.Key + "=" + kv.Value.Canonical()));
            if (Score != 0) { Sep(); Nl(); sb.Append("score=").Append(Score.ToString(CultureInfo.InvariantCulture)); }
            if (ScoreObjectivePoints != 0 || ScoreTimingBonuses != 0 || ScorePrisonerPoints != 0)
            {
                Sep(); Nl();
                sb.Append("scoreparts=").Append(ScoreObjectivePoints.ToString(CultureInfo.InvariantCulture)).Append(',')
                  .Append(ScoreTimingBonuses.ToString(CultureInfo.InvariantCulture)).Append(',').Append(ScorePrisonerPoints.ToString(CultureInfo.InvariantCulture));
            }
            if (Food != 0 || FoodNeed != 0 || FoodUnmet != 0)
            {
                Sep(); Nl();
                sb.Append("food=").Append(Food.ToString(CultureInfo.InvariantCulture)).Append(',').Append(FoodNeed.ToString(CultureInfo.InvariantCulture))
                  .Append(',').Append(FoodUnmet.ToString(CultureInfo.InvariantCulture));
            }
            if (ExhaustedTurns != 0) { Sep(); Nl(); sb.Append("exhausted=").Append(ExhaustedTurns.ToString(CultureInfo.InvariantCulture)); }
            if (Arms != 0) { Sep(); Nl(); sb.Append("arms=").Append(Arms.ToString(CultureInfo.InvariantCulture)); }
            if (DollarsConverted != 0) { Sep(); Nl(); sb.Append("dollars=").Append(DollarsConverted.ToString(CultureInfo.InvariantCulture)); }   // R-MONEY-004: only once converted
            // Prisoners (R-POW-001 to R-POW-005): written only once a surrender has happened, so a run with none hashes as before.
            IEnumerable<string> Counts(SortedDictionary<string, int> m) => m.Select(kv => kv.Key + "=" + kv.Value.ToString(CultureInfo.InvariantCulture));
            if (PrisonersHeld.Count > 0) Section("pow", '{', '}', Counts(PrisonersHeld));
            if (PrisonersReturned.Count > 0) Section("powret", '{', '}', Counts(PrisonersReturned));
            if (SoldiersHeld.Count > 0) Section("ownheld", '{', '}', Counts(SoldiersHeld));
            // R-WAR-005: gdd-0.3 only, so every other ruleset hashes as before.
            if (QuietTurns.Count > 0) Section("quiet", '{', '}', Counts(QuietTurns));
            if (EngagedFronts.Count > 0) Section("engaged", '[', ']', EngagedFronts);
            if (DisplacedByPlayer != 0) { Sep(); Nl(); sb.Append("displaced=").Append(DisplacedByPlayer.ToString(CultureInfo.InvariantCulture)); }   // R-CTRL-019: only after a Deport
            if (UsesPopulationLedger) Section("population-ledger", '{', '}', PopulationLedger.Canonical());
            if (UsesPopulationLedger && playerRegions.Count > 0)
            {
                Section("player-geography", '{', '}', playerGeography.Regions.Values.SelectMany(r => r.Canonical()));
                Section("player-regions", '{', '}', playerRegions.Values.Select(r => r.Canonical()));
            }
            return sb.ToString();
        }
    }

    /// <summary>R-ENEMY-007: a postponed operation card's kept option, and the turn (GameState.Turn) and date of its first
    /// postponement: the wait is counted from the turn, and a late launch's orders end later by the time since the date (Q4).
    /// Immutable, so GameState.Clone can share it.</summary>
    public sealed class PostponedOperation
    {
        public string Option { get; }
        public int Turn { get; }
        public DateTime Date { get; }
        public PostponedOperation(string option, int turn, DateTime date) { Option = option; Turn = turn; Date = date; }
    }
}