A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
fix(unity): smoke runs never touch the player's save; GameRoot review fixes
eyalgolanc1210a833883
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex 3b72b66e2..151b79967 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -4,6 +4,7 @@ using System.Collections;using System.Collections.Generic;using System.Globalization;using System.Linq;+using System.Text.RegularExpressions;using Statecraft.Game.Boot;using Statecraft.Game.Map;using Statecraft.Sim;@@ -24,7 +25,8 @@ namespace Statecraft.Game.UI[ExecuteAlways]public sealed class GameRoot : MonoBehaviour{- public const int DefaultSmokeTurns = 5;+ /// <summary>Turns a bare smoke flag ("?smoke", "-smoke") plays.</summary>+ internal const int DefaultSmokeTurns = 5;[SerializeField] GameBoot boot = null!;[SerializeField] UIDocument document = null!;@@ -43,13 +45,18 @@ namespace Statecraft.Game.UIpublic SimBridge? Bridge { get; private set; }/// <summary>Where the autosave lives; null (the default) = SaveStore.ForPlatform(). Tests set a temporary folder.</summary>- public SaveStore? Store { get; set; }+ internal SaveStore? Store { get; set; }public void Configure(GameBoot boot, UIDocument document, TextAsset strings, PortraitCatalog portraits, MapScene map,PlacementLayer placements, MapPointer pointer, CameraController cameraController){+ var oldBoot = this.boot;this.boot = boot; this.document = document; this.strings = strings; this.portraits = portraits; this.map = map;this.placements = placements; this.pointer = pointer; this.cameraController = cameraController;+ // An enabled GameRoot is already subscribed to the old boot's Ready (OnEnable): move the subscription.+ if (!isActiveAndEnabled) return;+ if (oldBoot != null) oldBoot.Ready -= Begin;+ if (this.boot != null) this.boot.Ready += Begin;}void OnEnable() { if (boot != null) boot.Ready += Begin; }@@ -60,19 +67,24 @@ namespace Statecraft.Game.UIShutdown();}- /// <summary>Smoke-test turn count: from the page URL on WebGL ("?smoke=N", or "?smoke" for DefaultSmokeTurns; the flag- /// must start a query parameter and end at a word boundary, UrlFlags), else from the command line ("-smoke N").- /// 0 when not asked.</summary>- public static int SmokeTurns(string? url, string[] args, bool webgl)+ // "smoke" as a whole query parameter: bare ("?smoke", "&smoke=") or with a number; it ends at '&', '#' or the end, so+ // "?smoke-x", "?smoker" and "?smoke=five" are not the flag (tighter than UrlFlags' word boundary, amendment A3).+ static readonly Regex SmokeQuery = new Regex(@"[?&]smoke(?:=(\d*))?(?=&|#|$)", RegexOptions.CultureInvariant);++ /// <summary>Smoke-test turn count: from the page URL on WebGL, else from the command line. "?smoke=N" / "-smoke N"+ /// play N turns (0 = off); a bare "?smoke" / "-smoke" plays DefaultSmokeTurns. 0 when not asked.</summary>+ internal static int SmokeTurns(string? url, string[] args, bool webgl){if (webgl){- if (!UrlFlags.Has(url, "smoke")) return 0;- var n = UrlFlags.Int(url, "smoke");- return n > 0 ? n : DefaultSmokeTurns;+ var m = SmokeQuery.Match(url ?? "");+ if (!m.Success) return 0;+ var digits = m.Groups[1].Value;+ return digits.Length == 0 ? DefaultSmokeTurns : int.TryParse(digits, NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? n : 0;}var i = Array.IndexOf(args, "-smoke");- return i >= 0 && i + 1 < args.Length && int.TryParse(args[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out var t) ? t : 0;+ if (i < 0) return 0;+ return i + 1 < args.Length && int.TryParse(args[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out var t) ? t : DefaultSmokeTurns;}public static int SmokeTurns() =>@@ -82,7 +94,7 @@ namespace Statecraft.Game.UIpublic void Begin(GameInputs inputs) => Begin(inputs, SmokeTurns());/// <summary>Starts (or restarts) the game over the built map. <paramref name="smoke"/> > 0 plays that many turns.</summary>- public void Begin(GameInputs inputs, int smoke)+ internal void Begin(GameInputs inputs, int smoke){if (inputs == null) throw new ArgumentNullException(nameof(inputs));foreach (var (value, field) in new (UnityEngine.Object?, string)[] { (document, nameof(document)), (strings, nameof(strings)),@@ -112,12 +124,19 @@ namespace Statecraft.Game.UIOwn(new CabinetPresenter(root, bridge, text, portraits));var names = SettlementPlacer.Parse(inputs.Map.SettlementsYaml).ToDictionary(s => s.Id, s => s.Name);var info = Own(new InfoPanelPresenter(root, bridge, text, names));- Own(new NewGamePresenter(root, bridge, store, toast, text, GameStart.NewSeed));- if (smoke == 0) Own(GameStart.Autosave(bridge, store, text, toast.Show));+ // A smoke session never touches the player's save: no autosave, and no New Game (which deletes the autosave).+ // Leaving New Game out is safer than handing it a throwaway store: no file is ever deleted, no path has to be+ // right on every platform, and the scripted run never presses it.+ if (smoke == 0)+ {+ Own(new NewGamePresenter(root, bridge, store, toast, text, GameStart.NewSeed));+ Own(GameStart.Autosave(bridge, store, text, toast.Append)); // appends: the turn's refusals stay visible+ }Func<Vector2, bool> overUi = p => UiPointer.IsOverUi(root.panel, p, Screen.height);var terrain = map.Terrain;var size = terrain.terrainData.size;+ var oldBounds = cameraController.Bounds;cameraController.IsOverUi = overUi;cameraController.Bounds = new Rect(terrain.transform.position.x, terrain.transform.position.z, size.x, size.z);pointer.Map = map;@@ -135,6 +154,8 @@ namespace Statecraft.Game.UIpointer.HexClicked -= onHex;if (pointer.IsOverUi == overUi) pointer.IsOverUi = null;if (cameraController.IsOverUi == overUi) cameraController.IsOverUi = null;+ if (pointer.Map == map) pointer.Map = null;+ cameraController.Bounds = oldBounds;}));drawn = null;RenderPlacementsIfChanged();@@ -192,9 +213,9 @@ namespace Statecraft.Game.UI{var shown = card.Shown;var option = root.Q<VisualElement>("event-options")?.Q<Button>();- if (option == null || guard >= 50) { log($"SMOKE FAIL event {shown.Id} has no option to press"); yield break; }+ if (option == null || guard >= 50) { log(FormattableString.Invariant($"SMOKE FAIL event {shown.Id} has no option to press")); yield break; }if (!Press(option, log)) yield break;- if (card.Shown == shown) { log($"SMOKE FAIL the option '{option.text}' for event {shown.Id} was not taken"); yield break; }+ if (card.Shown == shown) { log(FormattableString.Invariant($"SMOKE FAIL the option '{option.text}' for event {shown.Id} was not taken")); yield break; }yield return null;}var turn = bridge.State.Turn;@@ -205,7 +226,7 @@ namespace Statecraft.Game.UItry { pressed = Press(root.Q<Button>("end-turn"), log); }finally { bridge.TurnEnded -= count; }if (!pressed) yield break;- if (bridge.State.Turn != turn + 1) { log($"SMOKE FAIL End Turn did not end turn {turn}"); yield break; }+ if (bridge.State.Turn != turn + 1) { log(FormattableString.Invariant($"SMOKE FAIL End Turn did not end turn {turn}")); yield break; }var s = bridge.State;log(FormattableString.Invariant($"SMOKE turn {s.Turn} {s.Date:yyyy-MM-dd} refused {refused}"));}diff --git a/unity/Assets/Scripts/UI/GameStart.cs b/unity/Assets/Scripts/UI/GameStart.csindex 256e57103..b70eea0a5 100644--- a/unity/Assets/Scripts/UI/GameStart.cs+++ b/unity/Assets/Scripts/UI/GameStart.cs@@ -8,7 +8,8 @@ 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.- /// <paramref name="fresh"/> is used only by tests (New Game goes through SimBridge.Replace); it ignores the autosave.</summary>+ /// <paramref name="fresh"/> ignores the autosave (neither read nor set aside): GameRoot's smoke run uses it, so a smoke+ /// session never touches the player's save, and tests use it. New Game goes through SimBridge.Replace instead.</summary>public static class GameStart{public static ulong NewSeed() => (ulong)DateTime.UtcNow.Ticks;diff --git a/unity/Assets/Scripts/UI/ToastPresenter.cs b/unity/Assets/Scripts/UI/ToastPresenter.csindex 33d64df2b..04ffe1a97 100644--- a/unity/Assets/Scripts/UI/ToastPresenter.cs+++ b/unity/Assets/Scripts/UI/ToastPresenter.cs@@ -34,6 +34,11 @@ namespace Statecraft.Game.UIpublic void Show(string line) => Show(new[] { line });+ /// <summary>Adds a line under what is shown (alone when nothing is), e.g. a failed autosave after the turn's+ /// refusals.</summary>+ public void Append(string line) =>+ Show(label.style.display.value == DisplayStyle.Flex && label.text.Length > 0 ? label.text + "\n" + line : line);+/// <summary>Shows why an order was refused ("Not done: ...").</summary>public void Refuse(string reason) => Show(text.Format("toast.refused", reason));diff --git a/unity/Assets/Tests/EditMode/GameSceneTests.cs b/unity/Assets/Tests/EditMode/GameSceneTests.csindex 66dbfc5d8..e89d9ea47 100644--- a/unity/Assets/Tests/EditMode/GameSceneTests.cs+++ b/unity/Assets/Tests/EditMode/GameSceneTests.cs@@ -84,7 +84,7 @@ public class GameSceneTests{var root = Boot();Assert.IsNotNull(root.Bridge);- Assert.AreEqual(root.Bridge!.State.Date.Year.ToString(), Ui.Q<Label>("year").text);+ Assert.AreEqual(root.Bridge!.State.Date.Year.ToString(System.Globalization.CultureInfo.InvariantCulture), Ui.Q<Label>("year").text);Assert.AreEqual("Click the map to inspect a hex", Ui.Q<Label>("info-title").text);Assert.AreEqual(new DateTime(1948, 5, 15), root.Bridge.State.Date, "no autosave: a new game");var pointer = Object.FindFirstObjectByType<MapPointer>();@@ -166,6 +166,14 @@ public class GameSceneTestspublic void AClickOnTheTerrainFillsTheInfoPanel(){Boot();+ var pointer = Object.FindFirstObjectByType<MapPointer>();+ Assert.IsTrue(pointer.HandleClick(AimAtTelAviv()), "the ray hit the terrain");+ Assert.AreEqual("Tel Aviv", Ui.Q<Label>("info-title").text);+ }++ /// <summary>Points the main camera straight down at Tel Aviv and returns the screen centre.</summary>+ static Vector2 AimAtTelAviv()+ {var map = Object.FindFirstObjectByType<MapScene>();var c = Inputs.Content;var tlv = c.SettlementHexes.Single(s => s.Id == "tel_aviv");@@ -174,13 +182,12 @@ public class GameSceneTestsvar cam = Camera.main!;cam.transform.position = new Vector3(ground.x, 50_000f, ground.z);cam.transform.rotation = Quaternion.Euler(90, 0, 0);- var pointer = Object.FindFirstObjectByType<MapPointer>();- Assert.IsTrue(pointer.HandleClick(new Vector2(cam.pixelWidth / 2f, cam.pixelHeight / 2f)), "the ray hit the terrain");- Assert.AreEqual("Tel Aviv", Ui.Q<Label>("info-title").text);+ return new Vector2(cam.pixelWidth / 2f, cam.pixelHeight / 2f);}- // One label each presenter writes on every change: HUD, toast, info panel, Why, Budget, Defence, Cabinet.- static readonly string[] Watched = { "year", "toast", "info-title", "why-turn", "budget-money", "mob-level", "cabinet-coalition" };+ // One label each presenter writes on every change: HUD, toast, info panel, Why, Budget, Defence, Cabinet, event card+ // (the card writes its title while an event is open, so the test opens one first).+ static readonly string[] Watched = { "year", "toast", "info-title", "why-turn", "budget-money", "mob-level", "cabinet-coalition", "event-title" };// Carry 1, 3-7, 9: disabling GameRoot disposes every presenter, the autosave and its own hooks.[Test]@@ -188,10 +195,23 @@ public class GameSceneTests{var root = Boot();var bridge = root.Bridge!;+ var c = Inputs.Content;+ var g = GameSession.New(c, GoldenRun.Seed, Mode.Historical);+ while (!g.State.PendingEvents.Contains("armistice_egypt")) g.Step(new Command[0]);+ bridge.Replace(g);+ Assert.AreEqual(DisplayStyle.Flex, Ui.Q("event-card").style.display.value, "an event is open before the disable");var pointer = Object.FindFirstObjectByType<MapPointer>();+ var camera = Camera.main.GetComponent<CameraController>();+ var image = Ui.Q("minimap-image");+ var texture = image.style.backgroundImage.value.texture;+ Assert.IsTrue(texture != null, "the minimap has its texture");root.enabled = false;Assert.IsNull(pointer.IsOverUi, "the pointer no longer asks a disposed panel");- Assert.IsNull(Camera.main.GetComponent<CameraController>().IsOverUi);+ Assert.IsNull(camera.IsOverUi);+ Assert.IsNull(pointer.Map, "the pointer no longer picks on this map");+ Assert.AreEqual(float.MaxValue, camera.Bounds.width, "the camera bounds are restored");+ Assert.IsTrue(texture == null, "the minimap texture is destroyed");+ Assert.AreEqual(StyleKeyword.Null, image.style.backgroundImage.keyword, "nothing draws the destroyed texture");foreach (var label in Watched)Ui.Q<Label>(label).text = "untouched";var turn = bridge.State.Turn;@@ -203,6 +223,7 @@ public class GameSceneTestsUiTestKit.Press(Ui.Q<Button>("new-game")); UiTestKit.Press(Ui.Q<Button>("new-game"));Assert.AreSame(session, bridge.Session, "NewGamePresenter");Assert.AreEqual(DisplayStyle.None, Ui.Q("event-card").style.display.value, "EventCardPresenter hid its card");+ Assert.IsFalse(pointer.HandleClick(AimAtTelAviv()), "a map click no longer reaches the info panel");bridge.Queue(new SetMobilization(0.1));bridge.EndTurn();foreach (var label in Watched)@@ -229,15 +250,84 @@ public class GameSceneTestsAssert.AreEqual(hash, root.Bridge!.State.Hash(), "the next start continues the autosave");}- // Carry 11: the autosave subscribes after the toast, so a save failure is not cleared by the turn's own toast.+ // Carry 11 and review M4: the autosave subscribes after the toast and appends, so a save failure is shown next to+ // the turn's refusals, not cleared by them and not replacing them.[Test]- public void ASaveFailureIsNotHiddenByTheTurnsToast()+ public void ASaveFailureIsShownAlongsideTheTurnsRefusals(){File.WriteAllText(saveDir, "a file where the save folder should be");var root = Boot(new SaveStore(saveDir));+ var tlv = Inputs.Content.SettlementHexes.Single(s => s.Id == "tel_aviv");+ Assert.IsNull(root.Bridge!.Queue(new MapAction(MapActions.TransitCamp, tlv.Q, tlv.R)), "queued; the sim refuses it in 1948");LogAssert.Expect(LogType.Warning, new System.Text.RegularExpressions.Regex("^Autosave could not be written"));- root.Bridge!.EndTurn();- Assert.AreEqual(Text["save.write_failed"], Ui.Q<Label>("toast").text);+ root.Bridge.EndTurn();+ var lines = Ui.Q<Label>("toast").text.Split('\n');+ Assert.AreEqual(2, lines.Length, Ui.Q<Label>("toast").text);+ StringAssert.StartsWith("Not done: ", lines[0]);+ Assert.AreEqual(Text["save.write_failed"], lines[1]);+ Assert.AreEqual(DisplayStyle.Flex, Ui.Q("toast").style.display.value);+ }++ [Test]+ public void AppendAddsALineOrShowsItAlone()+ {+ using var ui = new UiTestKit();+ var bridge = new SimBridge(GameSession.New(Inputs.Content, GoldenRun.Seed, Mode.Historical), Text);+ using var toast = new ToastPresenter(ui.Root, bridge, Text);+ toast.Append("one");+ Assert.AreEqual("one", ui.Q<Label>("toast").text);+ Assert.AreEqual(DisplayStyle.Flex, ui.Q<Label>("toast").style.display.value);+ toast.Append("two");+ Assert.AreEqual("one\ntwo", ui.Q<Label>("toast").text);+ toast.Clear();+ toast.Append("three");+ Assert.AreEqual("three", ui.Q<Label>("toast").text);+ }++ // Review I1: a smoke run never touches the player's save, not even through New Game.+ [Test]+ public void ASmokeBootNeverTouchesThePlayersSave()+ {+ var player = new SimBridge(GameSession.New(Inputs.Content, 9, Mode.Historical), Text);+ player.EndTurn();+ Directory.CreateDirectory(saveDir);+ var path = Path.Combine(saveDir, SaveStore.AutosaveName);+ var saved = player.Session.Save.Write();+ File.WriteAllText(path, saved);+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ Object.FindFirstObjectByType<MapScene>().Build(Inputs.Map);+ var root = Object.FindFirstObjectByType<GameRoot>();+ root.Store = new SaveStore(saveDir);+ LogAssert.Expect(LogType.Warning, "SMOKE FAIL the smoke run needs play mode or a player");+ root.Begin(Inputs, 5);+ Assert.AreEqual(0, root.Bridge!.State.Turn, "a fresh game, not the player's");+ var session = root.Bridge.Session;+ UiTestKit.Press(Ui.Q<Button>("new-game")); UiTestKit.Press(Ui.Q<Button>("new-game"));+ Assert.AreSame(session, root.Bridge.Session, "New Game does nothing in a smoke run");+ root.Bridge.EndTurn();+ Assert.AreEqual(saved, File.ReadAllText(path), "the player's autosave is untouched");+ Assert.AreEqual(new[] { path }, Directory.GetFiles(saveDir));+ }++ // Review M6: Configure on an enabled GameRoot moves the Ready subscription to the new boot.+ [Test]+ public void ConfigureMovesTheReadySubscription()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var root = Object.FindFirstObjectByType<GameRoot>();+ var old = Object.FindFirstObjectByType<GameBoot>();+ var other = new GameObject("OtherBoot").AddComponent<GameBoot>();+ static int Listeners(GameBoot b) =>+ (typeof(GameBoot).GetField("Ready", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(b) as Delegate)?.GetInvocationList().Length ?? 0;+ Assert.AreEqual(1, Listeners(old), "subscribed while enabled");+ var so = new SerializedObject(root);+ Object R(string f) => so.FindProperty(f).objectReferenceValue;+ root.Configure(other, (UIDocument)R("document"), (TextAsset)R("strings"), (PortraitCatalog)R("portraits"), (MapScene)R("map"),+ (PlacementLayer)R("placements"), (MapPointer)R("pointer"), (CameraController)R("cameraController"));+ Assert.AreEqual(0, Listeners(old));+ Assert.AreEqual(1, Listeners(other));+ root.enabled = false;+ Assert.AreEqual(0, Listeners(other));}// Carry 10: placements are drawn at start and redrawn only when State.Placements changes.@@ -304,18 +394,34 @@ public class GameSceneTestsAssert.IsFalse(log.Any(l => l.StartsWith("SMOKE OK")));}- // Amendment A3: the URL flag must start a query parameter and end at a word boundary.+ // Amendment A3 and review M5: "smoke" must be a whole query parameter (bare, or =N); =0 means off; a bare flag+ // (URL or command line) runs DefaultSmokeTurns.[Test]public void SmokeTurnsComeFromTheUrlOrTheCommandLine(){- Assert.AreEqual(5, GameRoot.SmokeTurns("http://localhost:8000/?golden&smoke=5", new string[0], true));- Assert.AreEqual(3, GameRoot.SmokeTurns("http://localhost:8000/?smoke=3", new string[0], true));- Assert.AreEqual(GameRoot.DefaultSmokeTurns, GameRoot.SmokeTurns("http://localhost:8000/?smoke", new string[0], true));- Assert.AreEqual(0, GameRoot.SmokeTurns("http://localhost:8000/smoke-test/index.html", new string[0], true));- Assert.AreEqual(0, GameRoot.SmokeTurns("http://localhost:8000/?smoker=4", new string[0], true));- Assert.AreEqual(0, GameRoot.SmokeTurns("http://localhost:8000/", new string[0], true));- Assert.AreEqual(4, GameRoot.SmokeTurns(null, new[] { "Statecraft", "-smoke", "4" }, false));- Assert.AreEqual(0, GameRoot.SmokeTurns(null, new[] { "Statecraft" }, false));+ var none = new string[0];+ int Web(string url) => GameRoot.SmokeTurns(url, none, true);+ int Desk(params string[] args) => GameRoot.SmokeTurns(null, args, false);+ Assert.AreEqual(5, Web("http://localhost:8000/?golden&smoke=5"));+ Assert.AreEqual(3, Web("http://localhost:8000/?smoke=3"));+ Assert.AreEqual(3, Web("http://localhost:8000/?smoke=3&golden"));+ Assert.AreEqual(3, Web("http://localhost:8000/?smoke=3#top"));+ Assert.AreEqual(GameRoot.DefaultSmokeTurns, Web("http://localhost:8000/?smoke"));+ Assert.AreEqual(GameRoot.DefaultSmokeTurns, Web("http://localhost:8000/?smoke&golden"));+ Assert.AreEqual(GameRoot.DefaultSmokeTurns, Web("http://localhost:8000/?golden&smoke="));+ Assert.AreEqual(0, Web("http://localhost:8000/?smoke=0"), "explicitly off");+ Assert.AreEqual(0, Web("http://localhost:8000/smoke-test/index.html"));+ Assert.AreEqual(0, Web("http://localhost:8000/?smoker=4"));+ Assert.AreEqual(0, Web("http://localhost:8000/?smoke-x"));+ Assert.AreEqual(0, Web("http://localhost:8000/?smoke=five"));+ Assert.AreEqual(0, Web("http://localhost:8000/?nosmoke=5"));+ Assert.AreEqual(0, Web("http://localhost:8000/"));+ Assert.AreEqual(0, Web(null!));+ Assert.AreEqual(4, Desk("Statecraft", "-smoke", "4"));+ Assert.AreEqual(0, Desk("Statecraft", "-smoke", "0"), "explicitly off");+ Assert.AreEqual(GameRoot.DefaultSmokeTurns, Desk("Statecraft", "-smoke"));+ Assert.AreEqual(GameRoot.DefaultSmokeTurns, Desk("Statecraft", "-smoke", "-golden"));+ Assert.AreEqual(0, Desk("Statecraft"));Assert.AreEqual(0, GameRoot.SmokeTurns("http://localhost/?smoke=5", new[] { "Statecraft" }, false), "desktop reads only the command line");}}