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(ui): autosave every turn to a URL-independent folder, continue on start, New Game

eyalgolanb53f0f3b3f2b
diff --git a/unity/Assets/Scripts/SaveStore.cs b/unity/Assets/Scripts/SaveStore.cs
new file mode 100644
index 000000000..197a5e53c
--- /dev/null
+++ b/unity/Assets/Scripts/SaveStore.cs
@@ -0,0 +1,46 @@
+#nullable enable
+using System.IO;
+using UnityEngine;
+
+namespace Statecraft.Game
+{
+ /// <summary>Where the autosave lives (spec section 7: autosave every turn). On WebGL it is a fixed folder under the
+ /// /idbfs IndexedDB mount, not Application.persistentDataPath, because that path hashes the page's URL and itch.io
+ /// serves every upload from a new URL, which would hide old saves (tech notes section 3). The template sets
+ /// autoSyncPersistentDataPath, so closing the file persists it. Writes go to a .tmp file first, then replace.</summary>
+ public sealed class SaveStore
+ {
+ public const string WebDirectory = "/idbfs/statecraft-saves";
+ public const string AutosaveName = "autosave.txt";
+
+ public string Directory { get; }
+ public SaveStore(string directory) { Directory = directory; }
+
+ public static SaveStore ForPlatform() => new SaveStore(Application.platform == RuntimePlatform.WebGLPlayer
+ ? WebDirectory : Path.Combine(Application.persistentDataPath, "saves"));
+
+ public string AutosavePath => Path.Combine(Directory, AutosaveName);
+
+ public void WriteAutosave(string text)
+ {
+ System.IO.Directory.CreateDirectory(Directory);
+ var tmp = AutosavePath + ".tmp";
+ File.WriteAllText(tmp, text);
+ if (File.Exists(AutosavePath)) File.Delete(AutosavePath);
+ File.Move(tmp, AutosavePath);
+ }
+
+ public string? ReadAutosave() => File.Exists(AutosavePath) ? File.ReadAllText(AutosavePath) : null;
+
+ /// <summary>Moves an unreadable autosave aside (autosave.bad.txt) so it is kept for a bug report.</summary>
+ public void SetAsideAutosave()
+ {
+ if (!File.Exists(AutosavePath)) return;
+ var bad = Path.Combine(Directory, "autosave.bad.txt");
+ if (File.Exists(bad)) File.Delete(bad);
+ File.Move(AutosavePath, bad);
+ }
+
+ public void DeleteAutosave() { if (File.Exists(AutosavePath)) File.Delete(AutosavePath); }
+ }
+}
diff --git a/unity/Assets/Scripts/SaveStore.cs.meta b/unity/Assets/Scripts/SaveStore.cs.meta
new file mode 100644
index 000000000..6430b7f1a
--- /dev/null
+++ b/unity/Assets/Scripts/SaveStore.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: f39551df3c05d40978f43df45163b2d7
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/GameStart.cs b/unity/Assets/Scripts/UI/GameStart.cs
new file mode 100644
index 000000000..897b125ce
--- /dev/null
+++ b/unity/Assets/Scripts/UI/GameStart.cs
@@ -0,0 +1,56 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using Statecraft.Sim;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>Starting a session: continue the autosave when there is one (replayed to the same state hash), else a new
+ /// Historical game. Anything the player should know (a content-change warning, an unreadable save) goes to notes.
+ /// No failure while reading or replaying the autosave stops the game from starting: the file is set aside.</summary>
+ public static class GameStart
+ {
+ public static ulong NewSeed() => (ulong)DateTime.UtcNow.Ticks;
+
+ public static GameSession Begin(Content c, SaveStore store, Func<ulong> newSeed, List<string> notes, bool fresh = false)
+ {
+ if (!fresh)
+ {
+ try
+ {
+ var text = store.ReadAutosave();
+ if (text == null) return GameSession.New(c, newSeed(), Mode.Historical);
+ var loaded = GameSession.Load(c, text, out var warnings);
+ notes.AddRange(warnings);
+ return loaded;
+ }
+ catch (Exception e) // any failure (a bad save, a replay that throws): never block the start
+ {
+ try { store.SetAsideAutosave(); } catch (Exception) { /* even this must not stop the start */ }
+ notes.Add($"Your saved game could not be loaded ({e.Message}). A new game has started.");
+ }
+ }
+ return GameSession.New(c, newSeed(), Mode.Historical);
+ }
+
+ /// <summary>Writes the save after every turn. A write that fails (a full or read-only disk) never stops the game:
+ /// the reason goes to <paramref name="onError"/>. Dispose the result to stop autosaving.</summary>
+ public static IDisposable Autosave(SimBridge bridge, SaveStore store, Action<string>? onError = null)
+ {
+ void Save(IReadOnlyList<Rejection> _)
+ {
+ try { store.WriteAutosave(bridge.Session.Save.Write()); }
+ catch (Exception e) { onError?.Invoke($"Your game could not be saved ({e.Message})."); }
+ }
+ bridge.TurnEnded += Save;
+ return new Unsubscribe(() => bridge.TurnEnded -= Save);
+ }
+
+ sealed class Unsubscribe : IDisposable
+ {
+ readonly Action undo;
+ public Unsubscribe(Action undo) { this.undo = undo; }
+ public void Dispose() => undo();
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/GameStart.cs.meta b/unity/Assets/Scripts/UI/GameStart.cs.meta
new file mode 100644
index 000000000..4d525c1e6
--- /dev/null
+++ b/unity/Assets/Scripts/UI/GameStart.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 711429ca9db7a45b28d483078530746a
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/NewGamePresenter.cs b/unity/Assets/Scripts/UI/NewGamePresenter.cs
new file mode 100644
index 000000000..79380ef67
--- /dev/null
+++ b/unity/Assets/Scripts/UI/NewGamePresenter.cs
@@ -0,0 +1,41 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using Statecraft.Sim;
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>New Game asks for a second press (no browser confirm dialogs in WebGL), then deletes the autosave and
+ /// starts a new Historical game. Ending a turn in between cancels the request.</summary>
+ public sealed class NewGamePresenter : IDisposable
+ {
+ readonly VisualElement root; readonly SimBridge bridge; readonly SaveStore store; readonly ToastPresenter toast; readonly UiText text; readonly Func<ulong> seed;
+
+ public NewGamePresenter(VisualElement root, SimBridge bridge, SaveStore store, ToastPresenter toast, UiText text, Func<ulong> seed)
+ {
+ this.root = root; this.bridge = bridge; this.store = store; this.toast = toast; this.text = text; this.seed = seed;
+ button = root.Q<Button>("new-game");
+ button.clicked += Press;
+ bridge.TurnEnded += Disarm;
+ }
+
+ readonly Button button;
+
+ void Disarm(IReadOnlyList<Rejection> _) => Armed = false;
+
+ /// <summary>Unsubscribes from the bridge and the button (the owner calls this when disabled).</summary>
+ public void Dispose() { button.clicked -= Press; bridge.TurnEnded -= Disarm; }
+
+ public bool Armed { get; private set; }
+
+ void Press()
+ {
+ if (!Armed) { Armed = true; toast.Show(text["newgame.confirm"]); return; }
+ Armed = false;
+ store.DeleteAutosave();
+ bridge.Replace(GameSession.New(bridge.Content, seed(), Mode.Historical));
+ toast.Clear();
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/NewGamePresenter.cs.meta b/unity/Assets/Scripts/UI/NewGamePresenter.cs.meta
new file mode 100644
index 000000000..8dc7a6af7
--- /dev/null
+++ b/unity/Assets/Scripts/UI/NewGamePresenter.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: a455250ac1495451492ff2f4ba936a78
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/SaveUiTests.cs b/unity/Assets/Tests/EditMode/SaveUiTests.cs
new file mode 100644
index 000000000..ba1086da3
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/SaveUiTests.cs
@@ -0,0 +1,177 @@
+using System.Collections.Generic;
+using System.IO;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEngine.UIElements;
+using UnityEngine;
+
+public class SaveUiTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+ static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ static SaveStore TempStore() => new SaveStore(Path.Combine(Path.GetTempPath(), "statecraft-saves-" + System.Guid.NewGuid().ToString("N")));
+
+ [Test]
+ public void EveryTurnIsAutosavedAndTheNextStartContinuesIt()
+ {
+ var store = TempStore();
+ var notes = new List<string>();
+ var bridge = new SimBridge(GameStart.Begin(C, store, () => 77UL, notes), Text);
+ GameStart.Autosave(bridge, store);
+ bridge.Queue(new SetMobilization(1.0));
+ bridge.EndTurn(); bridge.EndTurn();
+ Assert.IsTrue(File.Exists(store.AutosavePath));
+ Assert.IsFalse(File.Exists(store.AutosavePath + ".tmp"));
+ var resumed = GameStart.Begin(C, store, () => 1UL, notes);
+ Assert.IsEmpty(notes);
+ Assert.AreEqual(bridge.State.Hash(), resumed.State.Hash());
+ Assert.AreEqual(2, resumed.State.Turn);
+ }
+
+ [Test]
+ public void AnUnreadableAutosaveIsSetAsideAndANewGameStarts()
+ {
+ var store = TempStore();
+ store.WriteAutosave("statecraft-save 9\ncontent x\nseed 1\nmode Historical\nend x\n");
+ var notes = new List<string>();
+ var session = GameStart.Begin(C, store, () => 5UL, notes);
+ Assert.AreEqual(0, session.State.Turn);
+ StringAssert.StartsWith("Your saved game could not be loaded (line 1: save schema version 9 is newer", notes[0]);
+ Assert.IsFalse(File.Exists(store.AutosavePath));
+ Assert.IsTrue(File.Exists(Path.Combine(store.Directory, "autosave.bad.txt")));
+ }
+
+ [Test]
+ public void ASaveWithAnUnsupportedModeIsSetAsideToo()
+ {
+ var store = TempStore();
+ var good = GameSession.New(C, 9, Mode.Historical).Save.Write();
+ store.WriteAutosave(good.Replace("mode Historical", "mode Open"));
+ var notes = new List<string>();
+ var session = GameStart.Begin(C, store, () => 6UL, notes);
+ Assert.AreEqual(0, session.State.Turn);
+ StringAssert.StartsWith("Your saved game could not be loaded (line 4: mode Open is not supported)", notes[0]);
+ Assert.IsTrue(File.Exists(Path.Combine(store.Directory, "autosave.bad.txt")));
+ }
+
+ [Test]
+ public void AFailureThatIsNotASaveExceptionNeverStopsTheStart()
+ {
+ // Another process holds the file: reading it throws IOException, not SaveException, and even setting it aside may fail.
+ var store = TempStore();
+ store.WriteAutosave(GameSession.New(C, 9, Mode.Historical).Save.Write());
+ using (new FileStream(store.AutosavePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
+ {
+ var notes = new List<string>();
+ GameSession? session = null;
+ Assert.DoesNotThrow(() => session = GameStart.Begin(C, store, () => 6UL, notes));
+ Assert.AreEqual(0, session!.State.Turn);
+ StringAssert.StartsWith("Your saved game could not be loaded (", notes[0]);
+ }
+ }
+
+ [Test]
+ public void NewGameNeedsASecondPress()
+ {
+ using var ui = new UiTestKit();
+ var store = TempStore();
+ var bridge = new SimBridge(GameSession.New(C, 3, Mode.Historical), Text);
+ GameStart.Autosave(bridge, store);
+ bridge.EndTurn();
+ var toast = new ToastPresenter(ui.Root, bridge, Text);
+ var newGame = new NewGamePresenter(ui.Root, bridge, store, toast, Text, () => 4UL);
+ ui.Press("new-game");
+ Assert.IsTrue(newGame.Armed);
+ Assert.AreEqual("Press New Game again to abandon this game and start over.", ui.Q<UnityEngine.UIElements.Label>("toast").text);
+ Assert.AreEqual(1, bridge.State.Turn);
+ ui.Press("new-game");
+ Assert.AreEqual(0, bridge.State.Turn);
+ Assert.IsFalse(File.Exists(store.AutosavePath));
+ }
+
+ [Test]
+ public void TheWebSaveFolderDoesNotDependOnThePageUrl() =>
+ Assert.AreEqual("/idbfs/statecraft-saves", SaveStore.WebDirectory);
+
+ [Test]
+ public void AFailingAutosaveWriteNeverStopsATurn()
+ {
+ var file = Path.Combine(Path.GetTempPath(), "statecraft-not-a-folder-" + System.Guid.NewGuid().ToString("N"));
+ File.WriteAllText(file, "x"); // a file where the folder should be
+ try
+ {
+ var bridge = new SimBridge(GameSession.New(C, 3, Mode.Historical), Text);
+ var errors = new List<string>();
+ GameStart.Autosave(bridge, new SaveStore(file), errors.Add);
+ Assert.DoesNotThrow(() => bridge.EndTurn());
+ Assert.AreEqual(1, bridge.State.Turn);
+ Assert.AreEqual(1, errors.Count);
+ StringAssert.StartsWith("Your game could not be saved", errors[0]);
+ }
+ finally { File.Delete(file); }
+ }
+
+ [Test]
+ public void ANewGameIgnoresTheAutosaveWhenAsked()
+ {
+ var store = TempStore();
+ var played = new SimBridge(GameSession.New(C, 3, Mode.Historical), Text);
+ GameStart.Autosave(played, store);
+ played.EndTurn();
+ var session = GameStart.Begin(C, store, () => 8UL, new List<string>(), fresh: true);
+ Assert.AreEqual(0, session.State.Turn);
+ Assert.IsTrue(File.Exists(store.AutosavePath), "an ignored save is left alone");
+ }
+
+ [Test]
+ public void ASaveMadeWithOtherContentLoadsWithANote()
+ {
+ var store = TempStore();
+ var text = GameSession.New(C, 9, Mode.Historical).Save.Write().Replace("content " + C.Hash, "content " + new string('0', C.Hash.Length));
+ store.WriteAutosave(text);
+ var notes = new List<string>();
+ var session = GameStart.Begin(C, store, () => 1UL, notes);
+ Assert.AreEqual(1, notes.Count);
+ StringAssert.Contains("different game content", notes[0]);
+ Assert.IsTrue(File.Exists(store.AutosavePath), "a warning is not a failure: the save is kept");
+ Assert.AreEqual(0, session.State.Turn);
+ }
+
+ [Test]
+ public void ArmingIsCancelledByATurnAndADisposedButtonDoesNothing()
+ {
+ using var ui = new UiTestKit();
+ var store = TempStore();
+ var bridge = new SimBridge(GameSession.New(C, 3, Mode.Historical), Text);
+ var toast = new ToastPresenter(ui.Root, bridge, Text);
+ var newGame = new NewGamePresenter(ui.Root, bridge, store, toast, Text, () => 4UL);
+ ui.Press("new-game");
+ Assert.IsTrue(newGame.Armed);
+ bridge.EndTurn();
+ Assert.IsFalse(newGame.Armed);
+ ui.Press("new-game");
+ Assert.AreEqual(1, bridge.State.Turn, "one press after a turn only arms again");
+ newGame.Dispose();
+ ui.Press("new-game"); ui.Press("new-game");
+ Assert.AreEqual(1, bridge.State.Turn);
+ }
+
+ [Test]
+ public void NewGameRefreshesTheScreens()
+ {
+ using var ui = new UiTestKit();
+ var store = TempStore();
+ var bridge = new SimBridge(GameSession.New(C, 3, Mode.Historical), Text);
+ var hud = new HudPresenter(ui.Root, bridge, Text);
+ var toast = new ToastPresenter(ui.Root, bridge, Text);
+ new NewGamePresenter(ui.Root, bridge, store, toast, Text, () => 4UL);
+ ui.Press("end-turn");
+ Assert.AreEqual("Turn 1", ui.Q<Label>("turn").text);
+ ui.Press("new-game"); ui.Press("new-game");
+ Assert.AreEqual("Turn 0", ui.Q<Label>("turn").text);
+ Assert.AreEqual(DisplayStyle.None, ui.Q<Label>("toast").style.display.value);
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/SaveUiTests.cs.meta b/unity/Assets/Tests/EditMode/SaveUiTests.cs.meta
new file mode 100644
index 000000000..97d346870
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/SaveUiTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: e10ef68d1e4174b0c91877b8491c349b
\ No newline at end of file
diff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxml
index 4fd28fbce..a2f55d7f2 100644
--- a/unity/Assets/UI/Game.uxml
+++ b/unity/Assets/UI/Game.uxml
@@ -39,6 +39,7 @@
<ui:Button name="nav-budget" text="Budget" />
<ui:Button name="nav-defence" text="Defence" />
<ui:Button name="nav-why" text="Why?" />
+ <ui:Button name="new-game" text="New Game" />
</ui:VisualElement>
<ui:VisualElement class="turn-box">
<ui:Label name="attention" class="muted" />
diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yaml
index 9a074f730..680cf6239 100644
--- a/unity/Assets/UI/strings.en.yaml
+++ b/unity/Assets/UI/strings.en.yaml
@@ -82,3 +82,4 @@ info.biome.hills: "Hills"
info.biome.mountains: "Mountains"
info.biome.valley: "Valley"
info.biome.desert: "Desert"
+newgame.confirm: "Press New Game again to abandon this game and start over."