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.

unity: the ?mvp=1 dev flag and the score on the HUD (refs #380) (#598)

Eyal Golanaef4e7a95b8f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ae42ac6a1..61d275e2b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,9 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
- GDD v0.1 Phase 1, the Unity queue takes the GDD orders (refs #380): `AssignWorkers`, `Train` and `CancelTraining`
now queue in the slice, one per city, per city and track, and per cohort; an unknown city, training track or cohort is
refused before End Turn. A reflection test fails for any command type that reaches the queue's default branch.
+- GDD v0.1 Phase 1, a dev flag and the score (refs #380): `?mvp=1` in the WebGL page's URL loads the content through
+ `MvpSlice.Overlay` (the GDD slice) for playtests. The golden check and the smoke run ignore it, and a slice game never
+ reads, sets aside or writes the player's autosave (and has no New Game). In the GDD loop the top bar shows the score.
- Sourced Hebrew names in content (refs #558, #193), data only (no screen shows them yet): `title_he` for 30 of 31
offices, plus `title_he_f` where a woman held the office (Labour, Foreign Affairs), `name_he` for 25 of 26 parties,
the 8 governments and the 25 game settlements, `body_he` for the 4 legislatures, each with its own `*_he_sources`
diff --git a/unity/Assets/Scripts/Boot/GameBoot.cs b/unity/Assets/Scripts/Boot/GameBoot.cs
index a0d62f497..37c399962 100644
--- a/unity/Assets/Scripts/Boot/GameBoot.cs
+++ b/unity/Assets/Scripts/Boot/GameBoot.cs
@@ -41,16 +41,30 @@ namespace Statecraft.Game.Boot
static readonly Regex BarePath = new Regex(@"(?<![\w:/.\\])(?:file://)?(?:/|[A-Za-z]:\\)[^\s'""()]+");
static string FileName(string path) => path.Substring(path.LastIndexOfAny(new[] { '/', '\\' }) + 1);
+ static readonly Regex MvpValue = new Regex(@"[?&]mvp=([^&#]*)", RegexOptions.CultureInvariant);
+
+ /// <summary>The ?mvp=1 dev flag (#380): load the content through MvpSlice.Overlay, the GDD slice, for playtests. Only
+ /// one "mvp" parameter whose value is exactly "1" turns it on (not "01", "1x" or a second value); the golden check and
+ /// the smoke run ignore it and keep the real content, so their pinned hashes hold.</summary>
+ internal static bool SliceRequested(string? url, bool golden, int smoke)
+ {
+ if (golden || smoke != 0) return false;
+ var values = MvpValue.Matches(url ?? "");
+ return values.Count == 1 && values[0].Groups[1].Value == "1";
+ }
+
async void Start()
{
DiagLog.Init();
DiagLog.BootPhase("player started");
- await BootAsync(LoadAsync);
+ var slice = SliceRequested(Application.absoluteURL, GoldenCheck.Requested(), Statecraft.Game.UI.GameRoot.SmokeTurns());
+ if (slice) Debug.Log("MVP SLICE: content through MvpSlice.Overlay (?mvp=1); the autosave is not used");
+ await BootAsync(() => LoadAsync(slice));
}
- static async Awaitable<GameInputs> LoadAsync() => Application.platform == RuntimePlatform.WebGLPlayer
- ? await GameInputs.FetchAsync(GameInputs.StreamingUrl(), Application.buildGUID)
- : GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);
+ static async Awaitable<GameInputs> LoadAsync(bool slice) => Application.platform == RuntimePlatform.WebGLPlayer
+ ? await GameInputs.FetchAsync(GameInputs.StreamingUrl(), Application.buildGUID, slice)
+ : GameInputs.FromDisk(Paths.Content, Paths.StreamingMap, slice);
/// <summary>The boot Start runs, with the loader passed in so a test can drive the real failure path.</summary>
internal async Awaitable BootAsync(Func<Awaitable<GameInputs>> load)
diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.cs
index af8af14d0..dc51fc239 100644
--- a/unity/Assets/Scripts/Boot/GameInputs.cs
+++ b/unity/Assets/Scripts/Boot/GameInputs.cs
@@ -50,6 +50,9 @@ namespace Statecraft.Game.Boot
{
public Content Content = null!;
public MapInputs Map = null!;
+ /// <summary>True when Content is the GDD slice (MvpSlice.Overlay over the real files: the ?mvp=1 dev flag, #380). A
+ /// slice game never touches the player's autosave (GameRoot).</summary>
+ public bool Slice;
public static MapInputs MapFromDisk(string contentDir, string mapDir) => new MapInputs
{
@@ -74,17 +77,18 @@ namespace Statecraft.Game.Boot
/// <summary>A map-only, cosmetic input: "" when the file is missing (the map then skips that layer with a warning).</summary>
static string ReadIfExists(string path) => File.Exists(path) ? File.ReadAllText(path) : "";
- public static GameInputs FromDisk(string contentDir, string mapDir) =>
- new GameInputs { Content = ContentLoader.Load(contentDir), Map = MapFromDisk(contentDir, mapDir) };
+ public static GameInputs FromDisk(string contentDir, string mapDir, bool slice = false) =>
+ new GameInputs { Content = slice ? MvpSlice.Load(contentDir) : ContentLoader.Load(contentDir), Map = MapFromDisk(contentDir, mapDir), Slice = slice };
/// <summary>Builds the inputs from fetched texts (keys are manifest paths) and the packed heightmap's bytes.</summary>
- public static GameInputs FromTexts(IReadOnlyDictionary<string, string> texts, IEnumerable<string> manifest, string heightmapJson, byte[] r16z)
+ public static GameInputs FromTexts(IReadOnlyDictionary<string, string> texts, IEnumerable<string> manifest, string heightmapJson, byte[] r16z, bool slice = false)
{
var events = manifest.Where(f => f.StartsWith("events/", StringComparison.Ordinal)).ToList();
- var content = ContentLoader.Load(rel => texts.TryGetValue(rel, out var t) ? t : null, events);
+ Func<string, string?> read = rel => texts.TryGetValue(rel, out var t) ? t : null;
+ var content = ContentLoader.Load(slice ? MvpSlice.Overlay(read) : read, events); // the slice: ?mvp=1 (#380)
return new GameInputs
{
- Content = content,
+ Content = content, Slice = slice,
Map = new MapInputs
{
HeightmapJson = heightmapJson, HeightmapR16z = r16z,
@@ -187,7 +191,7 @@ namespace Statecraft.Game.Boot
/// <summary>Fetches the manifest, then starts every download before awaiting any (parallel), then loads. A transient
/// failure is retried (Done). When one download fails for good, the others still running are aborted and disposed.
/// Every URL carries <paramref name="buildId"/> (WithBuildId; the player passes Application.buildGUID).</summary>
- public static async Awaitable<GameInputs> FetchAsync(string baseUrl, string buildId = "")
+ public static async Awaitable<GameInputs> FetchAsync(string baseUrl, string buildId = "", bool slice = false)
{
var manifest = ContentManifest.Parse(await Text(Start(WithBuildId(baseUrl + "/content/" + ContentManifest.FileName, buildId)), ContentManifest.FileName));
var requests = manifest.Select(f => (file: f, request: Start(WithBuildId(baseUrl + "/content/" + f, buildId)))).ToList();
@@ -200,7 +204,7 @@ namespace Statecraft.Game.Boot
var metaText = await Text(meta, "heightmap.json");
var r16zBytes = await Bytes(r16z, HeightmapCodec.FileName);
DiagLog.BootPhase($"downloaded {texts.Count + 3} files");
- var inputs = FromTexts(texts, manifest, metaText, r16zBytes);
+ var inputs = FromTexts(texts, manifest, metaText, r16zBytes, slice);
DiagLog.BootPhase("content parsed and validated");
return inputs;
}
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 8bf65236a..25c267b70 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -173,11 +173,12 @@ namespace Statecraft.Game.UI
var text = Strings();
var store = Store ?? SaveStore.ForPlatform();
var notes = new List<string>();
- // A smoke run is reproducible: a fresh game with the golden seed, never the player's autosave.
+ // A smoke run is reproducible: a fresh game with the golden seed, never the player's autosave. A slice game (?mvp=1,
+ // #380) is fresh too: the autosave was made with other rules, so it is neither read nor set aside.
bool resumed;
var session = smoke > 0
? GameStart.Begin(inputs.Content, store, () => GoldenRun.Seed, notes, text, out resumed, fresh: true)
- : GameStart.Begin(inputs.Content, store, GameStart.NewSeed, notes, text, out resumed);
+ : GameStart.Begin(inputs.Content, store, GameStart.NewSeed, notes, text, out resumed, fresh: inputs.Slice);
DiagLog.BootPhase($"session started (turn {session.State.Turn}, replayed)");
var bridge = Bridge = new SimBridge(session, text);
var root = document.rootVisualElement;
@@ -258,14 +259,18 @@ namespace Statecraft.Game.UI
var info = Own(new InfoPanelPresenter(root, bridge, text, names, nav: nav,
selectedUnit: () => unitLayer.Selected is string id ? unitLayer.Tokens.First(p => p.Token.Unit.Id == id) : (Statecraft.Game.Map.Units.PlacedToken?)null,
regions: regions, localitiesAt: localitiesAt));
- // 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.
+ // A smoke or slice session never touches the player's save: no autosave, and no New Game (which deletes the autosave).
+ // A smoke run gets no New Game at all: no file is ever deleted, no path has to be right on every platform, and the
+ // scripted run never presses it. A slice game (?mvp=1) hides the button and takes it out of the Tab order, and its
+ // presenter refuses every press (slice: true), so even a press that reaches it deletes nothing.
NewGamePresenter? newGame = null;
+ var newGameButton = root.Q<Button>("new-game");
+ newGameButton.style.display = inputs.Slice ? DisplayStyle.None : StyleKeyword.Null;
+ newGameButton.focusable = !inputs.Slice;
if (smoke == 0)
{
- newGame = 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
+ newGame = Own(new NewGamePresenter(root, bridge, store, toast, text, GameStart.NewSeed, slice: inputs.Slice));
+ if (!inputs.Slice) Own(GameStart.Autosave(bridge, store, text, toast.Append)); // appends: the turn's refusals stay visible
}
// An outcome clip holds the pointer while it shows and in the frame it closes (the skipping click selects no hex).
@@ -313,7 +318,7 @@ namespace Statecraft.Game.UI
SyncMinimap();
// The start screen goes up in the same frame the loading state ends, so the HUD never flashes before it. While it
// shows, the camera keys are off (keyboard pan would otherwise move the hidden map; plan amendment A4).
- if (startScreen && newGame != null)
+ if (startScreen && newGame != null && !inputs.Slice) // no start screen in a slice game: its New Game would be dead
{
var cam = cameraController;
var recording = Own(new DeclarationRecording(root, text, toast.Show)); // never built in automated runs (Skipped)
diff --git a/unity/Assets/Scripts/UI/HudModel.cs b/unity/Assets/Scripts/UI/HudModel.cs
index 5ce94a8cc..9adffcb13 100644
--- a/unity/Assets/Scripts/UI/HudModel.cs
+++ b/unity/Assets/Scripts/UI/HudModel.cs
@@ -21,7 +21,7 @@ namespace Statecraft.Game.UI
/// number of immigrants who arrived during the last turn.</summary>
public sealed class HudModel
{
- public string Year = "", Turn = "", Date = "", Attention = "", SecurityLevel = "";
+ public string Year = "", Turn = "", Date = "", Attention = "", SecurityLevel = "", Score = "";
public Meter Treasury, Immigration, Security, Support, Standing, Fx;
static double Arrivals(StepResult? r) => r == null ? 0 : r.Why.Where(w => w.System == "population").Sum(w => w.Delta);
@@ -78,6 +78,7 @@ namespace Statecraft.Game.UI
Date = t.Format("hud.date", PlayerText.Date(s.Date)),
Attention = t.Format("hud.attention", b.AttentionLeft, c.RulesAt(s.Date).AttentionPerTurn),
SecurityLevel = t.Format("hud.level", s.Rung),
+ Score = c.IsGdd ? t.Format("hud.score", s.Score) : "", // the GDD loop only (#380); PR 6 moves it
Treasury = Money("treasury", s.Treasury - s.Debt, prev == null ? (double?)null : prev.Treasury - prev.Debt),
Immigration = People(Arrivals(b.Session.Last), b.BeforeLast == null ? (double?)null : Arrivals(b.BeforeLast)),
Security = Points(s.Indicators["security"], prev?.Indicators["security"]),
diff --git a/unity/Assets/Scripts/UI/HudPresenter.cs b/unity/Assets/Scripts/UI/HudPresenter.cs
index cd2dcfe2b..c24cafb8c 100644
--- a/unity/Assets/Scripts/UI/HudPresenter.cs
+++ b/unity/Assets/Scripts/UI/HudPresenter.cs
@@ -168,6 +168,9 @@ namespace Statecraft.Game.UI
var m = HudModel.From(bridge, text);
Set("year", m.Year); Set("turn", m.Turn); Set("date", m.Date); Set("attention", m.Attention);
Set("security-level", m.SecurityLevel);
+ var score = root.Q<Label>("score"); // the GDD loop only (#380): hidden when HudModel gives none
+ score.text = m.Score;
+ score.style.display = m.Score.Length == 0 ? DisplayStyle.None : DisplayStyle.Flex;
Set("treasury", m.Treasury); Set("immigration", m.Immigration); Set("security", m.Security);
Set("support", m.Support); Set("standing", m.Standing); Set("fx", m.Fx);
root.Q<Button>("end-turn").SetEnabled(bridge.State.GameOver == null);
diff --git a/unity/Assets/Scripts/UI/NewGamePresenter.cs b/unity/Assets/Scripts/UI/NewGamePresenter.cs
index a90f327eb..c589aabbb 100644
--- a/unity/Assets/Scripts/UI/NewGamePresenter.cs
+++ b/unity/Assets/Scripts/UI/NewGamePresenter.cs
@@ -12,8 +12,10 @@ namespace Statecraft.Game.UI
{
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)
+ public NewGamePresenter(VisualElement root, SimBridge bridge, SaveStore store, ToastPresenter toast, UiText text, Func<ulong> seed,
+ bool slice = false)
{
+ this.slice = slice;
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;
@@ -21,6 +23,10 @@ namespace Statecraft.Game.UI
}
readonly Button button;
+ /// <summary>A slice game (?mvp=1): New Game never deletes the player's autosave. GameRoot hides the button and builds
+ /// no start screen in a slice game, but builds this presenter with slice: true, so this flag is the guard that stops
+ /// the delete.</summary>
+ readonly bool slice;
// Any change (an order, a turn, a new session) means the prompt no longer describes what is on screen.
void Disarm() => Armed = false;
@@ -45,6 +51,7 @@ namespace Statecraft.Game.UI
/// <summary>One press of New Game: the first arms and shows the prompt, the second starts the new game.</summary>
public void Press()
{
+ if (slice) return;
if (!Armed) { Armed = true; toast.Show(text["newgame.confirm"]); return; }
Armed = false;
bool deleted = true;
diff --git a/unity/Assets/Tests/EditMode/HudTests.cs b/unity/Assets/Tests/EditMode/HudTests.cs
index 440383298..3b84647b7 100644
--- a/unity/Assets/Tests/EditMode/HudTests.cs
+++ b/unity/Assets/Tests/EditMode/HudTests.cs
@@ -33,6 +33,47 @@ public class HudTests
Assert.AreEqual("", m.Treasury.Delta); // no previous turn yet
}
+ // ---- The score (#380): only in the GDD loop, from GameState.Score ----
+
+ static readonly Content Slice = MvpSlice.Load(Paths.Content);
+ static SimBridge SliceBridge() => new SimBridge(GameSession.New(Slice, GoldenRun.Seed, Mode.Historical), Text);
+
+ [Test]
+ public void TheLegacyLoopShowsNoScore()
+ {
+ Assert.AreEqual("", HudModel.From(NewBridge(), Text).Score);
+ using var ui = new UiTestKit();
+ using var hud = new HudPresenter(ui.Root, NewBridge(), Text);
+ Assert.AreEqual(DisplayStyle.None, ui.Q<Label>("score").style.display.value);
+ }
+
+ [Test]
+ public void TheSliceShowsItsScore()
+ {
+ var bridge = SliceBridge();
+ Assert.AreEqual("Score 0", HudModel.From(bridge, Text).Score);
+ bridge.State.Score = 150;
+ Assert.AreEqual("Score 150", HudModel.From(bridge, Text).Score);
+ // The value carries left-to-right marks in a Hebrew line (U+200E, #543), as every Hebrew value does.
+ var he = HudModel.From(bridge, He).Score;
+ Assert.AreEqual("ניקוד \u200E150\u200E", he);
+ Assert.AreEqual("ניקוד 150", he.Replace("\u200E", ""));
+ }
+
+ [Test]
+ public void TheBarShowsTheSlicesScore()
+ {
+ using var ui = new UiTestKit();
+ var bridge = SliceBridge();
+ using var hud = new HudPresenter(ui.Root, bridge, Text);
+ var label = ui.Q<Label>("score");
+ Assert.AreEqual("Score 0", label.text);
+ Assert.AreEqual(DisplayStyle.Flex, label.style.display.value);
+ bridge.State.Score = 150;
+ hud.Render();
+ Assert.AreEqual("Score 150", label.text);
+ }
+
[Test]
public void EndTurnAdvancesTheGameAndShowsChanges()
{
diff --git a/unity/Assets/Tests/EditMode/InfoPanelLayoutTests.cs b/unity/Assets/Tests/EditMode/InfoPanelLayoutTests.cs
index 6cd878c41..ebaa51fb5 100644
--- a/unity/Assets/Tests/EditMode/InfoPanelLayoutTests.cs
+++ b/unity/Assets/Tests/EditMode/InfoPanelLayoutTests.cs
@@ -25,7 +25,7 @@ public class InfoPanelLayoutTests
static Dictionary<string, string> Names() => SettlementPlacer.Parse(MapFile(SettlementPlacer.DefaultFileName)).ToDictionary(t => t.Id, t => t.Name);
/// <summary>Every window size the HUD's tests use (UiLayoutTests, PromoHudTests, StartScreenTests) and a 16:10 laptop.</summary>
- static readonly (int w, int h)[] Windows =
+ internal static readonly (int w, int h)[] Windows =
{
(1920, 1080), (1280, 720), (1366, 768), (1760, 1000), (1920, 1200), (1440, 900), (1680, 1050), (1024, 768), (1280, 1024),
(1024, 1024), (960, 1080), (800, 1000), (1531, 784), (2560, 1080), (1920, 900), (1600, 757), (1366, 657), (960, 600), (390, 844),
diff --git a/unity/Assets/Tests/EditMode/MvpFlagTests.cs b/unity/Assets/Tests/EditMode/MvpFlagTests.cs
new file mode 100644
index 000000000..fb5ef567d
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/MvpFlagTests.cs
@@ -0,0 +1,221 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Boot;
+using Statecraft.Game.Map;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+using UnityEditor.SceneManagement;
+using UnityEngine.UIElements;
+using Object = UnityEngine.Object;
+
+/// <summary>The ?mvp=1 dev flag (#380): it loads the content through MvpSlice.Overlay (the GDD slice) for playtests. It is
+/// off by default, the golden check and the smoke run ignore it, and a slice game never reads, sets aside or writes the
+/// player's autosave.</summary>
+public class MvpFlagTests
+{
+ const string Page = "https://example.org/statecraft/index.html";
+
+ [TestCase(Page + "?mvp=1", false, 0, ExpectedResult = true)]
+ [TestCase(Page + "?lang=he&mvp=1", false, 0, ExpectedResult = true)]
+ [TestCase(Page + "?mvp=1#top", false, 0, ExpectedResult = true)]
+ [TestCase(Page, false, 0, ExpectedResult = false)]
+ [TestCase(Page + "?mvp=0", false, 0, ExpectedResult = false)]
+ [TestCase(Page + "?mvp", false, 0, ExpectedResult = false)]
+ [TestCase(Page + "?mvp-x=1", false, 0, ExpectedResult = false)]
+ [TestCase(Page + "?mvp=2", false, 0, ExpectedResult = false)] // exactly "1": not any other number
+ [TestCase(Page + "?mvp=10", false, 0, ExpectedResult = false)]
+ [TestCase(Page + "?mvp=01", false, 0, ExpectedResult = false)]
+ [TestCase(Page + "?mvp=1x", false, 0, ExpectedResult = false)]
+ [TestCase(Page + "?mvp=1.5", false, 0, ExpectedResult = false)]
+ [TestCase(Page + "?mvp=1&mvp=0", false, 0, ExpectedResult = false)] // two values: not a clear request
+ [TestCase(Page + "?mvp=0&mvp=1", false, 0, ExpectedResult = false)]
+ [TestCase(Page + "?mvpx=1&mvp=1", false, 0, ExpectedResult = true)] // another parameter's name does not count
+ [TestCase(Page + "?xmvp=1", false, 0, ExpectedResult = false)]
+ [TestCase("", false, 0, ExpectedResult = false)]
+ [TestCase(null, false, 0, ExpectedResult = false)]
+ [TestCase(Page + "?golden&mvp=1", true, 0, ExpectedResult = false)] // the golden check runs the real content
+ [TestCase(Page + "?mvp=1&smoke=5", false, 5, ExpectedResult = false)] // and so does the smoke run
+ [TestCase(Page + "?golden&smoke=5&mvp=1", true, 5, ExpectedResult = false)]
+ public bool WhichUrlsTurnTheSliceOn(string? url, bool golden, int smoke) => GameBoot.SliceRequested(url, golden, smoke);
+
+ [Test]
+ public void WithoutTheFlagTheContentIsTheRealContent()
+ {
+ var inputs = GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);
+ Assert.IsFalse(inputs.Slice);
+ Assert.IsFalse(inputs.Content.IsGdd);
+ Assert.AreEqual(ContentLoader.Load(Paths.Content).Hash, inputs.Content.Hash, "the real content hash does not move");
+ }
+
+ [Test]
+ public void TheFlagLoadsTheSliceFromDisk()
+ {
+ var inputs = GameInputs.FromDisk(Paths.Content, Paths.StreamingMap, slice: true);
+ Assert.IsTrue(inputs.Slice);
+ Assert.IsTrue(inputs.Content.IsGdd);
+ Assert.AreEqual(new[] { "tel_aviv" }, inputs.Content.Cities.Select(c => c.Id).ToArray());
+ Assert.AreEqual(MvpSlice.Load(Paths.Content).Hash, inputs.Content.Hash);
+ }
+
+ /// <summary>The WebGL path: the fetched texts (keys are manifest paths), with and without the flag.</summary>
+ [Test]
+ public void TheFlagLoadsTheSliceFromFetchedTexts()
+ {
+ var manifest = ContentManifest.Collect(Paths.Content);
+ var texts = manifest.ToDictionary(f => f, f => File.ReadAllText(Path.Combine(Paths.Content, f)));
+ var meta = File.ReadAllText(Path.Combine(Paths.StreamingMap, "heightmap.json"));
+ var r16z = File.ReadAllBytes(Path.Combine(Paths.StreamingMap, HeightmapCodec.FileName));
+
+ var real = GameInputs.FromTexts(texts, manifest, meta, r16z);
+ Assert.IsFalse(real.Slice);
+ Assert.IsFalse(real.Content.IsGdd);
+ Assert.AreEqual(ContentLoader.Load(Paths.Content).Hash, real.Content.Hash);
+
+ var slice = GameInputs.FromTexts(texts, manifest, meta, r16z, slice: true);
+ Assert.IsTrue(slice.Slice);
+ Assert.IsTrue(slice.Content.IsGdd);
+ Assert.AreEqual(MvpSlice.Load(Paths.Content).Hash, slice.Content.Hash);
+ }
+
+ // ---- A slice game and the player's save ----
+
+ string saveDir = "";
+
+ [SetUp] public void TempSaves() => saveDir = Path.Combine(Path.GetTempPath(), "statecraft-mvp-" + Guid.NewGuid().ToString("N"));
+
+ [TearDown]
+ public void DiscardScene()
+ {
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ if (Directory.Exists(saveDir)) Directory.Delete(saveDir, true);
+ }
+
+ static GameInputs? sliceInputs;
+ static GameInputs SliceInputs => sliceInputs ??= GameInputs.FromDisk(Paths.Content, Paths.StreamingMap, slice: true);
+
+ GameRoot BootSlice()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ Object.FindFirstObjectByType<MapScene>().Build(SliceInputs.Map);
+ var root = Object.FindFirstObjectByType<GameRoot>();
+ root.Store = new SaveStore(saveDir);
+ root.Begin(SliceInputs, 0);
+ return root;
+ }
+
+ [Test]
+ public void ASliceGameLeavesThePlayersAutosaveAlone()
+ {
+ // The player's own game, saved by the real content.
+ var legacy = GameSession.New(ContentLoader.Load(Paths.Content), GoldenRun.Seed, Mode.Historical);
+ legacy.Step(Array.Empty<Command>());
+ var saved = legacy.Save.Write();
+ Directory.CreateDirectory(saveDir);
+ var path = Path.Combine(saveDir, SaveStore.AutosaveName);
+ File.WriteAllText(path, saved);
+
+ var root = BootSlice();
+ Assert.IsTrue(root.Bridge!.Content.IsGdd, "the slice is running");
+ Assert.AreEqual(0, root.Bridge.State.Turn, "a fresh slice game, not the player's save");
+ root.Bridge.EndTurn();
+ root.Bridge.EndTurn();
+
+ Assert.AreEqual(saved, File.ReadAllText(path), "the player's autosave is unchanged");
+ Assert.AreEqual(new[] { SaveStore.AutosaveName }, Directory.GetFiles(saveDir).Select(Path.GetFileName).ToArray(),
+ "nothing set aside, nothing added");
+ }
+
+ static GameInputs? realInputs;
+ static GameInputs RealInputs => realInputs ??= GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);
+
+ static UnityEngine.UIElements.Button NewGameButton() =>
+ Object.FindFirstObjectByType<UnityEngine.UIElements.UIDocument>().rootVisualElement.Q<UnityEngine.UIElements.Button>("new-game");
+
+ /// <summary>Defence in depth: even if a slice game ever got a New Game handler, pressing it twice (ask, confirm) would not
+ /// delete the player's autosave.</summary>
+ [Test]
+ public void NewGamePressedTwiceInASliceKeepsTheAutosave()
+ {
+ Directory.CreateDirectory(saveDir);
+ var path = Path.Combine(saveDir, SaveStore.AutosaveName);
+ File.WriteAllText(path, "the player's save");
+ using var ui = new UiTestKit();
+ var text = UiText.Parse(UnityEditor.AssetDatabase.LoadAssetAtPath<UnityEngine.TextAsset>(UiPaths.Strings).text);
+ var bridge = new SimBridge(GameSession.New(SliceInputs.Content, GoldenRun.Seed, Mode.Historical), text);
+ using var toast = new ToastPresenter(ui.Root, bridge, text);
+ using var newGame = new NewGamePresenter(ui.Root, bridge, new SaveStore(saveDir), toast, text, () => 7UL, slice: true);
+ var session = bridge.Session;
+ ui.Press("new-game");
+ ui.Press("new-game");
+ Assert.AreEqual("the player's save", File.ReadAllText(path), "the autosave is untouched");
+ Assert.AreSame(session, bridge.Session, "no new game started");
+ }
+
+ /// <summary>A slice game booted through GameRoot with the start screen asked for: no start screen, and New Game pressed
+ /// twice deletes nothing and starts nothing, even with its button forced back on screen (a regression that showed it).
+ /// The guard is the presenter's slice flag, which GameRoot must pass.</summary>
+ [Test]
+ public void ASliceGamesNewGameThroughGameRootDeletesNothing()
+ {
+ Directory.CreateDirectory(saveDir);
+ var path = Path.Combine(saveDir, SaveStore.AutosaveName);
+ File.WriteAllText(path, "the player's save");
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ Object.FindFirstObjectByType<MapScene>().Build(SliceInputs.Map);
+ var root = Object.FindFirstObjectByType<GameRoot>();
+ root.Store = new SaveStore(saveDir);
+ root.Begin(SliceInputs, 0, startScreen: true);
+ var ui = Object.FindFirstObjectByType<UIDocument>().rootVisualElement;
+ Assert.IsFalse(ui.Q("root").ClassListContains(StartScreenPresenter.OpenClass), "no start screen in a slice game");
+ var session = root.Bridge!.Session;
+ var button = ui.Q<Button>("new-game");
+ button.style.display = DisplayStyle.Flex; // as if a regression drew it again
+ UiTestKit.Press(button);
+ UiTestKit.Press(button);
+ Assert.AreEqual("the player's save", File.ReadAllText(path), "the autosave is untouched");
+ Assert.AreSame(session, root.Bridge.Session, "no new game started");
+ }
+
+ /// <summary>A slice game has no New Game (it would delete the player's autosave): the button is not drawn and is out of
+ /// the Tab order, rather than drawn and dead. A normal game keeps it, also after a slice game in the same scene.</summary>
+ [Test]
+ public void ASliceGameHasNoNewGameButton()
+ {
+ BootSlice();
+ var button = NewGameButton();
+ Assert.AreEqual(UnityEngine.UIElements.DisplayStyle.None, button.style.display.value, "not drawn");
+ Assert.IsFalse(button.focusable, "out of the Tab order");
+ Assert.IsFalse(button.canGrabFocus, "out of the Tab order");
+
+ var root = Object.FindFirstObjectByType<GameRoot>();
+ root.Begin(RealInputs, 0); // the same scene, now a normal game
+ Assert.AreNotEqual(UnityEngine.UIElements.DisplayStyle.None, button.style.display.value, "a normal game draws it");
+ Assert.IsTrue(button.focusable, "a normal game keeps it in the Tab order");
+ }
+
+ [Test]
+ public void ANormalGameHasItsNewGameButton()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ Object.FindFirstObjectByType<MapScene>().Build(RealInputs.Map);
+ var root = Object.FindFirstObjectByType<GameRoot>();
+ root.Store = new SaveStore(saveDir);
+ root.Begin(RealInputs, 0);
+ var button = NewGameButton();
+ Assert.AreNotEqual(UnityEngine.UIElements.DisplayStyle.None, button.style.display.value);
+ Assert.IsTrue(button.focusable);
+ }
+
+ [Test]
+ public void ASliceGameWritesNoAutosave()
+ {
+ var root = BootSlice();
+ root.Bridge!.EndTurn();
+ Assert.IsFalse(File.Exists(Path.Combine(saveDir, SaveStore.AutosaveName)));
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/MvpFlagTests.cs.meta b/unity/Assets/Tests/EditMode/MvpFlagTests.cs.meta
new file mode 100644
index 000000000..169956f5f
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/MvpFlagTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 77710788566b49c0b6a1adfb0625ebed
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/TopBarScoreLayoutTests.cs b/unity/Assets/Tests/EditMode/TopBarScoreLayoutTests.cs
new file mode 100644
index 000000000..033fb3d83
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/TopBarScoreLayoutTests.cs
@@ -0,0 +1,96 @@
+#nullable enable
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.TestTools;
+using UnityEngine.UIElements;
+
+/// <summary>The score in the top bar's date box (#380, 7b): a worst-case score stays inside the box's frame, on no other
+/// text, and whole, at every window size the HUD's tests use, in English and Hebrew.</summary>
+public class TopBarScoreLayoutTests
+{
+ static readonly Content Slice = MvpSlice.Load(Paths.Content);
+ static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ static UiText He => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");
+
+ /// <summary>Five digits with the thousands separator: well past what a Phase 1 or MVP run can score.</summary>
+ const int WorstScore = 99999;
+ /// <summary>The widest date line the box was sized for ("Turn 120 30 September 1956", Statecraft.uss .date-box).</summary>
+ static readonly System.DateTime WorstDate = new System.DateTime(1956, 9, 30);
+ const int WorstTurn = 120;
+
+ static Rect ContentBox(VisualElement e)
+ {
+ var b = e.worldBound; var s = e.resolvedStyle;
+ return Rect.MinMaxRect(b.xMin + s.borderLeftWidth + s.paddingLeft, b.yMin + s.borderTopWidth + s.paddingTop,
+ b.xMax - s.borderRightWidth - s.paddingRight, b.yMax - s.borderBottomWidth - s.paddingBottom);
+ }
+
+ static bool Inside(Rect inner, Rect outer) =>
+ inner.xMin >= outer.xMin - 0.5f && inner.xMax <= outer.xMax + 0.5f && inner.yMin >= outer.yMin - 0.5f && inner.yMax <= outer.yMax + 0.5f;
+
+ /// <summary>The label's text, measured on one line, fits its own box.</summary>
+ static bool Whole(TextElement l) =>
+ l.MeasureTextSize(l.text, 0, VisualElement.MeasureMode.Undefined, 0, VisualElement.MeasureMode.Undefined).x <= l.contentRect.width + 1f;
+
+ static bool Apart(Rect a, Rect b) => !Rect.MinMaxRect(a.xMin + 0.5f, a.yMin + 0.5f, a.xMax - 0.5f, a.yMax - 0.5f).Overlaps(b);
+
+ [UnityTest]
+ public IEnumerator AWorstCaseScoreStaysInsideTheDateBox()
+ {
+ var problems = new List<string>();
+ foreach (var (language, text, hebrew) in new[] { ("en", En, false), ("he", He, true) })
+ foreach (var (w, h) in InfoPanelLayoutTests.Windows)
+ {
+ var rt = new RenderTexture(w, h, 0);
+ var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel));
+ ps.targetTexture = rt;
+ var go = new GameObject("ScoreLayoutTest");
+ go.SetActive(false);
+ var doc = go.AddComponent<UIDocument>();
+ doc.panelSettings = ps;
+ doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
+ go.SetActive(true);
+ var root = doc.rootVisualElement;
+ root.Q("root").RemoveFromClassList("loading");
+ root.Q("root").EnableInClassList(UiLanguage.HebrewClass, hebrew);
+ var bridge = new SimBridge(GameSession.New(Slice, GoldenRun.Seed, Mode.Historical), text);
+ bridge.State.Score = WorstScore;
+ bridge.State.Date = WorstDate;
+ bridge.State.Turn = WorstTurn;
+ var hud = new HudPresenter(root, bridge, text);
+ try
+ {
+ var score = root.Q<Label>("score");
+ for (int i = 0; i < 20 && float.IsNaN(score.worldBound.width); i++) yield return null;
+ for (int i = 0; i < 3; i++) yield return null; // the bar's tier classes settle after the first layout
+ var at = $"{language} {w}x{h}";
+ Assert.AreEqual(text.Format("hud.score", WorstScore), score.text, $"{at}: precondition: the worst score shows");
+ Assert.AreEqual(text.Format("hud.date", PlayerText.Date(WorstDate)), root.Q<Label>("date").text, $"{at}: precondition: the widest date shows");
+ var box = root.Q(className: "date-box");
+ if (!Inside(score.worldBound, ContentBox(box))) problems.Add($"{at}: '{score.text}' {score.worldBound} leaves the date box's frame {ContentBox(box)}");
+ if (!Whole(score)) problems.Add($"{at}: '{score.text}' is clipped in {score.contentRect}");
+ foreach (var other in new[] { "year", "turn", "date" })
+ {
+ var o = root.Q<Label>(other);
+ if (!Apart(score.worldBound, o.worldBound)) problems.Add($"{at}: '{score.text}' {score.worldBound} overlaps {other} '{o.text}' {o.worldBound}");
+ if (!Whole(o)) problems.Add($"{at}: {other} '{o.text}' is clipped in {o.contentRect}");
+ // The turn and date labels' own fit in the frame at this widest date is #625 (on main before this PR,
+ // worse in Hebrew); this test checks only that the score keeps clear of them.
+ }
+ }
+ finally
+ {
+ hud.Dispose();
+ Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
+ }
+ }
+ Assert.IsEmpty(problems, string.Join("\n", problems));
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/TopBarScoreLayoutTests.cs.meta b/unity/Assets/Tests/EditMode/TopBarScoreLayoutTests.cs.meta
new file mode 100644
index 000000000..ba3d8b5dc
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/TopBarScoreLayoutTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 9e0891468df8486ea021c552b3bb4d0c
\ No newline at end of file
diff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxml
index f70c5efd3..fc808ecf0 100644
--- a/unity/Assets/UI/Game.uxml
+++ b/unity/Assets/UI/Game.uxml
@@ -8,7 +8,10 @@
<ui:VisualElement name="top-bar" class="panel top-bar">
<Statecraft.Game.UI.UiFrame corners="false" rule="false" />
<ui:VisualElement class="date-box">
- <ui:Label name="year" class="year" />
+ <ui:VisualElement class="year-row">
+ <ui:Label name="year" class="year" />
+ <ui:Label name="score" class="muted" />
+ </ui:VisualElement>
<ui:VisualElement class="date-row">
<ui:Label name="turn" class="muted" />
<ui:Label name="date" class="muted" />
diff --git a/unity/Assets/UI/Statecraft.uss b/unity/Assets/UI/Statecraft.uss
index 5e65eb991..8f02ae247 100644
--- a/unity/Assets/UI/Statecraft.uss
+++ b/unity/Assets/UI/Statecraft.uss
@@ -86,6 +86,9 @@ Button:disabled { color: var(--ink-dim); border-color: rgba(120, 120, 120, 0.4);
background-color: var(--navy-raised); border-width: 1px; border-color: var(--gold-dim); border-radius: 2px;
}
.date-row { flex-direction: row; }
+/* The year, and the GDD loop's score at the line's far end (#380): the year line has the room the date line lacks. */
+.year-row { flex-direction: row; justify-content: space-between; align-items: center; }
+#score { font-size: 17px; flex-shrink: 0; }
.date-row Label { font-size: 17px; margin-right: 8px; }
.year { -unity-font-definition: url("project://database/Assets/UI/Fonts/EBGaramond-SemiBold.ttf"); font-size: 32px; color: var(--ink); }
.meters { flex-direction: row; flex-grow: 1; align-items: center; }
@@ -589,7 +592,7 @@ Button:disabled { color: var(--ink-dim); border-color: rgba(120, 120, 120, 0.4);
.lang-he .event-reopen, .lang-he .event-hide, .lang-he .event-illustration, .lang-he .start-button, .lang-he .start-listen { -unity-text-align: middle-center; }
.lang-he .card-stat-name { -unity-text-align: middle-right; }
.lang-he .card-stat-value { -unity-text-align: middle-left; }
-.lang-he .top-bar, .lang-he .date-row, .lang-he .meters, .lang-he .meter, .lang-he .meter-row, .lang-he .nav, .lang-he .row,
+.lang-he .top-bar, .lang-he .year-row, .lang-he .date-row, .lang-he .meters, .lang-he .meter, .lang-he .meter-row, .lang-he .nav, .lang-he .row,
.lang-he .event-foot, .lang-he .event-head, .lang-he .info-panel, .lang-he .info-row, .lang-he .card-stat, .lang-he .pm-offices,
.lang-he .cabinet-house, .lang-he .party-chips, .lang-he .party-chip, .lang-he .defence-row, .lang-he .leaders, .lang-he .rung,
.lang-he .defence-budget, .lang-he #cabinet-seats .unity-scroll-view__content-container { flex-direction: row-reverse; }
diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yaml
index 3c552bcdf..0d21ed3e6 100644
--- a/unity/Assets/UI/strings.en.yaml
+++ b/unity/Assets/UI/strings.en.yaml
@@ -8,6 +8,7 @@ hud.date: "{0}"
hud.attention: "Attention {0:0.0} of {1:0.0}"
hud.people: "{0:N0}"
hud.level: "Level {0} of 5"
+hud.score: "Score {0:N0}"
hud.delta_people: "{0:+#,##0;-#,##0}"
# A top-bar meter in words, kept as its tooltip for a later accessibility layer (HudModel.Spoken): {0} the caption, {1}
# the value, {2} the change without its sign. Money: {0} the sign and the currency prefix from content ("IL ", "-IL ",
diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yaml
index 9557ab972..fad644b44 100644
--- a/unity/Assets/UI/strings.he.yaml
+++ b/unity/Assets/UI/strings.he.yaml
@@ -7,6 +7,7 @@ hud.date: "{0}"
hud.attention: "תשומת לב {0:0.0} מתוך {1:0.0}"
hud.people: "{0:N0}"
hud.level: "דרגה {0} מתוך 5"
+hud.score: "ניקוד {0:N0}"
hud.delta_people: "{0:+#,##0;-#,##0}"
hud.say: "{0}: {1}"
hud.say_up: "{0}: {1}, גידול של {2} מאז התור הקודם"