A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Hebrew refusals, batch 4: cabinet appointments End turn refuses read as the Cabinet screen words them (Refs #2707) (#2944)
Beri658825122dc5
diff --git a/changelog.d/2707-refusals-batch-4.md b/changelog.d/2707-refusals-batch-4.mdnew file mode 100644index 000000000..467ebbf6c--- /dev/null+++ b/changelog.d/2707-refusals-batch-4.md@@ -0,0 +1,5 @@+### Fixed++- In Hebrew, a cabinet appointment that End turn refuses now reads in Hebrew in the message under the top bar, worded as+ the Cabinet screen words it, with the person's, party's and office's Hebrew names and a Hebrew date. Before, it showed+ in English.diff --git a/sim/Statecraft.Sim/Cabinet.cs b/sim/Statecraft.Sim/Cabinet.csindex 053f64eae..a8a75e921 100644--- a/sim/Statecraft.Sim/Cabinet.cs+++ b/sim/Statecraft.Sim/Cabinet.cs@@ -47,6 +47,26 @@ namespace Statecraft.Sim{public const string Kind = "appoint";+ // CheckReason's English (#2707: constants, so the toast at End turn finds the UI's cabinet.reason.* string). The+ // text is unchanged; {0}/{1} are the office's title, the person's name, the party's name or a PlayerText.Date.+ public const string RefusedOfficeUnknown = "That office does not exist in this game";+ public const string RefusedHistoricalOffice = "{0} is a historical title, not an appointable office";+ public const string RefusedAbolished = "The office of {0} was abolished on {1}";+ public const string RefusedNotEstablished = "The office of {0} is not established until {1}";+ public const string RefusedSeveralHolders = "{0} can have several holders at once, and appointing to it is not part of the game yet";+ public const string RefusedPrimeMinister = "You are the Prime Minister: that office is not yours to fill";+ public const string RefusedPresident = "The President is elected by the Knesset, not appointed";+ public const string RefusedPersonUnknown = "That person is not in this game";+ public const string RefusedDied = "{0} died on {1}";+ public const string RefusedIsPresident = "{0} is the President";+ public const string RefusedIsChiefOfStaff = "{0} is the serving Chief of Staff";+ public const string RefusedAlreadyHolds = "{0} already holds the office of {1}";+ public const string RefusedNoGovernment = "No government is in office";+ public const string RefusedNotCareerOfficer = "{0} is not an IDF career officer";+ public const string RefusedPartyNotCoalition = "{0}'s party ({1}) is not in the coalition";++ static string Say(string format, params object[] values) => string.Format(System.Globalization.CultureInfo.InvariantCulture, format, values);+/// <summary>The player's appointee for the office on the date: appointed by then, same government, and alive (an/// appointee who dies leaves office on the date of death, and the historical holder applies again).</summary>static Appointment? Active(Content c, GameState s, string office, DateTime date)@@ -101,35 +121,35 @@ namespace Statecraft.Simpublic static CabinetReason? CheckReason(Content c, GameState s, string officeId, string personId){var office = c.Offices.FirstOrDefault(o => o.Id == officeId);- if (office == null) return new CabinetReason("office_unknown", "That office does not exist in this game");- if (office.HistoricalOnly) return new CabinetReason("historical_office", $"{office.Title} is a historical title, not an appointable office", officeId);+ if (office == null) return new CabinetReason("office_unknown", RefusedOfficeUnknown);+ if (office.HistoricalOnly) return new CabinetReason("historical_office", Say(RefusedHistoricalOffice, office.Title), officeId);if (office.Until.HasValue && s.Date >= office.Until.Value)- return new CabinetReason("abolished", $"The office of {office.Title} was abolished on {PlayerText.Date(office.Until.Value)}", officeId,+ return new CabinetReason("abolished", Say(RefusedAbolished, office.Title, PlayerText.Date(office.Until.Value)), officeId,office.Until.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture));if (office.From.HasValue && s.Date < office.From.Value)- return new CabinetReason("not_established", $"The office of {office.Title} is not established until {PlayerText.Date(office.From.Value)}", officeId,+ return new CabinetReason("not_established", Say(RefusedNotEstablished, office.Title, PlayerText.Date(office.From.Value)), officeId,office.From.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture));- if (office.SeveralHolders) return new CabinetReason("several_holders", $"{office.Title} can have several holders at once, and appointing to it is not part of the game yet", officeId);- if (officeId == "prime_minister") return new CabinetReason("prime_minister", "You are the Prime Minister: that office is not yours to fill");- if (officeId == "president") return new CabinetReason("president", "The President is elected by the Knesset, not appointed");+ if (office.SeveralHolders) return new CabinetReason("several_holders", Say(RefusedSeveralHolders, office.Title), officeId);+ if (officeId == "prime_minister") return new CabinetReason("prime_minister", RefusedPrimeMinister);+ if (officeId == "president") return new CabinetReason("president", RefusedPresident);var person = c.People.FirstOrDefault(p => p.Id == personId);- if (person == null) return new CabinetReason("person_unknown", "That person is not in this game");+ if (person == null) return new CabinetReason("person_unknown", RefusedPersonUnknown);if (person.Died.HasValue && s.Date >= person.Died.Value)- return new CabinetReason("died", $"{person.Name} died on {PlayerText.Date(person.Died.Value)}", personId,+ return new CabinetReason("died", Say(RefusedDied, person.Name, PlayerText.Date(person.Died.Value)), personId,person.Died.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture));- if (Holder(c, s, "president")?.Id == personId) return new CabinetReason("is_president", $"{person.Name} is the President", personId);+ if (Holder(c, s, "president")?.Id == personId) return new CabinetReason("is_president", Say(RefusedIsPresident, person.Name), personId);if (officeId != "chief_of_staff" && Holder(c, s, "chief_of_staff")?.Id == personId)- return new CabinetReason("is_chief_of_staff", $"{person.Name} is the serving Chief of Staff", personId);+ return new CabinetReason("is_chief_of_staff", Say(RefusedIsChiefOfStaff, person.Name), personId);if (Holder(c, s, officeId)?.Id == personId)- return new CabinetReason("already_holds", $"{person.Name} already holds the office of {office.Title}", personId, officeId);+ return new CabinetReason("already_holds", Say(RefusedAlreadyHolds, person.Name, office.Title), personId, officeId);var gov = Offices.Government(c, s.Date);- if (gov == null) return new CabinetReason("no_government", "No government is in office");+ if (gov == null) return new CabinetReason("no_government", RefusedNoGovernment);if (officeId == "chief_of_staff")return person.Offices.Any(t => t.Office == "chief_of_staff") ? null- : new CabinetReason("not_career_officer", $"{person.Name} is not an IDF career officer", personId);+ : new CabinetReason("not_career_officer", Say(RefusedNotCareerOfficer, person.Name), personId);var party = Offices.PartyOf(c, person, s.Date);if (party != "" && !gov.CoalitionOn(s.Date).Contains(party))- return new CabinetReason("party_not_coalition", $"{person.Name}'s party ({c.Parties.First(p => p.Id == party).Name}) is not in the coalition", personId, party);+ return new CabinetReason("party_not_coalition", Say(RefusedPartyNotCoalition, person.Name, c.Parties.First(p => p.Id == party).Name), personId, party);return null;}diff --git a/tools/tests/test_hebrew_ui.py b/tools/tests/test_hebrew_ui.pyindex a602ad7d3..4ac137434 100644--- a/tools/tests/test_hebrew_ui.py+++ b/tools/tests/test_hebrew_ui.py@@ -134,17 +134,17 @@ def test_every_cabinet_refusal_has_both_strings_and_the_english_is_the_sims_word(its interpolations as {0}, {1}, ... in order), so the English player sees what the sim says."""en, he = strings('strings.en.yaml'), strings('strings.he.yaml')src = (ROOT / 'sim/Statecraft.Sim/Cabinet.cs').read_text(encoding='utf-8')- paths = re.findall(r'new CabinetReason\("(\w+)",\s*(\$?)"((?:[^"\\]|\\.)*)"', src)+ # #2707: each path's English is a Refused* constant, already in {0}, {1}, ... form (Say formats it).+ consts = dict(re.findall(r'public const string (Refused\w+) = "((?:[^"\\]|\\.)*)";', src))+ paths = re.findall(r'new CabinetReason\("(\w+)",\s*(?:Say\()?(Refused\w+)', src)assert len(paths) == 15- assert len({kind for kind, _, _ in paths}) == len(paths) # one kind per return path- for kind, interpolated, english in paths:+ assert len({kind for kind, _ in paths}) == len(paths) # one kind per return path+ for kind, const in paths:key = 'cabinet.reason.' + kindassert key in en and key in he, key- n = iter(range(10))- template = re.sub(r'\{[^{}]+\}', lambda _: '{%d}' % next(n), english) if interpolated else english- assert en[key] == template, key+ assert en[key] == consts[const], keyassert not re.search('[A-Za-z]', he[key]), key- assert sorted(k for k in en if k.startswith('cabinet.reason.')) == sorted('cabinet.reason.' + k for k, _, _ in paths)+ assert sorted(k for k in en if k.startswith('cabinet.reason.')) == sorted('cabinet.reason.' + k for k, _ in paths)def test_the_cause_line_names_are_contents_names_in_english_and_hebrew_without_latin():diff --git a/unity/Assets/Scripts/UI/CabinetPresenter.cs b/unity/Assets/Scripts/UI/CabinetPresenter.csindex 485439639..5435638e7 100644--- a/unity/Assets/Scripts/UI/CabinetPresenter.cs+++ b/unity/Assets/Scripts/UI/CabinetPresenter.cs@@ -362,7 +362,7 @@ namespace Statecraft.Game.UIif (rejection.Command is Appoint a && Cabinet.CheckReason(c, preview.State, a.Office, a.Person) is CabinetReason reason&& reason.Text == rejection.Reason)return ReasonText(c, reason);- return SimBridge.ReasonText(text, rejection.Reason, c, bridge.TownNamesHe);+ return SimBridge.ReasonText(text, rejection.Reason, c, bridge.TownNamesHe, bridge.State.Date);}string ReasonText(Content c, CabinetReason reason)diff --git a/unity/Assets/Scripts/UI/SimBridge.cs b/unity/Assets/Scripts/UI/SimBridge.csindex af7590074..2e55e1fb2 100644--- a/unity/Assets/Scripts/UI/SimBridge.cs+++ b/unity/Assets/Scripts/UI/SimBridge.cs@@ -319,6 +319,12 @@ namespace Statecraft.Game.UI[EventSystem.RefusedOperationUnitsNotInPlace] = "event.operation_refused",[EventSystem.RefusedOperationArmisticeFirst] = "event.operation_refused_armistice_first",[EventSystem.RefusedOperationArmisticeSigned] = "event.operation_refused_armistice_signed",+ // #2707 batch 4: an appointment End turn refuses, as the Cabinet screen words it (CabinetPresenter.ReasonText)+ [Cabinet.RefusedOfficeUnknown] = "cabinet.reason.office_unknown",+ [Cabinet.RefusedPrimeMinister] = "cabinet.reason.prime_minister",+ [Cabinet.RefusedPresident] = "cabinet.reason.president",+ [Cabinet.RefusedPersonUnknown] = "cabinet.reason.person_unknown",+ [Cabinet.RefusedNoGovernment] = "cabinet.reason.no_government",};/// <summary>The sim's refusals that carry values (#2072: Combat.Check's Arms, Training.Reinforce's unit, settlement,@@ -358,14 +364,27 @@ namespace Statecraft.Game.UI(SettlementControl.RefusedWithdrawNeedsUnit, "capture.refusal.needs_unit"),(SettlementControl.RefusedNoFreeHex, "capture.refusal.no_free_hex"),(Cities.RefusedAlreadyCity, "capture.refusal.already_city"),+ // #2707 batch 4: the appointment refusals with a name or a date in them (ReasonValue words each in Hebrew)+ (Cabinet.RefusedHistoricalOffice, "cabinet.reason.historical_office"),+ (Cabinet.RefusedAbolished, "cabinet.reason.abolished"),+ (Cabinet.RefusedNotEstablished, "cabinet.reason.not_established"),+ (Cabinet.RefusedSeveralHolders, "cabinet.reason.several_holders"),+ (Cabinet.RefusedDied, "cabinet.reason.died"),+ (Cabinet.RefusedIsPresident, "cabinet.reason.is_president"),+ (Cabinet.RefusedIsChiefOfStaff, "cabinet.reason.is_chief_of_staff"),+ (Cabinet.RefusedAlreadyHolds, "cabinet.reason.already_holds"),+ (Cabinet.RefusedNotCareerOfficer, "cabinet.reason.not_career_officer"),+ (Cabinet.RefusedPartyNotCoalition, "cabinet.reason.party_not_coalition"),}.Select(x => (new Regex("^" + string.Join("(.+?)", Regex.Split(x.format, @"\{\d+(?::[^}]*)?\}").Select(Regex.Escape)) + "$"), x.key)).ToArray();/// <summary>A sim refusal in the UI's language where it has a string (<see cref="ReasonKeys"/>, <see cref="ReasonFormats"/>),/// else the sim's English as given. The queue's refusals, the unit card's (InfoPanelPresenter) and the end of turn's/// (ToastPresenter) go through it. With <paramref name="c"/> a value that is a settlement's name reads as the UI names the/// town (its Hebrew name from <paramref name="townsHe"/> in Hebrew), a course's English as why.cause.course.* and a money- /// amount in the content's format.</summary>- public static string ReasonText(UiText text, string reason, Content? c = null, IReadOnlyDictionary<string, string>? townsHe = null)+ /// amount in the content's format; in Hebrew a cabinet refusal's person, party and date too, and its office with+ /// <paramref name="date"/> (the turn's, for the title's days).</summary>+ public static string ReasonText(UiText text, string reason, Content? c = null, IReadOnlyDictionary<string, string>? townsHe = null,+ DateTime? date = null){if (ReasonKeys.TryGetValue(reason, out var key)){@@ -374,8 +393,12 @@ namespace Statecraft.Game.UI}foreach (var (pattern, format) in ReasonFormats)if (pattern.Match(reason) is { Success: true } m)+ {+ // An office's Hebrew title takes its holder's form: in "{0} already holds the office of {1}" that is {0}.+ var holder = format == "cabinet.reason.already_holds" ? c?.People.FirstOrDefault(p => p.Name == m.Groups[1].Value) : null;return text.Format(format, CountNoun(text, format,- m.Groups.Cast<Group>().Skip(1).Select(v => (object)ReasonValue(text, v.Value, c, townsHe)).ToArray()));+ m.Groups.Cast<Group>().Skip(1).Select(v => (object)ReasonValue(text, v.Value, c, townsHe, date, holder)).ToArray()));+ }return reason;}@@ -394,14 +417,24 @@ namespace Statecraft.Game.UIreturn values;}- static string ReasonValue(UiText text, string value, Content? c, IReadOnlyDictionary<string, string>? townsHe)+ static string ReasonValue(UiText text, string value, Content? c, IReadOnlyDictionary<string, string>? townsHe,+ DateTime? date = null, Person? holder = null){if (c == null) return value;var town = c.SettlementNames.FirstOrDefault(n => n.Value == value).Key;if (town != null)return text["ui.lang"] == UiLanguage.Hebrew && townsHe != null && townsHe.TryGetValue(town, out var he) && !string.IsNullOrWhiteSpace(he) ? he : value;var course = c.UnitTypes.FirstOrDefault(t => t.Facility != "" && Training.Course(t) == value);- return course != null ? text["why.cause.course." + Training.CourseId(course)] : value;+ if (course != null) return text["why.cause.course." + Training.CourseId(course)];+ // #2707 batch 4: a cabinet refusal's person, party, office and date, in Hebrew as CabinetPresenter.ReasonText gives+ // them. An office's Hebrew title depends on the day (TitleHeOn), so with no date it keeps the English, as the UI+ // does outside a title's days. English keeps the sim's own words.+ if (text["ui.lang"] != UiLanguage.Hebrew) return value;+ if (c.People.FirstOrDefault(p => p.Name == value) is Person person) return ContentNames.Of(text, person);+ if (c.Parties.FirstOrDefault(p => p.Name == value) is Party party) return ContentNames.Of(text, party);+ if (date != null && c.Offices.FirstOrDefault(o => o.Title == value) is Office office) return ContentNames.Of(text, office, holder, date.Value);+ return DateTime.TryParseExact(value, "d MMMM yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var day)+ ? Statecraft.Game.Map.Control1948.DateText(day, k => text[k]) : value;}/// <summary>Each settlement's Hebrew name (name_he), by id, for <see cref="Refuse"/>'s Hebrew (#2072): GameRoot sets it, asdiff --git a/unity/Assets/Scripts/UI/ToastPresenter.cs b/unity/Assets/Scripts/UI/ToastPresenter.csindex 53e3e884a..9315574d8 100644--- a/unity/Assets/Scripts/UI/ToastPresenter.cs+++ b/unity/Assets/Scripts/UI/ToastPresenter.cs@@ -30,7 +30,7 @@ namespace Statecraft.Game.UIpublic ToastPresenter(VisualElement root, SimBridge bridge, UiText text){label = root.Q<Label>("toast"); this.text = text; this.bridge = bridge;- onTurnEnded = r => Show(r.Select(x => text.Format("toast.refused", SimBridge.ReasonText(text, x.Reason, bridge.Content, TownNamesHe))));+ onTurnEnded = r => Show(r.Select(x => text.Format("toast.refused", SimBridge.ReasonText(text, x.Reason, bridge.Content, TownNamesHe, bridge.State.Date))));onCommitted = why => Show(why.Where(x => WhyKeys.All.Contains(x.Key)) // unit lines only: a call-up order's line (B1 key) is no toast.Select(x => UnitNames.Line(x, bridge.Content, units, text, TownNamesHe)));onRouteStep = _ =>diff --git a/unity/Assets/Tests/EditMode/HebrewUiTests.cs b/unity/Assets/Tests/EditMode/HebrewUiTests.csindex ed1fc7bdb..d9db19158 100644--- a/unity/Assets/Tests/EditMode/HebrewUiTests.cs+++ b/unity/Assets/Tests/EditMode/HebrewUiTests.cs@@ -271,6 +271,75 @@ public class HebrewUiTestsAssert.AreEqual(reason, SimBridge.ReasonText(He, reason, c, namesHe), "no reviewed line fits, so the sim's English");}+ // #2707 item 2, batch 4: a cabinet appointment the End turn refuses reads in the toast as the Cabinet screen words it+ // (cabinet.reason.*), with the person, the party, the office (for its holder, on the turn's date) and the date in Hebrew.+ // Real content: a sitting minister ordered into the office they hold, through the real toast; then a death, an abolished+ // office and a party outside the coalition through ReasonText, each with no Latin letter left.+ [Test]+ public void TheCabinetRefusalsReadInHebrewWithTheirNamesAndDates()+ {+ var game = Boot(UiLanguage.Hebrew);+ var bridge = game.Bridge!;+ var c = bridge.Content;+ var seat = Statecraft.Sim.Cabinet.Lineup(c, bridge.State)+ .Where(x => x.Holder != null && x.Holder.NameHe != "" && !x.Office.SeveralHolders && x.Office.Id != "prime_minister" && x.Office.Id != "president"+ && x.Office.TitleHeOn(x.Holder, bridge.State.Date) != "")+ .OrderByDescending(x => x.Holder!.TitleHeForm == Statecraft.Sim.TitleHeForms.Feminine).First();+ Assert.IsNull(bridge.Queue(new Statecraft.Sim.Appoint(seat.Office.Id, seat.Holder!.Id)), "precondition: the appointment is queued");+ bridge.EndTurn();+ var holds = He.Format("cabinet.reason.already_holds", ContentNames.Of(He, seat.Holder!), ContentNames.Of(He, seat.Office, seat.Holder, bridge.State.Date));+ StringAssert.Contains(He.Format("toast.refused", holds), Ui.Q<Label>("toast").text, "the toast names the minister and the office in Hebrew");+ StringAssert.DoesNotMatch("[A-Za-z]", holds);++ string Date(DateTime d) => Control1948.DateText(d, k => He[k]);+ string Say(string format, params object[] values) => string.Format(System.Globalization.CultureInfo.InvariantCulture, format, values);+ var date = bridge.State.Date;+ var dead = c.People.First(p => p.Died.HasValue && p.NameHe != "" && p.Name.Contains(' '));+ var office = c.Offices.First(o => o.Until.HasValue && o.TitleHeOn(null, date) != "");+ var party = c.Parties.First(p => p.NameHe != "" && p.Name.Contains(' '));+ var minister = c.People.First(p => p.NameHe != "" && p != dead);+ foreach (var (reason, expected) in new[]+ {+ (Say(Statecraft.Sim.Cabinet.RefusedDied, dead.Name, Statecraft.Sim.PlayerText.Date(dead.Died!.Value)),+ He.Format("cabinet.reason.died", dead.NameHe, Date(dead.Died!.Value))),+ (Say(Statecraft.Sim.Cabinet.RefusedAbolished, office.Title, Statecraft.Sim.PlayerText.Date(office.Until!.Value)),+ He.Format("cabinet.reason.abolished", ContentNames.Of(He, office, null, date), Date(office.Until!.Value))),+ (Say(Statecraft.Sim.Cabinet.RefusedPartyNotCoalition, minister.Name, party.Name),+ He.Format("cabinet.reason.party_not_coalition", minister.NameHe, party.NameHe)),+ })+ {+ Assert.AreEqual(reason, SimBridge.ReasonText(En, reason, c, null, date), "the English string is the sim's own");+ Assert.AreEqual(expected, SimBridge.ReasonText(He, reason, c, null, date), reason);+ StringAssert.DoesNotMatch("[A-Za-z]", expected, reason);+ }+ }++ // #2707 batch 4 review: the Cabinet queue preview's fallback (a refusal the screen's own CheckReason does not give back,+ // CabinetPresenter.PreviewReason) passes the turn's date, so an office in it reads by its Hebrew title. Red-first at+ // 582c108fc: no date, so the office kept its English title. The refusal is a queued appointment's "already holds", as the+ // press could break it; private, so it is reached by reflection, like CabinetPreviewShots reaches the screen.+ [Test]+ public void TheCabinetPreviewsFallbackRefusalNamesTheOfficeInHebrew()+ {+ using var ui = new UiTestKit();+ var c = Inputs.Content;+ var bridge = new SimBridge(Statecraft.Sim.GameSession.New(c, Statecraft.Sim.GoldenRun.Seed, Statecraft.Sim.Mode.Historical), He);+ using var cabinet = new CabinetPresenter(ui.Root, bridge, He, null);+ var date = bridge.State.Date;+ var seat = Statecraft.Sim.Cabinet.Lineup(c, bridge.State)+ .First(x => x.Holder != null && x.Holder.NameHe != "" && !x.Office.SeveralHolders && x.Office.TitleHeOn(x.Holder, date) != "");+ var holder = seat.Holder!;+ var reason = string.Format(System.Globalization.CultureInfo.InvariantCulture, Statecraft.Sim.Cabinet.RefusedAlreadyHolds, holder.Name, seat.Office.Title);+ var preview = Statecraft.Sim.Simulation.Preview(c, bridge.TurnStart, bridge.Session.Committed.ToList());+ var other = c.People.First(p => Statecraft.Sim.Cabinet.Check(c, preview.State, seat.Office.Id, p.Id) != reason); // so the fallback runs+ var rejection = new Statecraft.Sim.Rejection(new Statecraft.Sim.Appoint(seat.Office.Id, other.Id), reason);+ var method = typeof(CabinetPresenter).GetMethod("PreviewReason", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);+ var text = (string)method!.Invoke(cabinet, new object[] { c, rejection, preview });+ Assert.AreEqual(He.Format("cabinet.reason.already_holds", ContentNames.Of(He, holder), ContentNames.Of(He, seat.Office, holder, date)), text);+ StringAssert.Contains(seat.Office.TitleHeOn(holder, date), text, "the office by its Hebrew title");+ StringAssert.DoesNotMatch("[A-Za-z]", text);+ }+[Test]public void TheGameIsEnglishUnlessHebrewIsAskedFor(){