diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index ef3992ee..859742b2 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -7,7 +7,7 @@ body: attributes: value: | Danke! Das Spiel füllt Version, Plattform und Log selbst aus („Fehler melden“ im Hauptmenü oder im Browser-Menü). - Thanks! The game fills in version, platform and log itself ("Report a bug" in the main menu, the Windows starter or the browser menu). + Thanks! The game fills in version, platform and log itself ("Report a bug" in the main menu or the browser menu). - type: textarea id: what attributes: diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 9d32483a..c462f113 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -1,4 +1,4 @@ -# Builds the Windows program (U-Jagd-Windows.exe: starter window + game) on +# Builds the Windows program (U-Jagd-Windows.exe, starts straight into the game) on # every push and pull request. A push to main publishes it as the GitHub # release "v"; the program's update check reads that release. name: Windows program diff --git a/AGENTS.md b/AGENTS.md index 3079f71e..72e7dc1c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ ## Authority and scope -- This is U-Jagd 1.3.109 (`src/core/version.py`); current saves are v40-only. Treat these as compatibility contracts, not changelog entries. +- This is U-Jagd 1.3.110 (`src/core/version.py`); current saves are v40-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/CHANGELOG.de.md b/CHANGELOG.de.md index afffccf3..e70d00c0 100644 --- a/CHANGELOG.de.md +++ b/CHANGELOG.de.md @@ -4,6 +4,18 @@ Alle Versionen von U-Jagd, die neueste zuerst. Die [README](README.de.md) zeigt nur die neueste. +## 1.3.110 + +Version 1.3.110 installiert Updates nicht mehr von selbst. Gibt es ein neueres +Release, zeigen Startbildschirm und Hauptmenü dessen Version, den Eintrag aus +dem Änderungsprotokoll in der Spielsprache und eine Warnung, wenn Spielstände +dieser Version (auch die automatische Sicherung) damit nicht mehr laden, dazu +den Knopf **Jetzt updaten** (Taste U oder Klick). Erst dieser Knopf installiert +es: Auf der uConsole schließt das Spiel, aktualisiert sich auf das Release und +startet neu (der alte Hintergrund-Update-Timer schaltet sich selbst ab); das +Windows-Programm lädt die neue Datei im Hintergrund, prüft sie, tauscht sich +aus und startet neu. Ohne Netz erscheint kein Hinweis. + ## 1.3.109 Version 1.3.109 lässt die KI jede freie Station besetzen. Die neue Crew-Hilfe diff --git a/CHANGELOG.md b/CHANGELOG.md index e59c6398..7cbdc386 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ Every U-Jagd release, newest first. The [README](README.md) shows only the latest one. +## 1.3.110 + +Release 1.3.110 no longer installs updates on its own. When a newer release +is published, the start screen and the main menu show its version, its +changelog entry in the game language and a warning when saved games of this +version (the autosave too) will not load in it, plus the button **Update now** +(key U or a click). Only that button installs it: on the uConsole the game +closes, updates to the release and starts again (the old background update +timer switches itself off); the Windows program downloads the new file in the +background, checks it, swaps itself and restarts. Offline no notice appears. + ## 1.3.109 Release 1.3.109 lets the AI man every free station. The new crew assist diff --git a/README.de.md b/README.de.md index acef78ca..48d6d627 100644 --- a/README.de.md +++ b/README.de.md @@ -14,20 +14,17 @@ 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.109** +Aktuelle Version: **1.3.110** -Version 1.3.109 lässt die KI jede freie Station besetzen. Die neue Crew-Hilfe -(Shift+F2, in einer Mission aus der Mehrspieler-Lobby immer an) bemannt jede -Station der Fregatte und eines bemannten U-Boots, die niemand hält, damit -jeder Spieler bei einer Station bleiben kann: Die Station auf dem Bildschirm -der uConsole und jede Station, die ein Browser hält, bleiben bei ihrem -Spieler, und eine im Browser freigegebene Station („An KI übergeben“) geht -sofort an die KI zurück. Auf dem U-Boot weicht die KI aus, patrouilliert oder -läuft eine bekannte Fregatte an, hält die Rohre geladen und schießt auf eine -nahe Ortung, schnorchelt zum Laden, hält den Trimm und schickt die Leckteams. -In der Lobby kann die uConsole auch nur Gastgeber sein (Station „keine, nur -Gastgeber“): Sie spielt keine Station, Browser und KI besetzen jede. -Spielstände sind jetzt v40. +Version 1.3.110 installiert Updates nicht mehr von selbst. Gibt es ein neueres +Release, zeigen Startbildschirm und Hauptmenü dessen Version, den Eintrag aus +dem Änderungsprotokoll in der Spielsprache und eine Warnung, wenn Spielstände +dieser Version (auch die automatische Sicherung) damit nicht mehr laden, dazu +den Knopf **Jetzt updaten** (Taste U oder Klick). Erst dieser Knopf installiert +es: Auf der uConsole schließt das Spiel, aktualisiert sich auf das Release und +startet neu (der alte Hintergrund-Update-Timer schaltet sich selbst ab); das +Windows-Programm lädt die neue Datei im Hintergrund, prüft sie, tauscht sich +aus und startet neu. Ohne Netz erscheint kein Hinweis. Frühere Versionen: [CHANGELOG.de.md](CHANGELOG.de.md). @@ -180,9 +177,13 @@ U-Jagd private Netzwerke nutzen darf: zulassen, sonst können sich andere Geräte nicht verbinden. Das Protokoll liegt in `%USERPROFILE%\.u-jagd\logs\server.log`. -Hat das Spiel ein neueres Release geladen und beendet sich zum Installieren, -ersetzt sich das Programm selbst und startet die neue Version (eine -liegengebliebene `U-Jagd-Windows.exe.new` löscht es beim +Bei jedem Start fragt das Programm GitHub, ob es ein neueres Release gibt; +Startbildschirm und Hauptmenü des Spiels zeigen dann dessen Eintrag aus dem +Änderungsprotokoll (und eine Warnung, wenn Spielstände dieser Version darin +nicht mehr laden) und bieten **Jetzt updaten** an. Vor diesem Knopf wird nichts +installiert: Dann lädt es die neue Datei im Hintergrund (Fortschritt auf dem +Knopf), prüft Größe und SHA-256-Prüfsumme, schließt sich, ersetzt sich selbst +und startet die neue Version (eine liegengebliebene `U-Jagd-Windows.exe.new` löscht es beim nächsten Start). Das Programm ist nicht signiert, deshalb warnt Windows SmartScreen beim ersten Start eventuell ("Weitere Informationen", "Trotzdem ausführen"). Spielstände und Einstellungen @@ -211,8 +212,9 @@ gelöscht). Selbst bauen unter Windows: ## Schnellstart Auf der ClockworkPi uConsole installiert ein einziger Befehl das Spiel mit -Menüeintrag und automatischem Update (jeder Start holt das neueste Release; -ohne Netz startet die installierte Version): +Menüeintrag. Ein neues Release wird nie von selbst installiert: Der +Startbildschirm zeigt es mit seinem Eintrag aus dem Änderungsprotokoll und +installiert es erst bei **Jetzt updaten** (ohne Netz erscheint kein Hinweis): ```sh curl -fsSL https://raw.githubusercontent.com/db9979/uconsole_asw_game/main/packaging/uconsole/install.sh | sh diff --git a/README.md b/README.md index 35c22541..62e47957 100644 --- a/README.md +++ b/README.md @@ -12,19 +12,16 @@ 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.109** +Current release: **1.3.110** -Release 1.3.109 lets the AI man every free station. The new crew assist -(Shift+F2, always on in a mission started from the multiplayer lobby) crews -each station of the frigate and of a crewed submarine that nobody holds, so -every player can stay on one station: the station on the uConsole's screen and -every station a browser holds stay with their player, and a station released -in the browser ("Hand over to AI") goes straight back to the AI. On the -submarine the AI commands evasion, patrols or closes a known frigate, keeps -the tubes loaded and fires at a close fix, snorkels to charge, keeps the trim -and sends the damage-control teams. In the lobby the uConsole can also be -host only (station "none, host only"): it plays no station, and the browsers -and the AI crew every one. Saves are now v40. +Release 1.3.110 no longer installs updates on its own. When a newer release +is published, the start screen and the main menu show its version, its +changelog entry in the game language and a warning when saved games of this +version (the autosave too) will not load in it, plus the button **Update now** +(key U or a click). Only that button installs it: on the uConsole the game +closes, updates to the release and starts again (the old background update +timer switches itself off); the Windows program downloads the new file in the +background, checks it, swaps itself and restarts. Offline no notice appears. Earlier releases: [CHANGELOG.md](CHANGELOG.md). @@ -171,9 +168,13 @@ approved in the game (F9) as on the uConsole. Windows may ask once whether U-Jagd may use private networks: allow it, otherwise other devices cannot connect. The game log is kept in `%USERPROFILE%\.u-jagd\logs\server.log`. -When the game has downloaded a newer release and quits to install it, the -program replaces itself and starts the new version (a leftover -`U-Jagd-Windows.exe.new` is deleted at the next start). The build is not code-signed, +At every start the program asks GitHub whether a newer release exists; the +game's start screen and main menu then show its changelog entry (and a warning +when saves of this version will not load in it) and offer **Update now**. +Nothing is installed before that button is pressed: then it downloads the new +file in the background (progress on the button), checks its size and SHA-256 +digest, closes, replaces itself and starts the new version (a +leftover `U-Jagd-Windows.exe.new` is deleted at the next start). The build is not code-signed, so Windows SmartScreen may warn on the first start ("More info", "Run anyway"). Saves and settings live in `%USERPROFILE%\.u-jagd\` as on Linux. @@ -197,9 +198,10 @@ To build locally on Windows: `python -m pip install -e ".[windows]"` and ## Quick Start -On the ClockworkPi uConsole, one command installs the game with a menu entry -and automatic updates (every start fetches the newest release; offline the -installed version starts): +On the ClockworkPi uConsole, one command installs the game with a menu entry. +A newer release is never installed on its own: the start screen shows it with +its changelog entry and installs it when you press **Update now** (offline no +notice appears): ```sh curl -fsSL https://raw.githubusercontent.com/db9979/uconsole_asw_game/main/packaging/uconsole/install.sh | sh diff --git a/conftest.py b/conftest.py index 72226c5f..56ddd55a 100644 --- a/conftest.py +++ b/conftest.py @@ -9,6 +9,8 @@ import pytest sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) os.environ.setdefault("SDL_VIDEODRIVER", "dummy") os.environ.setdefault("SDL_AUDIODRIVER", "dummy") +# The game never asks GitHub for new releases from a test run. +os.environ.setdefault("U_JAGD_NO_UPDATE_CHECK", "1") def pytest_configure(config): diff --git a/data/i18n/de.json b/data/i18n/de.json index 71799a42..bb21ec2a 100644 --- a/data/i18n/de.json +++ b/data/i18n/de.json @@ -6321,5 +6321,12 @@ "commander.web.lobby_room_host_only": "Die uConsole ist nur Gastgeber: Jede Station wird im Browser oder von der KI gespielt.", "commander.local.advanced": "Erweiterte Netzwerkeinstellungen: {state}", "commander.local.advanced.open": "eingeblendet", - "commander.local.advanced.closed": "ausgeblendet" + "commander.local.advanced.closed": "ausgeblendet", + "update.available": "Update {version} verfügbar", + "update.installed": "Installiert: {version}", + "update.saves_break": "Spielstände dieser Version (auch die automatische Sicherung) laden mit dem neuen Update nicht mehr.", + "update.button": "U: Jetzt updaten", + "update.button_browser": "U: Jetzt updaten (Release-Seite)", + "update.failed": "Update fehlgeschlagen, U: nochmal", + "update.downloading": "Lade Update … {percent} %" } diff --git a/data/i18n/en.json b/data/i18n/en.json index b73a530a..66702450 100644 --- a/data/i18n/en.json +++ b/data/i18n/en.json @@ -6321,5 +6321,12 @@ "commander.web.lobby_room_host_only": "The uConsole only hosts: every station is played in the browser or by the AI.", "commander.local.advanced": "Advanced network settings: {state}", "commander.local.advanced.open": "shown", - "commander.local.advanced.closed": "hidden" + "commander.local.advanced.closed": "hidden", + "update.available": "Update {version} available", + "update.installed": "Installed: {version}", + "update.saves_break": "Saved games of this version (the autosave too) will not load in the new version.", + "update.button": "U: Update now", + "update.button_browser": "U: Update now (release page)", + "update.failed": "Update failed, U: try again", + "update.downloading": "Downloading update … {percent} %" } diff --git a/data/manual/00-quickstart.de.md b/data/manual/00-quickstart.de.md index 7e6000cc..66d868e8 100644 --- a/data/manual/00-quickstart.de.md +++ b/data/manual/00-quickstart.de.md @@ -85,12 +85,13 @@ Die Statuszeile unten zeigt das neueste Ereignis und die wichtigste Telemetrie; - **Kampagne** (Hauptmenü): sechs verkettete Einsätze in dem im Menü gewählten Seegebiet (Welt `W` und Seed; jeder Einsatz bleibt im selben Sektor). Übertragen werden die übrigen Torpedos (mindestens 2, höchstens 10), noch beschädigte Abteilungen, ein verlorener Hubschrauber und Ihr Ansehen bei der Führung (0-100, Start 50: +15 für einen Sieg, -20 für eine Niederlage, -10 für einen zivilen Verlust, +/-3 je erledigtem oder gescheitertem Auftrag). Nach jedem Einsatz läuft das Schiff in den Hafen: `1` volle Werftliegezeit (4 bis 8 Torpedos je nach Ansehen, alle Reparaturen, ein neuer Hubschrauber, Ansehen -5) oder `2` schnell wieder auslaufen (halbe Nachlieferung, Schäden bleiben an Bord, Ansehen +3); `Enter` läuft aus. Die Kampagne endet, wenn das Schiff verloren geht, das Ansehen unter 10 fällt oder der sechste Einsatz vorbei ist. Sie liegt in `~/.u-jagd/campaign.json`, getrennt von den Spielständen: ein während eines Kampagneneinsatzes gespeicherter Platz lädt als normale Mission; damit er zählt, wird der Einsatz aus dem Kampagnenbildschirm erneut gefahren. `N` startet eine neue Kampagne (bei laufender Kampagne zweimal). - **U-Boot-Kampagne** (Hauptmenü, Kampagne, `Tab`): fünf verkettete U-Boot-Missionen im selben Seegebiet, gespielt auf der U-Boot-Seite: Aufklärung, Durchbruch, Geleitzugangriff, Durchbruch, Geleitzugangriff. Übertragen werden die Torpedos des U-Boots, sein Rumpfschaden (höchstens 60 %) und Ihr Ansehen bei der U-Boot-Führung (0-100, Start 50: +15 für eine gewonnene, -20 für eine verlorene Mission). Nach jeder Mission läuft das U-Boot in seinen Stützpunkt: `1` volle Überholung (volle Torpedobeladung, Rumpf repariert, Ansehen -5) oder `2` schnell wieder auslaufen (die Hälfte von 4 bis 8 Torpedos je nach Ansehen kommt dazu, der Rumpfschaden bleibt, Ansehen +3); `Enter` läuft aus. Sie endet, wenn das U-Boot verloren geht, das Ansehen unter 10 fällt oder die fünfte Mission vorbei ist, und liegt in `~/.u-jagd/boat_campaign.json` neben der Kampagne der Fregatte. - **Einsatzbuch** (Hauptmenü): jede beendete Mission (nie eine Lektion) der Seite, die die uConsole gespielt hat, mit Datum, Mission, Realismusstufe, Ergebnis, Punkten und Minuten; der Bestwert je Mission und fünf Auszeichnungen je Seite: erster Sieg, ein Schuss ein Treffer (der Gegner mit einer einzigen Waffe versenkt), ohne Kratzer (kein Schaden), nie beschossen und Realist (ein Sieg auf der Stufe Realistisch). Die Fregatte trägt ihre Missionspunkte ein; das U-Boot zählt sein Ergebnis (Fregatte versenkt 1500, Geleitzug versenkt 1200, Durchbruch oder Meldung 1000, Entkommen 800, Überleben 600) plus bis zu 500 für ein unbeschädigtes Boot und 100 je übrigem Torpedo, mal dem Faktor der Stufe. `Links`/`Rechts` wechseln Fregatte und U-Boot, `Esc` zurück. Das Endpanel nennt die Punkte, einen neuen Bestwert und neue Auszeichnungen. Das Einsatzbuch ist `~/.u-jagd/logbook.json` (die neuesten 200 Missionen), nie Teil eines Spielstands. -- **Fehler melden** (Hauptmenü): schreibt `~/.u-jagd/bug-report.txt` (Version, Plattform und die neuesten Zeilen aus `~/.u-jagd/crash.log`, Ihr Benutzername aus Pfaden entfernt) und zeigt einen QR-Code, der am Handy ein neues GitHub-Issue mit Version und Plattform öffnet; dort die Datei anhängen. `Enter` öffnet das Issue mit Log in einem Browser, falls das Gerät einen hat, `Esc` geht zurück. Nach einem abgestürzten Start wählt das Hauptmenü diesen Eintrag vor und weist darauf hin. Gesendet wird erst, wenn Sie das Issue mit Ihrem eigenen GitHub-Konto abschicken. Der Windows-Starter („Fehler melden“) und das Einstellungsmenü im Browser haben denselben Link. +- **Fehler melden** (Hauptmenü): schreibt `~/.u-jagd/bug-report.txt` (Version, Plattform und die neuesten Zeilen aus `~/.u-jagd/crash.log`, Ihr Benutzername aus Pfaden entfernt) und zeigt einen QR-Code, der am Handy ein neues GitHub-Issue mit Version und Plattform öffnet; dort die Datei anhängen. `Enter` öffnet das Issue mit Log in einem Browser, falls das Gerät einen hat, `Esc` geht zurück. Nach einem abgestürzten Start wählt das Hauptmenü diesen Eintrag vor und weist darauf hin. Gesendet wird erst, wenn Sie das Issue mit Ihrem eigenen GitHub-Konto abschicken. Das Einstellungsmenü im Browser hat denselben Link. +- **Update-Hinweis** (Startbildschirm und Hauptmenü): Neue Versionen werden nie von selbst installiert. Beim Start fragt das Spiel einmal bei GitHub, ob es ein neueres Release gibt; dann zeigen der Startbildschirm (oben rechts) und das Hauptmenü (links neben den Einträgen) dessen Version, den Eintrag aus dem Änderungsprotokoll in der Spielsprache und eine Warnung, wenn Spielstände dieser Version (auch die automatische Sicherung) mit dem neuen Release nicht mehr laden, weil sich das Spielstandformat geändert hat. `U` oder ein Klick auf **Jetzt updaten** installiert es: Auf der uConsole schließt das Spiel, das kleine Fenster des Starters zeigt Download und Prüfung, und die neue Version startet; das Windows-Programm lädt die neue Datei im Hintergrund (Fortschritt auf dem Knopf), prüft Größe und SHA-256-Prüfsumme, schließt sich, ersetzt sich selbst und startet die neue Version; jede andere Installation öffnet die Release-Seite. Ohne Netz oder mit `U_JAGD_NO_UPDATE=1` erscheint kein Hinweis. - `S` / `L`: Speichern / Laden (Plätze 1-5). Spielstände sind exakt und deterministisch: ein geladenes Spiel läuft identisch weiter. - **Autosave:** Eine laufende Mission wird alle 5 Minuten und beim Beenden oder Verlassen ins Hauptmenü nach `~/.u-jagd/autosave.json` gespeichert, neben den fünf Plätzen. Das Hauptmenü beginnt dann mit **Einsatz fortsetzen**, das sie exakt weiterführt; nach einem Absturz ist es der letzte 5-Minuten-Stand. Eine beendete Mission (Sieg, Niederlage oder Schiff gesunken) und jede neue Mission löschen den Autosave. Der Web-Host (`--web-host`) speichert nicht automatisch. - `F10`: Optionen - Sprache, Vollbild, Audio, große Schrift, Tooltips, Bildrate (30 oder 60 FPS; 30 spart Rechenleistung auf der uConsole und ist voreingestellt), Ereignislog/Telemetrie als Statuszeile (Standard, mehr Platz für die Station) oder feste Leiste, und die **Realismusstufe** der nächsten Mission: **Einsteiger** (Bedienerassistenz an: automatische Linienbeschriftung, Blattfrequenz- und Katalog-/Senderkandidaten; der Computergegner greift zögerlicher an, wartet auf eine bessere Schusslösung und klassifiziert und startet als Fregatte seinen Hubschrauber 1,5-mal langsamer; Punkte 75 %), **Standard** (voreingestellt: Rohdaten und manuelle Analyse, der kalibrierte Gegner; Punkte 100 %) oder **Realistisch** (keine Assistenz; der Gegner greift entschlossener an, schießt auf eine gröbere Lösung und reagiert als Fregatte 30 % schneller; Punkte 125 %). Die Stufe stimmt nur den Computergegner ab, nie einen Menschen auf der anderen Seite, und eine laufende Mission behält die Stufe, mit der sie begann (die Zeile sagt dann "ab der nächsten Mission"). Das Endpanel zeigt die Stufe mit ihrem Punktefaktor; Spielstände behalten sie. Seite 2 (`Bild ab`/`Tab`): welche Seite der uConsole spielt, Fregatte (Standard) oder feindliches U-Boot; nur im Hauptmenü, nie gespeichert. Ein neues Spiel fragt ohnehin zuerst danach. Auf Seite 2 liegen auch die **geglätteten Kartenlinien** (standardmäßig aus; glättet Peilstriche, Küste und Plot, kostet auf der uConsole etwas Rechenzeit). Dazu die **gesprochenen Crew-Meldungen** (standardmäßig aus): die Crew meldet Torpedo im Wasser, neuen Kontakt mit Peilung, Sinkgeräusche, Torpedo los, Treffer, Gefechtsstationen, Seefernaufklärer auf Station und das Missionsende laut, Peilungen Ziffer für Ziffer. Die uConsole spricht über ein installiertes `espeak-ng` (`sudo apt install espeak-ng`) und bleibt ohne es stumm; Remote-Crew-Browser haben einen eigenen Schalter unter Einstellungen (Sprachausgabe des Browsers, in dessen Sprache). Spielt die uConsole das U-Boot, meldet stattdessen dessen Crew (siehe Kapitel Referenz). -- **Mehrspieler** (Hauptmenü): die Lobby, in der sich die Besatzung vor einem Einsatz trifft. Sie startet Remote Crew selbst im Crew-Modus und zeigt QR-Code, Adresse und Beitrittscode. Auf dem eigenen Hotspot des uConsole zeigt sie zwei nummerierte Schritte nebeneinander: **1** den WLAN-QR-Code mit WLAN-Name und Passwort (dem Hotspot beitreten), **2** den Seiten-QR-Code mit Adresse und Beitrittscode (die Crew-Seite öffnen). Die Browser koppeln, wählen Einheit und Stationen und drücken **Bereit**; sie sehen die Mission, was der uConsole spielt, und jedes Crewmitglied mit Stationen und Bereit-Häkchen. Am uConsole wählen `Auf`/`Ab` eine Zeile und `Links`/`Rechts` ändern sie: die Mission, die Einheit des uConsole und die Station, die er zeigt, oder **keine, nur Gastgeber**: Dann spielt der uConsole keine Station, die Browser können jede übernehmen, und die KI besetzt den Rest. **Mission für alle starten** startet einen Countdown von fünf Sekunden, den jeder Browser sieht; dann beginnt die Mission für alle gleichzeitig, und der uConsole öffnet seine gewählte Station. Ist ein Crewmitglied mit Station noch nicht bereit, fragt das erste `Enter` nach, ein zweites startet trotzdem. `Esc` bricht einen Countdown ab, sonst geht es zurück ins Hauptmenü, und Remote Crew läuft weiter. Endet eine Mission, die aus der Lobby gestartet wurde, kehren alle mit ihren Stationen in die Lobby zurück; die Bereit-Häkchen beginnen wieder von vorn. Jede Mission aus der Lobby hat die Crew-Hilfe an (`Shift+F2`). `F9` öffnet aus der Lobby die vollständigen Remote-Crew-Einstellungen. Mit `--multiplayer` gestartet, öffnet das Spiel die Lobby direkt nach dem Startbild. Auf einem Windows-PC startet `U-Jagd-Windows.exe` mit denselben Optionen direkt ins Spiel; ein eigenes Starterfenster gibt es nicht. -- `F9`: Commander / Remote Crew - Browser im LAN können Stationen übernehmen. Die Seite hat einen Schalter, **Mehrspieler**: `Enter` schaltet ihn auf der ersten lokalen Netzwerkadresse ein oder, wenn die uConsole kein Netz hat, auf ihrem eigenen Hotspot (sofern der Hotspot-Helfer installiert ist; der uConsole-Installer `install.sh` richtet ihn ein, wenn er kann, und gibt sonst einen Hinweis aus). Der Hotspot behält WLAN-Name und Passwort von einem Start zum nächsten, sodass ein Handy oder PC, das einmal beigetreten ist, sich von selbst wieder verbindet. Auf dem Hotspot zeigt die Seite beide Schritte zusammen: **1** den WLAN-QR-Code mit Name und Passwort, **2** den Seiten-QR-Code mit dem Beitrittscode. **Crew** zeigt die Spieler und ihre Stationen. **Erweiterte Netzwerkeinstellungen** blendet Netzwerkmodus (LAN oder Hotspot), Adresse und Port zur Handwahl ein; sie ändern sich nur bei ausgeschaltetem Mehrspieler. Dort erzeugt, solange Mehrspieler aus ist, **Neues Hotspot-Passwort** ein neues Hotspot-Passwort und behält den Namen; jedes Gerät muss dann mit dem neuen WLAN-QR-Code neu beitreten. Eine freie Station wird sofort mit allen ihren Rechten übernommen (auch Direktfeuer und Sonar-Liveaudio, wo die Station sie hat); eine Station, die ein Crewmitglied hält, wird angefragt, und der Inhaber (er sieht die Anfrage mit den Knöpfen Übergeben / Station behalten) oder der Host kann sie übergeben. Eine Station hat immer alle ihre Rechte; der Host kann jederzeit eine Station entziehen, das SimLog geben oder nehmen (Roster-Taste `L`) und bis zu zwei Browser zu reinen Beobachtern machen (Roster-Taste `O`): sie sehen jede Station beider Einheiten, ohne sie zu halten, können nichts befehlen und erhalten das SimLog mit Zeitstrahl zur Nachbesprechung und JSON-Export. Auf einem Windows-PC startet das Programm `U-Jagd-Windows.exe` das Spiel mit bereits eingeschalteter Remote Crew (Besatzungs- oder Solomodus) und zeigt Browser-Adresse, Beitrittscode und QR-Code; sein Feld Sprache stellt Starter, Spiel und Crew-Seiten zwischen English und Deutsch um und wird in den Einstellungen gespeichert. `--remote-crew` macht dasselbe über die Kommandozeile (siehe README). Die Crew-Seiten öffnen in der gespeicherten Sprache des Hosts (`F10`-Optionen auf der uConsole); der Knopf English/Deutsch in der Statusleiste des Browsers stellt nur diesen Browser um. Die Crew-Seite ist für Chrome oder Chromium (auch Edge) auf einem Desktop-PC gebaut; ein anderer Browser zeigt über dem Kopplungscode einen Hinweis, und eine Seite, die dort nicht starten kann, sagt das, statt endlos zu laden. Nach einem Update des Hosts lädt sich eine offene Browserseite einmal selbst neu und läuft so immer mit dem passenden Web-Client. +- **Mehrspieler** (Hauptmenü): die Lobby, in der sich die Besatzung vor einem Einsatz trifft. Sie startet Remote Crew selbst im Crew-Modus und zeigt QR-Code, Adresse und Beitrittscode. Auf dem eigenen Hotspot des uConsole zeigt sie zwei nummerierte Schritte nebeneinander: **1** den WLAN-QR-Code mit WLAN-Name und Passwort (dem Hotspot beitreten), **2** den Seiten-QR-Code mit Adresse und Beitrittscode (die Crew-Seite öffnen). Die Browser koppeln, wählen Einheit und Stationen und drücken **Bereit**; sie sehen die Mission, was der uConsole spielt, und jedes Crewmitglied mit Stationen und Bereit-Häkchen. Am uConsole wählen `Auf`/`Ab` eine Zeile und `Links`/`Rechts` ändern sie: die Mission, die Einheit des uConsole und die Station, die er zeigt, oder **keine, nur Gastgeber**: Dann spielt der uConsole keine Station, die Browser können jede übernehmen, und die KI besetzt den Rest. **Mission für alle starten** startet einen Countdown von fünf Sekunden, den jeder Browser sieht; dann beginnt die Mission für alle gleichzeitig, und der uConsole öffnet seine gewählte Station. Ist ein Crewmitglied mit Station noch nicht bereit, fragt das erste `Enter` nach, ein zweites startet trotzdem. `Esc` bricht einen Countdown ab, sonst geht es zurück ins Hauptmenü, und Remote Crew läuft weiter. Endet eine Mission, die aus der Lobby gestartet wurde, kehren alle mit ihren Stationen in die Lobby zurück; die Bereit-Häkchen beginnen wieder von vorn. Jede Mission aus der Lobby hat die Crew-Hilfe an (`Shift+F2`). `F9` öffnet aus der Lobby die vollständigen Remote-Crew-Einstellungen. Mit `--multiplayer` gestartet, öffnet das Spiel die Lobby direkt nach dem Startbild. +- `F9`: Commander / Remote Crew - Browser im LAN können Stationen übernehmen. Die Seite hat einen Schalter, **Mehrspieler**: `Enter` schaltet ihn auf der ersten lokalen Netzwerkadresse ein oder, wenn die uConsole kein Netz hat, auf ihrem eigenen Hotspot (sofern der Hotspot-Helfer installiert ist; der uConsole-Installer `install.sh` richtet ihn ein, wenn er kann, und gibt sonst einen Hinweis aus). Der Hotspot behält WLAN-Name und Passwort von einem Start zum nächsten, sodass ein Handy oder PC, das einmal beigetreten ist, sich von selbst wieder verbindet. Auf dem Hotspot zeigt die Seite beide Schritte zusammen: **1** den WLAN-QR-Code mit Name und Passwort, **2** den Seiten-QR-Code mit dem Beitrittscode. **Crew** zeigt die Spieler und ihre Stationen. **Erweiterte Netzwerkeinstellungen** blendet Netzwerkmodus (LAN oder Hotspot), Adresse und Port zur Handwahl ein; sie ändern sich nur bei ausgeschaltetem Mehrspieler. Dort erzeugt, solange Mehrspieler aus ist, **Neues Hotspot-Passwort** ein neues Hotspot-Passwort und behält den Namen; jedes Gerät muss dann mit dem neuen WLAN-QR-Code neu beitreten. Eine freie Station wird sofort mit allen ihren Rechten übernommen (auch Direktfeuer und Sonar-Liveaudio, wo die Station sie hat); eine Station, die ein Crewmitglied hält, wird angefragt, und der Inhaber (er sieht die Anfrage mit den Knöpfen Übergeben / Station behalten) oder der Host kann sie übergeben. Eine Station hat immer alle ihre Rechte; der Host kann jederzeit eine Station entziehen, das SimLog geben oder nehmen (Roster-Taste `L`) und bis zu zwei Browser zu reinen Beobachtern machen (Roster-Taste `O`): sie sehen jede Station beider Einheiten, ohne sie zu halten, können nichts befehlen und erhalten das SimLog mit Zeitstrahl zur Nachbesprechung und JSON-Export. Auf einem Windows-PC startet das Programm `U-Jagd-Windows.exe` mit denselben Kommandozeilenoptionen direkt ins Spiel; ein eigenes Starterfenster gibt es nicht, und **Mehrspieler** im Hauptmenü (oder `--multiplayer`, siehe README) öffnet die Lobby mit eingeschalteter Remote Crew. Die Crew-Seiten öffnen in der gespeicherten Sprache des Hosts (`F10`-Optionen auf der uConsole); der Knopf English/Deutsch in der Statusleiste des Browsers stellt nur diesen Browser um. Die Crew-Seite ist für Chrome oder Chromium (auch Edge) auf einem Desktop-PC gebaut; ein anderer Browser zeigt über dem Kopplungscode einen Hinweis, und eine Seite, die dort nicht starten kann, sagt das, statt endlos zu laden. Nach einem Update des Hosts lädt sich eine offene Browserseite einmal selbst neu und läuft so immer mit dem passenden Web-Client. ## Handy-Ausguck und Sehrohr {#qs-phone} diff --git a/data/manual/00-quickstart.en.md b/data/manual/00-quickstart.en.md index 57fd0362..f49875fa 100644 --- a/data/manual/00-quickstart.en.md +++ b/data/manual/00-quickstart.en.md @@ -85,12 +85,13 @@ The bottom status ticker shows the newest event and key telemetry; `F11` opens t - **Campaign** (main menu): six linked missions in the sea area chosen in the menu (world `W` and seed; every mission keeps the same sector). Carried over are the torpedoes left (at least 2, at most 10), compartments still damaged, a lost helicopter and your standing with HQ (0-100, start 50: +15 for a win, -20 for a loss, -10 for a civilian loss, +/-3 per task done or failed). After each mission the ship calls at port: `1` full refit (4 to 8 torpedoes by standing, all repairs, a new helicopter, standing -5) or `2` quick turnaround (half that restock, damage stays aboard, standing +3); `Enter` sails. The campaign ends when the ship is lost, standing falls below 10, or the sixth mission is done. It is kept in `~/.u-jagd/campaign.json`, apart from the save slots: a slot saved during a campaign mission loads as a plain mission; to count, the mission is sailed again from the campaign screen. `N` starts a new campaign (twice while one is running). - **Submarine campaign** (main menu, Campaign, `Tab`): five linked submarine missions in the same sea area, played on the submarine side: reconnaissance, breakthrough, convoy attack, breakthrough, convoy attack. Carried over are the submarine's torpedoes, its hull damage (at most 60 %) and your standing with submarine command (0-100, start 50: +15 for a mission won, -20 for one lost). After each mission the submarine calls at its base: `1` full refit (full torpedo load, hull repaired, standing -5) or `2` quick turnaround (half of 4 to 8 torpedoes by standing added, the hull damage stays, standing +3); `Enter` puts to sea. It ends when the submarine is lost, standing falls below 10, or the fifth mission is done, and is kept in `~/.u-jagd/boat_campaign.json` beside the frigate's campaign. - **Logbook** (main menu): every finished mission (never a lesson) for the side the uConsole played, with date, mission, realism level, result, score and minutes; the best score per mission and five awards per side: first victory, one shot one kill (the enemy sunk with a single weapon), unscathed (no damage), never fired at, and realist (a victory on the Realistic level). The frigate files its mission score; the submarine counts its outcome (sinking the frigate 1500, sinking the convoy 1200, breakthrough or report 1000, escape 800, surviving 600) plus up to 500 for an undamaged boat and 100 per torpedo left, times the level's factor. `Left`/`Right` switch frigate and submarine, `Esc` back. The end panel names the score, a new best and new awards. The logbook is `~/.u-jagd/logbook.json` (the newest 200 missions), never part of a save. -- **Report a bug** (main menu): writes `~/.u-jagd/bug-report.txt` (version, platform and the newest lines of `~/.u-jagd/crash.log`, with your user name removed from paths) and shows a QR code that opens a new GitHub issue on a phone with version and platform filled in; attach the file there. `Enter` opens the issue with the log in a browser if the device has one, `Esc` goes back. After a crashed start the main menu selects this entry and says so. Nothing is sent until you submit the issue with your own GitHub account. The Windows starter ("Report a bug") and the browser settings menu have the same link. +- **Report a bug** (main menu): writes `~/.u-jagd/bug-report.txt` (version, platform and the newest lines of `~/.u-jagd/crash.log`, with your user name removed from paths) and shows a QR code that opens a new GitHub issue on a phone with version and platform filled in; attach the file there. `Enter` opens the issue with the log in a browser if the device has one, `Esc` goes back. After a crashed start the main menu selects this entry and says so. Nothing is sent until you submit the issue with your own GitHub account. The browser settings menu has the same link. +- **Update notice** (start screen and main menu): new releases are never installed on their own. At launch the game asks GitHub once whether a newer release exists; if so, the start screen (top right) and the main menu (left of the entries) show its version, its changelog entry in the game language and, when saved games of this version (the autosave too) will not load in the new release because the save format changed, a warning. `U` or a click on **Update now** installs it: on the uConsole the game closes, the launcher's small window shows the download and check and the new version starts; the Windows program downloads it in the background (progress on the button), checks its size and SHA-256 digest, closes, replaces itself and starts the new version; any other installation opens the release page. Offline, or with `U_JAGD_NO_UPDATE=1`, no notice appears. - `S` / `L`: save / load (slots 1-5). Saves are exact and deterministic: a loaded game continues identically. - **Autosave:** a running mission is saved every 5 minutes and when you quit or leave it for the main menu, to `~/.u-jagd/autosave.json` beside the five slots. The main menu then starts with **Continue mission**, which resumes it exactly; after a crash it holds the last 5-minute save. A mission that ends (won, lost or ship sunk) and any new mission delete the autosave. The web host (`--web-host`) does not autosave. - `F10`: options - language, fullscreen, audio, large text, tooltips, frame rate (30 or 60 FPS; 30 saves CPU on the uConsole and is the default), event log / telemetry as status ticker (default, more room for the station) or docked band, and the **realism level** for the next mission: **Beginner** (operator assistance on: automatic line labels, blade-rate and catalogue/emitter candidates; the computer opponent attacks less eagerly, waits for a better firing solution and, as the frigate, classifies and launches its helicopter 1.5 times slower; score 75 %), **Standard** (default: raw data and manual analysis, the calibrated opponent; score 100 %) or **Realistic** (no assistance; the opponent attacks more eagerly, fires on a rougher solution and reacts 30 % faster as the frigate; score 125 %). The level only tunes the computer opponent, never a human on the other side, and a running mission keeps the level it started with (the row then says "from the next mission"). The end panel shows the level with its score factor; saves keep it. Page 2 (`PgDn`/`Tab`): which side the uConsole plays, frigate (default) or hostile submarine; only in the main menu, never saved. A new game asks for it first anyway. Page 2 also holds **anti-aliased chart lines** (off by default; smooths bearing lines, coast and plot at some CPU cost on the uConsole). And **spoken crew reports** (off by default): the crew says torpedo in the water, new contact with bearing, breaking-up noises, torpedo away, hit, action stations, patrol aircraft on station and the mission result aloud, bearings digit by digit. The uConsole speaks through an installed `espeak-ng` (`sudo apt install espeak-ng`) and stays silent without it; Remote Crew browsers have their own switch under Settings (the browser's speech synthesis, in the browser's language). With the uConsole on the submarine the submarine's crew reports instead (see the reference chapter). -- **Multiplayer** (main menu): the lobby where the crew meets before a mission. It starts Remote Crew in crew mode by itself and shows the QR code, address and join code. On the uConsole's own hotspot it shows two numbered steps side by side: **1** the Wi-Fi QR code with the Wi-Fi name and password (join the hotspot), **2** the page QR code with the address and join code (open the crew page). Browsers pair, choose their unit and stations and press **Ready**; they see the mission, what the uConsole plays and every crewmate with their stations and ready tick. On the uConsole, `Up`/`Down` choose a row and `Left`/`Right` change it: the mission, the unit the uConsole plays and the station it shows, or **none, host only**: then the uConsole plays no station, the browsers can take every one and the AI crews the rest. **Start the mission for everyone** starts a five-second countdown that every browser sees, then the mission begins for all at once and the uConsole opens on its chosen station. If a crewmate with a station is not ready yet, the first `Enter` asks again and a second one starts anyway. `Esc` cancels a countdown, otherwise it leads back to the main menu while Remote Crew keeps running. When a mission started from the lobby ends, everyone returns to the lobby with their stations; the ready ticks start again from zero. Every mission started from the lobby has the crew assist on (`Shift+F2`). `F9` opens the full Remote Crew settings from the lobby. Started with `--multiplayer`, the game opens the lobby straight after the start screen. On a Windows PC, `U-Jagd-Windows.exe` starts straight into the game with the same options; there is no separate starter window. -- `F9`: Commander / Remote Crew - lets browser clients on the LAN take stations. The page has one switch, **Multiplayer**: `Enter` turns it on on the first local network address, or, when the uConsole has no network, on its own hotspot (if the hotspot helper is installed; the uConsole installer `install.sh` sets it up when it can and otherwise prints a note). The hotspot keeps its Wi-Fi name and password from one start to the next, so a phone or PC that joined once reconnects by itself. On the hotspot the page shows the two steps together: **1** the Wi-Fi QR code with name and password, **2** the page QR code with the join code. **Crew** lists the players and their stations. **Advanced network settings** shows the network mode (LAN or hotspot), the address and the port for a manual choice; they change only while multiplayer is off. There, while multiplayer is off, **New hotspot password** makes a new hotspot password and keeps the name; every device then has to join again with the new Wi-Fi QR code. A free station is taken at once with all of its rights (including direct fire and live sonar audio where the station has them); a station a crewmate holds is requested, and the holder (who sees the request with Hand over / Keep station buttons) or the host can hand it over. A station always carries its full rights; the host can revoke a station, grant or withdraw the SimLog (roster key `L`) at any time, and can make up to two browsers read-only observers (roster key `O`): they watch any station of either unit without holding it, cannot command, and get the SimLog with a debrief timeline and JSON export. On a Windows PC the program `U-Jagd-Windows.exe` starts the game with Remote Crew already on (crew or solo mode) and shows the browser address, join code and QR code; its Language box switches the starter, the game and the crew pages between English and Deutsch and is saved in the settings. `--remote-crew` does the same from the command line (see the README). The crew pages open in the host's saved language (`F10` options on the uConsole); the English/Deutsch button in the browser's status bar switches that browser alone. The crew page is built for Chrome or Chromium (also Edge) on a desktop PC; another browser shows a hint above the pairing code, and a page that cannot start there says so instead of loading forever. After a host update an open browser page reloads itself once, so it always runs the web client that matches the host. +- **Multiplayer** (main menu): the lobby where the crew meets before a mission. It starts Remote Crew in crew mode by itself and shows the QR code, address and join code. On the uConsole's own hotspot it shows two numbered steps side by side: **1** the Wi-Fi QR code with the Wi-Fi name and password (join the hotspot), **2** the page QR code with the address and join code (open the crew page). Browsers pair, choose their unit and stations and press **Ready**; they see the mission, what the uConsole plays and every crewmate with their stations and ready tick. On the uConsole, `Up`/`Down` choose a row and `Left`/`Right` change it: the mission, the unit the uConsole plays and the station it shows, or **none, host only**: then the uConsole plays no station, the browsers can take every one and the AI crews the rest. **Start the mission for everyone** starts a five-second countdown that every browser sees, then the mission begins for all at once and the uConsole opens on its chosen station. If a crewmate with a station is not ready yet, the first `Enter` asks again and a second one starts anyway. `Esc` cancels a countdown, otherwise it leads back to the main menu while Remote Crew keeps running. When a mission started from the lobby ends, everyone returns to the lobby with their stations; the ready ticks start again from zero. Every mission started from the lobby has the crew assist on (`Shift+F2`). `F9` opens the full Remote Crew settings from the lobby. Started with `--multiplayer`, the game opens the lobby straight after the start screen. +- `F9`: Commander / Remote Crew - lets browser clients on the LAN take stations. The page has one switch, **Multiplayer**: `Enter` turns it on on the first local network address, or, when the uConsole has no network, on its own hotspot (if the hotspot helper is installed; the uConsole installer `install.sh` sets it up when it can and otherwise prints a note). The hotspot keeps its Wi-Fi name and password from one start to the next, so a phone or PC that joined once reconnects by itself. On the hotspot the page shows the two steps together: **1** the Wi-Fi QR code with name and password, **2** the page QR code with the join code. **Crew** lists the players and their stations. **Advanced network settings** shows the network mode (LAN or hotspot), the address and the port for a manual choice; they change only while multiplayer is off. There, while multiplayer is off, **New hotspot password** makes a new hotspot password and keeps the name; every device then has to join again with the new Wi-Fi QR code. A free station is taken at once with all of its rights (including direct fire and live sonar audio where the station has them); a station a crewmate holds is requested, and the holder (who sees the request with Hand over / Keep station buttons) or the host can hand it over. A station always carries its full rights; the host can revoke a station, grant or withdraw the SimLog (roster key `L`) at any time, and can make up to two browsers read-only observers (roster key `O`): they watch any station of either unit without holding it, cannot command, and get the SimLog with a debrief timeline and JSON export. On a Windows PC the program `U-Jagd-Windows.exe` starts straight into the game with the same command-line options; there is no separate starter window, and **Multiplayer** in the main menu (or `--multiplayer`, see the README) opens the lobby with Remote Crew on. The crew pages open in the host's saved language (`F10` options on the uConsole); the English/Deutsch button in the browser's status bar switches that browser alone. The crew page is built for Chrome or Chromium (also Edge) on a desktop PC; another browser shows a hint above the pairing code, and a page that cannot start there says so instead of loading forever. After a host update an open browser page reloads itself once, so it always runs the web client that matches the host. ## Phone lookout and periscope {#qs-phone} diff --git a/docs/install-uconsole.en.md b/docs/install-uconsole.en.md index a6e698dd..75b033e4 100644 --- a/docs/install-uconsole.en.md +++ b/docs/install-uconsole.en.md @@ -7,7 +7,7 @@ repository . The target system is a uConsole with a Debian-based ClockworkPi distribution, particularly a CM5 system. Commands without `sudo` run as a regular user. -## 0. One-command install with automatic updates (recommended) +## 0. One-command install with update notice (recommended) Run a single command in the uConsole terminal as your normal user (not with `sudo`): @@ -25,20 +25,24 @@ The installer - creates the `.venv` virtual environment, - adds the menu entry **Games > U-Jagd**, a desktop shortcut and the command `~/.local/bin/u-jagd`, -- enables a systemd user timer that checks for updates in the background three - minutes after boot and every six hours after that. +- brings the checkout to the newest GitHub release and switches off the + background timer of older versions (up to 1.3.109). -**Automatic updates:** every start from the menu, the desktop or `u-jagd` first -fetches the newest GitHub release (tag `vX.Y.Z`, the same source as the Windows -starter) and then starts the game; while there is no release yet, the uConsole -follows the `main` branch. When dependencies change, `pip install -e .` runs -automatically. Without internet the installed version starts at once: a connection test to -GitHub (at most 2.5 s) then skips the whole update check, and a stalled git -download gives up after 60 s at most. A new version that -does not even start (`main.py --version` fails) is rolled back, and only the -next version is tried again. Local changes in the checkout, a branch other than -`main`, or a running game leave everything untouched. Log: -`~/.u-jagd/updater.log`. Saves under `~/.u-jagd/` are not touched. +**Updates only on request:** since 1.3.110 nothing is installed on its own. +At start the game asks GitHub once in the background for the newest release +(tag `vX.Y.Z`, the same source as the Windows program). When it is newer, the +start screen (top right) and the main menu (left of the entries) show the new version, +its changelog entry in the game language, a warning when saved games of this +version (the autosave too) will not load in the new update (a different save +format), and the button **Update now** (key U or a click). Without internet no +notice appears. Only the button closes the game and runs +`u_jagd_updater.py install`: it waits until the game has closed, fetches the +release, runs `pip install -e .` when dependencies changed and starts the new +version. A new version that does not even start (`main.py --version` fails) is +rolled back, and only the next version is tried again. Local changes in the +checkout or a branch other than `main` leave everything untouched. A stalled +git download gives up after 60 s at most. Log: `~/.u-jagd/updater.log`. Saves +under `~/.u-jagd/` are not touched. **Crash log:** every game start writes a start and an end line to `~/.u-jagd/crash.log`. If the game ends on an error, the traceback is there; @@ -55,18 +59,18 @@ phone; attach the file there. After a crash the main menu offers the entry at the next start. **Start window:** right after the click a small "U-Jagd" window shows the -current step (checking for updates, downloading the update, installing -dependencies, checking the new version, starting U-Jagd). It closes as soon as -the game shows its first frame. A second start while U-Jagd is already starting -or running opens no second game; it shows "U-Jagd is already running." for -three seconds instead (and brings the game window to the front when `wmctrl` is -installed). If the background update is running, the start waits for it and -says so. `U_JAGD_NO_SPLASH=1` turns the window off. +current step (starting U-Jagd; after **Update now** also waiting for U-Jagd to +close, downloading the update, installing dependencies, checking the new +version). It closes as soon as the game shows its first frame. A second start +while U-Jagd is already starting or running opens no second game; it shows +"U-Jagd is already running." for three seconds instead (and brings the game +window to the front when `wmctrl` is installed). `U_JAGD_NO_SPLASH=1` turns +the window off. Game arguments are passed through, for example `u-jagd --windowed`. Start once -without updating: `U_JAGD_NO_UPDATE=1 u-jagd`. Always take the newest `main` -instead of releases: `U_JAGD_UPDATE_CHANNEL=main u-jagd`. To remove the menu -entry, command and timer (game and saves stay): +without looking for updates: `U_JAGD_NO_UPDATE=1 u-jagd`. Take the newest +`main` instead of releases when updating: `U_JAGD_UPDATE_CHANNEL=main`. To +remove the menu entry and command (game and saves stay): ```sh sh ~/games/u-jagd/packaging/uconsole/install.sh --uninstall diff --git a/docs/install-uconsole.md b/docs/install-uconsole.md index bcb9124e..3182521a 100644 --- a/docs/install-uconsole.md +++ b/docs/install-uconsole.md @@ -7,7 +7,7 @@ aus dem Repository . Zielsystem ist eine uConsole mit Debian-basierter ClockworkPi-Distribution, insbesondere ein CM5-System. Befehle ohne `sudo` laufen als normaler Benutzer. -## 0. Schnellinstallation mit automatischem Update (empfohlen) +## 0. Schnellinstallation mit Update-Hinweis (empfohlen) Ein einziger Befehl im Terminal der uConsole, als normaler Benutzer (nicht mit `sudo`): @@ -25,22 +25,26 @@ Der Installer - richtet die virtuelle Umgebung `.venv` ein, - legt den Menüeintrag **Spiele > U-Jagd**, eine Verknüpfung auf dem Desktop und den Befehl `~/.local/bin/u-jagd` an, -- aktiviert einen systemd-Benutzertimer, der drei Minuten nach dem Hochfahren - und danach alle sechs Stunden im Hintergrund nach Updates sucht. +- bringt den Checkout auf das neueste GitHub-Release und schaltet den + Hintergrund-Timer älterer Versionen (bis 1.3.109) ab. -**Automatisches Update:** Jeder Start über Menü, Desktop oder `u-jagd` holt -zuerst das neueste GitHub-Release (Tag `vX.Y.Z`, dieselbe Quelle wie das -Windows-Programm) und startet dann das Spiel; gibt es noch kein Release, folgt -die uConsole dem Zweig `main`. Ändern sich die Abhängigkeiten, wird -`pip install -e .` automatisch ausgeführt. Ohne Internet startet die -installierte Version sofort: Ein Verbindungstest zu GitHub (höchstens 2,5 s) -überspringt dann die ganze Update-Suche, und hängende Git-Abrufe brechen nach -spätestens 60 s ab. Startet eine neue Version nicht einmal +**Updates nur auf Knopfdruck:** Seit 1.3.110 wird nichts mehr von selbst +installiert. Beim Start fragt das Spiel im Hintergrund einmal bei GitHub nach +dem neuesten Release (Tag `vX.Y.Z`, dieselbe Quelle wie das Windows-Programm). +Ist es neuer, zeigen der Startbildschirm (oben rechts) und das Hauptmenü +(links neben den Einträgen) die neue Version, den Eintrag aus dem Änderungsprotokoll in der +Spielsprache, einen Warnhinweis, wenn Spielstände dieser Version (auch die +automatische Sicherung) mit dem neuen Update nicht mehr laden (anderes +Spielstandformat), und den Knopf **Jetzt updaten** (Taste U oder Klick). Ohne +Internet erscheint einfach kein Hinweis. Erst der Knopf beendet das Spiel und +startet `u_jagd_updater.py install`: Es wartet, bis das Spiel geschlossen ist, +holt das Release, führt bei geänderten Abhängigkeiten `pip install -e .` aus +und startet die neue Version. Startet eine neue Version nicht einmal (`main.py --version` schlägt fehl), wird sie zurückgerollt und erst die -nächste Version wieder versucht. Bei eigenen Änderungen im Checkout, auf einem -anderen Zweig als `main` oder während das Spiel läuft wird nichts verändert. -Protokoll: `~/.u-jagd/updater.log`. Speicherstände unter `~/.u-jagd/` bleiben -unberührt. +nächste Version wieder versucht. Bei eigenen Änderungen im Checkout oder auf +einem anderen Zweig als `main` wird nichts verändert. Hängende Git-Abrufe +brechen nach spätestens 60 s ab. Protokoll: `~/.u-jagd/updater.log`. +Speicherstände unter `~/.u-jagd/` bleiben unberührt. **Absturzprotokoll:** Jeder Spielstart schreibt nach `~/.u-jagd/crash.log` eine Start- und eine Endzeile. Endet das Spiel durch einen Fehler, steht dort @@ -58,18 +62,18 @@ GitHub-Issue öffnet; die Datei dort anhängen. Nach einem Absturz bietet das Hauptmenü den Punkt beim nächsten Start an. **Startfenster:** Sofort nach dem Klick erscheint ein kleines Fenster „U-Jagd“ -mit dem aktuellen Schritt (Suche nach Updates, Lade Update, Installiere -Abhängigkeiten, Prüfe neue Version, Starte U-Jagd). Es schließt sich, sobald -das Spiel sein erstes Bild zeigt. Ein zweiter Start, während U-Jagd schon -startet oder läuft, öffnet kein zweites Spiel, sondern zeigt drei Sekunden lang -„U-Jagd läuft bereits.“ (und holt das Spielfenster nach vorn, wenn `wmctrl` -installiert ist). Läuft gerade das Hintergrund-Update, wartet der Start darauf -und zeigt das an. `U_JAGD_NO_SPLASH=1` schaltet das Fenster ab. +mit dem aktuellen Schritt (Starte U-Jagd; nach **Jetzt updaten** auch Warte, +bis U-Jagd beendet ist, Lade Update, Installiere Abhängigkeiten, Prüfe neue +Version). Es schließt sich, sobald das Spiel sein erstes Bild zeigt. Ein +zweiter Start, während U-Jagd schon startet oder läuft, öffnet kein zweites +Spiel, sondern zeigt drei Sekunden lang „U-Jagd läuft bereits.“ (und holt das +Spielfenster nach vorn, wenn `wmctrl` installiert ist). +`U_JAGD_NO_SPLASH=1` schaltet das Fenster ab. Spielparameter werden durchgereicht, etwa `u-jagd --windowed`. Einmal ohne -Update starten: `U_JAGD_NO_UPDATE=1 u-jagd`. Statt Releases immer den neuesten -Stand von `main` holen: `U_JAGD_UPDATE_CHANNEL=main u-jagd`. Menüeintrag, -Befehl und Timer entfernen (Spiel und Speicherstände bleiben): +Update-Suche starten: `U_JAGD_NO_UPDATE=1 u-jagd`. Statt Releases beim +Update den neuesten Stand von `main` holen: `U_JAGD_UPDATE_CHANNEL=main`. +Menüeintrag und Befehl entfernen (Spiel und Speicherstände bleiben): ```sh sh ~/games/u-jagd/packaging/uconsole/install.sh --uninstall diff --git a/docs/manual/handbuch.de.pdf b/docs/manual/handbuch.de.pdf index 5d64d69f..0d482ed9 100644 Binary files a/docs/manual/handbuch.de.pdf and b/docs/manual/handbuch.de.pdf differ diff --git a/docs/manual/manual.de.md b/docs/manual/manual.de.md index 93371b66..788b1685 100644 --- a/docs/manual/manual.de.md +++ b/docs/manual/manual.de.md @@ -132,12 +132,13 @@ Die Statuszeile unten zeigt das neueste Ereignis und die wichtigste Telemetrie; - **Kampagne** (Hauptmenü): sechs verkettete Einsätze in dem im Menü gewählten Seegebiet (Welt `W` und Seed; jeder Einsatz bleibt im selben Sektor). Übertragen werden die übrigen Torpedos (mindestens 2, höchstens 10), noch beschädigte Abteilungen, ein verlorener Hubschrauber und Ihr Ansehen bei der Führung (0-100, Start 50: +15 für einen Sieg, -20 für eine Niederlage, -10 für einen zivilen Verlust, +/-3 je erledigtem oder gescheitertem Auftrag). Nach jedem Einsatz läuft das Schiff in den Hafen: `1` volle Werftliegezeit (4 bis 8 Torpedos je nach Ansehen, alle Reparaturen, ein neuer Hubschrauber, Ansehen -5) oder `2` schnell wieder auslaufen (halbe Nachlieferung, Schäden bleiben an Bord, Ansehen +3); `Enter` läuft aus. Die Kampagne endet, wenn das Schiff verloren geht, das Ansehen unter 10 fällt oder der sechste Einsatz vorbei ist. Sie liegt in `~/.u-jagd/campaign.json`, getrennt von den Spielständen: ein während eines Kampagneneinsatzes gespeicherter Platz lädt als normale Mission; damit er zählt, wird der Einsatz aus dem Kampagnenbildschirm erneut gefahren. `N` startet eine neue Kampagne (bei laufender Kampagne zweimal). - **U-Boot-Kampagne** (Hauptmenü, Kampagne, `Tab`): fünf verkettete U-Boot-Missionen im selben Seegebiet, gespielt auf der U-Boot-Seite: Aufklärung, Durchbruch, Geleitzugangriff, Durchbruch, Geleitzugangriff. Übertragen werden die Torpedos des U-Boots, sein Rumpfschaden (höchstens 60 %) und Ihr Ansehen bei der U-Boot-Führung (0-100, Start 50: +15 für eine gewonnene, -20 für eine verlorene Mission). Nach jeder Mission läuft das U-Boot in seinen Stützpunkt: `1` volle Überholung (volle Torpedobeladung, Rumpf repariert, Ansehen -5) oder `2` schnell wieder auslaufen (die Hälfte von 4 bis 8 Torpedos je nach Ansehen kommt dazu, der Rumpfschaden bleibt, Ansehen +3); `Enter` läuft aus. Sie endet, wenn das U-Boot verloren geht, das Ansehen unter 10 fällt oder die fünfte Mission vorbei ist, und liegt in `~/.u-jagd/boat_campaign.json` neben der Kampagne der Fregatte. - **Einsatzbuch** (Hauptmenü): jede beendete Mission (nie eine Lektion) der Seite, die die uConsole gespielt hat, mit Datum, Mission, Realismusstufe, Ergebnis, Punkten und Minuten; der Bestwert je Mission und fünf Auszeichnungen je Seite: erster Sieg, ein Schuss ein Treffer (der Gegner mit einer einzigen Waffe versenkt), ohne Kratzer (kein Schaden), nie beschossen und Realist (ein Sieg auf der Stufe Realistisch). Die Fregatte trägt ihre Missionspunkte ein; das U-Boot zählt sein Ergebnis (Fregatte versenkt 1500, Geleitzug versenkt 1200, Durchbruch oder Meldung 1000, Entkommen 800, Überleben 600) plus bis zu 500 für ein unbeschädigtes Boot und 100 je übrigem Torpedo, mal dem Faktor der Stufe. `Links`/`Rechts` wechseln Fregatte und U-Boot, `Esc` zurück. Das Endpanel nennt die Punkte, einen neuen Bestwert und neue Auszeichnungen. Das Einsatzbuch ist `~/.u-jagd/logbook.json` (die neuesten 200 Missionen), nie Teil eines Spielstands. -- **Fehler melden** (Hauptmenü): schreibt `~/.u-jagd/bug-report.txt` (Version, Plattform und die neuesten Zeilen aus `~/.u-jagd/crash.log`, Ihr Benutzername aus Pfaden entfernt) und zeigt einen QR-Code, der am Handy ein neues GitHub-Issue mit Version und Plattform öffnet; dort die Datei anhängen. `Enter` öffnet das Issue mit Log in einem Browser, falls das Gerät einen hat, `Esc` geht zurück. Nach einem abgestürzten Start wählt das Hauptmenü diesen Eintrag vor und weist darauf hin. Gesendet wird erst, wenn Sie das Issue mit Ihrem eigenen GitHub-Konto abschicken. Der Windows-Starter („Fehler melden“) und das Einstellungsmenü im Browser haben denselben Link. +- **Fehler melden** (Hauptmenü): schreibt `~/.u-jagd/bug-report.txt` (Version, Plattform und die neuesten Zeilen aus `~/.u-jagd/crash.log`, Ihr Benutzername aus Pfaden entfernt) und zeigt einen QR-Code, der am Handy ein neues GitHub-Issue mit Version und Plattform öffnet; dort die Datei anhängen. `Enter` öffnet das Issue mit Log in einem Browser, falls das Gerät einen hat, `Esc` geht zurück. Nach einem abgestürzten Start wählt das Hauptmenü diesen Eintrag vor und weist darauf hin. Gesendet wird erst, wenn Sie das Issue mit Ihrem eigenen GitHub-Konto abschicken. Das Einstellungsmenü im Browser hat denselben Link. +- **Update-Hinweis** (Startbildschirm und Hauptmenü): Neue Versionen werden nie von selbst installiert. Beim Start fragt das Spiel einmal bei GitHub, ob es ein neueres Release gibt; dann zeigen der Startbildschirm (oben rechts) und das Hauptmenü (links neben den Einträgen) dessen Version, den Eintrag aus dem Änderungsprotokoll in der Spielsprache und eine Warnung, wenn Spielstände dieser Version (auch die automatische Sicherung) mit dem neuen Release nicht mehr laden, weil sich das Spielstandformat geändert hat. `U` oder ein Klick auf **Jetzt updaten** installiert es: Auf der uConsole schließt das Spiel, das kleine Fenster des Starters zeigt Download und Prüfung, und die neue Version startet; das Windows-Programm lädt die neue Datei im Hintergrund (Fortschritt auf dem Knopf), prüft Größe und SHA-256-Prüfsumme, schließt sich, ersetzt sich selbst und startet die neue Version; jede andere Installation öffnet die Release-Seite. Ohne Netz oder mit `U_JAGD_NO_UPDATE=1` erscheint kein Hinweis. - `S` / `L`: Speichern / Laden (Plätze 1-5). Spielstände sind exakt und deterministisch: ein geladenes Spiel läuft identisch weiter. - **Autosave:** Eine laufende Mission wird alle 5 Minuten und beim Beenden oder Verlassen ins Hauptmenü nach `~/.u-jagd/autosave.json` gespeichert, neben den fünf Plätzen. Das Hauptmenü beginnt dann mit **Einsatz fortsetzen**, das sie exakt weiterführt; nach einem Absturz ist es der letzte 5-Minuten-Stand. Eine beendete Mission (Sieg, Niederlage oder Schiff gesunken) und jede neue Mission löschen den Autosave. Der Web-Host (`--web-host`) speichert nicht automatisch. - `F10`: Optionen - Sprache, Vollbild, Audio, große Schrift, Tooltips, Bildrate (30 oder 60 FPS; 30 spart Rechenleistung auf der uConsole und ist voreingestellt), Ereignislog/Telemetrie als Statuszeile (Standard, mehr Platz für die Station) oder feste Leiste, und die **Realismusstufe** der nächsten Mission: **Einsteiger** (Bedienerassistenz an: automatische Linienbeschriftung, Blattfrequenz- und Katalog-/Senderkandidaten; der Computergegner greift zögerlicher an, wartet auf eine bessere Schusslösung und klassifiziert und startet als Fregatte seinen Hubschrauber 1,5-mal langsamer; Punkte 75 %), **Standard** (voreingestellt: Rohdaten und manuelle Analyse, der kalibrierte Gegner; Punkte 100 %) oder **Realistisch** (keine Assistenz; der Gegner greift entschlossener an, schießt auf eine gröbere Lösung und reagiert als Fregatte 30 % schneller; Punkte 125 %). Die Stufe stimmt nur den Computergegner ab, nie einen Menschen auf der anderen Seite, und eine laufende Mission behält die Stufe, mit der sie begann (die Zeile sagt dann "ab der nächsten Mission"). Das Endpanel zeigt die Stufe mit ihrem Punktefaktor; Spielstände behalten sie. Seite 2 (`Bild ab`/`Tab`): welche Seite der uConsole spielt, Fregatte (Standard) oder feindliches U-Boot; nur im Hauptmenü, nie gespeichert. Ein neues Spiel fragt ohnehin zuerst danach. Auf Seite 2 liegen auch die **geglätteten Kartenlinien** (standardmäßig aus; glättet Peilstriche, Küste und Plot, kostet auf der uConsole etwas Rechenzeit). Dazu die **gesprochenen Crew-Meldungen** (standardmäßig aus): die Crew meldet Torpedo im Wasser, neuen Kontakt mit Peilung, Sinkgeräusche, Torpedo los, Treffer, Gefechtsstationen, Seefernaufklärer auf Station und das Missionsende laut, Peilungen Ziffer für Ziffer. Die uConsole spricht über ein installiertes `espeak-ng` (`sudo apt install espeak-ng`) und bleibt ohne es stumm; Remote-Crew-Browser haben einen eigenen Schalter unter Einstellungen (Sprachausgabe des Browsers, in dessen Sprache). Spielt die uConsole das U-Boot, meldet stattdessen dessen Crew (siehe Kapitel Referenz). -- **Mehrspieler** (Hauptmenü): die Lobby, in der sich die Besatzung vor einem Einsatz trifft. Sie startet Remote Crew selbst im Crew-Modus und zeigt QR-Code, Adresse und Beitrittscode. Auf dem eigenen Hotspot des uConsole zeigt sie zwei nummerierte Schritte nebeneinander: **1** den WLAN-QR-Code mit WLAN-Name und Passwort (dem Hotspot beitreten), **2** den Seiten-QR-Code mit Adresse und Beitrittscode (die Crew-Seite öffnen). Die Browser koppeln, wählen Einheit und Stationen und drücken **Bereit**; sie sehen die Mission, was der uConsole spielt, und jedes Crewmitglied mit Stationen und Bereit-Häkchen. Am uConsole wählen `Auf`/`Ab` eine Zeile und `Links`/`Rechts` ändern sie: die Mission, die Einheit des uConsole und die Station, die er zeigt, oder **keine, nur Gastgeber**: Dann spielt der uConsole keine Station, die Browser können jede übernehmen, und die KI besetzt den Rest. **Mission für alle starten** startet einen Countdown von fünf Sekunden, den jeder Browser sieht; dann beginnt die Mission für alle gleichzeitig, und der uConsole öffnet seine gewählte Station. Ist ein Crewmitglied mit Station noch nicht bereit, fragt das erste `Enter` nach, ein zweites startet trotzdem. `Esc` bricht einen Countdown ab, sonst geht es zurück ins Hauptmenü, und Remote Crew läuft weiter. Endet eine Mission, die aus der Lobby gestartet wurde, kehren alle mit ihren Stationen in die Lobby zurück; die Bereit-Häkchen beginnen wieder von vorn. Jede Mission aus der Lobby hat die Crew-Hilfe an (`Shift+F2`). `F9` öffnet aus der Lobby die vollständigen Remote-Crew-Einstellungen. Mit `--multiplayer` gestartet, öffnet das Spiel die Lobby direkt nach dem Startbild. Auf einem Windows-PC startet `U-Jagd-Windows.exe` mit denselben Optionen direkt ins Spiel; ein eigenes Starterfenster gibt es nicht. -- `F9`: Commander / Remote Crew - Browser im LAN können Stationen übernehmen. Die Seite hat einen Schalter, **Mehrspieler**: `Enter` schaltet ihn auf der ersten lokalen Netzwerkadresse ein oder, wenn die uConsole kein Netz hat, auf ihrem eigenen Hotspot (sofern der Hotspot-Helfer installiert ist; der uConsole-Installer `install.sh` richtet ihn ein, wenn er kann, und gibt sonst einen Hinweis aus). Der Hotspot behält WLAN-Name und Passwort von einem Start zum nächsten, sodass ein Handy oder PC, das einmal beigetreten ist, sich von selbst wieder verbindet. Auf dem Hotspot zeigt die Seite beide Schritte zusammen: **1** den WLAN-QR-Code mit Name und Passwort, **2** den Seiten-QR-Code mit dem Beitrittscode. **Crew** zeigt die Spieler und ihre Stationen. **Erweiterte Netzwerkeinstellungen** blendet Netzwerkmodus (LAN oder Hotspot), Adresse und Port zur Handwahl ein; sie ändern sich nur bei ausgeschaltetem Mehrspieler. Dort erzeugt, solange Mehrspieler aus ist, **Neues Hotspot-Passwort** ein neues Hotspot-Passwort und behält den Namen; jedes Gerät muss dann mit dem neuen WLAN-QR-Code neu beitreten. Eine freie Station wird sofort mit allen ihren Rechten übernommen (auch Direktfeuer und Sonar-Liveaudio, wo die Station sie hat); eine Station, die ein Crewmitglied hält, wird angefragt, und der Inhaber (er sieht die Anfrage mit den Knöpfen Übergeben / Station behalten) oder der Host kann sie übergeben. Eine Station hat immer alle ihre Rechte; der Host kann jederzeit eine Station entziehen, das SimLog geben oder nehmen (Roster-Taste `L`) und bis zu zwei Browser zu reinen Beobachtern machen (Roster-Taste `O`): sie sehen jede Station beider Einheiten, ohne sie zu halten, können nichts befehlen und erhalten das SimLog mit Zeitstrahl zur Nachbesprechung und JSON-Export. Auf einem Windows-PC startet das Programm `U-Jagd-Windows.exe` das Spiel mit bereits eingeschalteter Remote Crew (Besatzungs- oder Solomodus) und zeigt Browser-Adresse, Beitrittscode und QR-Code; sein Feld Sprache stellt Starter, Spiel und Crew-Seiten zwischen English und Deutsch um und wird in den Einstellungen gespeichert. `--remote-crew` macht dasselbe über die Kommandozeile (siehe README). Die Crew-Seiten öffnen in der gespeicherten Sprache des Hosts (`F10`-Optionen auf der uConsole); der Knopf English/Deutsch in der Statusleiste des Browsers stellt nur diesen Browser um. Die Crew-Seite ist für Chrome oder Chromium (auch Edge) auf einem Desktop-PC gebaut; ein anderer Browser zeigt über dem Kopplungscode einen Hinweis, und eine Seite, die dort nicht starten kann, sagt das, statt endlos zu laden. Nach einem Update des Hosts lädt sich eine offene Browserseite einmal selbst neu und läuft so immer mit dem passenden Web-Client. +- **Mehrspieler** (Hauptmenü): die Lobby, in der sich die Besatzung vor einem Einsatz trifft. Sie startet Remote Crew selbst im Crew-Modus und zeigt QR-Code, Adresse und Beitrittscode. Auf dem eigenen Hotspot des uConsole zeigt sie zwei nummerierte Schritte nebeneinander: **1** den WLAN-QR-Code mit WLAN-Name und Passwort (dem Hotspot beitreten), **2** den Seiten-QR-Code mit Adresse und Beitrittscode (die Crew-Seite öffnen). Die Browser koppeln, wählen Einheit und Stationen und drücken **Bereit**; sie sehen die Mission, was der uConsole spielt, und jedes Crewmitglied mit Stationen und Bereit-Häkchen. Am uConsole wählen `Auf`/`Ab` eine Zeile und `Links`/`Rechts` ändern sie: die Mission, die Einheit des uConsole und die Station, die er zeigt, oder **keine, nur Gastgeber**: Dann spielt der uConsole keine Station, die Browser können jede übernehmen, und die KI besetzt den Rest. **Mission für alle starten** startet einen Countdown von fünf Sekunden, den jeder Browser sieht; dann beginnt die Mission für alle gleichzeitig, und der uConsole öffnet seine gewählte Station. Ist ein Crewmitglied mit Station noch nicht bereit, fragt das erste `Enter` nach, ein zweites startet trotzdem. `Esc` bricht einen Countdown ab, sonst geht es zurück ins Hauptmenü, und Remote Crew läuft weiter. Endet eine Mission, die aus der Lobby gestartet wurde, kehren alle mit ihren Stationen in die Lobby zurück; die Bereit-Häkchen beginnen wieder von vorn. Jede Mission aus der Lobby hat die Crew-Hilfe an (`Shift+F2`). `F9` öffnet aus der Lobby die vollständigen Remote-Crew-Einstellungen. Mit `--multiplayer` gestartet, öffnet das Spiel die Lobby direkt nach dem Startbild. +- `F9`: Commander / Remote Crew - Browser im LAN können Stationen übernehmen. Die Seite hat einen Schalter, **Mehrspieler**: `Enter` schaltet ihn auf der ersten lokalen Netzwerkadresse ein oder, wenn die uConsole kein Netz hat, auf ihrem eigenen Hotspot (sofern der Hotspot-Helfer installiert ist; der uConsole-Installer `install.sh` richtet ihn ein, wenn er kann, und gibt sonst einen Hinweis aus). Der Hotspot behält WLAN-Name und Passwort von einem Start zum nächsten, sodass ein Handy oder PC, das einmal beigetreten ist, sich von selbst wieder verbindet. Auf dem Hotspot zeigt die Seite beide Schritte zusammen: **1** den WLAN-QR-Code mit Name und Passwort, **2** den Seiten-QR-Code mit dem Beitrittscode. **Crew** zeigt die Spieler und ihre Stationen. **Erweiterte Netzwerkeinstellungen** blendet Netzwerkmodus (LAN oder Hotspot), Adresse und Port zur Handwahl ein; sie ändern sich nur bei ausgeschaltetem Mehrspieler. Dort erzeugt, solange Mehrspieler aus ist, **Neues Hotspot-Passwort** ein neues Hotspot-Passwort und behält den Namen; jedes Gerät muss dann mit dem neuen WLAN-QR-Code neu beitreten. Eine freie Station wird sofort mit allen ihren Rechten übernommen (auch Direktfeuer und Sonar-Liveaudio, wo die Station sie hat); eine Station, die ein Crewmitglied hält, wird angefragt, und der Inhaber (er sieht die Anfrage mit den Knöpfen Übergeben / Station behalten) oder der Host kann sie übergeben. Eine Station hat immer alle ihre Rechte; der Host kann jederzeit eine Station entziehen, das SimLog geben oder nehmen (Roster-Taste `L`) und bis zu zwei Browser zu reinen Beobachtern machen (Roster-Taste `O`): sie sehen jede Station beider Einheiten, ohne sie zu halten, können nichts befehlen und erhalten das SimLog mit Zeitstrahl zur Nachbesprechung und JSON-Export. Auf einem Windows-PC startet das Programm `U-Jagd-Windows.exe` mit denselben Kommandozeilenoptionen direkt ins Spiel; ein eigenes Starterfenster gibt es nicht, und **Mehrspieler** im Hauptmenü (oder `--multiplayer`, siehe README) öffnet die Lobby mit eingeschalteter Remote Crew. Die Crew-Seiten öffnen in der gespeicherten Sprache des Hosts (`F10`-Optionen auf der uConsole); der Knopf English/Deutsch in der Statusleiste des Browsers stellt nur diesen Browser um. Die Crew-Seite ist für Chrome oder Chromium (auch Edge) auf einem Desktop-PC gebaut; ein anderer Browser zeigt über dem Kopplungscode einen Hinweis, und eine Seite, die dort nicht starten kann, sagt das, statt endlos zu laden. Nach einem Update des Hosts lädt sich eine offene Browserseite einmal selbst neu und läuft so immer mit dem passenden Web-Client. ### Handy-Ausguck und Sehrohr diff --git a/docs/manual/manual.en.md b/docs/manual/manual.en.md index d10bd609..3dbeeb26 100644 --- a/docs/manual/manual.en.md +++ b/docs/manual/manual.en.md @@ -132,12 +132,13 @@ The bottom status ticker shows the newest event and key telemetry; `F11` opens t - **Campaign** (main menu): six linked missions in the sea area chosen in the menu (world `W` and seed; every mission keeps the same sector). Carried over are the torpedoes left (at least 2, at most 10), compartments still damaged, a lost helicopter and your standing with HQ (0-100, start 50: +15 for a win, -20 for a loss, -10 for a civilian loss, +/-3 per task done or failed). After each mission the ship calls at port: `1` full refit (4 to 8 torpedoes by standing, all repairs, a new helicopter, standing -5) or `2` quick turnaround (half that restock, damage stays aboard, standing +3); `Enter` sails. The campaign ends when the ship is lost, standing falls below 10, or the sixth mission is done. It is kept in `~/.u-jagd/campaign.json`, apart from the save slots: a slot saved during a campaign mission loads as a plain mission; to count, the mission is sailed again from the campaign screen. `N` starts a new campaign (twice while one is running). - **Submarine campaign** (main menu, Campaign, `Tab`): five linked submarine missions in the same sea area, played on the submarine side: reconnaissance, breakthrough, convoy attack, breakthrough, convoy attack. Carried over are the submarine's torpedoes, its hull damage (at most 60 %) and your standing with submarine command (0-100, start 50: +15 for a mission won, -20 for one lost). After each mission the submarine calls at its base: `1` full refit (full torpedo load, hull repaired, standing -5) or `2` quick turnaround (half of 4 to 8 torpedoes by standing added, the hull damage stays, standing +3); `Enter` puts to sea. It ends when the submarine is lost, standing falls below 10, or the fifth mission is done, and is kept in `~/.u-jagd/boat_campaign.json` beside the frigate's campaign. - **Logbook** (main menu): every finished mission (never a lesson) for the side the uConsole played, with date, mission, realism level, result, score and minutes; the best score per mission and five awards per side: first victory, one shot one kill (the enemy sunk with a single weapon), unscathed (no damage), never fired at, and realist (a victory on the Realistic level). The frigate files its mission score; the submarine counts its outcome (sinking the frigate 1500, sinking the convoy 1200, breakthrough or report 1000, escape 800, surviving 600) plus up to 500 for an undamaged boat and 100 per torpedo left, times the level's factor. `Left`/`Right` switch frigate and submarine, `Esc` back. The end panel names the score, a new best and new awards. The logbook is `~/.u-jagd/logbook.json` (the newest 200 missions), never part of a save. -- **Report a bug** (main menu): writes `~/.u-jagd/bug-report.txt` (version, platform and the newest lines of `~/.u-jagd/crash.log`, with your user name removed from paths) and shows a QR code that opens a new GitHub issue on a phone with version and platform filled in; attach the file there. `Enter` opens the issue with the log in a browser if the device has one, `Esc` goes back. After a crashed start the main menu selects this entry and says so. Nothing is sent until you submit the issue with your own GitHub account. The Windows starter ("Report a bug") and the browser settings menu have the same link. +- **Report a bug** (main menu): writes `~/.u-jagd/bug-report.txt` (version, platform and the newest lines of `~/.u-jagd/crash.log`, with your user name removed from paths) and shows a QR code that opens a new GitHub issue on a phone with version and platform filled in; attach the file there. `Enter` opens the issue with the log in a browser if the device has one, `Esc` goes back. After a crashed start the main menu selects this entry and says so. Nothing is sent until you submit the issue with your own GitHub account. The browser settings menu has the same link. +- **Update notice** (start screen and main menu): new releases are never installed on their own. At launch the game asks GitHub once whether a newer release exists; if so, the start screen (top right) and the main menu (left of the entries) show its version, its changelog entry in the game language and, when saved games of this version (the autosave too) will not load in the new release because the save format changed, a warning. `U` or a click on **Update now** installs it: on the uConsole the game closes, the launcher's small window shows the download and check and the new version starts; the Windows program downloads it in the background (progress on the button), checks its size and SHA-256 digest, closes, replaces itself and starts the new version; any other installation opens the release page. Offline, or with `U_JAGD_NO_UPDATE=1`, no notice appears. - `S` / `L`: save / load (slots 1-5). Saves are exact and deterministic: a loaded game continues identically. - **Autosave:** a running mission is saved every 5 minutes and when you quit or leave it for the main menu, to `~/.u-jagd/autosave.json` beside the five slots. The main menu then starts with **Continue mission**, which resumes it exactly; after a crash it holds the last 5-minute save. A mission that ends (won, lost or ship sunk) and any new mission delete the autosave. The web host (`--web-host`) does not autosave. - `F10`: options - language, fullscreen, audio, large text, tooltips, frame rate (30 or 60 FPS; 30 saves CPU on the uConsole and is the default), event log / telemetry as status ticker (default, more room for the station) or docked band, and the **realism level** for the next mission: **Beginner** (operator assistance on: automatic line labels, blade-rate and catalogue/emitter candidates; the computer opponent attacks less eagerly, waits for a better firing solution and, as the frigate, classifies and launches its helicopter 1.5 times slower; score 75 %), **Standard** (default: raw data and manual analysis, the calibrated opponent; score 100 %) or **Realistic** (no assistance; the opponent attacks more eagerly, fires on a rougher solution and reacts 30 % faster as the frigate; score 125 %). The level only tunes the computer opponent, never a human on the other side, and a running mission keeps the level it started with (the row then says "from the next mission"). The end panel shows the level with its score factor; saves keep it. Page 2 (`PgDn`/`Tab`): which side the uConsole plays, frigate (default) or hostile submarine; only in the main menu, never saved. A new game asks for it first anyway. Page 2 also holds **anti-aliased chart lines** (off by default; smooths bearing lines, coast and plot at some CPU cost on the uConsole). And **spoken crew reports** (off by default): the crew says torpedo in the water, new contact with bearing, breaking-up noises, torpedo away, hit, action stations, patrol aircraft on station and the mission result aloud, bearings digit by digit. The uConsole speaks through an installed `espeak-ng` (`sudo apt install espeak-ng`) and stays silent without it; Remote Crew browsers have their own switch under Settings (the browser's speech synthesis, in the browser's language). With the uConsole on the submarine the submarine's crew reports instead (see the reference chapter). -- **Multiplayer** (main menu): the lobby where the crew meets before a mission. It starts Remote Crew in crew mode by itself and shows the QR code, address and join code. On the uConsole's own hotspot it shows two numbered steps side by side: **1** the Wi-Fi QR code with the Wi-Fi name and password (join the hotspot), **2** the page QR code with the address and join code (open the crew page). Browsers pair, choose their unit and stations and press **Ready**; they see the mission, what the uConsole plays and every crewmate with their stations and ready tick. On the uConsole, `Up`/`Down` choose a row and `Left`/`Right` change it: the mission, the unit the uConsole plays and the station it shows, or **none, host only**: then the uConsole plays no station, the browsers can take every one and the AI crews the rest. **Start the mission for everyone** starts a five-second countdown that every browser sees, then the mission begins for all at once and the uConsole opens on its chosen station. If a crewmate with a station is not ready yet, the first `Enter` asks again and a second one starts anyway. `Esc` cancels a countdown, otherwise it leads back to the main menu while Remote Crew keeps running. When a mission started from the lobby ends, everyone returns to the lobby with their stations; the ready ticks start again from zero. Every mission started from the lobby has the crew assist on (`Shift+F2`). `F9` opens the full Remote Crew settings from the lobby. Started with `--multiplayer`, the game opens the lobby straight after the start screen. On a Windows PC, `U-Jagd-Windows.exe` starts straight into the game with the same options; there is no separate starter window. -- `F9`: Commander / Remote Crew - lets browser clients on the LAN take stations. The page has one switch, **Multiplayer**: `Enter` turns it on on the first local network address, or, when the uConsole has no network, on its own hotspot (if the hotspot helper is installed; the uConsole installer `install.sh` sets it up when it can and otherwise prints a note). The hotspot keeps its Wi-Fi name and password from one start to the next, so a phone or PC that joined once reconnects by itself. On the hotspot the page shows the two steps together: **1** the Wi-Fi QR code with name and password, **2** the page QR code with the join code. **Crew** lists the players and their stations. **Advanced network settings** shows the network mode (LAN or hotspot), the address and the port for a manual choice; they change only while multiplayer is off. There, while multiplayer is off, **New hotspot password** makes a new hotspot password and keeps the name; every device then has to join again with the new Wi-Fi QR code. A free station is taken at once with all of its rights (including direct fire and live sonar audio where the station has them); a station a crewmate holds is requested, and the holder (who sees the request with Hand over / Keep station buttons) or the host can hand it over. A station always carries its full rights; the host can revoke a station, grant or withdraw the SimLog (roster key `L`) at any time, and can make up to two browsers read-only observers (roster key `O`): they watch any station of either unit without holding it, cannot command, and get the SimLog with a debrief timeline and JSON export. On a Windows PC the program `U-Jagd-Windows.exe` starts the game with Remote Crew already on (crew or solo mode) and shows the browser address, join code and QR code; its Language box switches the starter, the game and the crew pages between English and Deutsch and is saved in the settings. `--remote-crew` does the same from the command line (see the README). The crew pages open in the host's saved language (`F10` options on the uConsole); the English/Deutsch button in the browser's status bar switches that browser alone. The crew page is built for Chrome or Chromium (also Edge) on a desktop PC; another browser shows a hint above the pairing code, and a page that cannot start there says so instead of loading forever. After a host update an open browser page reloads itself once, so it always runs the web client that matches the host. +- **Multiplayer** (main menu): the lobby where the crew meets before a mission. It starts Remote Crew in crew mode by itself and shows the QR code, address and join code. On the uConsole's own hotspot it shows two numbered steps side by side: **1** the Wi-Fi QR code with the Wi-Fi name and password (join the hotspot), **2** the page QR code with the address and join code (open the crew page). Browsers pair, choose their unit and stations and press **Ready**; they see the mission, what the uConsole plays and every crewmate with their stations and ready tick. On the uConsole, `Up`/`Down` choose a row and `Left`/`Right` change it: the mission, the unit the uConsole plays and the station it shows, or **none, host only**: then the uConsole plays no station, the browsers can take every one and the AI crews the rest. **Start the mission for everyone** starts a five-second countdown that every browser sees, then the mission begins for all at once and the uConsole opens on its chosen station. If a crewmate with a station is not ready yet, the first `Enter` asks again and a second one starts anyway. `Esc` cancels a countdown, otherwise it leads back to the main menu while Remote Crew keeps running. When a mission started from the lobby ends, everyone returns to the lobby with their stations; the ready ticks start again from zero. Every mission started from the lobby has the crew assist on (`Shift+F2`). `F9` opens the full Remote Crew settings from the lobby. Started with `--multiplayer`, the game opens the lobby straight after the start screen. +- `F9`: Commander / Remote Crew - lets browser clients on the LAN take stations. The page has one switch, **Multiplayer**: `Enter` turns it on on the first local network address, or, when the uConsole has no network, on its own hotspot (if the hotspot helper is installed; the uConsole installer `install.sh` sets it up when it can and otherwise prints a note). The hotspot keeps its Wi-Fi name and password from one start to the next, so a phone or PC that joined once reconnects by itself. On the hotspot the page shows the two steps together: **1** the Wi-Fi QR code with name and password, **2** the page QR code with the join code. **Crew** lists the players and their stations. **Advanced network settings** shows the network mode (LAN or hotspot), the address and the port for a manual choice; they change only while multiplayer is off. There, while multiplayer is off, **New hotspot password** makes a new hotspot password and keeps the name; every device then has to join again with the new Wi-Fi QR code. A free station is taken at once with all of its rights (including direct fire and live sonar audio where the station has them); a station a crewmate holds is requested, and the holder (who sees the request with Hand over / Keep station buttons) or the host can hand it over. A station always carries its full rights; the host can revoke a station, grant or withdraw the SimLog (roster key `L`) at any time, and can make up to two browsers read-only observers (roster key `O`): they watch any station of either unit without holding it, cannot command, and get the SimLog with a debrief timeline and JSON export. On a Windows PC the program `U-Jagd-Windows.exe` starts straight into the game with the same command-line options; there is no separate starter window, and **Multiplayer** in the main menu (or `--multiplayer`, see the README) opens the lobby with Remote Crew on. The crew pages open in the host's saved language (`F10` options on the uConsole); the English/Deutsch button in the browser's status bar switches that browser alone. The crew page is built for Chrome or Chromium (also Edge) on a desktop PC; another browser shows a hint above the pairing code, and a page that cannot start there says so instead of loading forever. After a host update an open browser page reloads itself once, so it always runs the web client that matches the host. ### Phone lookout and periscope diff --git a/docs/manual/manual.en.pdf b/docs/manual/manual.en.pdf index 44ef6c6d..e6342ba7 100644 Binary files a/docs/manual/manual.en.pdf and b/docs/manual/manual.en.pdf differ diff --git a/docs/resume.md b/docs/resume.md index baaeded9..ea3eb323 100644 --- a/docs/resume.md +++ b/docs/resume.md @@ -1652,4 +1652,4 @@ Notizen Phase 1: - 1.3.78: 3D-Modelle der Einheiten (`src/ui/unit_models.py`): 10 Klassen; Kriegsschiff/Handelsschiff/Kleinfahrzeug/U-Boot/Luftfahrzeug aus den Ausguck-Silhouetten (Klassenzuordnung über `lookout_id.surface_classes` wie `stations/bridge.py`), Torpedo/Täuschkörper/Tiere als Rotationskörper mit Platten; Einheitenanalysator (erste Seite, Reiter `3D`) und Einheiteneditor (Browser und Bearbeiten), uConsole mit 12 Hz gecachtem Drehteller (`ModelView`), Browser über `views/model-view.js` mit den von `tools/gen_web_schema.py` erzeugten Netzen (`views/unit-models.js`). Okulare: Lagewinkel `lookout_id.angle_on_bow` (10°-Schritte, nur nach Erkennen, transient `_lookout_aspect`/`orders._aspect`, nie gespeichert) als `aob_deg` in den Zeilen/Projektionen; `unit_models.draw_in_scene` bzw. `drawInScene` ab 16 px mit Sprite-Cache, an der Wasserlinie abgeschnitten. - 1.3.80: Varianten je Typ (`src/ui/unit_variants.py`, Daten `data/unit_models/variants.json` aus Wikipedia/typisch): 111 Katalogtypen parametrisch (Rumpf, Aufbauten, Masten, Schornsteine, Geschütze, VLS, Flugdeck, Kräne, Ladung; U-Boot Turm/Ruder/Buckel; Flugzeug Flügel/Leitwerk). `mesh_for(key)` fällt auf die Klasse zurück; Okulare zeigen den gesehenen echten Typ (`unit_variants.entity_model`, transient in `_lookout_aspect`/`orders._model`, Feld `model` der Umrisse); Browser lädt `views/unit-variants-{naval,civil,subs}.js` bei Bedarf. - 1.3.86: 3D-Modelle massiv: `src/ui/model_bsp.py` (Browser `views/model-bsp.js`, gleiche Regeln) baut je Modell einmal eine BSP und liefert die exakte Zeichenreihenfolge statt Sortierung nach Flächenmitte; Rumpfbeplankung einseitig, nach außen gewunden, zu Linien kollabierte Enden entfallen; Rümpfe 20 Spanten, U-Boote 23x14, Flugzeugrümpfe 23x12; Aufbauten in Decksstufen (`unit_variants._house`, `_TIERS`), Türme als Stromlinienkörper (`_fin`). `tests/test_model_bsp.py` vergleicht mit einem Tiefenpuffer. -- Startoptionen und Windows-Programm ohne Starterfenster: `--multiplayer` öffnet nach dem Startbild die Lobby (`Game.open_lobby()`, wie der Hauptmenü-Eintrag); `--remote-crew` ist ein verborgener Alias, `--solo-crew` bleibt als verborgene Expertenoption (einziger Weg in den Solomodus), `--play-sub` und `--status-file` (samt `CommanderConsole.publish_status`) sind entfernt. `src/launcher/app.py` (Tk-Starter), seine Tests und alle `launcher.*`-Katalogschlüssel sind gelöscht; `entry.main()` startet `main.main(argv)` direkt (führendes `--game` wird ignoriert), löscht vorher ein liegengebliebenes `.new`, gibt den Exit-Code durch und startet bei `update.UPDATE_EXIT_CODE` (falls vorhanden, per `getattr`) mit vorhandenem `.new` `update.launch_install`. `--self-test`/`--update-self-test` bleiben (ohne GUI-Teil); die PyInstaller-Spec schließt `tkinter` aus. +- Startoptionen und Windows-Programm ohne Starterfenster: `--multiplayer` öffnet nach dem Startbild die Lobby (`Game.open_lobby()`, wie der Hauptmenü-Eintrag); `--remote-crew` ist ein verborgener Alias, `--solo-crew` bleibt als verborgene Expertenoption (einziger Weg in den Solomodus), `--play-sub` und `--status-file` (samt `CommanderConsole.publish_status`) sind entfernt. `src/launcher/app.py` (Tk-Starter), seine Tests und alle `launcher.*`-Katalogschlüssel sind gelöscht; `entry.main()` startet `main.main(argv)` direkt (führendes `--game` wird ignoriert; ein liegengebliebenes `.new` löscht die Update-Prüfung des Spiels), gibt den Exit-Code durch und übernimmt bei `update.UPDATE_EXIT_CODE` die Aufgabe des alten Starters: `.new` holen, falls noch nicht da, dann `update.launch_install` (Rückgabe 0, bei Fehler bleibt 75). Normal installiert das eingefrorene Spiel selbst (Modus `windows`). `--self-test`/`--update-self-test` bleiben (ohne GUI-Teil); die PyInstaller-Spec schließt `tkinter` aus. diff --git a/docs/station-shortcuts.de.md b/docs/station-shortcuts.de.md index 3956ea87..2b36a9a0 100644 --- a/docs/station-shortcuts.de.md +++ b/docs/station-shortcuts.de.md @@ -1,4 +1,4 @@ -# U-Jagd 1.3.109 - Stations- und Tastenkürzel +# U-Jagd 1.3.110 - Stations- und Tastenkürzel Druckfassung: [`station-shortcuts.de.pdf`](station-shortcuts.de.pdf). Maßgeblich ist die implementierte lokale Bedienung. Stationsnummern und diff --git a/docs/station-shortcuts.de.pdf b/docs/station-shortcuts.de.pdf index f8ed2e93..0dbf1919 100644 Binary files a/docs/station-shortcuts.de.pdf and b/docs/station-shortcuts.de.pdf differ diff --git a/main.py b/main.py index 2e2d6ce5..1d67faeb 100644 --- a/main.py +++ b/main.py @@ -5,6 +5,7 @@ import argparse import ipaddress import os import random +import sys from pathlib import Path from urllib.parse import urlsplit @@ -80,10 +81,10 @@ def main(argv=None) -> int: os.environ["SDL_AUDIODRIVER"] = "dummy" # Without a terminal (uConsole menu entry) a crash would leave no trace: # ~/.u-jagd/crash.log records start, end and any traceback or fatal signal. - return run_logged(lambda: _start(args)) + return run_logged(lambda: _start(args, argv)) -def _start(args) -> int: +def _start(args, argv=None) -> int: auth = WebHostAuth(Path.home() / ".u-jagd" / "web-host.json") if args.web_host else None if args.reset_web_host_password: auth.reset_local() @@ -120,8 +121,12 @@ def _start(args) -> int: elif args.multiplayer: # As the main-menu entry: the lobby starts Remote Crew in crew mode. game.open_lobby() + check = getattr(game, "start_update_check", None) + if check is not None and not args.web_host: + # Only a notice: a newer release is installed when the player asks. + check(None, argv if argv is not None else sys.argv[1:]) game.run() - return 0 + return getattr(game, "update_exit_code", 0) if __name__ == "__main__": diff --git a/packaging/uconsole/README.md b/packaging/uconsole/README.md index 9c8b4009..aef573d6 100644 --- a/packaging/uconsole/README.md +++ b/packaging/uconsole/README.md @@ -7,11 +7,13 @@ curl -fsSL https://raw.githubusercontent.com/db9979/uconsole_asw_game/main/packa ``` Danach startet das Spiel über **Spiele > U-Jagd**, die Desktop-Verknüpfung oder -`~/.local/bin/u-jagd`. Jeder Start holt zuerst das neueste Release und startet -dann das Spiel; ohne Netz startet sofort die installierte Version. Zusätzlich -sucht ein Hintergrund-Timer alle sechs Stunden nach Updates. Beim Start zeigt -ein kleines Fenster sofort, was gerade passiert (Update-Suche, Download, -Start); ein zweiter Start öffnet das Spiel nicht doppelt. +`~/.local/bin/u-jagd`. Updates werden nie von selbst installiert: Gibt es ein +neues Release, zeigt der Startbildschirm (und das Hauptmenü) die Version, den +Eintrag aus dem Änderungsprotokoll, einen Hinweis, falls alte Spielstände damit +nicht mehr laden, und den Knopf **Jetzt updaten** (Taste U). Erst dann schließt +das Spiel, ein kleines Fenster zeigt Download und Prüfung, und die neue Version +startet. Ohne Netz erscheint einfach kein Hinweis. Ein zweiter Start öffnet das +Spiel nicht doppelt. Hat die uConsole NetworkManager und das WLAN-Gerät `wlan0`, richtet der Installer auch den kleinen Hotspot-Helfer für den Mehrspieler ein (fragt einmal diff --git a/packaging/uconsole/install.sh b/packaging/uconsole/install.sh index 48762b26..4f5bbecb 100755 --- a/packaging/uconsole/install.sh +++ b/packaging/uconsole/install.sh @@ -4,13 +4,14 @@ # curl -fsSL https://raw.githubusercontent.com/db9979/uconsole_asw_game/main/packaging/uconsole/install.sh | sh # # Clones (or adopts) the game in $U_JAGD_DIR (default ~/games/u-jagd), creates -# its .venv, adds a menu/desktop entry, the `u-jagd` command and a background -# update timer. Every start then updates to the newest GitHub release first; -# offline the installed version starts. Run as the normal user, not with sudo. +# its .venv, brings it to the newest GitHub release and adds a menu/desktop +# entry and the `u-jagd` command. Later releases are never installed on their +# own: the game shows a new release on its start screen and installs it when +# you press "Update now". Run as the normal user, not with sudo. # On a machine with NetworkManager and a wlan0 Wi-Fi device it also installs # the small hotspot helper (asks for the sudo password once); without it, or # with U_JAGD_NO_HOTSPOT=1, it prints a note and the game installs anyway. -# sh install.sh --uninstall removes the menu entry, command and timer. +# sh install.sh --uninstall removes the menu entry and command. set -eu REPO_URL=https://github.com/db9979/uconsole_asw_game.git @@ -106,7 +107,7 @@ else git clone --branch main "$REPO_URL" "$APP_DIR" fi -python3 "$APP_DIR/packaging/uconsole/u_jagd_updater.py" update +U_JAGD_UPDATE_NOW=1 python3 "$APP_DIR/packaging/uconsole/u_jagd_updater.py" update python3 "$APP_DIR/packaging/uconsole/u_jagd_updater.py" setup setup_hotspot || note "hotspot helper setup skipped." say "installed. Start it from the menu (Games > U-Jagd) or with: ~/.local/bin/u-jagd" diff --git a/packaging/uconsole/u-jagd-launch b/packaging/uconsole/u-jagd-launch index cb3c2e66..5df62a6e 100755 --- a/packaging/uconsole/u-jagd-launch +++ b/packaging/uconsole/u-jagd-launch @@ -1,7 +1,7 @@ #!/bin/sh -# U-Jagd starter: update to the newest release (best effort), then start the game. -# Game arguments are passed through, e.g. `u-jagd --windowed`. -# U_JAGD_NO_UPDATE=1 skips the update for one start. +# U-Jagd starter: start the game (it shows new releases and installs one only +# on "Update now"). Game arguments are passed through, e.g. `u-jagd --windowed`. +# U_JAGD_NO_UPDATE=1 also skips the search for new releases for one start. set -eu self=$(readlink -f -- "$0") exec python3 "$(dirname -- "$self")/u_jagd_updater.py" launch "$@" diff --git a/packaging/uconsole/u_jagd_updater.py b/packaging/uconsole/u_jagd_updater.py index 2f85cf52..58150614 100755 --- a/packaging/uconsole/u_jagd_updater.py +++ b/packaging/uconsole/u_jagd_updater.py @@ -4,16 +4,24 @@ Runs with the system ``python3`` and only the standard library, so it keeps working even when the game's virtual environment is broken. Commands: -``launch [game args]`` update (best effort), then replace this process with - the game (``.venv/bin/python main.py``). -``update`` update only; used by the background systemd timer. -``setup`` create/refresh the venv, menu entry, ``~/.local/bin`` - command and the background timer (the installer). +``launch [game args]`` replace this process with the game + (``.venv/bin/python main.py``); never updates. +``install [game args]`` "Update now" in the game: wait until the game has + closed, update to the newest release, then start it. +``update`` with ``U_JAGD_UPDATE_NOW=1`` (the installer) update + only; otherwise (the retired background timer of + releases up to 1.3.109) switch that timer off. +``setup`` create/refresh the venv, menu entry and ``~/.local/bin`` + command (the installer); removes the old timer. ``uninstall`` remove that desktop integration again (keeps the game directory and ``~/.u-jagd`` saves). +Since 1.3.110 nothing is installed automatically: the game shows a newer +release with its changelog on the start screen and installs it only when the +player presses "Update now". + Update source: the newest GitHub release (tag ``vX.Y.Z``, the same source the -Windows starter uses). Without any release the checkout follows ``origin/main``; +Windows program uses). Without any release the checkout follows ``origin/main``; ``U_JAGD_UPDATE_CHANNEL=main`` forces that. Offline, a local modification, a non-main branch or a running game skips the update and the installed version starts. A new version whose ``main.py --version`` fails is rolled back. @@ -49,6 +57,7 @@ GIT_TIMEOUT_S = 60 GIT_ENV = {"GIT_TERMINAL_PROMPT": "0", "GIT_HTTP_LOW_SPEED_LIMIT": "1000", "GIT_HTTP_LOW_SPEED_TIME": "15"} PIP_TIMEOUT_S = 1200 +INSTALL_WAIT_S = 120 # "Update now": the game saves and closes in this time VERIFY_TIMEOUT_S = 90 LOG_MAX_BYTES = 256 * 1024 APP_ID = "u-jagd" @@ -240,6 +249,7 @@ MESSAGES = { "rollback": "Update fehlgeschlagen, starte bisherige Version …", "start": "Starte U-Jagd …", "busy": "Hintergrund-Update läuft, bitte warten …", + "closing": "Warte, bis U-Jagd beendet ist …", "running": "U-Jagd läuft bereits.", "failed": "Start fehlgeschlagen, siehe ~/.u-jagd/updater.log", }, @@ -251,6 +261,7 @@ MESSAGES = { "rollback": "Update failed, starting the previous version …", "start": "Starting U-Jagd …", "busy": "Background update running, please wait …", + "closing": "Waiting for U-Jagd to close …", "running": "U-Jagd is already running.", "failed": "Start failed, see ~/.u-jagd/updater.log", }, @@ -444,22 +455,33 @@ def show_briefly(app: Path, key: str) -> None: pass -def launch(argv: list[str], app: Path = APP_DIR) -> int: +def launch(argv: list[str], app: Path = APP_DIR, install: bool = False) -> int: + """Start the game; ``install`` first updates to the newest release.""" lock = GameLock() splash = None if not lock.try_acquire(): - if lock.holder() != "update": + if install: + # "Update now": the game that asked is still closing. + splash = Splash(app) + splash.status("closing") + if not lock.acquire(INSTALL_WAIT_S): + log("game did not close; update not installed") + splash.close() + return 1 + elif lock.holder() != "update": log("U-Jagd is already running or starting; second start ignored") show_briefly(app, "running") return 0 - splash = Splash(app) - splash.status("busy") - if not lock.acquire(PIP_TIMEOUT_S): - splash.close() - return 1 + else: + splash = Splash(app) + splash.status("busy") + if not lock.acquire(PIP_TIMEOUT_S): + splash.close() + return 1 lock.set_role("launch") splash = splash or Splash(app) - update(app, progress=splash.status) + if install: + update(app, progress=splash.status) try: ensure_venv(app) except (OSError, subprocess.SubprocessError) as exc: @@ -480,6 +502,11 @@ def launch(argv: list[str], app: Path = APP_DIR) -> int: def background_update(app: Path = APP_DIR) -> int: + if not os.environ.get("U_JAGD_UPDATE_NOW"): + # The timer of releases up to 1.3.109 still calls this: turn it off. + log("automatic updates are off; the game offers new releases itself") + retire_timer() + return 0 lock = GameLock() if not lock.try_acquire(): log("game running; background update postponed") @@ -508,8 +535,8 @@ def desktop_entry(app: Path) -> str: "Name=U-Jagd\n" "GenericName=Anti-Submarine Warfare\n" "GenericName[de]=U-Boot-Jagd\n" - "Comment=Anti Sub Marine Warfare on uConsole (updates itself)\n" - "Comment[de]=U-Boot-Jagd auf der uConsole (aktualisiert sich selbst)\n" + "Comment=Anti Sub Marine Warfare on uConsole\n" + "Comment[de]=U-Boot-Jagd auf der uConsole\n" f"Exec=\"{launcher}\"\n" f"Icon={icon}\n" "Terminal=false\n" @@ -518,20 +545,23 @@ def desktop_entry(app: Path) -> str: ) -def systemd_units(app: Path) -> dict[str, str]: - script = app / "packaging/uconsole/u_jagd_updater.py" - return { - "u-jagd-update.service": ( - "[Unit]\nDescription=U-Jagd background update\n" - "After=network-online.target\n\n" - "[Service]\nType=oneshot\n" - f"ExecStart=/usr/bin/env python3 \"{script}\" update\n" - "Nice=10\nIOSchedulingClass=idle\n"), - "u-jagd-update.timer": ( - "[Unit]\nDescription=Check for U-Jagd updates\n\n" - "[Timer]\nOnBootSec=3min\nOnUnitActiveSec=6h\nPersistent=true\n\n" - "[Install]\nWantedBy=timers.target\n"), - } +TIMER_UNITS = ("u-jagd-update.timer", "u-jagd-update.service") + + +def retire_timer() -> None: + """Switch off and remove the background update timer of older releases.""" + systemctl("disable", "--now", TIMER_UNITS[0]) + removed = False + for name in TIMER_UNITS: + path = config_home() / "systemd/user" / name + if path.is_symlink() or path.exists(): + try: + path.unlink() + removed = True + except OSError: + pass + if removed: + systemctl("daemon-reload") def write_text(path: Path, text: str, mode: int = 0o644) -> None: @@ -580,28 +610,21 @@ def setup(app: Path = APP_DIR) -> int: if bin_link.is_symlink() or bin_link.exists(): bin_link.unlink() bin_link.symlink_to(app / "packaging/uconsole/u-jagd-launch") - for name, text in systemd_units(app).items(): - write_text(config_home() / "systemd/user" / name, text) - if systemctl("daemon-reload") and systemctl("enable", "--now", "u-jagd-update.timer"): - log("background update timer enabled") - else: - log("systemd user timer unavailable; updates run at every start only") + retire_timer() log(f"setup complete in {app}") return 0 def uninstall() -> int: - systemctl("disable", "--now", "u-jagd-update.timer") + retire_timer() paths = [data_home() / "applications" / f"{APP_ID}.desktop", Path.home() / ".local/bin" / APP_ID] - paths += [config_home() / "systemd/user" / name for name in systemd_units(APP_DIR)] desk = desktop_dir() if desk is not None: paths.append(desk / f"{APP_ID}.desktop") for path in paths: if path.is_symlink() or path.exists(): path.unlink() - systemctl("daemon-reload") log(f"desktop integration removed; game files stay in {APP_DIR}") return 0 @@ -610,6 +633,8 @@ def main(argv: list[str]) -> int: command = argv[0] if argv else "launch" if command == "launch": return launch(argv[1:]) + if command == "install": + return launch(argv[1:], install=True) if command == "update": return background_update() if command == "setup": diff --git a/src/core/bugreport.py b/src/core/bugreport.py index f93d5fea..1c288117 100644 --- a/src/core/bugreport.py +++ b/src/core/bugreport.py @@ -7,7 +7,7 @@ from the query string; the player reviews the text and submits it with their own account, so nothing leaves the device without their consent. * ``issue_url()`` carries the newest lines of ``~/.u-jagd/crash.log`` and is - opened in a browser (uConsole desktop, Windows starter). + opened in a browser (uConsole desktop, Windows PC). * ``short_issue_url()`` carries only version, platform and context so it fits the on-screen QR code a phone scans (the uConsole usually has no browser). * ``write_report()`` stores the whole report as ``~/.u-jagd/bug-report.txt`` diff --git a/src/core/game.py b/src/core/game.py index 08fe951b..b85e640f 100644 --- a/src/core/game.py +++ b/src/core/game.py @@ -102,13 +102,14 @@ from src.core.game_bugreport import (BUG_REPORT_ENTRY, MAIN_MENU_ENTRIES, BugReportMixin) from src.core.game_welcome import WelcomeMixin from src.core.game_lobby import LobbyMixin +from src.core.game_update import UpdateNoticeMixin class Game(PicturesMixin, OperatorMixin, DrawMixin, MissionBridgeMixin, EventMixin, SimMixin, RadarPictureMixin, AswWeaponsMixin, RbuMixin, CasualtiesMixin, SaveMixin, TaskingMixin, IncidentsMixin, CrewMixin, MpaMixin, DebriefMixin, TrainingMixin, CampaignMixin, LogbookMixin, ReportsMixin, BugReportMixin, AutosaveMixin, WelcomeMixin, - LobbyMixin): + LobbyMixin, UpdateNoticeMixin): # Options overlay rows in display order; the last two open sub-menus. _OPTION_ROWS = ("language", "fullscreen", "audio", "large_text", "tooltips", "simlog", "night_mode", "high_contrast", "frame_rate", @@ -222,6 +223,7 @@ class Game(PicturesMixin, OperatorMixin, DrawMixin, MissionBridgeMixin, EventMix self.main_menu = bool(start_menu) self.main_menu_sel = 0 self._init_bug_report() + self._init_update_notice() self._init_logbook() self._init_autosave() self._autosave_armed = False diff --git a/src/core/game_draw.py b/src/core/game_draw.py index 2f08429c..84e8c6ea 100644 --- a/src/core/game_draw.py +++ b/src/core/game_draw.py @@ -146,6 +146,8 @@ class DrawMixin: # Support link: main menu page only, never over a mission. draw_support_corner(s, config.SCREEN_W - 24, 600, config.COLOR_TEXT, config.COLOR_TEXT_DIM) + if not self.welcome_active: + self.draw_update_notice(s, splash=False) elif self.menu_screen == WELCOME_SCREEN: self._draw_welcome_page() elif self.menu_screen == BUG_REPORT_ENTRY: @@ -325,6 +327,7 @@ class DrawMixin: s.fill(config.COLOR_BG) if self.splash_active: draw_splash(s, self._t - self.splash_started_at, self.tr) + self.draw_update_notice(s, splash=True) elif self.editor is not None: self.editor.draw(s) if isinstance(self.editor, MissionEditor) and self.editor.mode == "browser": @@ -1272,6 +1275,7 @@ class DrawMixin: self.update(dt, audio_dt=wall_dt) self.autosave_tick(wall_dt) self.lobby_tick(wall_dt) + self.update_tick() self._perf_debug_log(wall_dt) if self.web_mode: game_visible() diff --git a/src/core/game_events.py b/src/core/game_events.py index 11723737..79ec00db 100644 --- a/src/core/game_events.py +++ b/src/core/game_events.py @@ -478,6 +478,8 @@ class EventMixin: and getattr(e, "mod", 0) & pygame.KMOD_ALT): self.toggle_fullscreen() return + if self.handle_update_event(e): + return if self.splash_active: if e.type == pygame.QUIT: self.running = False diff --git a/src/core/game_update.py b/src/core/game_update.py new file mode 100644 index 00000000..5cd9f4c2 --- /dev/null +++ b/src/core/game_update.py @@ -0,0 +1,243 @@ +"""Update notice on the start screen and the main menu (1.3.110). + +A published newer release is never installed on its own. At launch a daemon +thread asks GitHub once (``src/launcher/update.fetch_notice``); when a newer +release exists, the splash and the main menu show its version, its changelog +entry in the game language, whether saves stop loading (a different +``SAVE_VERSION``) and an "Update now" button (key U or a click). + +The button hands over to whatever installed the game: the Windows program +downloads its new ``.exe`` in the background (size and SHA-256 checked), swaps +it in once it has closed and starts it (``src/launcher/update.py``); in the +``starter`` mode it exits with ``UPDATE_EXIT_CODE`` and the Windows entry +point (``src/launcher/entry.py``) does that. The uConsole launcher (``u_jagd_updater.py install``) waits for the game +to close, updates, then starts it again. Any other install opens the release +page in the browser. Nothing here touches simulation state. +""" + +from __future__ import annotations + +import os +from pathlib import Path +import shutil +import subprocess +import sys +import threading +import webbrowser + +import pygame + +from src.core import config +from src.core.i18n import message, raw_text +from src.core.version import APP_VERSION, SAVE_VERSION +from src.launcher import update +from src.launcher.update import UPDATE_EXIT_CODE +from src.ui import layout + +UPDATE_MODES = ("windows", "starter", "uconsole", "browser") +ROOT = Path(__file__).resolve().parents[2] +UPDATER = ROOT / "packaging" / "uconsole" / "u_jagd_updater.py" +# Start screen: top right, over the sky; main menu: left of the entries. +SPLASH_NOTICE_RECT = (792, 26, 462, 282) +MENU_NOTICE_RECT = (24, 148, 344, 412) +PANEL_FILL = (4, 16, 20, 205) +ACCENT = (236, 204, 128) + + +def default_update_mode() -> str: + """How "Update now" installs: the uConsole launcher for its own checkout.""" + if getattr(sys, "frozen", False): + return "windows" + if (os.name == "posix" and UPDATER.exists() and (ROOT / ".git").exists() + and Path(sys.prefix).resolve() == (ROOT / ".venv").resolve()): + return "uconsole" + return "browser" + + +def remove_stale_download() -> None: + """Delete an ``.new`` left by an update that could not swap in.""" + for suffix in (".new", ".new.part"): + try: + os.remove(os.path.abspath(sys.executable) + suffix) + except OSError: + pass + + +class UpdateNoticeMixin: + def _init_update_notice(self) -> None: + self.update_notice = None + self.update_mode = "browser" + self.update_args: tuple = () + self.update_failed = False + self.update_exit_code = 0 + self._update_thread = None + self._update_button = None + # Windows download: percent while running, then the file to swap in. + self.update_progress = None + self._update_ready = None + + def start_update_check(self, mode: str | None = None, args=()) -> bool: + """Ask GitHub once in the background; False when checks are off.""" + if (os.environ.get("U_JAGD_NO_UPDATE_CHECK") or os.environ.get("U_JAGD_NO_UPDATE") + or self.web_mode or self._update_thread is not None): + return False + self.update_mode = mode if mode in UPDATE_MODES else default_update_mode() + self.update_args = tuple(str(arg) for arg in args) + if self.update_mode == "windows": + remove_stale_download() + + def work() -> None: + try: + notice = update.fetch_notice(APP_VERSION) + except update.UpdateError: + return # offline: no notice at all + self.update_notice = notice # one reference store, read by draw + + self._update_thread = threading.Thread(target=work, name="update-check", daemon=True) + self._update_thread.start() + return True + + def update_notice_visible(self) -> bool: + return self.update_notice is not None and ( + self.splash_active + or (self.in_menu and self.main_menu and self.editor is None + and not self.administration_open and not self.welcome_active)) + + # --- action ------------------------------------------------------------- + + def request_update(self) -> bool: + """"Update now": hand over to the installer; True when the game ends.""" + notice = self.update_notice + if notice is None: + return False + if self.update_mode == "windows": + self._download_windows_update(notice) + return False + if self.update_mode == "starter": + self.update_exit_code = UPDATE_EXIT_CODE + self.running = False + return True + if self.update_mode == "uconsole" and self._spawn_updater(): + self.running = False + return True + if self.update_mode == "uconsole": + self.update_failed = True + return False + webbrowser.open(notice.page) + return False + + def _spawn_updater(self) -> bool: + """Start ``u_jagd_updater.py install``; it waits until this game quits.""" + python = shutil.which("python3") or sys.executable + try: + subprocess.Popen([python, str(UPDATER), "install", *self.update_args], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, close_fds=True, + start_new_session=True) + except OSError: + return False + return True + + def _download_windows_update(self, notice) -> None: + """Fetch the new program beside this one; ``update_tick`` swaps it.""" + if self.update_progress is not None: + return # already downloading + self.update_failed = False + self.update_progress = 0 + executable = os.path.abspath(sys.executable) + target = f"{executable}.new" + + def progress(done: int, total: int) -> None: + self.update_progress = int(done * 100 / max(1, total)) + + def work() -> None: + try: + release = update.check_latest(APP_VERSION) + if release is None: + webbrowser.open(notice.page) + self.update_progress = None + return + update.download(release, target, progress=progress) + except update.UpdateError: + self.update_failed = True + self.update_progress = None + return + self._update_ready = (executable, target) + + threading.Thread(target=work, name="update-download", daemon=True).start() + + def update_tick(self) -> None: + """Main loop: once the download is complete, swap and restart.""" + ready, self._update_ready = self._update_ready, None + if ready is None: + return + try: + update.launch_install(*ready, log=str(Path.home() / ".u-jagd" / "updater.log")) + except update.UpdateError: + self.update_failed = True + self.update_progress = None + return + self.running = False # the script replaces the file once we have exited + + def handle_update_event(self, e) -> bool: + """Key U or a click on the button while the notice shows.""" + if not self.update_notice_visible(): + return False + if e.type == pygame.KEYDOWN and e.key == pygame.K_u: + self.request_update() + return True + if e.type == pygame.MOUSEBUTTONDOWN and getattr(e, "button", 0) == 1: + canvas = self._window_to_canvas(getattr(e, "pos", None)) + if (canvas is not None and self._update_button is not None + and self._update_button.collidepoint(canvas)): + self.request_update() + return True + return False + + # --- drawing ------------------------------------------------------------ + + def draw_update_notice(self, surface, splash: bool) -> None: + notice = self.update_notice + self._update_button = None + if notice is None: + return + rect = pygame.Rect(SPLASH_NOTICE_RECT if splash else MENU_NOTICE_RECT) + panel = pygame.Surface(rect.size, pygame.SRCALPHA) + panel.fill(PANEL_FILL) + surface.blit(panel, rect) + pygame.draw.rect(surface, ACCENT, rect, 1) + layout.corner_brackets(surface, rect) + x, w = rect.x + 12, rect.w - 24 + y = rect.y + 8 + layout.blit_line(surface, message("update.available", version=notice.version), + (x, y, w, 26), ACCENT, size=20) + y += 26 + layout.blit_line(surface, message("update.installed", version=APP_VERSION), + (x, y, w, 20), config.COLOR_TEXT_DIM, size=14) + y += 22 + button_h = 34 + warn_h = 58 if notice.breaks_saves(SAVE_VERSION) else 0 + notes_h = rect.bottom - 10 - button_h - 6 - warn_h - y + notes = notice.notes_for(self.translator.language) + if notes and notes_h > 16: + layout.blit_block(surface, raw_text(notes), x, y, w, notes_h, + config.COLOR_TEXT, size=14, min_size=12) + y += max(0, notes_h) + if warn_h: + layout.blit_block(surface, "update.saves_break", x, y, w, warn_h, + config.COLOR_WARN, size=14, min_size=12) + y += warn_h + button = pygame.Rect(x, rect.bottom - 10 - button_h, w, button_h) + pygame.draw.rect(surface, (18, 60, 56), button, border_radius=4) + pygame.draw.rect(surface, ACCENT, button, 1, border_radius=4) + if self.update_failed: + label = "update.failed" + elif self.update_progress is not None: + label = message("update.downloading", percent=self.update_progress) + elif self.update_mode == "browser": + label = "update.button_browser" + else: + label = "update.button" + layout.blit_line(surface, label, button.inflate(-12, -6), ACCENT, size=18, + align="center") + self._update_button = button diff --git a/src/core/version.py b/src/core/version.py index 9d41245e..661f483a 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.109" +APP_VERSION = "1.3.110" SAVE_VERSION = 40 SAVE_SCHEMA = "u-jagd-save-v40" SPLASH_TEXT = ( diff --git a/src/launcher/__init__.py b/src/launcher/__init__.py index a69c3af8..48bf224d 100644 --- a/src/launcher/__init__.py +++ b/src/launcher/__init__.py @@ -1 +1 @@ -"""Windows starter: runs the game as Remote Crew server and keeps it updated.""" +"""Windows program: entry point (straight into the game) and self-update.""" diff --git a/src/launcher/entry.py b/src/launcher/entry.py index ab1d9fc2..f9322079 100644 --- a/src/launcher/entry.py +++ b/src/launcher/entry.py @@ -100,32 +100,30 @@ def update_self_test(report: str) -> int: return 0 -def remove_stale_update() -> None: - """Delete an ``.new`` left by an update that could not swap in.""" - if getattr(sys, "frozen", False): - for suffix in (".new", ".new.part"): - try: - os.remove(os.path.abspath(sys.executable) + suffix) - except OSError: - pass - - def _install_update(code: int) -> int: - """After the game asked for an update, swap in ``.new`` and restart. + """The game quit with ``update.UPDATE_EXIT_CODE``: install the release. - The game downloads and verifies the new program itself and then quits - with ``update.UPDATE_EXIT_CODE``; only the frozen program can replace its - own file. Returns 0 once the install script runs, else ``code``. + Normally the frozen game downloads and swaps in the new program itself + ("Update now", ``src/core/game_update.py``); this is the hand-over the + old starter did: fetch the newest release to ``.new`` unless it is + already there (size and SHA-256 checked), then start the install script + that replaces this file once it has exited and starts the new version. + Only the frozen program can replace itself. Returns 0 once the script + runs, else ``code``. """ + from src.core.version import APP_VERSION from src.launcher import update if not getattr(sys, "frozen", False): return code executable = os.path.abspath(sys.executable) downloaded = f"{executable}.new" - if not os.path.isfile(downloaded): - return code try: + if not os.path.isfile(downloaded): + release = update.check_latest(APP_VERSION) + if release is None: + return code + update.download(release, downloaded) update.launch_install(executable, downloaded, log=str(log_path())) except update.UpdateError: return code @@ -133,15 +131,16 @@ def _install_update(code: int) -> int: def run_game(argv: list[str]) -> int: - """Run the game with ``main.py``'s command line; return its exit code.""" + """Run the game with ``main.py``'s command line; return its exit code. + + A stale ``.new`` is removed by the game's own update check. + """ _ensure_streams() - remove_stale_update() import main as game_main from src.launcher import update code = game_main.main(argv) - update_code = getattr(update, "UPDATE_EXIT_CODE", None) - if update_code is not None and code == update_code: + if code == update.UPDATE_EXIT_CODE: return _install_update(code) return code diff --git a/src/launcher/update.py b/src/launcher/update.py index 09e8253e..d1a9649e 100644 --- a/src/launcher/update.py +++ b/src/launcher/update.py @@ -239,3 +239,114 @@ def launch_install(executable: str, downloaded: str, args=(), log=None, env=clean_environment(os.environ), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) return script + + +# --- update notice (game splash, main menu and starter) -------------------- + +# The game exits with this code after "Update now" when the starter runs it. +UPDATE_EXIT_CODE = 75 +RAW_FILE = "https://raw.githubusercontent.com/{repository}/{tag}/{path}" +MAX_TEXT_BYTES = 1 << 21 +MAX_NOTES_CHARS = 700 +_ENTRY = re.compile(r"^## (\d+\.\d+\.\d+)\s*$", re.MULTILINE) +_SAVE_VERSION = re.compile(r"^SAVE_VERSION\s*=\s*(\d{1,4})\s*$", re.MULTILINE) +_LINK = re.compile(r"!?\[([^\]]*)\]\([^)]*\)") +_CHANGELOGS = {"en": "CHANGELOG.md", "de": "CHANGELOG.de.md"} + + +@dataclass(frozen=True) +class Notice: + """A newer published release: its version, notes per language and saves.""" + + version: str + page: str + notes: dict + save_version: int | None + + def notes_for(self, language: str) -> str: + return self.notes.get(language) or self.notes.get("en") or "" + + def breaks_saves(self, current_save_version: int) -> bool: + """Saves of this build no longer load in the new release.""" + return self.save_version is not None and self.save_version != current_save_version + + +def changelog_entry(text: str, version: str) -> str: + """The text under ``## version`` in a changelog, ``""`` when missing.""" + matches = list(_ENTRY.finditer(text)) + for index, match in enumerate(matches): + if match.group(1) == version: + end = matches[index + 1].start() if index + 1 < len(matches) else len(text) + return text[match.end():end].strip() + return "" + + +def plain_notes(text: object, limit: int = MAX_NOTES_CHARS) -> str: + """Release notes as one plain paragraph (no Markdown), at most ``limit``.""" + if type(text) is not str: + return "" + text = _LINK.sub(r"\1", text[:limit * 8]) + text = re.sub(r"[`*_#>]", "", text) + text = " ".join(text.split()) + if len(text) > limit: + text = text[:limit - 1].rsplit(" ", 1)[0].rstrip(",;:") + "…" + return text + + +def parse_save_version(text: str) -> int | None: + match = _SAVE_VERSION.search(text) + return int(match.group(1)) if match else None + + +def _fetch_text(url: str, opener, timeout: float, agent: str) -> str: + request = urllib.request.Request(url, headers={"User-Agent": agent}) + try: + with opener(request, timeout=timeout) as response: + return _read_bounded(response, MAX_TEXT_BYTES).decode("utf-8") + except (OSError, ValueError, UpdateError): + return "" + + +def fetch_notice(current: str, opener=urllib.request.urlopen, + timeout: float = 8.0) -> Notice | None: + """The newer latest release with its changelog entry, ``None`` if current. + + Nothing is downloaded or installed. The English notes are the release + text (the changelog entry, see ``tools/changelog_notes.py``); the German + entry and the release's ``SAVE_VERSION`` are read from the tagged files. + Raises ``UpdateError`` when GitHub cannot be asked (offline). + """ + agent = f"u-jagd/{current}" + request = urllib.request.Request(LATEST_RELEASE_API, headers={ + "Accept": "application/vnd.github+json", "User-Agent": agent}) + try: + with opener(request, timeout=timeout) as response: + payload = json.loads(_read_bounded(response, MAX_METADATA_BYTES)) + except urllib.error.HTTPError as exc: + if exc.code == 404: + return None + raise UpdateError(str(exc)) from exc + except (OSError, ValueError) as exc: + raise UpdateError(str(exc)) from exc + if not isinstance(payload, dict) or payload.get("draft") or payload.get("prerelease"): + return None + tag = payload.get("tag_name") + version, installed = parse_version(tag), parse_version(current) + if version is None or installed is None or version <= installed: + return None + number = ".".join(map(str, version)) + tag = f"v{number}" + + def raw(path: str) -> str: + return _fetch_text(RAW_FILE.format(repository=REPOSITORY, tag=tag, path=path), + opener, timeout, agent) + + notes = {} + for language, path in _CHANGELOGS.items(): + notes[language] = plain_notes(changelog_entry(raw(path), number)) + if not notes["en"]: + notes["en"] = plain_notes(payload.get("body")) + page = payload.get("html_url") + return Notice(number, page if _https_github(page) else RELEASES_PAGE, + {key: value for key, value in notes.items() if value}, + parse_save_version(raw("src/core/version.py"))) diff --git a/tests/test_packaging.py b/tests/test_packaging.py index f7135485..ba63c3de 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -86,7 +86,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.109.dist-info/METADATA") for name in wheel_names) + assert any(name.endswith("-1.3.110.dist-info/METADATA") for name in wheel_names) source = next(tmp_path.glob("u_jagd-*.tar.gz")) with tarfile.open(source) as archive: @@ -139,7 +139,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.109'; " + "from src.core.version import APP_VERSION; assert APP_VERSION == '1.3.110'; " "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 d4dec69a..9a08fcb6 100644 --- a/tests/test_startup.py +++ b/tests/test_startup.py @@ -14,9 +14,9 @@ from src.world.real_coast import sector_for_seed def test_release_version_and_exact_splash_text(): - assert APP_VERSION == "1.3.109" + assert APP_VERSION == "1.3.110" assert SPLASH_TEXT == ( - "Anti Sub Marine Warfare on uConsole by Dominik Bornhäußer Version 1.3.109" + "Anti Sub Marine Warfare on uConsole by Dominik Bornhäußer Version 1.3.110" ) diff --git a/tests/test_uconsole_updater.py b/tests/test_uconsole_updater.py index 1ef55c2b..420485ec 100644 --- a/tests/test_uconsole_updater.py +++ b/tests/test_uconsole_updater.py @@ -197,15 +197,18 @@ def test_setup_and_uninstall_desktop_integration(tmp_path, monkeypatch): monkeypatch.setattr(module, "ensure_venv", lambda app, force_install=False: None) monkeypatch.setattr(module, "systemctl", lambda *args: True) monkeypatch.setattr(module, "desktop_dir", lambda: home / "Desktop") + old_units = home / ".config/systemd/user" + old_units.mkdir(parents=True) + for name in module.TIMER_UNITS: + (old_units / name).write_text("[Unit]\n") assert module.setup(ROOT) == 0 entry = (home / ".local/share/applications/u-jagd.desktop").read_text() assert f'Exec="{LAUNCH}"' in entry and "Categories=Game;" in entry assert (home / "Desktop/u-jagd.desktop").stat().st_mode & stat.S_IXUSR assert (home / ".local/bin/u-jagd").resolve() == LAUNCH - timer = (home / ".config/systemd/user/u-jagd-update.timer").read_text() - assert "OnUnitActiveSec=6h" in timer - service = (home / ".config/systemd/user/u-jagd-update.service").read_text() - assert f'"{UPDATER}" update' in service + assert "aktualisiert sich selbst" not in entry + # No background timer any more; the one of older releases is removed. + assert not (home / ".config/systemd/user/u-jagd-update.timer").exists() assert module.uninstall() == 0 assert not (home / ".local/bin/u-jagd").is_symlink() assert not (home / ".local/share/applications/u-jagd.desktop").exists() @@ -315,16 +318,74 @@ def test_start_during_background_update_waits_then_starts(tmp_path, monkeypatch) monkeypatch.setattr(module.GameLock, "acquire", acquire) with pytest.raises(Execed): module.launch(["--windowed"]) - assert released and calls["shown"] == [] and calls["updated"] == 1 + assert released and calls["shown"] == [] and calls["updated"] == 0 assert (tmp_path / ".u-jagd/updater.lock").read_text().startswith("game ") -def test_first_start_updates_and_marks_game(tmp_path, monkeypatch): +def test_start_never_updates_and_marks_game(tmp_path, monkeypatch): module = load_updater() calls = launch_env(module, tmp_path, monkeypatch) with pytest.raises(Execed): module.launch([]) - assert calls["updated"] == 1 and "U_JAGD_SPLASH_FD" not in calls["env"] + assert calls["updated"] == 0 and "U_JAGD_SPLASH_FD" not in calls["env"] + + +def test_update_now_waits_for_the_game_then_updates_and_starts(tmp_path, monkeypatch): + module = load_updater() + calls = launch_env(module, tmp_path, monkeypatch) + game = module.GameLock() + assert game.try_acquire() + game.set_role("game") + waited = [] + + def acquire(self, timeout_s): + os.close(game.fd) # the game has saved and closed + waited.append(timeout_s) + return self.try_acquire() + + monkeypatch.setattr(module.GameLock, "acquire", acquire) + with pytest.raises(Execed): + module.main(["install", "--windowed"]) + assert waited == [module.INSTALL_WAIT_S] and calls["shown"] == [] + assert calls["updated"] == 1 + + +def test_update_now_gives_up_when_the_game_stays_open(tmp_path, monkeypatch): + module = load_updater() + calls = launch_env(module, tmp_path, monkeypatch) + game = module.GameLock() + assert game.try_acquire() + monkeypatch.setattr(module.GameLock, "acquire", lambda self, timeout_s: False) + assert module.launch([], install=True) == 1 + assert calls["updated"] == 0 and "env" not in calls + os.close(game.fd) + + +def test_old_background_timer_only_switches_itself_off(tmp_path, monkeypatch): + module = load_updater() + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.delenv("U_JAGD_UPDATE_NOW", raising=False) + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config")) + units = tmp_path / "config/systemd/user" + units.mkdir(parents=True) + for name in module.TIMER_UNITS: + (units / name).write_text("[Unit]\n") + commands = [] + monkeypatch.setattr(module, "systemctl", lambda *args: commands.append(args) or True) + monkeypatch.setattr(module, "update", lambda app=None: pytest.fail("installed by timer")) + assert module.background_update() == 0 + assert ("disable", "--now", "u-jagd-update.timer") in commands + assert not any(units.iterdir()) + + +def test_installer_update_still_installs(tmp_path, monkeypatch): + module = load_updater() + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setenv("U_JAGD_UPDATE_NOW", "1") + done = [] + monkeypatch.setattr(module, "update", lambda app=None: done.append(app) or True) + assert module.background_update() == 0 and len(done) == 1 + assert 'U_JAGD_UPDATE_NOW=1 python3' in INSTALL.read_text() def test_game_closes_start_window_pipe_once(monkeypatch): diff --git a/tests/test_update_notice.py b/tests/test_update_notice.py new file mode 100644 index 00000000..f099f61e --- /dev/null +++ b/tests/test_update_notice.py @@ -0,0 +1,313 @@ +"""Update notice: new releases are shown with their changelog, never installed +until the player presses "Update now" (1.3.110).""" + +import io +import json +import time +import urllib.error + +import pygame +import pytest + +from src.core import game_update +from src.core.game import Game +from src.core.version import APP_VERSION, SAVE_VERSION +from src.launcher import update +from src.ui import layout + +CHANGELOG_EN = """# Changelog + +## 9.9.9 + +Release 9.9.9 adds a **lighthouse**. See [the manual](docs/manual.md) and +`L` for the `lamp`. + +## 1.3.106 + +Older. +""" +CHANGELOG_DE = CHANGELOG_EN.replace("adds a", "bringt einen").replace("## 1.3.106", "## 1.0.0") + + +class _Response(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + + +def _opener(save_version=SAVE_VERSION, tag="v9.9.9", files=None): + files = files if files is not None else { + "CHANGELOG.md": CHANGELOG_EN, "CHANGELOG.de.md": CHANGELOG_DE, + "src/core/version.py": f'APP_VERSION = "9.9.9"\nSAVE_VERSION = {save_version}\n'} + seen = [] + + def opener(request, timeout): + url = request.full_url + seen.append(url) + if url == update.LATEST_RELEASE_API: + return _Response(json.dumps({ + "tag_name": tag, "draft": False, "prerelease": False, "body": "Body text.", + "html_url": "https://github.com/db9979/uconsole_asw_game/releases/tag/v9.9.9", + }).encode()) + prefix = f"https://raw.githubusercontent.com/{update.REPOSITORY}/v9.9.9/" + assert url.startswith(prefix) + path = url[len(prefix):] + if path not in files: + raise urllib.error.HTTPError(url, 404, "Not Found", {}, None) + return _Response(files[path].encode()) + + opener.seen = seen + return opener + + +def test_notice_carries_changelog_in_both_languages_and_save_break(): + notice = update.fetch_notice("1.3.106", opener=_opener(save_version=SAVE_VERSION + 1)) + assert notice.version == "9.9.9" + assert notice.notes_for("en") == ("Release 9.9.9 adds a lighthouse. See the manual " + "and L for the lamp.") + assert notice.notes_for("de").startswith("Release 9.9.9 bringt einen lighthouse") + assert notice.breaks_saves(SAVE_VERSION) + assert not update.fetch_notice("1.3.106", opener=_opener()).breaks_saves(SAVE_VERSION) + assert notice.page.endswith("/releases/tag/v9.9.9") + + +def test_notice_falls_back_to_release_text_and_unknown_save_version(): + notice = update.fetch_notice("1.3.106", opener=_opener(files={})) + assert notice.notes_for("de") == "Body text." # English release text + assert notice.save_version is None and not notice.breaks_saves(SAVE_VERSION) + + +def test_no_notice_for_current_older_or_missing_releases(): + for tag in ("v1.3.106", "v1.0.0", "latest"): + assert update.fetch_notice("1.3.106", opener=_opener(tag=tag)) is None + + def missing(request, timeout): + raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, None) + + assert update.fetch_notice("1.3.106", opener=missing) is None + + def offline(request, timeout): + raise urllib.error.URLError("offline") + + with pytest.raises(update.UpdateError): + update.fetch_notice("1.3.106", opener=offline) + + +def test_plain_notes_are_bounded_and_markdown_free(): + text = update.plain_notes("# Head\n\n" + "word " * 500) + assert len(text) <= update.MAX_NOTES_CHARS and text.endswith("…") + assert "#" not in text + assert update.plain_notes(None) == "" + assert update.changelog_entry(CHANGELOG_EN, "1.3.106") == "Older." + assert update.changelog_entry(CHANGELOG_EN, "2.0.0") == "" + + +def _notice(save_version=SAVE_VERSION): + return update.Notice("9.9.9", update.RELEASES_PAGE, + {"en": "Adds a lighthouse.", "de": "Bringt einen Leuchtturm."}, + save_version) + + +def _game(**kwargs): + return Game(seed=7, start_menu=True, audio_enabled=False, **kwargs) + + +def test_check_is_off_in_tests_and_web_mode(monkeypatch): + game = _game(show_splash=True) + monkeypatch.setenv("U_JAGD_NO_UPDATE_CHECK", "1") + assert game.start_update_check() is False + monkeypatch.delenv("U_JAGD_NO_UPDATE_CHECK") + monkeypatch.delenv("U_JAGD_NO_UPDATE", raising=False) + game.web_mode = True + assert game.start_update_check() is False + + +def test_background_check_sets_the_notice_without_installing(monkeypatch): + monkeypatch.delenv("U_JAGD_NO_UPDATE_CHECK", raising=False) + monkeypatch.delenv("U_JAGD_NO_UPDATE", raising=False) + monkeypatch.setattr(update, "fetch_notice", lambda current: _notice()) + game = _game(show_splash=True) + assert game.start_update_check("browser") is True + game._update_thread.join(5) + assert game.update_notice.version == "9.9.9" and game.running + monkeypatch.setattr(update, "fetch_notice", + lambda current: (_ for _ in ()).throw(update.UpdateError("offline"))) + offline = _game(show_splash=True) + offline.start_update_check("browser") + offline._update_thread.join(5) + assert offline.update_notice is None + + +def _texts(game): + with layout.capture_text() as texts: + game.draw() + return " ".join(item["text"] for item in texts) + + +def test_splash_and_main_menu_show_version_notes_and_save_warning(): + game = _game(show_splash=True) + game.update_notice = _notice(save_version=SAVE_VERSION + 1) + text = _texts(game) + assert "9.9.9" in text and "lighthouse" in text and "Update now" in text + assert "will not load" in text + assert game._update_button is not None + game.splash_active = False + game.update_notice = _notice() + text = _texts(game) + assert "9.9.9" in text and "will not load" not in text + assert game._update_button.right < 380 # left of the main-menu panel + assert game._update_button.bottom <= 560 # above the world and seed lines + game.update_notice = None + assert "9.9.9" not in _texts(game) + + +def test_german_notice_uses_german_notes(): + from src.core.preferences import Preferences + game = _game(show_splash=True, preferences=Preferences(language="de")) + game.update_notice = _notice(save_version=SAVE_VERSION + 1) + text = _texts(game) + assert "Leuchtturm" in text and "Jetzt updaten" in text and "nicht mehr" in text + + +def test_windows_downloads_in_the_game_then_swaps_and_quits(monkeypatch, tmp_path): + exe = tmp_path / "U-Jagd-Windows.exe" + monkeypatch.setattr(game_update.sys, "executable", str(exe)) + (tmp_path / "U-Jagd-Windows.exe.new").write_bytes(b"old") + release = update.Release("9.9.9", "https://github.com/x.exe", 3, None, update.RELEASES_PAGE) + monkeypatch.setattr(update, "check_latest", lambda current: release) + downloads, installs = [], [] + + def download(rel, target, progress=None): + progress(3, 3) + downloads.append(target) + + monkeypatch.setattr(update, "download", download) + monkeypatch.setattr(update, "launch_install", + lambda exe_path, target, log=None: installs.append((exe_path, target))) + monkeypatch.delenv("U_JAGD_NO_UPDATE_CHECK", raising=False) + monkeypatch.delenv("U_JAGD_NO_UPDATE", raising=False) + monkeypatch.setattr(update, "fetch_notice", lambda current: None) + game = _game(show_splash=True) + game.start_update_check("windows") + assert not (tmp_path / "U-Jagd-Windows.exe.new").exists() # stale swap removed + game._update_thread.join(5) + game.update_notice = _notice() + game.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_u, mod=0)) + for _ in range(100): + if game._update_ready is not None: + break + time.sleep(0.02) + assert downloads == [f"{exe}.new"] and game.update_progress == 100 + assert "100 %" in _texts(game) + game.update_tick() + assert installs == [(str(exe), f"{exe}.new")] and not game.running + + +def test_windows_download_failure_can_be_retried(monkeypatch): + def fail(current): + raise update.UpdateError("offline") + + monkeypatch.setattr(update, "check_latest", fail) + game = _game(show_splash=False) + game.update_notice = _notice() + game.update_mode = "windows" + game.request_update() + for _ in range(100): + if game.update_failed: + break + time.sleep(0.02) + assert game.update_failed and game.update_progress is None and game.running + + +def test_u_on_splash_hands_over_to_the_starter(): + game = _game(show_splash=True) + game.update_notice = _notice() + game.update_mode = "starter" + game.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_u, mod=0)) + assert not game.running and game.update_exit_code == update.UPDATE_EXIT_CODE + + +def test_u_without_notice_only_leaves_the_splash(): + game = _game(show_splash=True) + game.splash_started_at -= 1.0 + game.update_mode = "starter" + game.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_u, mod=0)) + assert game.running and not game.splash_active and game.update_exit_code == 0 + + +def test_uconsole_mode_starts_the_launcher_and_quits(monkeypatch): + started = [] + monkeypatch.setattr(game_update.subprocess, "Popen", + lambda args, **kwargs: started.append((args, kwargs))) + game = _game(show_splash=False) + game.update_notice = _notice() + game.update_mode = "uconsole" + game.update_args = ("--windowed",) + game.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_u, mod=0)) + args, kwargs = started[0] + assert args[1:] == [str(game_update.UPDATER), "install", "--windowed"] + assert kwargs["close_fds"] and kwargs["start_new_session"] + assert not game.running and game.update_exit_code == 0 + + +def test_uconsole_mode_reports_a_failed_start(monkeypatch): + def fail(*args, **kwargs): + raise OSError("no python3") + + monkeypatch.setattr(game_update.subprocess, "Popen", fail) + game = _game(show_splash=False) + game.update_notice = _notice() + game.update_mode = "uconsole" + assert game.request_update() is False and game.running and game.update_failed + assert "try again" in _texts(game) + + +def test_other_installs_open_the_release_page(monkeypatch): + opened = [] + monkeypatch.setattr(game_update.webbrowser, "open", opened.append) + game = _game(show_splash=False) + game.update_notice = _notice() + game.update_mode = "browser" + game.draw() + center = game._update_button.center + monkeypatch.setattr(game, "_window_to_canvas", lambda pos: pos) + game.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=center)) + assert opened == [update.RELEASES_PAGE] and game.running + + +def test_notice_hidden_under_overlays_and_during_a_mission(): + game = _game(show_splash=False) + game.update_notice = _notice() + assert game.update_notice_visible() + game._open_administration("quit") + assert not game.update_notice_visible() + game2 = Game(seed=7, start_menu=False, show_splash=False, audio_enabled=False) + game2.update_notice = _notice() + assert not game2.update_notice_visible() + + +def test_main_returns_the_update_exit_code(monkeypatch): + import main as entry + + calls = [] + + class FakeGame: + update_exit_code = 0 + + def __init__(self, **_kwargs): + self.commander = type("C", (), {"port": 8765, "status_path": None})() + + def start_update_check(self, mode=None, args=()): + calls.append((mode, tuple(args))) + + def run(self): + self.update_exit_code = update.UPDATE_EXIT_CODE + + monkeypatch.setattr(entry, "Game", FakeGame) + monkeypatch.setattr(entry, "load_preferences", lambda: type( + "P", (), {"fullscreen": False, "audio": False})()) + assert entry.main(["--windowed", "5"]) == update.UPDATE_EXIT_CODE + assert calls == [(None, ("--windowed", "5"))] + assert APP_VERSION diff --git a/tests/test_windows_launcher.py b/tests/test_windows_launcher.py index 1bd950bf..25897b7c 100644 --- a/tests/test_windows_launcher.py +++ b/tests/test_windows_launcher.py @@ -134,19 +134,6 @@ def test_launch_install_starts_the_script_with_a_clean_environment(monkeypatch, assert "move /Y" in open(script, encoding="utf-8").read() -def test_the_program_removes_a_stale_update_before_the_game(monkeypatch, tmp_path): - exe = tmp_path / "U-Jagd-Windows.exe" - for name in ("U-Jagd-Windows.exe.new", "U-Jagd-Windows.exe.new.part"): - (tmp_path / name).write_bytes(b"x") - monkeypatch.setattr(sys, "frozen", True, raising=False) - monkeypatch.setattr(sys, "executable", str(exe)) - import main as game_main - - monkeypatch.setattr(game_main, "main", lambda argv: 0) - assert entry.main([]) == 0 - assert not list(tmp_path.glob("U-Jagd-Windows.exe.*")) - - def _fake_game_main(monkeypatch, code): import main as game_main @@ -181,43 +168,64 @@ def test_the_update_exit_code_installs_the_downloaded_program(monkeypatch, tmp_p exe.write_bytes(b"old") monkeypatch.setattr(sys, "frozen", True, raising=False) monkeypatch.setattr(sys, "executable", str(exe)) - monkeypatch.setattr(update, "UPDATE_EXIT_CODE", 75, raising=False) installs = [] monkeypatch.setattr(update, "launch_install", lambda executable, downloaded, args=(), log=None: installs.append((executable, downloaded, args, log))) + monkeypatch.setattr(update, "check_latest", + lambda current: pytest.fail("already downloaded")) import main as game_main def game_downloads(argv): (tmp_path / "U-Jagd-Windows.exe.new").write_bytes(b"new") - return 75 + return update.UPDATE_EXIT_CODE monkeypatch.setattr(game_main, "main", game_downloads) assert entry.main([]) == 0 assert installs == [(str(exe), f"{exe}.new", (), str(entry.log_path()))] - # Nothing downloaded: no install, the code is passed through. - installs.clear() - monkeypatch.setattr(game_main, "main", lambda argv: 75) - assert entry.main([]) == 75 and installs == [] - # A failed install script keeps the code too. - monkeypatch.setattr(game_main, "main", game_downloads) + # A failed install script keeps the code. def broken(*_args, **_kwargs): raise update.UpdateError("no temp dir") monkeypatch.setattr(update, "launch_install", broken) - assert entry.main([]) == 75 + assert entry.main([]) == update.UPDATE_EXIT_CODE -def test_without_an_update_exit_code_every_code_is_passed_through(monkeypatch, tmp_path): +def test_the_update_exit_code_fetches_the_release_first(monkeypatch, tmp_path): exe = tmp_path / "U-Jagd-Windows.exe" monkeypatch.setattr(sys, "frozen", True, raising=False) monkeypatch.setattr(sys, "executable", str(exe)) - monkeypatch.delattr(update, "UPDATE_EXIT_CODE", raising=False) + release = update.Release("9.9.9", ASSET_URL, 4, "0" * 64, update.RELEASES_PAGE) + steps = [] + monkeypatch.setattr(update, "check_latest", lambda current: steps.append("check") or release) + monkeypatch.setattr(update, "download", + lambda found, target, **_kw: steps.append(("download", found, target))) monkeypatch.setattr(update, "launch_install", - lambda *a, **k: pytest.fail("no install without the exit code")) - _fake_game_main(monkeypatch, 75) - assert entry.main([]) == 75 + lambda executable, downloaded, args=(), log=None: + steps.append(("install", downloaded))) + _fake_game_main(monkeypatch, update.UPDATE_EXIT_CODE) + assert entry.main([]) == 0 + assert steps == ["check", ("download", release, f"{exe}.new"), + ("install", f"{exe}.new")] + # No newer release or offline: nothing is installed, the code stays. + steps.clear() + monkeypatch.setattr(update, "check_latest", lambda current: None) + assert entry.main([]) == update.UPDATE_EXIT_CODE and steps == [] + + def offline(current): + raise update.UpdateError("offline") + + monkeypatch.setattr(update, "check_latest", offline) + assert entry.main([]) == update.UPDATE_EXIT_CODE and steps == [] + + +def test_from_source_the_update_exit_code_is_passed_through(monkeypatch): + monkeypatch.setattr(sys, "frozen", False, raising=False) + monkeypatch.setattr(update, "launch_install", + lambda *a, **k: pytest.fail("only the frozen program replaces itself")) + _fake_game_main(monkeypatch, update.UPDATE_EXIT_CODE) + assert entry.main([]) == update.UPDATE_EXIT_CODE def test_the_windows_program_has_no_starter_window(): @@ -257,6 +265,40 @@ def test_prepare_uses_the_routed_private_address_without_linux_ioctls(monkeypatc assert offline.hosts == ("127.0.0.1",) +def test_game_main_checks_for_updates_and_returns_the_update_exit_code(monkeypatch): + import main as entry + + calls = [] + + class FakeConsole: + port = 8765 + + def autostart_solo(self): + calls.append(("solo", self.port)) + + class FakeGame: + update_exit_code = 0 + + def __init__(self, **_kwargs): + self.commander = FakeConsole() + + def start_update_check(self, mode=None, args=()): + calls.append(("update_check", mode, tuple(args))) + + def run(self): + calls.append("run") + self.update_exit_code = exit_code + + monkeypatch.setattr(entry, "Game", FakeGame) + monkeypatch.setattr(entry, "load_preferences", lambda: type( + "P", (), {"fullscreen": False, "audio": False})()) + exit_code = 0 + assert entry.main(["--solo-crew", "--web-port", "9000", "5"]) == 0 + assert calls == [("solo", 9000), + ("update_check", None, ("--solo-crew", "--web-port", "9000", "5")), + "run"] + exit_code = update.UPDATE_EXIT_CODE + assert entry.main(["5"]) == update.UPDATE_EXIT_CODE def test_frozen_self_test_runs_a_mission_and_serves_remote_crew(tmp_path): from src.launcher import entry