From a989ac87c75cd6fbdce69a4bdd4e75bc7c3db563 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 28 Sep 2026 06:03:19 +0000 Subject: [PATCH] Mission editor: pick the reference sector from a list (1.3.2) The World tab's Kind and Reference rows are now closed choices: Enter opens a pick list (FieldRow.choices in the shared FieldList) instead of free text. Reference lists the 128 packaged sectors with their countries; picking one makes the world a 500 NM reference world. The preview draws the chosen sector's coast from a once-per-process sector cache. Closes the Phase 13 deviation "text field instead of sector selection". App 1.3.2, saves stay v22. EN/DE catalog, manual and README updated. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01AS36Eg72iLviiSVbCUVNAi --- AGENTS.md | 2 +- README.de.md | 7 ++- README.md | 6 +- data/i18n/de.json | 4 ++ data/i18n/en.json | 4 ++ data/manual/10-reference.de.md | 2 +- data/manual/10-reference.en.md | 2 +- docs/manual/manual.de.md | 2 +- docs/manual/manual.en.md | 2 +- docs/resume.md | 12 ++++ src/core/version.py | 2 +- src/ui/editor_widgets.py | 101 ++++++++++++++++++++++++++++++++- src/ui/mission_editor.py | 67 ++++++++++++++++++++-- tests/test_editor_widgets.py | 56 ++++++++++++++++++ tests/test_mission_editor.py | 47 +++++++++++++++ tests/test_packaging.py | 4 +- tests/test_startup.py | 4 +- 17 files changed, 305 insertions(+), 19 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4160b4b2..3a7a4fca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ ## Authority and scope -- This is U-Jagd 1.3.1 (`src/core/version.py`); current saves are v22-only. Treat these as compatibility contracts, not changelog entries. +- This is U-Jagd 1.3.2 (`src/core/version.py`); current saves are v22-only. Treat these as compatibility contracts, not changelog entries. - Resolve conflicts in this order: executable code and focused tests; packaged JSON/runtime resources; `pyproject.toml` and provenance/license notices; `README.md`; design/history documents under `docs/`. A plan or old comment is not an implementation contract. - Preserve explicit compatibility tests and user data unless a task intentionally changes the contract. Add a regression test for behavior changes. - Older phase/milestone labels under `docs/GDD.md`, `docs/implementation-plan.md`, `docs/plan-0.1.6.md`, and `docs/plan-0.1.7.md` are historical. Current resumable work is tracked in `docs/plan-1.3.md` and `docs/resume.md`. diff --git a/README.de.md b/README.de.md index af2ce326..271d3e9c 100644 --- a/README.de.md +++ b/README.de.md @@ -12,7 +12,12 @@ Sie führen eine fiktive Fregatte und wechseln zwischen neun Arbeitsplätzen, um zu navigieren, zu suchen, Kontakte zu klassifizieren, Ziele zu bekämpfen und das Schiff einsatzfähig zu halten. -Aktuelle Version: **1.3.0** +Aktuelle Version: **1.3.2** + +Version 1.3.2 lässt im Missionseditor die Referenzwelt einer Mission aus einer +Liste der 128 mitgelieferten Sektoren (mit ihren Ländern) wählen, statt +`sector:` einzutippen; die Vorschau zeichnet die Küste des gewählten +Sektors. Spielstände bleiben v22. Version 1.3.0 erweitert Simulation und Werkzeuge der Besatzung, ohne die Balance von 1.0.0 zu verschieben (77 Kalibrierungsmetriken unverändert): ein diff --git a/README.md b/README.md index 60af7498..7e7ed5bc 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,11 @@ around the ClockworkPi uConsole's 1280 x 720 workspace. You command a fictional frigate and move between nine workstations to navigate, search, classify, engage, and keep the ship operational. -Current release: **1.3.1** +Current release: **1.3.2** + +Release 1.3.2 lets the Mission Editor pick a mission's reference world from a +list of the 128 packaged sectors (with their countries) instead of typing +`sector:`, and its preview draws the chosen sector's coast. Saves stay v22. Release 1.3.1 gives the crewed submarine a radio room (a seventh boat station: HQ's broadcast with a contact report on the frigate, and situation diff --git a/data/i18n/de.json b/data/i18n/de.json index 0e3221c3..c6c51ca1 100644 --- a/data/i18n/de.json +++ b/data/i18n/de.json @@ -2549,6 +2549,10 @@ "editor.path_result": "{action}: {path}", "editor.preview_seed": "Seed: {seed}", "editor.preview_markers": "Markierungen: {count}", + "editor.sector_choice": "{sector} {countries}", + "editor.choose_hint": "Hoch/Runter: wählen | Enter: übernehmen | Esc: abbrechen", + "editor.preview_sector": "Referenzsektor {sector}: {countries}", + "editor.preview_fixed_world": "Feste Welt (ohne Küstendaten)", "editor.preview_events": "Ereignisse: {count}", "editor.open_hint": "Enter: öffnen/klonen", "editor.new_hint": "Strg+N: neu", diff --git a/data/i18n/en.json b/data/i18n/en.json index eeda11a5..2bcbe12a 100644 --- a/data/i18n/en.json +++ b/data/i18n/en.json @@ -2549,6 +2549,10 @@ "editor.path_result": "{action}: {path}", "editor.preview_seed": "Seed: {seed}", "editor.preview_markers": "Markers: {count}", + "editor.sector_choice": "{sector} {countries}", + "editor.choose_hint": "Up/Down: choose | Enter: take | Esc: cancel", + "editor.preview_sector": "Reference sector {sector}: {countries}", + "editor.preview_fixed_world": "Fixed world (no packaged coast)", "editor.preview_events": "Events: {count}", "editor.open_hint": "Enter: open/clone", "editor.new_hint": "Ctrl+N: new", diff --git a/data/manual/10-reference.de.md b/data/manual/10-reference.de.md index a1cac212..2569caa6 100644 --- a/data/manual/10-reference.de.md +++ b/data/manual/10-reference.de.md @@ -142,7 +142,7 @@ Die obere Leiste zeigt die sieben Stationen des Boots als Reiter: `1` Führung, ## Mission und Wertung {#ref-mission} -- Szenarien: 1 Patrouille, 2 Doppeljagd, 3 Nuklear-Abfang, 4 Zufall (eigene Schwierigkeit). Eigene Missionen starten aus dem Missionseditor (`F5` in dessen Browser). Die Laufzeit übernimmt den Umfang des Editors: eine 500-sm-Welt fest oder als paketierter Referenzsektor (`sector:0` bis `sector:127`), das eingestellte Wetter, platzierte U-Boote, Überwasserschiffe, Luftfahrzeuge (Patrouille in einem 10-sm-Kasten mit Profilgeschwindigkeit), Tiere und ruhende Täuschkörper, gesäte Zufallsgruppen, zeitgesteuerte Ereignisse (Meldung, Erscheinen, Wetter, Ziel) und die Ziele Versenken, Überstehen, Schützen (die benannten Einheiten bis zum Zeitlimit erhalten) und Erreichen (den Radius des Zielpunkts betreten). Benutzerprofile, Torpedos und andere Weltgrößen werden beim Start abgewiesen. +- Szenarien: 1 Patrouille, 2 Doppeljagd, 3 Nuklear-Abfang, 4 Zufall (eigene Schwierigkeit). Eigene Missionen starten aus dem Missionseditor (`F5` in dessen Browser). Die Laufzeit übernimmt den Umfang des Editors: eine 500-sm-Welt fest oder als paketierter Referenzsektor (`sector:0` bis `sector:127`), das eingestellte Wetter, platzierte U-Boote, Überwasserschiffe, Luftfahrzeuge (Patrouille in einem 10-sm-Kasten mit Profilgeschwindigkeit), Tiere und ruhende Täuschkörper, gesäte Zufallsgruppen, zeitgesteuerte Ereignisse (Meldung, Erscheinen, Wetter, Ziel) und die Ziele Versenken, Überstehen, Schützen (die benannten Einheiten bis zum Zeitlimit erhalten) und Erreichen (den Radius des Zielpunkts betreten). Benutzerprofile, Torpedos und andere Weltgrößen werden beim Start abgewiesen. Im Editor-Reiter Welt öffnet `Enter` auf Art oder Referenz eine Auswahlliste (`Hoch`/`Runter`, `Bild auf`/`Bild ab`, `Enter` übernimmt, `Esc` bricht ab); Referenz listet die 128 Sektoren mit ihren Ländern, und die Wahl eines Sektors macht die Welt zu einer 500-sm-Referenzwelt. Der Reiter Vorschau zeichnet dann die Küste dieses Sektors. - Sieg: alle Ziele versenkt oder Zeitlimit überlebt. Niederlage: eigenes Schiff versenkt, ziviler Treffer, Ziel 150 sm vom Start entfernt oder Zeit abgelaufen. - Punkte: 1000 je versenktem U-Boot, 200 je unverbrauchtem Torpedo, 500 ohne zivile Verluste, bis zu 500 Zeitbonus. - Nachbesprechung: Nach Missionsende öffnet `D` im Endfenster die Nachbesprechung. Sie spielt die Mission ab und zeigt die Wahrheit neben dem, was die Crew wusste: die echten Kurse von Schiff und feindlichen Booten, die Kontakte der Crew dort, wo sie sie verortet hatte (reine Peilungen als Peilstrahlen), Waffen, Bojen und Luftfahrzeuge. Daneben stehen die Zeit des ersten Kontakts, der ersten Ortung und der Klassifizierung, abgefeuerte Waffen und versenkte Boote, der mittlere Fehler der Ortungen und alle Ereignisse; eine "verpasste Chance" ist ein feindliches Boot, das mindestens 5 min lang höchstens 4 sm entfernt war, ohne dass es einen Kontakt gab, mit dem Hinweis über oder unter der Sprungschicht. `Links`/`Rechts` blättern (Shift: 1 min), `Auf`/`Ab` oder `Bild auf`/`Bild ab` springen zwischen Ereignissen, ein Klick in die Zeitleiste springt dorthin, `D` oder `Esc` kehrt zurück. Aufgezeichnet wird alle 10 s (bei langen Missionen gröber); die Nachbesprechung ist während der Mission nie sichtbar und wird nicht gespeichert: nach dem Laden deckt sie die Mission ab dem Laden ab. diff --git a/data/manual/10-reference.en.md b/data/manual/10-reference.en.md index 0f98c7b2..9d717217 100644 --- a/data/manual/10-reference.en.md +++ b/data/manual/10-reference.en.md @@ -142,7 +142,7 @@ The top bar shows the boat's seven stations as tabs: `1` Command, `2` Sonar, `3` ## Mission and scoring {#ref-mission} -- Scenarios: 1 Patrol, 2 Double hunt, 3 Nuclear intercept, 4 Random (custom difficulty). User missions start from the Mission Editor (`F5` in its browser). The runtime takes the editor's scope: a 500 NM fixed world or a packaged reference sector (`sector:0` to `sector:127`), the authored weather, placed submarines, surface ships, aircraft (patrolling a 10 NM box at profile speed), animals and static decoys, seeded random groups, timed events (message, spawn, weather, objective) and the objectives sink, survive, protect (keep the named units alive until the time limit) and reach (enter the objective point's radius). User unit profiles, torpedoes and other world sizes are refused at start. +- Scenarios: 1 Patrol, 2 Double hunt, 3 Nuclear intercept, 4 Random (custom difficulty). User missions start from the Mission Editor (`F5` in its browser). The runtime takes the editor's scope: a 500 NM fixed world or a packaged reference sector (`sector:0` to `sector:127`), the authored weather, placed submarines, surface ships, aircraft (patrolling a 10 NM box at profile speed), animals and static decoys, seeded random groups, timed events (message, spawn, weather, objective) and the objectives sink, survive, protect (keep the named units alive until the time limit) and reach (enter the objective point's radius). User unit profiles, torpedoes and other world sizes are refused at start. In the editor's World tab, `Enter` on Kind or Reference opens a pick list (`Up`/`Down`, `PgUp`/`PgDn`, `Enter` takes, `Esc` cancels); Reference lists the 128 sectors with their countries, and picking one makes the world a 500 NM reference world. The Preview tab then draws that sector's coast. - Win: all targets sunk, or survive the time limit. Lose: own ship sunk, civilian hit, target 150 NM from its start, or time out. - Score: 1000 per sunk submarine, 200 per unused torpedo, 500 without civilian losses, up to 500 time bonus. - Debrief: after the mission ends, `D` on the end panel opens the debrief. It replays the mission with the truth beside what the crew knew: the true tracks of the ship and the hostile boats, the crew's contacts where it had placed them (bearing-only contacts as bearing lines), weapons, buoys and aircraft. Beside the chart it lists the time of the first contact, first fix and classification, weapons fired and boats sunk, the mean error of the crew's fixes, and every event; a "missed chance" is a hostile boat within 4 NM for at least 5 min without any contact, marked above or below the layer. `Left`/`Right` step (Shift: 1 min), `Up`/`Down` or `PgUp`/`PgDn` jump between events, a click on the timeline jumps there, `D` or `Esc` returns. The debrief is recorded every 10 s (coarser on long missions), is never shown during a mission and is not saved: after a load it covers the mission from the load onwards. diff --git a/docs/manual/manual.de.md b/docs/manual/manual.de.md index 024630e8..d6e88cb1 100644 --- a/docs/manual/manual.de.md +++ b/docs/manual/manual.de.md @@ -1182,7 +1182,7 @@ Die obere Leiste zeigt die sieben Stationen des Boots als Reiter: `1` Führung, ### Mission und Wertung -- Szenarien: 1 Patrouille, 2 Doppeljagd, 3 Nuklear-Abfang, 4 Zufall (eigene Schwierigkeit). Eigene Missionen starten aus dem Missionseditor (`F5` in dessen Browser). Die Laufzeit übernimmt den Umfang des Editors: eine 500-sm-Welt fest oder als paketierter Referenzsektor (`sector:0` bis `sector:127`), das eingestellte Wetter, platzierte U-Boote, Überwasserschiffe, Luftfahrzeuge (Patrouille in einem 10-sm-Kasten mit Profilgeschwindigkeit), Tiere und ruhende Täuschkörper, gesäte Zufallsgruppen, zeitgesteuerte Ereignisse (Meldung, Erscheinen, Wetter, Ziel) und die Ziele Versenken, Überstehen, Schützen (die benannten Einheiten bis zum Zeitlimit erhalten) und Erreichen (den Radius des Zielpunkts betreten). Benutzerprofile, Torpedos und andere Weltgrößen werden beim Start abgewiesen. +- Szenarien: 1 Patrouille, 2 Doppeljagd, 3 Nuklear-Abfang, 4 Zufall (eigene Schwierigkeit). Eigene Missionen starten aus dem Missionseditor (`F5` in dessen Browser). Die Laufzeit übernimmt den Umfang des Editors: eine 500-sm-Welt fest oder als paketierter Referenzsektor (`sector:0` bis `sector:127`), das eingestellte Wetter, platzierte U-Boote, Überwasserschiffe, Luftfahrzeuge (Patrouille in einem 10-sm-Kasten mit Profilgeschwindigkeit), Tiere und ruhende Täuschkörper, gesäte Zufallsgruppen, zeitgesteuerte Ereignisse (Meldung, Erscheinen, Wetter, Ziel) und die Ziele Versenken, Überstehen, Schützen (die benannten Einheiten bis zum Zeitlimit erhalten) und Erreichen (den Radius des Zielpunkts betreten). Benutzerprofile, Torpedos und andere Weltgrößen werden beim Start abgewiesen. Im Editor-Reiter Welt öffnet `Enter` auf Art oder Referenz eine Auswahlliste (`Hoch`/`Runter`, `Bild auf`/`Bild ab`, `Enter` übernimmt, `Esc` bricht ab); Referenz listet die 128 Sektoren mit ihren Ländern, und die Wahl eines Sektors macht die Welt zu einer 500-sm-Referenzwelt. Der Reiter Vorschau zeichnet dann die Küste dieses Sektors. - Sieg: alle Ziele versenkt oder Zeitlimit überlebt. Niederlage: eigenes Schiff versenkt, ziviler Treffer, Ziel 150 sm vom Start entfernt oder Zeit abgelaufen. - Punkte: 1000 je versenktem U-Boot, 200 je unverbrauchtem Torpedo, 500 ohne zivile Verluste, bis zu 500 Zeitbonus. - Nachbesprechung: Nach Missionsende öffnet `D` im Endfenster die Nachbesprechung. Sie spielt die Mission ab und zeigt die Wahrheit neben dem, was die Crew wusste: die echten Kurse von Schiff und feindlichen Booten, die Kontakte der Crew dort, wo sie sie verortet hatte (reine Peilungen als Peilstrahlen), Waffen, Bojen und Luftfahrzeuge. Daneben stehen die Zeit des ersten Kontakts, der ersten Ortung und der Klassifizierung, abgefeuerte Waffen und versenkte Boote, der mittlere Fehler der Ortungen und alle Ereignisse; eine "verpasste Chance" ist ein feindliches Boot, das mindestens 5 min lang höchstens 4 sm entfernt war, ohne dass es einen Kontakt gab, mit dem Hinweis über oder unter der Sprungschicht. `Links`/`Rechts` blättern (Shift: 1 min), `Auf`/`Ab` oder `Bild auf`/`Bild ab` springen zwischen Ereignissen, ein Klick in die Zeitleiste springt dorthin, `D` oder `Esc` kehrt zurück. Aufgezeichnet wird alle 10 s (bei langen Missionen gröber); die Nachbesprechung ist während der Mission nie sichtbar und wird nicht gespeichert: nach dem Laden deckt sie die Mission ab dem Laden ab. diff --git a/docs/manual/manual.en.md b/docs/manual/manual.en.md index 3f944a19..d791e5ee 100644 --- a/docs/manual/manual.en.md +++ b/docs/manual/manual.en.md @@ -1181,7 +1181,7 @@ The top bar shows the boat's seven stations as tabs: `1` Command, `2` Sonar, `3` ### Mission and scoring -- Scenarios: 1 Patrol, 2 Double hunt, 3 Nuclear intercept, 4 Random (custom difficulty). User missions start from the Mission Editor (`F5` in its browser). The runtime takes the editor's scope: a 500 NM fixed world or a packaged reference sector (`sector:0` to `sector:127`), the authored weather, placed submarines, surface ships, aircraft (patrolling a 10 NM box at profile speed), animals and static decoys, seeded random groups, timed events (message, spawn, weather, objective) and the objectives sink, survive, protect (keep the named units alive until the time limit) and reach (enter the objective point's radius). User unit profiles, torpedoes and other world sizes are refused at start. +- Scenarios: 1 Patrol, 2 Double hunt, 3 Nuclear intercept, 4 Random (custom difficulty). User missions start from the Mission Editor (`F5` in its browser). The runtime takes the editor's scope: a 500 NM fixed world or a packaged reference sector (`sector:0` to `sector:127`), the authored weather, placed submarines, surface ships, aircraft (patrolling a 10 NM box at profile speed), animals and static decoys, seeded random groups, timed events (message, spawn, weather, objective) and the objectives sink, survive, protect (keep the named units alive until the time limit) and reach (enter the objective point's radius). User unit profiles, torpedoes and other world sizes are refused at start. In the editor's World tab, `Enter` on Kind or Reference opens a pick list (`Up`/`Down`, `PgUp`/`PgDn`, `Enter` takes, `Esc` cancels); Reference lists the 128 sectors with their countries, and picking one makes the world a 500 NM reference world. The Preview tab then draws that sector's coast. - Win: all targets sunk, or survive the time limit. Lose: own ship sunk, civilian hit, target 150 NM from its start, or time out. - Score: 1000 per sunk submarine, 200 per unused torpedo, 500 without civilian losses, up to 500 time bonus. - Debrief: after the mission ends, `D` on the end panel opens the debrief. It replays the mission with the truth beside what the crew knew: the true tracks of the ship and the hostile boats, the crew's contacts where it had placed them (bearing-only contacts as bearing lines), weapons, buoys and aircraft. Beside the chart it lists the time of the first contact, first fix and classification, weapons fired and boats sunk, the mean error of the crew's fixes, and every event; a "missed chance" is a hostile boat within 4 NM for at least 5 min without any contact, marked above or below the layer. `Left`/`Right` step (Shift: 1 min), `Up`/`Down` or `PgUp`/`PgDn` jump between events, a click on the timeline jumps there, `D` or `Esc` returns. The debrief is recorded every 10 s (coarser on long missions), is never shown during a mission and is not saved: after a load it covers the mission from the load onwards. diff --git a/docs/resume.md b/docs/resume.md index 34cfe0c4..9bfb213d 100644 --- a/docs/resume.md +++ b/docs/resume.md @@ -1542,3 +1542,15 @@ Notizen Phase 1: nicht bitgleich (transienter Overlap-Add-Zustand des Audioempfaengers, wie bei der Fregatte); der Continuation-Test vergleicht sie deshalb nicht, alle Simulationsfelder sind ueber 300 s identisch. + +## Editor-Sektorauswahl (2026-09-28, App 1.3.2) + +- Offener Punkt aus Phase 13 erledigt: `FieldRow.choices` macht eine Zeile + zur geschlossenen Auswahl; `Enter` öffnet in `FieldList` eine Auswahlliste + (Hoch/Runter, Bild auf/ab, Pos1/Ende, Mausrad, Klick; `Enter` übernimmt, + `Esc` bricht ab). Im Missionseditor nutzen `world.kind` (fixed/reference) + und `world.reference` (die 128 Sektoren mit Ländern) diese Liste. +- Die Wahl eines Sektors setzt `world.kind = "reference"` und + `size_nm = 500`. Die Vorschau zeichnet die Küste des Referenzsektors aus + einem einmal pro Prozess geladenen Sektor-Cache (`sector_summaries`). +- Weiter offen aus 1.3: OffscreenCanvas (Phase 11), VDS (Phase 7). diff --git a/src/core/version.py b/src/core/version.py index e188feb3..3b9383f5 100644 --- a/src/core/version.py +++ b/src/core/version.py @@ -4,7 +4,7 @@ This module is deliberately dependency-free because setuptools imports the version while building the project. """ -APP_VERSION = "1.3.1" +APP_VERSION = "1.3.2" SAVE_VERSION = 22 SAVE_SCHEMA = "u-jagd-save-v22" SPLASH_TEXT = ( diff --git a/src/ui/editor_widgets.py b/src/ui/editor_widgets.py index 139d30a8..7c0ed697 100644 --- a/src/ui/editor_widgets.py +++ b/src/ui/editor_widgets.py @@ -298,6 +298,9 @@ class FieldRow: value: Any setter: Callable[[Any], None] header: bool = False + # A closed value set: Enter opens a pick list of (value, display text) + # instead of free text editing. Display text is drawn raw. + choices: Callable[[], list[tuple[Any, str]]] | None = None def section_header(group: str) -> FieldRow: @@ -377,6 +380,15 @@ class FieldList: self.input = TextField(maximum=4096) self.original: Any = None self.error = "" + self.choice_items: list[tuple[Any, str]] = [] + self.choice_index = 0 + self.choice_scroll = 0 + self._choice_rect: pygame.Rect | None = None + self._choice_row_height = 26 + + @property + def choosing(self) -> bool: + return self.editing and bool(self.choice_items) @property def selected_row(self) -> FieldRow | None: @@ -411,6 +423,11 @@ class FieldList: if row is None or row.header: return False self.original = row.value + self.choice_items = list(row.choices()) if row.choices is not None else [] + if row.choices is not None and not self.choice_items: + return False + self.choice_index = next((index for index, (value, _) in enumerate(self.choice_items) + if value == row.value), 0) self.input.value = value_text(row.value) self.input.selected_all = True self.input._key_text = "" @@ -422,15 +439,26 @@ class FieldList: if not self.editing: return False self.editing = False + self.choice_items = [] self.error = "" return True + def move_choice(self, amount: int) -> bool: + if not self.choosing: + return False + before = self.choice_index + self.choice_index = max(0, min(len(self.choice_items) - 1, self.choice_index + amount)) + return before != self.choice_index + def apply_edit(self, tr: Tr = IDENTITY_TR) -> bool: row = self.selected_row if not self.editing or row is None: return False try: - value = parse_value(self.input.value, self.original, row.path) + if self.choice_items: + value = self.choice_items[self.choice_index][0] + else: + value = parse_value(self.input.value, self.original, row.path) row.setter(value) except ContentValidationError as exc: self.error = localized_error(exc, tr) @@ -439,6 +467,7 @@ class FieldList: self.error = f"{row.path}: {exc}" return True self.editing = False + self.choice_items = [] self.error = "" return True @@ -462,6 +491,8 @@ class FieldList: def handle_event(self, event: pygame.event.Event, rect: pygame.Rect, row_height: int = 32, tr: Tr = IDENTITY_TR) -> bool: + if self.choosing: + return self._handle_choice_event(event, rect) if self.editing: if event.type == pygame.KEYDOWN: if event.key in (pygame.K_RETURN, pygame.K_KP_ENTER): @@ -499,9 +530,68 @@ class FieldList: return True if changed or self.editing else True return False + def _handle_choice_event(self, event: pygame.event.Event, rect: pygame.Rect) -> bool: + """The open pick list owns all input until Enter or Esc.""" + page = max(1, (self._choice_rect.height if self._choice_rect else rect.height) + // self._choice_row_height - 1) + if event.type == pygame.KEYDOWN: + if event.key in (pygame.K_RETURN, pygame.K_KP_ENTER): + return self.apply_edit() + if event.key == pygame.K_ESCAPE: + return self.cancel_edit() + steps = {pygame.K_UP: -1, pygame.K_k: -1, pygame.K_DOWN: 1, pygame.K_j: 1, + pygame.K_PAGEUP: -page, pygame.K_PAGEDOWN: page, + pygame.K_HOME: -len(self.choice_items), pygame.K_END: len(self.choice_items)} + if event.key in steps: + self.move_choice(steps[event.key]) + return True + position = event_position(event) + if event.type == pygame.MOUSEWHEEL: + self.move_choice(-event.y) + return True + if event.type == pygame.MOUSEBUTTONDOWN and getattr(event, "button", 0) == 1 and position: + box = self._choice_rect + if box is None or not box.collidepoint(position): + return self.cancel_edit() + index = self.choice_scroll + int((position[1] - box.y) // self._choice_row_height) + if 0 <= index < len(self.choice_items): + self.choice_index = index + return self.apply_edit() + return True + return event.type == pygame.TEXTINPUT + + def _draw_choices(self, surface: pygame.Surface, rect: pygame.Rect, + anchor: pygame.Rect, value_x: int) -> None: + """Draw the pick list under (or above) the edited row, inside rect.""" + height = self._choice_row_height + below = rect.bottom - anchor.bottom + above = anchor.top - rect.top + room = below if below >= above else above + visible = max(1, min(len(self.choice_items), (room - 4) // height)) + box_h = visible * height + 4 + top = anchor.bottom if below >= above else anchor.top - box_h + box = pygame.Rect(value_x, top, max(1, rect.right - value_x - 4), box_h) + self._choice_rect = box + self.choice_scroll = max(0, min(self.choice_scroll, len(self.choice_items) - visible)) + if self.choice_index < self.choice_scroll: + self.choice_scroll = self.choice_index + elif self.choice_index >= self.choice_scroll + visible: + self.choice_scroll = self.choice_index - visible + 1 + pygame.draw.rect(surface, PALETTE.panel, box) + pygame.draw.rect(surface, PALETTE.focus, box, 1) + for offset, (_, label) in enumerate( + self.choice_items[self.choice_scroll:self.choice_scroll + visible]): + index = self.choice_scroll + offset + item = pygame.Rect(box.x + 2, box.y + 2 + offset * height, box.width - 4, height) + if index == self.choice_index: + pygame.draw.rect(surface, PALETTE.raised, item) + draw_text(surface, raw_text(label), item.inflate(-8, 0), size=13, + color=PALETTE.focus if index == self.choice_index else PALETTE.text) + def draw(self, surface: pygame.Surface, rect: pygame.Rect, *, tr: Tr = IDENTITY_TR, label_width: int = 245, row_height: int = 32) -> None: pygame.draw.rect(surface, PALETTE.background, rect) + choice_anchor: tuple[pygame.Rect, int] | None = None visible = max(1, rect.height // row_height) self.scroll = max(0, min(self.scroll, max(0, len(self.rows) - visible))) if self.selected < self.scroll: @@ -531,10 +621,17 @@ class FieldList: max(1, row_rect.right - label_rect.right - 12), row_height - 6) draw_text(surface, tr(row.label), label_rect, color=PALETTE.text if selected else PALETTE.dim, size=13) - if selected and self.editing: + if selected and self.choosing: + pygame.draw.rect(surface, PALETTE.focus, value_rect, 1) + draw_text(surface, raw_text(self.choice_items[self.choice_index][1]), + value_rect.inflate(-8, 0), size=14) + choice_anchor = (row_rect, value_rect.x) + elif selected and self.editing: self.input.draw(surface, value_rect, focused=True) else: draw_text(surface, raw_text(value_text(row.value)), value_rect, size=14) + if choice_anchor is not None: + self._draw_choices(surface, rect, *choice_anchor) def _leaf_rows(current: dict[str, Any], current_prefix: str, diff --git a/src/ui/mission_editor.py b/src/ui/mission_editor.py index 6c8d6c36..d9c1fafe 100644 --- a/src/ui/mission_editor.py +++ b/src/ui/mission_editor.py @@ -9,12 +9,29 @@ from typing import Any, Iterable, Mapping import pygame from src.core.i18n import raw_text, translation_scope -from src.core.mission_definition import (MISSION_FIELD_METADATA, MissionDefinition, - default_mission) +from src.core.mission_definition import (MISSION_FIELD_METADATA, REFERENCE_PREFIX, + MissionDefinition, default_mission, + reference_sector_index) from src.data.user_content import ContentRecord, UserContentStore from src.data.validation import (ContentValidationError, localized_error, localized_issue) from src.ui import editor_widgets as widgets +from src.world.real_coast import SECTOR_COUNT, sector_for_index + +WORLD_KINDS = ("fixed", "reference") +_SECTOR_SUMMARIES: list[tuple[int, tuple[str, ...], tuple[tuple[tuple[float, float], ...], ...]]] = [] + + +def sector_summaries(): + """(index, countries, landmass outlines) of every packaged sector, loaded + once per process: the pick list and the preview coast read this cache.""" + if not _SECTOR_SUMMARIES: + for index in range(SECTOR_COUNT): + sector, _ = sector_for_index(index) + outlines = tuple(tuple((float(x), float(y)) for x, y in land["points"]) + for land in sector["landmasses"]) + _SECTOR_SUMMARIES.append((index, tuple(sector["countries"]), outlines)) + return _SECTOR_SUMMARIES class MissionEditor: @@ -218,6 +235,12 @@ class MissionEditor: if "reference" not in data["world"]: rows.append(widgets.FieldRow("world.reference", "field.reference", "", lambda value: data["world"].__setitem__("reference", value))) + for row in rows: + if row.path == "world.kind": + row.choices = lambda: [(kind, kind) for kind in WORLD_KINDS] + elif row.path == "world.reference": + row.choices = self._sector_choices + row.setter = lambda value, world=data["world"]: self._set_reference(world, value) elif self.tab == "objective": rows = widgets.mapping_rows(data["objective"], "objective") elif self.tab == "units": @@ -280,6 +303,21 @@ class MissionEditor: rows = [] self.fields.set_rows(rows) + def _sector_choices(self) -> list[tuple[str, str]]: + return [(f"{REFERENCE_PREFIX}{index}", + self.tr("editor.sector_choice", sector=f"{REFERENCE_PREFIX}{index}", + countries=" / ".join(countries[:3]))) + for index, countries, _ in sector_summaries()] + + @staticmethod + def _set_reference(world: dict[str, Any], value: Any) -> None: + """Picking a sector makes the world a reference world at the only + runtime size; typing any other text stays a plain edit.""" + world["reference"] = value + if reference_sector_index(value) is not None: + world["kind"] = "reference" + world["size_nm"] = 500.0 + def _add_exact(self) -> None: values = self._data()["units"]["exact"] profile = sorted(self.profile_keys)[0] if self.profile_keys else "sub" @@ -390,9 +428,13 @@ class MissionEditor: self.status = localized_error(exc, self.tr) return True handled = self.fields.handle_event(event, self._rects.get("fields", pygame.Rect(40, 150, 900, 450))) - if self.fields.error: + if self.fields.choosing: + self.status = self.tr("editor.choose_hint") + elif self.fields.error: self.status = self.fields.error elif handled: + if self.status == self.tr("editor.choose_hint"): + self.status = "" self._sync_fields() return handled if self._delete_pending is not None: @@ -439,6 +481,8 @@ class MissionEditor: pygame.K_HOME, pygame.K_END, pygame.K_PAGEUP, pygame.K_PAGEDOWN): return True if self.fields.handle_event(event, self._rects.get("fields", pygame.Rect(40, 150, 900, 450))): + if self.fields.choosing: + self.status = self.tr("editor.choose_hint") return True if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: @@ -586,7 +630,17 @@ class MissionEditor: pygame.draw.rect(surface, (9, 28, 35), map_rect) pygame.draw.rect(surface, widgets.PALETTE.border, map_rect, 1) world_size = preview["world_size_nm"] + world = self._data()["world"] + reference = (reference_sector_index(world.get("reference")) + if world.get("kind") == "reference" else None) with widgets.clipped(surface, map_rect): + if reference is not None: + scale = map_rect.width / world_size + for outline in sector_summaries()[reference][2]: + points = [(map_rect.x + x * scale, map_rect.y + y * scale) for x, y in outline] + if len(points) >= 3: + pygame.draw.polygon(surface, widgets.PALETTE.raised, points) + pygame.draw.lines(surface, widgets.PALETTE.dim, True, points) for sector in preview["sectors"]: box = pygame.Rect(map_rect.x + sector["x"] / world_size * map_rect.width, map_rect.y + sector["y"] / world_size * map_rect.height, @@ -600,11 +654,14 @@ class MissionEditor: round(map_rect.y + marker["y"] / world_size * map_rect.height)) pygame.draw.circle(surface, colors.get(marker["side"], widgets.PALETTE.text), point, 5, 1) details = pygame.Rect(map_rect.right + 14, inner.y, max(1, inner.right - map_rect.right - 14), inner.height) - lines = (self.tr("editor.preview_seed", seed=preview["seed"]), + lines = ((self.tr("editor.preview_sector", sector=f"{REFERENCE_PREFIX}{reference}", + countries=", ".join(sector_summaries()[reference][1])) + if reference is not None else self.tr("editor.preview_fixed_world")), + self.tr("editor.preview_seed", seed=preview["seed"]), self.tr("editor.preview_markers", count=len(preview["markers"])), self.tr("editor.preview_events", count=len(preview["events"])), self.tr("editor.static_only"), self.tr("editor.runtime_scope")) for row, line in enumerate(lines): widgets.draw_text(surface, line, (details.x, details.y + row * 30, details.width, 26), - color=widgets.PALETTE.focus if row >= 3 else widgets.PALETTE.text) + color=widgets.PALETTE.focus if row >= 4 else widgets.PALETTE.text) diff --git a/tests/test_editor_widgets.py b/tests/test_editor_widgets.py index 136a63ef..598c1c44 100644 --- a/tests/test_editor_widgets.py +++ b/tests/test_editor_widgets.py @@ -97,3 +97,59 @@ def test_filter_field_textinput_dedup_matches_key_text(): pygame.event.Event(pygame.TEXTINPUT, text="q")) assert consumed assert field.text == "q" + + +def _keydown(key): + return pygame.event.Event(pygame.KEYDOWN, key=key, unicode="", mod=0) + + +def _choice_fields(taken): + fields = FieldList() + fields.set_rows([FieldRow("world.kind", "kind", "fixed", taken.append, + choices=lambda: [("fixed", "fixed"), ("reference", "reference")])]) + return fields + + +def test_choice_row_opens_pick_list_and_applies_the_chosen_value(): + taken = [] + fields = _choice_fields(taken) + rect = pygame.Rect(0, 0, 400, 300) + assert fields.handle_event(_keydown(pygame.K_RETURN), rect) + assert fields.choosing and fields.choice_index == 0 + assert fields.handle_event(_keydown(pygame.K_DOWN), rect) + assert fields.handle_event(_keydown(pygame.K_DOWN), rect) # clamps at the end + assert fields.choice_index == 1 + # Text typed into an open pick list is swallowed, not parsed. + assert fields.handle_event(pygame.event.Event(pygame.TEXTINPUT, text="x"), rect) + assert fields.handle_event(_keydown(pygame.K_RETURN), rect) + assert taken == ["reference"] + assert not fields.editing and not fields.choosing + + +def test_choice_row_escape_keeps_the_value(): + taken = [] + fields = _choice_fields(taken) + rect = pygame.Rect(0, 0, 400, 300) + fields.handle_event(_keydown(pygame.K_RETURN), rect) + fields.handle_event(_keydown(pygame.K_END), rect) + assert fields.handle_event(_keydown(pygame.K_ESCAPE), rect) + assert taken == [] and not fields.editing + + +def test_choice_row_click_uses_the_drawn_list_geometry(): + taken = [] + fields = _choice_fields(taken) + rect = pygame.Rect(0, 0, 400, 300) + surface = pygame.Surface((400, 300)) + fields.begin_edit() + fields.draw(surface, rect) + box = fields._choice_rect + assert box is not None and rect.contains(box) + row = fields._choice_row_height + assert fields.handle_event(_click((box.x + 10.0, box.y + 2 + row * 1.5)), rect) + assert taken == ["reference"] + # A click outside an open list closes it without a change. + fields.begin_edit() + fields.draw(surface, rect) + assert fields.handle_event(_click((5.0, 5.0)), rect) + assert taken == ["reference"] and not fields.editing diff --git a/tests/test_mission_editor.py b/tests/test_mission_editor.py index 73cbc31d..116cb4a0 100644 --- a/tests/test_mission_editor.py +++ b/tests/test_mission_editor.py @@ -126,3 +126,50 @@ def test_mission_authoring_events_add_edit_delete_and_save(tmp_path, language): assert (tmp_path / language / "missions" / "user.edited.json").exists() editor.draw(surface) pygame.quit() + + +def _world_row(editor, path): + editor.tab_index = editor.tabs.index("world") + editor._sync_fields() + index = next(i for i, row in enumerate(editor.fields.rows) if row.path == path) + editor.fields.selected = index + return editor.fields.rows[index] + + +def test_world_reference_is_picked_from_the_packaged_sectors(tmp_path): + pygame.init() + editor = MissionEditor(store=UserContentStore(tmp_path), profile_keys={"sub"}, + tr=Translator("en").translate) + editor.new("user.sector_pick") + row = _world_row(editor, "world.reference") + choices = row.choices() + assert len(choices) == 128 + assert choices[17][0] == "sector:17" and "Greece" in choices[17][1] + key = lambda k: pygame.event.Event(pygame.KEYDOWN, key=k, unicode="", mod=0) + assert editor.handle_event(key(pygame.K_RETURN)) + assert editor.fields.choosing and editor.status + for _ in range(17): + editor.handle_event(key(pygame.K_DOWN)) + editor.draw(pygame.Surface((1280, 720))) + assert editor.handle_event(key(pygame.K_RETURN)) + world = editor.current.data["world"] + assert world["reference"] == "sector:17" and not editor.status + assert world["kind"] == "reference" and world["size_nm"] == 500.0 + assert not [p for p in editor.validate() if p.path.startswith("world")] + pygame.quit() + + +def test_world_kind_is_a_closed_choice_and_preview_draws_the_sector_coast(tmp_path): + pygame.init() + editor = MissionEditor(store=UserContentStore(tmp_path), profile_keys={"sub"}, + tr=Translator("de").translate) + editor.new("user.sector_preview") + assert [value for value, _ in _world_row(editor, "world.kind").choices()] == ["fixed", "reference"] + surface = pygame.Surface((1280, 720)) + editor.tab_index = editor.tabs.index("preview") + editor.draw(surface) + fixed = pygame.image.tobytes(surface, "RGB") + editor.current.data["world"].update(kind="reference", reference="sector:17") + editor.draw(surface) + assert pygame.image.tobytes(surface, "RGB") != fixed + pygame.quit() diff --git a/tests/test_packaging.py b/tests/test_packaging.py index fec599af..87c03650 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -85,7 +85,7 @@ def test_source_and_wheel_contain_editor_templates(tmp_path): (ROOT / "data/contact_analysis" / name).read_bytes() assert any(name.endswith(".dist-info/licenses/THIRD_PARTY_NOTICES.md") for name in wheel_names) - assert any(name.endswith("-1.3.1.dist-info/METADATA") for name in wheel_names) + assert any(name.endswith("-1.3.2.dist-info/METADATA") for name in wheel_names) source = next(tmp_path.glob("u_jagd-*.tar.gz")) with tarfile.open(source) as archive: @@ -136,7 +136,7 @@ def test_source_and_wheel_contain_editor_templates(tmp_path): [sys.executable, "-c", "from importlib import resources; " "assert resources.files('data.editor_templates').joinpath('mission.json').is_file(); " - "from src.core.version import APP_VERSION; assert APP_VERSION == '1.3.1'; " + "from src.core.version import APP_VERSION; assert APP_VERSION == '1.3.2'; " "from src.commander.server import CommanderServer; " "server=CommanderServer(); server.start('127.0.0.1',0); server.stop(); " "from src.core import manual; page=manual.html_page('de'); assert 'station-sonar' in page; " diff --git a/tests/test_startup.py b/tests/test_startup.py index 502f9500..cc9ff441 100644 --- a/tests/test_startup.py +++ b/tests/test_startup.py @@ -12,9 +12,9 @@ from src.world.real_coast import sector_for_seed def test_release_version_and_exact_splash_text(): - assert APP_VERSION == "1.3.1" + assert APP_VERSION == "1.3.2" assert SPLASH_TEXT == ( - "Anti Sub Marine Warfare on uConsole by Dominik Bornhäußer Version 1.3.1" + "Anti Sub Marine Warfare on uConsole by Dominik Bornhäußer Version 1.3.2" )