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.

Civ movement S2: the session commits orders and the save keeps the open turn (Refs #1398) (#1447)

Eyal Golan0d00900b0d6b
diff --git a/changelog.d/1398-s2.md b/changelog.d/1398-s2.md
new file mode 100644
index 000000000..cd9f10ad4
--- /dev/null
+++ b/changelog.d/1398-s2.md
@@ -0,0 +1,6 @@
+- Sim groundwork for Civ-style movement (#1398): `GameSession.Commit` takes a move or a unit order at once and
+ `GameSession.EndTurn` runs the committed orders before the waiting ones (R-TURN-004). Saves are schema 3 and keep the
+ turn in progress, so a reload keeps what was done (R-SAVE-003).
+### Changed
+- A schema 2 save of the GDD game that has a player attack, or that no longer replays to its saved hash, is refused with
+ the "earlier version of the game's rules" message (R-SAVE-004).
diff --git a/docs/rules/mvp.md b/docs/rules/mvp.md
index f0d700846..29025fb04 100644
--- a/docs/rules/mvp.md
+++ b/docs/rules/mvp.md
@@ -16,6 +16,8 @@ R-TURN-002: An event that asks for a decision opens its window on the 15th on or
R-TURN-003: In the historical run, no more than 6 months pass from one card to the next (or from the last card to the game's end), and no more than 2 when the country is at full war (security level 5) on any turn of the stretch (owner, 15 October 2026, Q-CUT-8: "6 months, 2 in wartime"; the M3 gap ruling restated in months).
+R-TURN-004: A move (`Move`) and a unit order (`UnitOrder`) other than Send home take effect at once and are final (the owner, 23 October 2026: "No undo, like Civ"): each is committed to the turn in progress, in the order given, and the game shows the state after them (`Simulation.Preview`). Every other order waits for End turn, may be changed or withdrawn until then, and costs and runs as before. End turn runs the route step (R-MOVE-009), then the committed orders in the order given, then the waiting orders in the order queued, as one batch (`Simulation.Step`), so a waiting order never changes the result of a committed one (spec 2026-10-23 section 3).
+
## The loop switch
R-LOOP-001: `systems.loop` in eras.yaml is `legacy` (the default) or `gdd`, and every era has the same value. Its ruleset id, which a save records, is `legacy` or `gdd-0.1`.
@@ -54,6 +56,10 @@ R-SAVE-001: A save names the ruleset it was played under (`ruleset legacy` or `r
R-SAVE-002: A save that names a ruleset this build does not know, or a newer save schema, was made by a newer version of the game and is refused with the code `newer_version` (N2).
+R-SAVE-003: Save schema 3 adds the open turn: after the last `turn`, a line `open` and the turn in progress's committed orders (R-TURN-004), one a line (a waiting order there is refused: the save was edited); the `end` hash is still the state's after the last finished turn. Loading replays the turns, then commits the open orders again; one refused on the same content means the save is damaged (`SaveException`), and on other content the rest are dropped with the `replay_differs` warning. A schema 2 save has no open turn and loads as before (but see R-SAVE-004).
+
+R-SAVE-004: A schema 2 save of the GDD game with a player attack (`order <unit> attack <q> <r>`) is refused with the code `older_rules` (R-SAVE-001): its attacks were standing orders, so it would replay differently (the owner, 23 October 2026: "Refuse with a clear message"). So is a schema 2 GDD save whose replay under the current rules does not end on its saved hash (instant capture, the full-points step). Other schema 2 saves load.
+
## Cities
Each GDD turn resolves in the order of the approved plan's section 2.3 (decision D-A6): production, then housing and Social cohesion, then arrivals.
diff --git a/sim/Statecraft.Sim.Tests/GameSessionTurnTests.cs b/sim/Statecraft.Sim.Tests/GameSessionTurnTests.cs
new file mode 100644
index 000000000..0f066f925
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/GameSessionTurnTests.cs
@@ -0,0 +1,93 @@
+using System;
+using System.Linq;
+using Statecraft.Sim;
+using Xunit;
+
+/// <summary>R-TURN-004 and R-SAVE-003 (spec 2026-10-23 sections 3.3 and 3.4): committed orders are final, shown at once,
+/// run first at End turn, and survive a reload.</summary>
+public class GameSessionTurnTests
+{
+ static readonly Content C = ContentLoader.Load(RealContentTests.ContentRoot());
+
+ static GameSession Fresh() => GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+
+ [Fact]
+ public void ACommittedMoveShowsAtOnceAndEndTurnRunsIt()
+ {
+ var session = Fresh();
+ var move = GoldenRun.SmokeMove(C, session.State);
+ var before = (session.State.Units[move.Unit].Q, session.State.Units[move.Unit].R);
+ Assert.Null(session.Commit(move));
+ Assert.Equal((move.Q, move.R), (session.Now.State.Units[move.Unit].Q, session.Now.State.Units[move.Unit].R));
+ Assert.Equal(before, (session.State.Units[move.Unit].Q, session.State.Units[move.Unit].R));
+ var ended = session.EndTurn(new Command[0]);
+ Assert.Equal(GoldenRun.PlaySmokeOrders(C).Hash(), ended.State.Hash());
+ Assert.Empty(session.Committed);
+ }
+
+ [Fact]
+ public void ARefusedOrderIsNotCommitted()
+ {
+ var session = Fresh();
+ Assert.Equal("That unit is already there", session.Commit(new Move(0, session.State.Units[0].Q, session.State.Units[0].R)));
+ Assert.Empty(session.Committed);
+ Assert.Throws<ArgumentException>(() => session.Commit(new BuyArms(1)));
+ Assert.Throws<ArgumentException>(() => session.Commit(new UnitOrder(0, Demobilization.SendHome))); // waits for End turn
+ }
+
+ // R-TURN-004: deferred orders run after the committed ones, whatever order they were given in.
+ [Fact]
+ public void DeferredOrdersRunAfterCommittedOnes()
+ {
+ var session = Fresh();
+ var move = GoldenRun.SmokeMove(C, session.State);
+ session.Commit(move);
+ session.EndTurn(new Command[] { new BuyArms(1) });
+ Assert.Equal(new Command[] { move }.Concat(new Command[] { new BuyArms(1) }).Select(x => x.Kind),
+ session.Save.Turns.Last().Select(x => x.Kind));
+ }
+
+ // R-SAVE-003: a reload in the middle of a turn keeps what was done.
+ [Fact]
+ public void AReloadKeepsTheOpenTurn()
+ {
+ var session = Fresh();
+ var move = GoldenRun.SmokeMove(C, session.State);
+ session.Commit(move);
+ var loaded = GameSession.Load(C, session.Save.Write(), out var warnings);
+ Assert.Empty(warnings);
+ Assert.Equal(session.Now.State.Hash(), loaded.Now.State.Hash());
+ Assert.Equal(new[] { "move" }, loaded.Committed.Select(x => x.Kind));
+ }
+
+ [Fact]
+ public void StepRefusesWhileOrdersAreCommitted()
+ {
+ var session = Fresh();
+ session.Commit(GoldenRun.SmokeMove(C, session.State));
+ Assert.Throws<InvalidOperationException>(() => session.Step(new Command[0]));
+ }
+
+ // R-SAVE-004: a schema 2 GDD save with a player attack (a standing order then) is refused as older rules.
+ [Fact]
+ public void ASchema2SaveWithAnAttackIsRefusedAsOlderRules()
+ {
+ var session = Fresh();
+ var text = session.Save.Write().Replace("statecraft-save 3", "statecraft-save 2")
+ .Replace("end ", "turn\norder 0 attack 10 10\nend ");
+ var e = Assert.Throws<SaveException>(() => GameSession.Load(C, text, out _));
+ Assert.Equal(SaveException.OlderRules, e.Code);
+ }
+
+ // R-SAVE-004: a schema 2 GDD save that does not replay to its saved hash gets the clear older-rules message; a schema 3
+ // one that does not is still damaged (no code).
+ [Fact]
+ public void ASchema2SaveThatReplaysDifferentlyIsRefusedAsOlderRules()
+ {
+ static string WrongEnd(string text) { var end = text.Substring(text.LastIndexOf("end ", StringComparison.Ordinal) + 4, 64); return text.Replace("end " + end, "end " + new string('0', 64)); }
+ var two = WrongEnd(Fresh().Save.Write().Replace("statecraft-save 3", "statecraft-save 2"));
+ Assert.Equal(SaveException.OlderRules, Assert.Throws<SaveException>(() => GameSession.Load(C, two, out _)).Code);
+ var three = WrongEnd(Fresh().Save.Write());
+ Assert.Null(Assert.Throws<SaveException>(() => GameSession.Load(C, three, out _)).Code);
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/SaveGameTests.cs b/sim/Statecraft.Sim.Tests/SaveGameTests.cs
index 78b785676..5454fb36a 100644
--- a/sim/Statecraft.Sim.Tests/SaveGameTests.cs
+++ b/sim/Statecraft.Sim.Tests/SaveGameTests.cs
@@ -36,6 +36,49 @@ public class SaveGameTests
return g;
}
+ // R-SAVE-003: the open turn's committed orders are written after the turns and read back in order.
+ [Fact]
+ public void TheOpenTurnRoundTrips()
+ {
+ var save = new SaveGame(new string('a', 64), 7, Mode.Historical, SaveGame.GddRuleset, new string('b', 64));
+ save.SetOpen(new Command[] { new Move(1, 2, 3), new UnitOrder(1, Orders.Hold) });
+ var text = save.Write();
+ Assert.StartsWith("statecraft-save 3\n", text);
+ Assert.Contains("open\nmove 1 2 3\norder 1 hold\nend ", text);
+ var back = SaveGame.Parse(text);
+ Assert.Equal(3, back.Version);
+ Assert.Equal(new[] { "move", "unit_order" }, back.Open.Select(x => x.Kind));
+ }
+
+ // R-SAVE-003: a finished turn ends the open one.
+ [Fact]
+ public void RecordingATurnClearsTheOpenTurn()
+ {
+ var c = TurnPreviewTests.Plain();
+ var session = GameSession.New(c, 1, Mode.Historical);
+ session.Save.SetOpen(new Command[] { new Move(0, 1, 1) });
+ session.Step(new Command[0]);
+ Assert.Empty(session.Save.Open);
+ Assert.DoesNotContain("\nopen\n", session.Save.Write());
+ }
+
+ // R-SAVE-003: the open turn holds committed orders only (R-TURN-004); a waiting order there means the save was edited.
+ [Fact]
+ public void AnOpenTurnWithAWaitingOrderIsRefused()
+ {
+ var text = "statecraft-save 3\ncontent " + new string('a', 64) + "\nseed 1\nmode Historical\nruleset gdd-0.1\nopen\narms 1\nend " + new string('b', 64) + "\n";
+ var e = Assert.Throws<SaveException>(() => SaveGame.Parse(text));
+ Assert.Equal(7, e.Line);
+ }
+
+ // R-SAVE-002 is unchanged: an older schema has no open turn, and a line "open" in it is refused.
+ [Fact]
+ public void ASchema2SaveWithAnOpenLineIsRefused()
+ {
+ var text = "statecraft-save 2\ncontent " + new string('a', 64) + "\nseed 1\nmode Historical\nruleset gdd-0.1\nturn\nopen\nend " + new string('b', 64) + "\n";
+ Assert.Throws<SaveException>(() => SaveGame.Parse(text));
+ }
+
[Fact]
public void ASaveReplaysToTheSameStateHash()
{
@@ -111,7 +154,7 @@ public class SaveGameTests
var c = Fixture1();
var text = Played(c).Save.Write();
var lines = text.Split('\n');
- Assert.Equal("statecraft-save 2", lines[0]);
+ Assert.Equal("statecraft-save 3", lines[0]);
Assert.Equal("content " + c.Hash, lines[1]);
Assert.Equal("seed 99", lines[2]);
Assert.Equal("mode Historical", lines[3]);
@@ -157,7 +200,7 @@ public class SaveGameTests
}
[Theory]
- [InlineData("statecraft-save 3", 1, "line 1: save schema version 3 is newer than this game (2)")]
+ [InlineData("statecraft-save 4", 1, "line 1: save schema version 4 is newer than this game (3)")]
[InlineData("statecraft-save x", 1, "line 1: bad schema version")]
[InlineData("chess-save 1", 1, "line 1: expected 'statecraft-save'")]
public void BadHeadersAreRejected(string first, int line, string message)
@@ -178,7 +221,7 @@ public class SaveGameTests
{
var c = Fixture1();
var lines = Played(c).Save.Write().Split('\n').ToList();
- lines.Insert(6, command); // after the first "turn" (schema 2: the ruleset line is line 5)
+ lines.Insert(6, command); // after the first "turn" (schemas 2 and 3: ruleset is line 5)
var ex = Assert.Throws<SaveException>(() => GameSession.Load(c, string.Join("\n", lines), out _));
Assert.Equal(7, ex.Line);
Assert.Equal("line 7: " + message, ex.Message);
@@ -255,7 +298,7 @@ public class SaveGameTests
Assert.Throws<ArgumentNullException>(() => g.Step(new Command[] { new Appoint(null!, "pm_one") }));
Assert.Throws<ArgumentNullException>(() => g.Step(new Command[] { new MapAction(null!, 1, 1) }));
Assert.Empty(g.Save.Turns); // nothing half-recorded
- Assert.StartsWith("statecraft-save 2\n", g.Save.Write());
+ Assert.StartsWith("statecraft-save 3\n", g.Save.Write());
}
[Fact]
@@ -514,7 +557,7 @@ public class SaveGameTests
[Theory]
[InlineData("statecraft-save 0", "unknown save schema version 0")]
- [InlineData("statecraft-save 3", "save schema version 3 is newer than this game (2)")]
+ [InlineData("statecraft-save 4", "save schema version 4 is newer than this game (3)")]
[InlineData("statecraft-save -1", "bad schema version")]
public void SchemaVersionsOutsideOneAreRefused(string first, string message)
{
@@ -542,7 +585,7 @@ public class SaveGameTests
var g = GameSession.New(Fixture1(), 1, Mode.Historical);
Assert.Throws<ArgumentException>(() => g.Step(new Command[] { new Foreign() }));
g.Step(new Command[0]);
- Assert.StartsWith("statecraft-save 2\n", g.Save.Write());
+ Assert.StartsWith("statecraft-save 3\n", g.Save.Write());
Assert.Single(g.Save.Turns);
}
@@ -582,7 +625,7 @@ public class SaveGameTests
var g = GameSession.New(c, 1, Mode.Historical);
g.Step(HistoricalAI.Commands(c, g.State));
var text = g.Save.Write();
- Assert.StartsWith("statecraft-save 2\n", text);
+ Assert.StartsWith("statecraft-save 3\n", text);
Assert.Contains("\nruleset gdd-0.1\n", text);
Assert.Equal("gdd-0.1", SaveGame.Parse(text).Ruleset);
Assert.Equal(g.State.Hash(), GameSession.Load(c, text, out var warnings).State.Hash());
@@ -595,10 +638,10 @@ public class SaveGameTests
{
var c = Fixture1();
var g = Played(c);
- var v1 = g.Save.Write().Replace("statecraft-save 2\n", "statecraft-save 1\n").Replace("ruleset legacy\n", "");
+ var v1 = g.Save.Write().Replace("statecraft-save 3\n", "statecraft-save 1\n").Replace("ruleset legacy\n", "");
Assert.Equal("legacy", SaveGame.Parse(v1).Ruleset);
Assert.Equal(g.State.Hash(), GameSession.Load(c, v1, out _).State.Hash());
- Assert.StartsWith("statecraft-save 2\n", SaveGame.Parse(v1).Write()); // written back as schema 2
+ Assert.StartsWith("statecraft-save 3\n", SaveGame.Parse(v1).Write()); // written back as the current schema
Assert.Contains("\nruleset legacy\n", SaveGame.Parse(v1).Write());
}
@@ -615,7 +658,7 @@ public class SaveGameTests
Assert.Equal(SaveException.OlderRules, ex.Code);
Assert.Equal("This save was made with an earlier version of the game's rules.", ex.Message);
Assert.DoesNotContain("new game", ex.Message);
- var v1 = g.Save.Write().Replace("statecraft-save 2\n", "statecraft-save 1\n").Replace("ruleset legacy\n", "");
+ var v1 = g.Save.Write().Replace("statecraft-save 3\n", "statecraft-save 1\n").Replace("ruleset legacy\n", "");
var ex1 = Assert.Throws<SaveException>(() => GameSession.Load(real, v1, out _));
Assert.Equal((ex.Code, ex.Message), (ex1.Code, ex1.Message));
}
@@ -633,8 +676,8 @@ public class SaveGameTests
Assert.Contains("This save was made with a newer version of the game", ex.Message);
Assert.DoesNotContain("new game", ex.Message);
Assert.Equal(SaveException.NewerVersion, Assert.Throws<SaveException>(() => GameSession.Load(real, text, out _)).Code);
- var schema3 = text.Replace("statecraft-save 2\n", "statecraft-save 3\n");
- Assert.Equal(SaveException.NewerVersion, Assert.Throws<SaveException>(() => SaveGame.Parse(schema3)).Code);
+ var schema4 = text.Replace("statecraft-save 3\n", "statecraft-save 4\n");
+ Assert.Equal(SaveException.NewerVersion, Assert.Throws<SaveException>(() => SaveGame.Parse(schema4)).Code);
}
// R-SAVE-001
diff --git a/sim/Statecraft.Sim/GameSession.cs b/sim/Statecraft.Sim/GameSession.cs
index 89af93c8b..7bd2f2052 100644
--- a/sim/Statecraft.Sim/GameSession.cs
+++ b/sim/Statecraft.Sim/GameSession.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Linq;
namespace Statecraft.Sim
{
@@ -18,8 +19,17 @@ namespace Statecraft.Sim
/// the save.</summary>
public StepResult? BeforeLast { get; private set; }
public SaveGame Save { get; }
+ readonly List<Command> committed = new List<Command>();
+ /// <summary>R-TURN-004: the turn's committed orders, in the order given: final, shown at once, run first at End turn.</summary>
+ public IReadOnlyList<Command> Committed => committed;
+ /// <summary>The state the screen shows: the turn's start after its committed orders (Simulation.Preview).</summary>
+ public PreviewResult Now { get; private set; }
- GameSession(Content c, GameState s, SaveGame save) { Content = c; State = s; Save = save; }
+ GameSession(Content c, GameState s, SaveGame save)
+ {
+ Content = c; State = s; Save = save;
+ Now = Simulation.Preview(c, s, Array.Empty<Command>());
+ }
public static GameSession New(Content c, ulong seed, Mode mode)
{
@@ -28,15 +38,41 @@ namespace Statecraft.Sim
return new GameSession(c, s, new SaveGame(c.Hash, seed, mode, c.Ruleset, s.Hash()));
}
- /// <summary>Runs one turn and records it in the save.</summary>
- public StepResult Step(IReadOnlyList<Command> commands)
+ /// <summary>R-TURN-004: commits a move or a unit order. Null when taken (it is shown at once and saved in the open
+ /// turn, R-SAVE-003), else the sim's reason, with nothing changed. A deferred order is a programmer error.</summary>
+ public string? Commit(Command cmd)
+ {
+ if (cmd == null) throw new ArgumentNullException(nameof(cmd));
+ if (!Simulation.IsInstant(cmd)) throw new ArgumentException($"'{cmd.Kind}' waits for End turn; only a move or a unit order other than Send home is committed.", nameof(cmd));
+ var next = Simulation.Preview(Content, State, committed.Concat(new[] { cmd }).ToList());
+ var refused = next.Rejected.FirstOrDefault(r => ReferenceEquals(r.Command, cmd));
+ if (refused != null) return refused.Reason;
+ committed.Add(cmd);
+ Now = next;
+ Save.SetOpen(committed);
+ return null;
+ }
+
+ /// <summary>Ends the turn: the committed orders, then <paramref name="deferred"/>, as one batch (R-TURN-004).</summary>
+ public StepResult EndTurn(IReadOnlyList<Command> deferred)
{
- var r = Simulation.Step(Content, State, commands);
- Save.Record(commands, r.State);
+ if (deferred == null) throw new ArgumentNullException(nameof(deferred));
+ var batch = committed.Concat(deferred).ToList();
+ var r = Simulation.Step(Content, State, batch);
+ Save.Record(batch, r.State);
Previous = State; State = r.State; BeforeLast = Last; Last = r;
+ committed.Clear();
+ Now = Simulation.Preview(Content, State, committed);
return r;
}
+ /// <summary>Runs one turn with these commands and records it (no orders may be committed).</summary>
+ public StepResult Step(IReadOnlyList<Command> commands)
+ {
+ if (committed.Count > 0) throw new InvalidOperationException("Orders are committed this turn: end it with EndTurn.");
+ return EndTurn(commands);
+ }
+
/// <summary>Load warning: the save was made with other content, so the replayed game may differ (spec section 7).</summary>
public const string ContentChanged = "content_changed";
/// <summary>Load warning: made with other content, the replay then ended on a different state than the saved game.</summary>
@@ -57,6 +93,10 @@ namespace Statecraft.Sim
throw saved.Ruleset == SaveGame.LegacyRuleset
? new SaveException(0, "This save was made with an earlier version of the game's rules.", SaveException.OlderRules)
: new SaveException(0, "This save was made with a newer version of the game's rules.", SaveException.NewerVersion);
+ // R-SAVE-004: schema 2 stored player attacks as standing orders, which the current rules no longer replay alike.
+ if (saved.Version < 3 && saved.Ruleset == SaveGame.GddRuleset
+ && saved.Turns.Any(t => t.Any(x => x is UnitOrder o && o.Order == Combat.Attack)))
+ throw new SaveException(0, "This save was made with an earlier version of the game's rules.", SaveException.OlderRules);
var list = new List<string>();
bool sameContent = saved.ContentHash == c.Hash;
if (!sameContent) list.Add(ContentChanged);
@@ -67,9 +107,19 @@ namespace Statecraft.Sim
catch (Exception e) { throw new SaveException(FormattableString.Invariant($"turn {turnNo + 1}: {e.Message}"), e); }
if (session.State.Hash() != saved.FinalHash)
{
+ if (saved.Version < 3 && saved.Ruleset == SaveGame.GddRuleset)
+ throw new SaveException(0, "This save was made with an earlier version of the game's rules.", SaveException.OlderRules);
if (sameContent) throw new SaveException(0, "The replay does not match the saved game: the save is damaged or was edited, or the game has a bug.");
list.Add(ReplayDiffers);
}
+ foreach (var cmd in saved.Open)
+ {
+ var reason = session.Commit(cmd);
+ if (reason == null) continue;
+ if (sameContent) throw new SaveException(0, $"The open turn's order '{cmd.Kind}' was refused: {reason}");
+ if (!list.Contains(ReplayDiffers)) list.Add(ReplayDiffers);
+ break;
+ }
warnings = list;
return session;
}
diff --git a/sim/Statecraft.Sim/SaveGame.cs b/sim/Statecraft.Sim/SaveGame.cs
index 70fe14560..c5a87b41c 100644
--- a/sim/Statecraft.Sim/SaveGame.cs
+++ b/sim/Statecraft.Sim/SaveGame.cs
@@ -30,7 +30,7 @@ namespace Statecraft.Sim
/// <summary>
/// A save is seed + command log + content hash + schema version (spec section 3); loading replays it. Text format,
/// one item per line:
- /// statecraft-save 2 schema version (a schema 1 save has no ruleset line and is legacy)
+ /// statecraft-save 3 schema version (a schema 1 save has no ruleset line and is legacy)
/// content &lt;hex&gt; Content.Hash of the content it was played with
/// seed &lt;ulong&gt; / mode Historical
/// ruleset legacy|gdd-0.1 the rules it was played under (Content.Ruleset); another ruleset refuses it (R-SAVE-001),
@@ -41,12 +41,13 @@ namespace Statecraft.Sim
/// train CITY TRACK N | untrain COHORT | pioneer UNIT ACTION SITE | stop UNIT |
/// project KIND CITY Q R | unproject PROJECT | arms N |
/// capture SETTLEMENT OUTCOME
+ /// open starts the turn in progress's committed command list; it comes after every turn
/// end &lt;hex&gt; GameState.Hash() after the last turn (checks the replay)
/// Doubles are IEEE bit patterns in hex, so replays are exact; strings are percent-escaped (Uri.EscapeDataString).
/// </summary>
public sealed class SaveGame
{
- public const int SchemaVersion = 2;
+ public const int SchemaVersion = 3;
/// <summary>The ruleset of the legacy loop (Content.Ruleset).</summary>
public const string LegacyRuleset = "legacy";
/// <summary>The ruleset of the GDD v0.1 loop (eras.yaml systems.loop: gdd).</summary>
@@ -58,7 +59,10 @@ namespace Statecraft.Sim
/// <summary>Each turn as its canonical command lines. The save keeps text, not the caller's objects, so nothing
/// outside can change a recorded turn; <see cref="Turns"/> parses fresh copies on demand.</summary>
readonly List<List<string>> turns = new List<List<string>>();
+ readonly List<string> open = new List<string>();
+ /// <summary>The schema version parsed from this save; a new save uses <see cref="SchemaVersion"/>.</summary>
+ public int Version { get; private set; }
public string ContentHash { get; }
public ulong Seed { get; }
public Mode Mode { get; }
@@ -67,6 +71,8 @@ namespace Statecraft.Sim
/// <summary>The recorded turns as new command objects each time it is read (changing them changes nothing in the save).</summary>
public IReadOnlyList<IReadOnlyList<Command>> Turns =>
turns.Select(t => (IReadOnlyList<Command>)t.Select(l => ParseCommand(0, l)).ToList().AsReadOnly()).ToList().AsReadOnly();
+ /// <summary>The open turn's committed orders as new command objects each time it is read (R-SAVE-003).</summary>
+ public IReadOnlyList<Command> Open => open.Select(l => ParseCommand(0, l)).ToList().AsReadOnly();
/// <summary>GameState.Hash() after the last recorded turn (the new game's hash before any turn).</summary>
public string FinalHash { get; private set; }
@@ -74,7 +80,7 @@ namespace Statecraft.Sim
{
ContentHash = contentHash ?? throw new ArgumentNullException(nameof(contentHash));
if (ruleset != LegacyRuleset && ruleset != GddRuleset) throw new ArgumentException($"unknown ruleset '{ruleset}'", nameof(ruleset));
- Seed = seed; Mode = mode; Ruleset = ruleset;
+ Version = SchemaVersion; Seed = seed; Mode = mode; Ruleset = ruleset;
FinalHash = initialHash ?? throw new ArgumentNullException(nameof(initialHash));
}
@@ -86,6 +92,16 @@ namespace Statecraft.Sim
// A recorded turn is immutable: the caller keeps its own objects (an AllocateBudget's dictionary is theirs to reuse).
turns.Add(commands.Select(Format).ToList());
FinalHash = after.Hash();
+ open.Clear();
+ }
+
+ /// <summary>Replaces the turn in progress with canonical copies of its committed orders (R-SAVE-003).</summary>
+ internal void SetOpen(IReadOnlyList<Command> commands)
+ {
+ if (commands == null) throw new ArgumentNullException(nameof(commands));
+ var lines = commands.Select(Format).ToList();
+ open.Clear();
+ open.AddRange(lines);
}
public string Write()
@@ -101,6 +117,11 @@ namespace Statecraft.Sim
sb.Append("turn\n");
foreach (var line in t) sb.Append(line).Append('\n');
}
+ if (open.Count > 0)
+ {
+ sb.Append("open\n");
+ foreach (var line in open) sb.Append(line).Append('\n');
+ }
sb.Append("end ").Append(FinalHash).Append('\n');
return sb.ToString();
}
@@ -175,12 +196,27 @@ namespace Statecraft.Sim
var end = Head(n - 1, "end", 2)[1];
if (!IsHash(end)) throw new SaveException(n, "bad end hash");
var save = new SaveGame(content, seed, mode, ruleset, end);
+ save.Version = version;
List<string>? current = null;
+ bool sawOpen = false;
for (int i = first; i < n - 1; i++)
{
- if (lines[i] == "turn") { current = new List<string>(); save.turns.Add(current); continue; }
+ if (version >= 3 && lines[i] == "open")
+ {
+ if (sawOpen) throw new SaveException(i + 1, "'open' must come last, once");
+ sawOpen = true; current = save.open; continue;
+ }
+ if (lines[i] == "turn")
+ {
+ if (sawOpen) throw new SaveException(i + 1, "'open' must come last, once");
+ current = new List<string>(); save.turns.Add(current); continue;
+ }
if (current == null) throw new SaveException(i + 1, "command before the first 'turn'");
- current.Add(Format(ParseCommand(i + 1, lines[i]))); // canonical form, validated now
+ var cmd = ParseCommand(i + 1, lines[i]);
+ // The open turn holds committed orders only (R-TURN-004); a waiting order there means the save was edited.
+ if (ReferenceEquals(current, save.open) && !Simulation.IsInstant(cmd))
+ throw new SaveException(i + 1, "only a move or a unit order other than Send home can be in the open turn");
+ current.Add(Format(cmd)); // canonical form, validated now
}
return save;
}