A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
UI: say save-load warnings and boot failures in the player's language (fixes #637) (#705)
Beriaeee8583f615
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6c1906ad0..9f387476e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -695,6 +695,11 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIBIt decodes to the same bytes, so the terrain is unchanged (#44).### Fixed+- A save that loads with warnings (made with other game content; then a replay that differs) says each warning in the+ player's language (refs #637): `GameSession.Load` returns the kind (`content_changed`, `replay_differs`) instead of+ English text, the UI shows `save.warning.<kind>` from both strings files, and the kind goes to the log. A boot failure+ no longer shows the exception's English text either: the loading line gives the short reason `boot.reason_other`, and+ the full reason stays in the log. The Hebrew waits for the native reviewer (#564). No golden moves.- In the Hebrew UI the top bar's date plate shows the date in Hebrew, "15 במאי 1948", through the same `date.*` stringsas the map's front-line date (refs #687). Before, it read "15 May 1948". English is unchanged.- Map labels (refs #599): close over Jaffa's harbour the "Tel Aviv" and "Jaffa" pills no longer read swapped. Every pilldiff --git a/docs/m3-release.md b/docs/m3-release.mdindex 36301bc57..55f7005b0 100644--- a/docs/m3-release.md+++ b/docs/m3-release.md@@ -326,8 +326,8 @@ Published at: (owner fills in)6. Record the result below. This plan is not a completed itch.io test or a Firefox/Safari/Windows runtime check.**Separate changed-content replay check:** after the unchanged-content control, a build with intentional content changes-may show "This save was made with different game content; the replayed game may differ." Record that warning and both-builds' git commits. Matching date/turn in this case is not evidence of exact state preservation, and it does not+may show "This save is from an earlier version of the game, so events may unfold a little differently."+Record that warning and both builds' git commits. Matching date/turn in this case is not evidence of exact state preservation, and it does notreplace the unchanged-content persistence control above. A changed state hash may be a replay effect rather than a storage failure.Result: not run on itch.io (owner step).diff --git a/sim/Statecraft.Sim.Tests/MapActionTests.cs b/sim/Statecraft.Sim.Tests/MapActionTests.csindex 8462c58f4..393c662d8 100644--- a/sim/Statecraft.Sim.Tests/MapActionTests.cs+++ b/sim/Statecraft.Sim.Tests/MapActionTests.cs@@ -227,7 +227,7 @@ public class MapActionTestsAssert.NotEqual(Fixture.Files["rules.yaml"], rules);var stale = ContentLoader.Load(Fixture.Write(new Dictionary<string, string> { ["rules.yaml"] = rules }));var loaded = GameSession.Load(stale, save, out var warnings);- Assert.Contains(warnings, w => w.Contains("different game content"));+ Assert.Contains(GameSession.ContentChanged, warnings);Assert.Null(MapActions.At(loaded.State, hex.Q, hex.R));var refused = Assert.Single(loaded.Last!.Rejected);Assert.Equal("That map action is not available in this game", refused.Reason);diff --git a/sim/Statecraft.Sim.Tests/SaveGameTests.cs b/sim/Statecraft.Sim.Tests/SaveGameTests.csindex dd0e1e573..44f54a3d4 100644--- a/sim/Statecraft.Sim.Tests/SaveGameTests.cs+++ b/sim/Statecraft.Sim.Tests/SaveGameTests.cs@@ -108,7 +108,7 @@ public class SaveGameTestsvar text = Played(Fixture1()).Save.Write();var other = Fixture1("90");GameSession.Load(other, text, out var warnings);- Assert.Equal(new[] { "This save was made with different game content; the replayed game may differ.", "The replayed game differs from the saved one." }, warnings);+ Assert.Equal(new[] { GameSession.ContentChanged, GameSession.ReplayDiffers }, warnings); // kinds, not display text (#637)}[Fact]diff --git a/sim/Statecraft.Sim/GameSession.cs b/sim/Statecraft.Sim/GameSession.csindex 80f5868d5..89af93c8b 100644--- a/sim/Statecraft.Sim/GameSession.cs+++ b/sim/Statecraft.Sim/GameSession.cs@@ -37,9 +37,16 @@ namespace Statecraft.Simreturn r;}+ /// <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>+ public const string ReplayDiffers = "replay_differs";+/// <summary>Parses and replays a save. Throws SaveException when the text is malformed, or when the content is the/// same but the replay ends on a different hash (a determinism bug). Content made with other content loads with a- /// warning (spec section 7), and a second warning if the replay then differs from the saved game.</summary>+ /// warning (spec section 7), and a second warning if the replay then differs from the saved game. The warnings are+ /// kinds (<see cref="ContentChanged"/>, <see cref="ReplayDiffers"/>), not display text: the UI says each in the+ /// player's language, as it does SaveException.Code (#637).</summary>public static GameSession Load(Content c, string saveText, out IReadOnlyList<string> warnings){if (c == null) throw new ArgumentNullException(nameof(c));@@ -52,7 +59,7 @@ namespace Statecraft.Sim: new SaveException(0, "This save was made with a newer version of the game's rules.", SaveException.NewerVersion);var list = new List<string>();bool sameContent = saved.ContentHash == c.Hash;- if (!sameContent) list.Add("This save was made with different game content; the replayed game may differ.");+ if (!sameContent) list.Add(ContentChanged);var session = New(c, saved.Seed, saved.Mode);int turnNo = 0;try { foreach (var turn in saved.Turns) { session.Step(turn); turnNo++; } }@@ -61,7 +68,7 @@ namespace Statecraft.Simif (session.State.Hash() != saved.FinalHash){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("The replayed game differs from the saved one.");+ list.Add(ReplayDiffers);}warnings = list;return session;diff --git a/unity/Assets/Scripts/Boot/GameBoot.cs b/unity/Assets/Scripts/Boot/GameBoot.csindex a0d62f497..a31182db6 100644--- a/unity/Assets/Scripts/Boot/GameBoot.cs+++ b/unity/Assets/Scripts/Boot/GameBoot.cs@@ -1,6 +1,5 @@#nullable enableusing System;-using System.Text.RegularExpressions;using Statecraft.Game.Map;using UnityEngine;@@ -16,8 +15,8 @@ namespace Statecraft.Game.Bootpublic GameInputs? Inputs { get; private set; }public string? Error { get; private set; }public event Action<GameInputs>? Ready;- /// <summary>Raised with the reason when the boot fails (a failed fetch, a content error): GameRoot shows it on the- /// loading line (M3 final review I5).</summary>+ /// <summary>Raised with the reason when the boot fails (a failed fetch, a content error): GameRoot shows a short+ /// localised reason on the loading line instead (M3 final review I5, #637).</summary>public event Action<string>? Failed;public void Configure(MapScene mapScene) => map = mapScene;@@ -30,17 +29,6 @@ namespace Statecraft.Game.BootFailed?.Invoke(reason);}- /// <summary>The failure reason as the player sees it: absolute local paths (a desktop player reads its files from- /// disk, file:// URIs included) shortened to the file name; http(s) URLs and plain reasons are kept. Error and the- /// log keep the full reason (pre-merge rereview).</summary>- public static string ForPlayer(string reason) =>- BarePath.Replace(QuotedPath.Replace(reason, m => m.Groups[1].Value + FileName(m.Groups[2].Value) + m.Groups[1].Value),- m => FileName(m.Value));-- static readonly Regex QuotedPath = new Regex(@"(['""])((?:file://|/|[A-Za-z]:\\)[^'""]*)\1");- static readonly Regex BarePath = new Regex(@"(?<![\w:/.\\])(?:file://)?(?:/|[A-Za-z]:\\)[^\s'""()]+");- static string FileName(string path) => path.Substring(path.LastIndexOfAny(new[] { '/', '\\' }) + 1);-async void Start(){DiagLog.Init();diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex 6d3a394e3..6fb24371e 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -89,13 +89,14 @@ namespace Statecraft.Game.UIif ((boot == null || boot.Error == null) && Bridge == null) ShowLoading();}- /// <summary>A boot failure replaces the loading line with the reason; the loading state stays, so no half-built panel- /// shows (M3 final review I5).</summary>+ /// <summary>A boot failure replaces the loading line with a short reason in the player's language; the loading state+ /// stays, so no half-built panel shows (M3 final review I5). <paramref name="reason"/> is an exception's English text+ /// (a file path, a content error): it stays in GameBoot.Error and the log, never on screen (#637).</summary>internal void OnBootFailed(string reason){var text = ShowLoading();var line = text == null ? null : document.rootVisualElement.Q<Label>("loading");- if (line != null) Say(line, text!.Format("boot.failed", GameBoot.ForPlayer(reason).TrimEnd('.')), text["ui.lang"] == UiLanguage.Hebrew);+ if (line != null) Say(line, text!.Format("boot.failed", text["boot.reason_other"]), text["ui.lang"] == UiLanguage.Hebrew);}/// <summary>Puts the loading line in the UI's language (boot.loading, #193). In Hebrew the root also gets its markdiff --git a/unity/Assets/Scripts/UI/GameStart.cs b/unity/Assets/Scripts/UI/GameStart.csindex 3cdac058f..0d599c7e0 100644--- a/unity/Assets/Scripts/UI/GameStart.cs+++ b/unity/Assets/Scripts/UI/GameStart.cs@@ -31,7 +31,13 @@ namespace Statecraft.Game.UIvar saved = store.ReadAutosave();if (saved == null) return GameSession.New(c, newSeed(), Mode.Historical);var loaded = GameSession.Load(c, saved, out var warnings);- notes.AddRange(warnings);+ // The sim returns warning kinds, not text (#637): each is said in the player's language, the kind goes+ // to the log. A kind with no string is only logged, so a new kind never sets a loadable save aside.+ foreach (var kind in warnings)+ {+ UnityEngine.Debug.LogWarning("Autosave loaded with a warning: " + kind);+ if (text.Has("save.warning." + kind)) notes.Add(text["save.warning." + kind]);+ }resumed = true;return loaded;}diff --git a/unity/Assets/Tests/EditMode/GameSceneTests.cs b/unity/Assets/Tests/EditMode/GameSceneTests.csindex 0cbee0678..3ed0deacd 100644--- a/unity/Assets/Tests/EditMode/GameSceneTests.cs+++ b/unity/Assets/Tests/EditMode/GameSceneTests.cs@@ -718,7 +718,8 @@ public class GameSceneTestsboot.Fail("people.yaml: people[x].name: required");for (int i = 0; i < 5; i++) yield return null;var ui = doc.rootVisualElement;- Assert.AreEqual("Statecraft could not start: people.yaml: people[x].name: required. Reload the page.", ui.Q<Label>("loading").text);+ // #637: the player reads a short localised reason; the content error stays in Error and the log.+ Assert.AreEqual("Statecraft could not start: its files failed to load. Reload the page.", ui.Q<Label>("loading").text);Assert.AreEqual(DisplayStyle.Flex, ui.Q<Label>("loading").resolvedStyle.display);Assert.IsTrue(ui.Q("root").ClassListContains("loading"), "the panels stay hidden");Assert.AreEqual(Visibility.Hidden, ui.Q("info-panel").resolvedStyle.visibility);@@ -758,7 +759,7 @@ public class GameSceneTests_ = boot.BootAsync(() => throw new IOException("Could not find file '/Users/someone/Statecraft Israel.app/Contents/Resources/Data/StreamingAssets/map/heightmap.json'."));for (int i = 0; i < 3; i++) yield return null;var line = doc.rootVisualElement.Q<Label>("loading").text;- Assert.AreEqual("Statecraft could not start: Could not find file 'heightmap.json'. Reload the page.", line);+ Assert.AreEqual("Statecraft could not start: its files failed to load. Reload the page.", line); // #637: no exception textStringAssert.DoesNotContain("/Users/", line);}finally@@ -768,11 +769,4 @@ public class GameSceneTestsif (rt != null) { rt.Release(); Object.DestroyImmediate(rt); }}}-- [TestCase("Could not find file '/Users/a b/x/content/people.yaml'.", "Could not find file 'people.yaml'.")]- [TestCase(@"Could not find file 'C:\Games\Statecraft\StreamingAssets\map\hexes.json'.", "Could not find file 'hexes.json'.")]- [TestCase("heightmap.r16z: Cannot connect to destination host (file:///Users/me/Data/StreamingAssets/map/heightmap.r16z)", "heightmap.r16z: Cannot connect to destination host (heightmap.r16z)")]- [TestCase("people.yaml: people[x].name: required", "people.yaml: people[x].name: required")]- [TestCase("manifest.json: HTTP/1.1 404 Not Found (http://localhost:8766/StreamingAssets/content/manifest.json)", "manifest.json: HTTP/1.1 404 Not Found (http://localhost:8766/StreamingAssets/content/manifest.json)")]- public void BootFailureTextKeepsOnlyFileNames(string reason, string shown) => Assert.AreEqual(shown, GameBoot.ForPlayer(reason));}diff --git a/unity/Assets/Tests/EditMode/HebrewUiTests.cs b/unity/Assets/Tests/EditMode/HebrewUiTests.csindex e4f0bb2b4..7aa69440f 100644--- a/unity/Assets/Tests/EditMode/HebrewUiTests.cs+++ b/unity/Assets/Tests/EditMode/HebrewUiTests.cs@@ -343,7 +343,7 @@ public class HebrewUiTests_ = boot.BootAsync(() => throw new IOException("Could not find file '/Users/someone/Statecraft Israel.app/Contents/Resources/Data/StreamingAssets/map/heightmap.json'."));if (failFirst) game.Started();var t = language == UiLanguage.Hebrew ? He : En;- Assert.AreEqual(t.Format("boot.failed", "Could not find file 'heightmap.json'"), Ui.Q<Label>("loading").text, $"{language}, {order}");+ Assert.AreEqual(t.Format("boot.failed", t["boot.reason_other"]), Ui.Q<Label>("loading").text, $"{language}, {order}"); // #637Assert.AreEqual(language == UiLanguage.Hebrew, Ui.Q("root").ClassListContains(UiLanguage.HebrewClass), $"{language}, {order}: the face");}}diff --git a/unity/Assets/Tests/EditMode/SaveUiTests.cs b/unity/Assets/Tests/EditMode/SaveUiTests.csindex 1d2f45170..e428f6147 100644--- a/unity/Assets/Tests/EditMode/SaveUiTests.cs+++ b/unity/Assets/Tests/EditMode/SaveUiTests.cs@@ -1,6 +1,7 @@#nullable enableusing System.Collections.Generic;using System.IO;+using System.Linq;using NUnit.Framework;using Statecraft.Game;using Statecraft.Game.UI;@@ -149,6 +150,27 @@ public class SaveUiTestspublic override string? ReadAutosave() => throw new SaveException(0, "made by a future version", "a_code_with_no_string");}+ /// <summary>#637: a load warning kind with no string (a kind added to the sim before its strings) is only logged. It+ /// must not throw inside Begin, which would set a loadable save aside as unreadable.</summary>+ [Test]+ public void ALoadWarningKindWithNoStringIsOnlyLogged()+ {+ var yaml = AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text;+ var key = "save.warning." + GameSession.ContentChanged + ":";+ StringAssert.Contains("\n" + key, yaml);+ var text = UiText.Parse(string.Join("\n", yaml.Split('\n').Where(l => !l.StartsWith(key))));+ Assert.IsFalse(text.Has("save.warning." + GameSession.ContentChanged));+ var store = TempStore();+ store.WriteAutosave(GameSession.New(C, 9, Mode.Historical).Save.Write().Replace("content " + C.Hash, "content " + new string('0', 64)));+ var notes = new List<string>();+ LogAssert.Expect(LogType.Warning, "Autosave loaded with a warning: " + GameSession.ContentChanged);+ GameStart.Begin(C, store, () => 6UL, notes, text, out var resumed);+ Assert.IsTrue(resumed, "the save is continued, not set aside");+ Assert.IsEmpty(notes);+ Assert.IsTrue(File.Exists(store.AutosavePath));+ Assert.IsFalse(File.Exists(Path.Combine(store.Directory, "autosave.bad.txt")));+ }+/// <summary>The start never blocks: a refusal code with no string falls back to the one short localised reason (#631),/// instead of throwing a missing-key error out of GameStart.Begin.</summary>[Test]@@ -188,6 +210,32 @@ public class SaveUiTestsAssert.AreEqual(1, System.Text.RegularExpressions.Regex.Matches(en, "new game").Count, "said once (N4)");}+ /// <summary>#637: a save that loads with warnings (made with other content; and then a replay that ends elsewhere) is+ /// continued, and each warning kind is said in the player's language, English and Hebrew, never the sim's English. The+ /// sim returns the kind; the kind goes to the log.</summary>+ [TestCase("strings.en.yaml", "content_changed")]+ [TestCase("strings.he.yaml", "content_changed")]+ [TestCase("strings.en.yaml", "content_changed", "replay_differs")]+ [TestCase("strings.he.yaml", "content_changed", "replay_differs")]+ public void ALoadWarningIsSaidInThePlayersLanguage(string file, params string[] kinds)+ {+ var text = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Folder + "/" + file).text, file);+ var played = GameSession.New(C, 9, Mode.Historical);+ played.Step(new Command[] { new SetMobilization(1.0) });+ var save = played.Save.Write().Replace("content " + C.Hash, "content " + new string('0', 64));+ if (kinds.Length > 1) save = save.Replace("seed 9", "seed 10"); // other content, so a replay that ends elsewhere only warns+ var store = TempStore();+ store.WriteAutosave(save);+ var notes = new List<string>();+ foreach (var kind in kinds) LogAssert.Expect(LogType.Warning, "Autosave loaded with a warning: " + kind);+ var session = GameStart.Begin(C, store, () => 6UL, notes, text, out var resumed);+ Assert.IsTrue(resumed);+ Assert.AreEqual(1, session.State.Turn);+ var expected = new List<string>();+ foreach (var kind in kinds) expected.Add(text.Has("save.warning." + kind) ? text["save.warning." + kind] : "<no string save.warning." + kind + ">");+ Assert.AreEqual(expected.ToArray(), notes.ToArray(), file);+ }+[Test]public void AReadThatFailsAndASetAsideThatFailsNeverStopTheStart(){@@ -370,9 +418,9 @@ public class SaveUiTestsvar 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>();+ LogAssert.Expect(LogType.Warning, "Autosave loaded with a warning: " + GameSession.ContentChanged);var session = GameStart.Begin(C, store, () => 1UL, notes, Text);- Assert.AreEqual(1, notes.Count);- StringAssert.Contains("different game content", notes[0]);+ Assert.AreEqual(new[] { Text["save.warning." + GameSession.ContentChanged] }, notes.ToArray()); // #637Assert.IsTrue(File.Exists(store.AutosavePath), "a warning is not a failure: the file is kept until the next turn's autosave replaces it");Assert.AreEqual(0, session.State.Turn);}diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yamlindex 172d5c097..bcd553448 100644--- a/unity/Assets/UI/strings.en.yaml+++ b/unity/Assets/UI/strings.en.yaml@@ -256,5 +256,8 @@ save.unreadable: "Your saved game could not be loaded ({0}). A new game has starsave.reason_other: "the file could not be read or replayed"save.refused.older_rules: "Your saved game was made with an earlier version of the game's rules and cannot be continued. A new game has started."save.refused.newer_version: "Your saved game was made with a newer version of the game and cannot be opened here. A new game has started."+save.warning.content_changed: "This save is from an earlier version of the game, so events may unfold a little differently."+save.warning.replay_differs: "The game was restored, but not exactly as it was saved."boot.failed: "Statecraft could not start: {0}. Reload the page."+boot.reason_other: "its files failed to load"save.write_failed: "Your game could not be saved."diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yamlindex 4e1f1adfb..9a3a48360 100644--- a/unity/Assets/UI/strings.he.yaml+++ b/unity/Assets/UI/strings.he.yaml@@ -250,5 +250,12 @@ save.unreadable: "לא ניתן היה לטעון את המשחק השמור ({0save.reason_other: "לא ניתן היה לקרוא את הקובץ או לשחזר את המשחק"save.refused.older_rules: "המשחק השמור נוצר בגרסה קודמת של חוקי המשחק ואי אפשר להמשיך אותו. משחק חדש התחיל."save.refused.newer_version: "המשחק השמור נוצר בגרסה חדשה יותר של המשחק ואי אפשר לפתוח אותו כאן. משחק חדש התחיל."+# save.warning.*: a save made with other content is continued, and each warning kind the sim returns+# (GameSession.ContentChanged, ReplayDiffers) is said here, not in the sim's English (#637). For the native reviewer (#564).+save.warning.content_changed: "השמירה הזאת מגרסה קודמת של המשחק, לכן ייתכן שהאירועים יתפתחו קצת אחרת."+save.warning.replay_differs: "המשחק שוחזר, אבל לא בדיוק כפי שנשמר."boot.failed: "לא ניתן היה להפעיל את Statecraft: {0}. יש לטעון את הדף מחדש."+# boot.reason_other fills boot.failed's {0} instead of the exception's English text, which goes to the log (#637).+# For the native reviewer (#564).+boot.reason_other: "קבצי המשחק לא נטענו"save.write_failed: "לא ניתן היה לשמור את המשחק."