Compare commits
19 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
31b28652db | |
|
|
8acff1058a | |
|
|
c5e303db9f | |
|
|
9492b92e80 | |
|
|
42bf545b35 | |
|
|
22aef15efc | |
|
|
88f957b5ed | |
|
|
547c13ce7f | |
|
|
9ef9318a51 | |
|
|
4afd260bab | |
|
|
34678665a8 | |
|
|
a926ea1ae4 | |
|
|
b2684a2188 | |
|
|
b72898cd56 | |
|
|
3bccab12fa | |
|
|
4c29eda3c3 | |
|
|
6f614c8595 | |
|
|
e1f4c35c35 | |
|
|
4caed5bc15 |
|
|
@ -17,3 +17,5 @@ venv/
|
||||||
# Python-Cache
|
# Python-Cache
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
|
|
||||||
|
*.un~
|
||||||
|
|
|
||||||
96
README.md
96
README.md
|
|
@ -27,18 +27,20 @@ Jedes Spiel arbeitet als vollständig gekapseltes Modul mit **eigener Erfahrungs
|
||||||
* **XP-gegen-Gold-Tausch:** Regulär `10.000 XP` für `+10 Gold` (ausschließlich aus dem XP-Pool des jeweiligen Spiels).
|
* **XP-gegen-Gold-Tausch:** Regulär `10.000 XP` für `+10 Gold` (ausschließlich aus dem XP-Pool des jeweiligen Spiels).
|
||||||
* **Divine Punishment:** Wer im jeweiligen Spiel einmal den Rang *Gottheit* erreicht hat, zahlt für Gold-Tausche das $10$-fache der Durchschnitts-XP des Vorlevels und kann maximal bis auf die Untergrenze von *Schöpfergeist V* zurückfallen.
|
* **Divine Punishment:** Wer im jeweiligen Spiel einmal den Rang *Gottheit* erreicht hat, zahlt für Gold-Tausche das $10$-fache der Durchschnitts-XP des Vorlevels und kann maximal bis auf die Untergrenze von *Schöpfergeist V* zurückfallen.
|
||||||
* **The Devil's Deal:** Ist die Untergrenze von *Schöpfergeist V* erreicht, kann ein anderes Seelen-Profil geopfert werden (sofern dieses **im selben Spiel** mindestens den Rang **Stütze I** hält), um `+10 Gold` zu erhalten. Während eines aktiven Pakts sind alle anderen Menüs und Spiele gesperrt (*Auto-Save & Resume-Zwang*), bis die Runde entschieden ist.
|
* **The Devil's Deal:** Ist die Untergrenze von *Schöpfergeist V* erreicht, kann ein anderes Seelen-Profil geopfert werden (sofern dieses **im selben Spiel** mindestens den Rang **Stütze I** hält), um `+10 Gold` zu erhalten. Während eines aktiven Pakts sind alle anderen Menüs und Spiele gesperrt (*Auto-Save & Resume-Zwang*), bis die Runde entschieden ist.
|
||||||
* ** Gemeinsames Solitaire-Framework (`games/solitaire/base/`):**
|
* **Universelles HUD-, Statistik- & Einstellungs-System:**
|
||||||
|
* **Zentralisierte Leisten (`GothTopbar` & `SolitaireBottomBar`):** Einheitliche, schlanke Kopfleiste (mit verzögerungsfreiem Level/XP-Badge-Update ohne Layout-Redraw) sowie eine gerahmte untere HUD- und Aktionsleiste mit dynamischen Links-/Rechts-Overflow-Flügeln für kompakte Auflösungen (z. B. `1366×768`).
|
||||||
|
* **Zentrale Einheits-Statistik (`UnifiedStatsView`):** Spielübergreifendes Vollbild-Overlay (direkt aus jedem laufenden Tisch ohne Zerstörung des Spielstands aufrufbar) mit Umschaltern für Gesamtprofil, Einzelspiele, Spielvarianten sowie Blackjack-/Poker-Goldbeutel.
|
||||||
|
* **Kombinierter Einstellungs-Dialog, `GothSwitch` & Hover-Hilfe:** Vereint Live-Sprachwechsel (**DE / EN**), zweikanalige Audio-Regler (Ambiance/Musik & Soundeffekte) und einen weich animierten Toggle-Switch (`GothSwitch`), über den kontextsensitive Hover-Tooltips (`Helvetica` für optimale Lesbarkeit) auf Aktions-Buttons global ein- oder ausgeschaltet werden können.
|
||||||
|
* **Gemeinsames Solitaire-Framework (`games/solitaire/base/`):**
|
||||||
* **Garantiert lösbare Deals & 4 Schwierigkeitsstufen:** Vorab-Prüfung durch spielspezifische Solver und konstruktive Deal-Generatoren von *Stufe 1 – Akolyth (Leicht)* bis *Stufe 4 – Gottheit (Gnadenlos)*.
|
* **Garantiert lösbare Deals & 4 Schwierigkeitsstufen:** Vorab-Prüfung durch spielspezifische Solver und konstruktive Deal-Generatoren von *Stufe 1 – Akolyth (Leicht)* bis *Stufe 4 – Gottheit (Gnadenlos)*.
|
||||||
* **Flüssige 60-FPS-Animationen (`CardFlightAnimator`):** Nicht-blockierender Kartenflug mit kubischem Ease-Out, Snap-Back bei ungültigen Drops und verzögerungsfreiem `flush()` bei schnellen Klickserien.
|
* **Flüssige 60-FPS-Animationen (`CardFlightAnimator`):** Nicht-blockierender Kartenflug mit kubischem Ease-Out, Snap-Back bei ungültigen Drops und verzögerungsfreiem `flush()` bei schnellen Klickserien.
|
||||||
* **Komfort, Auto-Save & Fairness:** Spielzeit startet erst bei der ersten echten Karten-/Tipp-Interaktion, pausiert automatisch bei Fokusverlust, speichert jeden Zug persistent inkl. unbegrenztem `Strg+Z` bis Zug $0$ sowie `⟲ Anfang` (`Strg+Shift+Z`) und erkennt Sackgassen automatisch. Das Aufgeben einer begonnenen Partie zieht $40\,\%$ der regulären Sieg-XP ab (geschützt durch das *Schöpfergeist V*-Minimum).
|
* **Komfort, Auto-Save & Fairness:** Spielzeit startet erst bei der ersten echten Karten-/Tipp-Interaktion, pausiert automatisch bei Fokusverlust, speichert jeden Zug persistent inkl. unbegrenztem `Strg+Z` bis Zug $0$ sowie `⟲ Anfang` (`Strg+Shift+Z`) und erkennt Sackgassen automatisch. Das Aufgeben einer begonnenen Partie zieht $40\,\%$ der regulären Sieg-XP ab (geschützt durch das *Schöpfergeist V*-Minimum).
|
||||||
* **7 KI-Schwierigkeitsgrade (Stufe 0 bis Stufe 6 „Gottheit“):**
|
* **7 KI-Schwierigkeitsgrade (Stufe 0 bis Stufe 6 „Gottheit“):**
|
||||||
* Frei konfigurierbare Gegner-Slots mit persistent gespeicherten Namen und KI-Stufen pro Tischspiel (`bot_configs`).
|
* Frei konfigurierbare Gegner-Slots mit persistent gespeicherten Namen und KI-Stufen pro Tischspiel (`bot_configs`).
|
||||||
* **Gothic UI, Spiel-Icons, Custom Fonts & Cross-Platform Integration:**
|
* **Gothic UI, Spiel-Icons, Custom Fonts & Cross-Platform Integration:**
|
||||||
* Eigene hochauflösende Spiel-Icons (`resources/images/game_icons/*.ico`) auf den Hauptmenü-Kacheln mit automatischer Freistellung und abgerundeter Maskierung sowie ein gerahmter Damast-Spieltisch (`general_table.jpg`) mit dynamischer Rahmen-Innenberechnung für alle Solo-Tische.
|
* Eigene hochauflösende Spiel-Icons (`resources/images/game_icons/*.ico`) auf den Hauptmenü-Kacheln mit automatischer Freistellung und abgerundeter Maskierung, freigestellte RGBA-Tische (`poker_table.png`) mit dynamischer Rahmenbreiten-Anpassung (`box_background.png`) sowie nahtloses Hintergrund-Slicing.
|
||||||
* Dynamischer Laufzeit-Font-Loader (`view/font_loader.py`) für mitgelieferte `.ttf`-Schriften (`OldLondon.ttf` & `OldLondonAlternate.ttf`) komplett ohne Systeminstallation unter **Windows**, **Linux**, **ChromeOS (Crostini)** und **macOS**.
|
* Dynamischer Laufzeit-Font-Loader (`view/font_loader.py`) für mitgelieferte `.ttf`-Schriften (`OldLondon.ttf` & `OldLondonAlternate.ttf`) komplett ohne Systeminstallation unter **Windows**, **Linux**, **ChromeOS (Crostini)** und **macOS**.
|
||||||
* Plattformübergreifendes Anwendungs-Icon (`game_icon.ico` inkl. Windows-Taskbar-ID, Multi-Size X11/Wayland `WM_CLASS` & macOS-Dock-Unterstützung).
|
* Plattformübergreifendes Anwendungs-Icon (`game_icon.ico` inkl. Windows-Taskbar-ID, Multi-Size X11/Wayland `WM_CLASS` & macOS-Dock-Unterstützung) sowie automatische Speicherung & Wiederherstellung von Fenstergröße, Bildschirmposition und Maximiert-/Vollbild-Status (`view/window_state.py`).
|
||||||
* Automatische Speicherung & Wiederherstellung von Fenstergröße, Bildschirmposition und Maximiert-/Vollbild-Status (`view/window_state.py`).
|
|
||||||
* Vollständige Zweisprachigkeit (**Deutsch / Englisch**) im Live-Wechsel sowie zweikanalige Audio-Steuerung (Ambiance/Hintergrundmusik & Soundeffekte).
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -46,9 +48,9 @@ Jedes Spiel arbeitet als vollständig gekapseltes Modul mit **eigener Erfahrungs
|
||||||
|
|
||||||
| Kategorie | Spiel | Status | Varianten & Besonderheiten | Detail-Doku |
|
| Kategorie | Spiel | Status | Varianten & Besonderheiten | Detail-Doku |
|
||||||
| :--- | :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
| **Glück** | **Blackjack** | Spielbar | *Klassisch* (2 Decks) & *Hoher Einsatz* (6 Decks), bis zu 3 Bots, Devil's Gambit Wettbaum, Split/Double, `7-7-7` Sofortsieg | [`games/blackjack/README.md`](games/blackjack/README.md) |
|
| **Glück** | **Blackjack** | Spielbar | *Klassisch* (2 Decks) & *Hoher Einsatz* (6 Decks), bis zu 4 Bots an den Tischecken, Devil's Gambit Wettbaum, Split/Double, `7-7-7` Sofortsieg, Hover-Tooltips | [`games/blackjack/README.md`](games/blackjack/README.md) |
|
||||||
| **Glück** | **Texas Hold'em** | Spielbar | *Klassisch* & *Hoher Einsatz*, 6-Max Tisch (1–5 Bots), gleicher Start-Ante, Pre-Flop bis Showdown, All-In & Side-Pots, Info-Hilfesystem | [`games/poker/README.md`](games/poker/README.md) |
|
| **Glück** | **Texas Hold'em** | Spielbar | *Klassisch* & *Hoher Einsatz*, Vollbild 6-Max Tisch (1–5 Bots), gleicher Start-Ante, Pre-Flop bis Showdown, All-In & Side-Pots, spoilerfreie *Kartenreferenz* (`PokerHandsOverlay`) & Hover-Tooltips | [`games/poker/README.md`](games/poker/README.md) |
|
||||||
| **Solo** | **Solitaire-Basis** | Aktiv | Gemeinsame Engine, `CardFlightAnimator`, `SolitaireTableBgRenderer`, Auto-Save/Resume & In-Game-Statistik | [`games/solitaire/README.md`](games/solitaire/README.md) |
|
| **Solo** | **Solitaire-Basis** | Aktiv | Gemeinsame Engine (`SolitaireCard` + `SolitaireBaseEngine`), `SolitaireBottomBar`, `CardFlightAnimator`, `SolitaireTableBgRenderer` & Auto-Save/Resume | [`games/solitaire/README.md`](games/solitaire/README.md) |
|
||||||
| **Solo** | **Klondike** | Spielbar | *1 Karte ziehen* & *3 Karten ziehen*, 7 Spalten, Vorab-Solver, 4 Schwierigkeitsgrade, 3-Zyklen-Stagnationssperre & Auto-Ende | [`games/solitaire/klondike/README.md`](games/solitaire/klondike/README.md) |
|
| **Solo** | **Klondike** | Spielbar | *1 Karte ziehen* & *3 Karten ziehen*, 7 Spalten, Vorab-Solver, 4 Schwierigkeitsgrade, 3-Zyklen-Stagnationssperre & Auto-Ende | [`games/solitaire/klondike/README.md`](games/solitaire/klondike/README.md) |
|
||||||
| **Solo** | **FreeCell** | Spielbar | *Standard*, 8 offene Spalten, 4 Freie Zellen, exakte Supermove-Formel, Best-First-Solver & Smart-Auto-Move | [`games/solitaire/freecell/README.md`](games/solitaire/freecell/README.md) |
|
| **Solo** | **FreeCell** | Spielbar | *Standard*, 8 offene Spalten, 4 Freie Zellen, exakte Supermove-Formel, Best-First-Solver & Smart-Auto-Move | [`games/solitaire/freecell/README.md`](games/solitaire/freecell/README.md) |
|
||||||
| **Solo** | **Spider Solitaire** | Spielbar | *1 Farbe*, *2 Farben* & *4 Farben*, 104 Karten auf 10 Spalten, strenge Austeil-Regel, konstruktiver Deal-Generator & 8 Sequenz-Slots | [`games/solitaire/spider_solitaire/README.md`](games/solitaire/spider_solitaire/README.md) |
|
| **Solo** | **Spider Solitaire** | Spielbar | *1 Farbe*, *2 Farben* & *4 Farben*, 104 Karten auf 10 Spalten, strenge Austeil-Regel, konstruktiver Deal-Generator & 8 Sequenz-Slots | [`games/solitaire/spider_solitaire/README.md`](games/solitaire/spider_solitaire/README.md) |
|
||||||
|
|
@ -64,9 +66,13 @@ the_goth_cardgame_collection/
|
||||||
├── main.py # Einstiegspunkt, OS-Icon, Font-Registrierung & Window-Persistence
|
├── main.py # Einstiegspunkt, OS-Icon, Font-Registrierung & Window-Persistence
|
||||||
├── build.py # Build-Skript (aktuelles OS oder Cross-Platform-Paketierung)
|
├── build.py # Build-Skript (aktuelles OS oder Cross-Platform-Paketierung)
|
||||||
├── user_data.db # Automatisch beim Start erzeugte lokale Spielstand- & Statistik-DB
|
├── user_data.db # Automatisch beim Start erzeugte lokale Spielstand- & Statistik-DB
|
||||||
|
├── build_scripts/
|
||||||
|
│ ├── rebuild_internal_db.py # Baut internal_base.db sauber aus resources/code_res/sql/*.sql neu
|
||||||
|
│ ├── check_i18n.ps1 # AST-Tiefenprüfung aller t(...)-Aufrufe, Konstanten & Platzhalter
|
||||||
|
│ └── check_multi_class_files.ps1 # Prüft projektweit die strikte 1-Klasse-pro-Datei-Regel
|
||||||
├── controller/
|
├── controller/
|
||||||
│ ├── app_controller.py # Hauptsteuerung, Profil-Session & Devil's-Deal-Sperrlogik
|
│ ├── app_controller.py # Hauptsteuerung, Profil-Session & Devil's-Deal-Sperrlogik
|
||||||
│ ├── app_context.py # Schnittstelle zwischen Core-App und den Spielmodulen
|
│ ├── app_context.py # Schlanke Schnittstelle zwischen Core-App, Settings, Stats & Spielen
|
||||||
│ └── game_loader.py # Dynamischer Discovery-Loader für games/**/start.py
|
│ └── game_loader.py # Dynamischer Discovery-Loader für games/**/start.py
|
||||||
├── models/
|
├── models/
|
||||||
│ ├── card.py # Karten-Datenmodell
|
│ ├── card.py # Karten-Datenmodell
|
||||||
|
|
@ -80,26 +86,27 @@ the_goth_cardgame_collection/
|
||||||
│ │ ├── game_constants.py # Zentrale Konstanten, Farbpalette & Spiel-Konfigurationen
|
│ │ ├── game_constants.py # Zentrale Konstanten, Farbpalette & Spiel-Konfigurationen
|
||||||
│ │ ├── i18n.py # Übersetzungs-Cache & Sprachumschaltung (DE/EN)
|
│ │ ├── i18n.py # Übersetzungs-Cache & Sprachumschaltung (DE/EN)
|
||||||
│ │ ├── sql_queries.py # Alle SQL-Statements & User-DB-DDL
|
│ │ ├── sql_queries.py # Alle SQL-Statements & User-DB-DDL
|
||||||
│ │ ├── internal_base.sql # Vollständiger SQL-Seed (nur für manuelle DB-Neuerstellung)
|
│ │ ├── sql/ # Modulare Seed-Skripte (01_allgemein.sql, 02_blackjack.sql, 03_poker.sql, ...)
|
||||||
│ │ └── internal_base.db # Fertig mitgelieferte Read-Only-Stammdatenbank
|
│ │ └── internal_base.db # Fertig mitgelieferte Read-Only-Stammdatenbank
|
||||||
│ ├── fonts/ # Lokale TTF-Schriften (OldLondon.ttf, OldLondonAlternate.ttf)
|
│ ├── fonts/ # Lokale TTF-Schriften (OldLondon.ttf, OldLondonAlternate.ttf)
|
||||||
│ ├── images/ # UI-Grafiken, Banner, Tischhintergründe (poker_table.jpg, general_table.jpg)
|
│ ├── images/ # UI-Grafiken, Rahmenboxen, Switch-Assets & Tischhintergründe
|
||||||
│ │ ├── cards/default/ # Spielkarten-Grafiken & Kartenrücken
|
│ │ ├── cards/default/ # Spielkarten-Grafiken & Kartenrücken
|
||||||
│ │ └── game_icons/ # Modulspezifische Spiel-Icons (*.ico) für Hauptmenü-Kacheln
|
│ │ └── game_icons/ # Modulspezifische Spiel-Icons (*.ico) für Hauptmenü-Kacheln
|
||||||
│ └── sounds/ # Musik (Beyond_The_Iron_Gate, The_Midnight_Hand) & SFX
|
│ └── sounds/ # Musik (Beyond_The_Iron_Gate, The_Midnight_Hand) & SFX
|
||||||
├── view/
|
├── view/
|
||||||
│ ├── main_window.py # Hauptfenster-Container & Hintergrund-Skalierung
|
│ ├── main_window.py # Hauptfenster-Container & Hintergrund-Skalierung
|
||||||
│ ├── assets_manager.py # PIL/ImageTk-Cache für Karten, Banner, Buttons & GIF-Frames
|
│ ├── assets_manager.py # PIL/ImageTk-Cache für Karten, Rahmenboxen, Buttons & Hintergrund-Slices
|
||||||
│ ├── font_loader.py # Plattformübergreifender TTF-Loader & Georgia->OldLondon-Bridge
|
│ ├── font_loader.py # Plattformübergreifender TTF-Loader & OldLondon-Textrenderer
|
||||||
|
│ ├── unified_stats_view.py # Zentrale Vollbild-Statistikansicht für alle Spiele & Goldbeutel
|
||||||
│ ├── window_state.py # Speicherung/Wiederherstellung von Fenstergröße & Position
|
│ ├── window_state.py # Speicherung/Wiederherstellung von Fenstergröße & Position
|
||||||
│ ├── dialogs/ # Globale Overlays (z. B. AudioSettingsDialog)
|
│ ├── dialogs/ # Kombinierter Einstellungs-Dialog (Sprache, Hover-Hilfe & Audio)
|
||||||
│ ├── menus/ # LoginView, MainMenuView (mit Game-Icons), StatisticsView
|
│ ├── menus/ # LoginView & MainMenuView (mit Game-Icons)
|
||||||
│ └── widgets/ # ImageButton, BotSetupWidget, StatsBoardWidget, InfoBadge
|
│ └── widgets/ # GothTopbar, ImageButton (mit Hover-Tip), GothSwitch, GothDropdown, ...
|
||||||
└── games/
|
└── games/
|
||||||
├── blackjack/ # Eigenständiges Blackjack-Modul (MVC + eigene README.md)
|
├── blackjack/ # Eigenständiges Blackjack-Modul (MVC + eigene README.md)
|
||||||
├── poker/ # Eigenständiges 6-Max Texas Hold'em-Modul (MVC + eigene README.md)
|
├── poker/ # Eigenständiges 6-Max Texas Hold'em-Modul inkl. PokerHandsOverlay
|
||||||
└── solitaire/ # Solitaire-Suite (inkl. Architektur-README.md)
|
└── solitaire/ # Solitaire-Suite (inkl. Architektur-README.md)
|
||||||
├── base/ # Gemeinsame Engine, CardFlightAnimator, Tisch-Theme & StatsView
|
├── base/ # SolitaireCard, SolitaireBaseEngine, SolitaireBottomBar, Animator & Theme
|
||||||
├── klondike/ # Klondike (Draw 1 & Draw 3, Solver, MVC + eigene README.md)
|
├── klondike/ # Klondike (Draw 1 & Draw 3, Solver, MVC + eigene README.md)
|
||||||
├── freecell/ # FreeCell (Supermove-Formel, Solver, MVC + eigene README.md)
|
├── freecell/ # FreeCell (Supermove-Formel, Solver, MVC + eigene README.md)
|
||||||
└── spider_solitaire/ # Spider Solitaire (1/2/4 Farben, Generator, MVC + eigene README.md)
|
└── spider_solitaire/ # Spider Solitaire (1/2/4 Farben, Generator, MVC + eigene README.md)
|
||||||
|
|
@ -131,18 +138,22 @@ python3 build.py --target current
|
||||||
python3 build.py --target all
|
python3 build.py --target all
|
||||||
~~~
|
~~~
|
||||||
|
|
||||||
#### D. Hinweis zur Stammdatenbank (`internal_base.db`)
|
#### D. Stammdatenbank (`internal_base.db`) & Qualitätsprüfung
|
||||||
Die Datei `resources/code_res/internal_base.db` wird **komplett fertig und einsatzbereit mitgeliefert** – im normalen Betrieb oder beim Bauen muss nichts an der Datenbank gemacht werden.
|
Die Datei `resources/code_res/internal_base.db` wird **komplett fertig und einsatzbereit mitgeliefert**.
|
||||||
Die Datei `internal_base.sql` enthält den gesamten Datenbestand als Voll-Backup und wird **ausschließlich dann** benötigt, wenn man die Stammdatenbank absichtlich von Hand modifiziert oder beschädigt hat und sie komplett frisch aufbauen möchte:
|
Werden während der Entwicklung Übersetzungen oder Spielvarianten in `resources/code_res/sql/*.sql` geändert, lässt sich die Datenbank jederzeit neu erzeugen und statisch gegen alle `t(...)`-Aufrufe sowie Architektur-Regeln prüfen:
|
||||||
~~~bash
|
~~~powershell
|
||||||
sqlite3 resources/code_res/internal_base.db < resources/code_res/internal_base.sql
|
# Stammdatenbank neu aufbauen & alle i18n-Keys (inkl. verschachtelter Konstanten) prüfen:
|
||||||
|
.\build_scripts\check_i18n.ps1 -RebuildDb
|
||||||
|
|
||||||
|
# Projektweit prüfen, dass jede Python-Datei maximal eine Klasse enthält:
|
||||||
|
.\build_scripts\check_multi_class_files.ps1
|
||||||
~~~
|
~~~
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 6. Architektur-Richtlinien
|
### 6. Architektur-Richtlinien
|
||||||
1. **Striktes 1-Klasse-pro-Datei-Prinzip** für klare Zuständigkeiten.
|
1. **Striktes 1-Klasse-pro-Datei-Prinzip** für klare Zuständigkeiten (automatisiert prüfbar via `check_multi_class_files.ps1`).
|
||||||
2. **Keine Hardcodings:** Alle UI-Texte (`DE`/`EN`) liegen in `base_i18n`, SQL-Abfragen in `sql_queries.py`, Konstanten in `game_constants.py`.
|
2. **Keine Hardcodings:** Alle UI-Texte (`DE`/`EN`) liegen in `base_i18n` (`resources/code_res/sql/`), SQL-Abfragen in `sql_queries.py`, Konstanten in `game_constants.py`.
|
||||||
3. **Plugin-Einstiegspunkt:** Jedes Spielmodul besitzt eine `start.py` mit `GAME_TITLE_KEY`, `GAME_FOLDER_ID`, `GAME_CATEGORY` und `start_game(context)` und wird automatisch vom `GameLoader` eingebunden.
|
3. **Plugin-Einstiegspunkt:** Jedes Spielmodul besitzt eine `start.py` mit `GAME_TITLE_KEY`, `GAME_FOLDER_ID`, `GAME_CATEGORY` und `start_game(context)` und wird automatisch vom `GameLoader` eingebunden.
|
||||||
4. **Zeilenenden:** Über `.gitattributes` werden plattformübergreifend saubere `LF`-Zeilenenden für Quellcode und SQL-Dateien erzwungen.
|
4. **Zeilenenden:** Über `.gitattributes` werden plattformübergreifend saubere `LF`-Zeilenenden für Quellcode und SQL-Dateien erzwungen.
|
||||||
|
|
||||||
|
|
@ -171,6 +182,10 @@ Every game runs as a self-contained module with **strictly isolated progression
|
||||||
* **XP-to-Gold Exchange:** Base rate of `10,000 XP` for `+10 Gold` drawn strictly from that specific game's XP pool.
|
* **XP-to-Gold Exchange:** Base rate of `10,000 XP` for `+10 Gold` drawn strictly from that specific game's XP pool.
|
||||||
* **Divine Punishment:** Once a profile has ever reached *Deity* in a game, exchanging XP costs $10\times$ the average XP of the previous level, dropping no lower than the floor of *Creator Spirit V*.
|
* **Divine Punishment:** Once a profile has ever reached *Deity* in a game, exchanging XP costs $10\times$ the average XP of the previous level, dropping no lower than the floor of *Creator Spirit V*.
|
||||||
* **The Devil's Deal:** At the *Creator Spirit V* floor, players may permanently sacrifice another soul profile (holding at least **Support I** in that **exact same game**) for `+10 Gold`. Active pacts lock navigation and enforce auto-save/resume until the hand is resolved.
|
* **The Devil's Deal:** At the *Creator Spirit V* floor, players may permanently sacrifice another soul profile (holding at least **Support I** in that **exact same game**) for `+10 Gold`. Active pacts lock navigation and enforce auto-save/resume until the hand is resolved.
|
||||||
|
* **Unified HUD, Statistics & Settings Architecture:**
|
||||||
|
* **Centralized Bars (`GothTopbar` & `SolitaireBottomBar`):** Streamlined universal topbar (featuring zero-relayout Level/XP badge updates) paired with a framed bottom HUD & action bar with dynamic left/right overflow wings for compact screens (such as `1366×768`).
|
||||||
|
* **Unified Statistics Overlay (`UnifiedStatsView`):** Single full-screen overlay accessible from any active table without destroying the underlying game state, featuring filters for overall profile stats, individual games, variants, and Blackjack/Poker Gold pouches.
|
||||||
|
* **Combined Settings Dialog, `GothSwitch` & Hover Tooltips:** Combines live **DE / EN** language switching, dual-channel audio sliders (Ambiance/Music & SFX), and a custom-animated toggle switch (`GothSwitch`) that globally enables or disables clean `Helvetica` hover tooltips across action buttons.
|
||||||
* **Shared Solitaire Framework (`games/solitaire/base/`):**
|
* **Shared Solitaire Framework (`games/solitaire/base/`):**
|
||||||
* **Guaranteed Solvable Deals & 4 Difficulty Tiers:** Pre-verified deals via dedicated solvers and constructive reverse generators ranging from *Tier 1 – Acolyte (Easy)* to *Tier 4 – Deity (Merciless)*.
|
* **Guaranteed Solvable Deals & 4 Difficulty Tiers:** Pre-verified deals via dedicated solvers and constructive reverse generators ranging from *Tier 1 – Acolyte (Easy)* to *Tier 4 – Deity (Merciless)*.
|
||||||
* **Smooth 60fps Animations (`CardFlightAnimator`):** Non-blocking cubic ease-out card flights, invalid-drop snap-back, and zero-lag `flush()` during rapid click sequences.
|
* **Smooth 60fps Animations (`CardFlightAnimator`):** Non-blocking cubic ease-out card flights, invalid-drop snap-back, and zero-lag `flush()` during rapid click sequences.
|
||||||
|
|
@ -178,10 +193,9 @@ Every game runs as a self-contained module with **strictly isolated progression
|
||||||
* **7 AI Difficulty Tiers (Level 0 to Level 6 "Deity"):**
|
* **7 AI Difficulty Tiers (Level 0 to Level 6 "Deity"):**
|
||||||
* Configurable opponent seats with persistent names and AI levels per table game (`bot_configs`).
|
* Configurable opponent seats with persistent names and AI levels per table game (`bot_configs`).
|
||||||
* **Gothic UI, Game Tile Icons, Bundled Fonts & Cross-Platform Integration:**
|
* **Gothic UI, Game Tile Icons, Bundled Fonts & Cross-Platform Integration:**
|
||||||
* Custom per-game icons (`resources/images/game_icons/*.ico`) rendered on main menu tiles with automatic badge cropping and rounded supersampled corners, paired with a framed damask table background (`general_table.jpg`) with frame-aware card insets across all Solitaire tables.
|
* Custom per-game icons (`resources/images/game_icons/*.ico`) rendered on main menu tiles with automatic badge cropping and rounded supersampled corners, transparent RGBA tables (`poker_table.png`) with dynamic box sizing (`box_background.png`), and seamless background slicing.
|
||||||
* Runtime `.ttf` font loader (`OldLondon.ttf`, `OldLondonAlternate.ttf`) requiring zero OS-level font installation on **Windows**, **Linux**, **ChromeOS (Crostini)**, and **macOS**.
|
* Runtime `.ttf` font loader (`OldLondon.ttf`, `OldLondonAlternate.ttf`) requiring zero OS-level font installation on **Windows**, **Linux**, **ChromeOS (Crostini)**, and **macOS**.
|
||||||
* Cross-platform window & taskbar icon support (`game_icon.ico`) plus automatic window size, position, and maximized/fullscreen persistence (`WindowStatePersistence`).
|
* Cross-platform window & taskbar icon support (`game_icon.ico`) plus automatic window size, position, and maximized/fullscreen persistence (`WindowStatePersistence`).
|
||||||
* Live **DE / EN** localization and dual-channel audio controls (Ambiance/Music & SFX).
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -189,9 +203,9 @@ Every game runs as a self-contained module with **strictly isolated progression
|
||||||
|
|
||||||
| Category | Game | Status | Variants & Highlights | Module Docs |
|
| Category | Game | Status | Variants & Highlights | Module Docs |
|
||||||
| :--- | :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
| **Luck** | **Blackjack** | Playable | *Classic* (2 Decks) & *High Stakes* (6 Decks), up to 3 Bots, Devil's Gambit betting tree, Split/Double, `7-7-7` instant win | [`games/blackjack/README.md`](games/blackjack/README.md) |
|
| **Luck** | **Blackjack** | Playable | *Classic* (2 Decks) & *High Stakes* (6 Decks), up to 4 corner Bots, Devil's Gambit betting tree, Split/Double, `7-7-7` instant win, hover tooltips | [`games/blackjack/README.md`](games/blackjack/README.md) |
|
||||||
| **Luck** | **Texas Hold'em** | Playable | *Classic* & *High Stakes*, 6-Max Arena (1–5 Bots), equal entry ante, Pre-Flop to Showdown, All-In & Side Pots, info tooltips | [`games/poker/README.md`](games/poker/README.md) |
|
| **Luck** | **Texas Hold'em** | Playable | *Classic* & *High Stakes*, full-canvas 6-Max Arena (1–5 Bots), equal entry ante, Pre-Flop to Showdown, All-In & Side Pots, spoiler-free *Card Reference* (`PokerHandsOverlay`) & hover tooltips | [`games/poker/README.md`](games/poker/README.md) |
|
||||||
| **Solo** | **Solitaire Core** | Active | Shared engine, `CardFlightAnimator`, `SolitaireTableBgRenderer`, auto-save/resume & in-game stats view | [`games/solitaire/README.md`](games/solitaire/README.md) |
|
| **Solo** | **Solitaire Core** | Active | Shared engine (`SolitaireCard` + `SolitaireBaseEngine`), `SolitaireBottomBar`, `CardFlightAnimator`, `SolitaireTableBgRenderer` & auto-save/resume | [`games/solitaire/README.md`](games/solitaire/README.md) |
|
||||||
| **Solo** | **Klondike** | Playable | *Draw 1* & *Draw 3*, 7 cascades, pre-deal solver, 4 difficulty tiers, 3-cycle stagnation lock & Auto-Finish | [`games/solitaire/klondike/README.md`](games/solitaire/klondike/README.md) |
|
| **Solo** | **Klondike** | Playable | *Draw 1* & *Draw 3*, 7 cascades, pre-deal solver, 4 difficulty tiers, 3-cycle stagnation lock & Auto-Finish | [`games/solitaire/klondike/README.md`](games/solitaire/klondike/README.md) |
|
||||||
| **Solo** | **FreeCell** | Playable | *Standard*, 8 open cascades, 4 FreeCells, exact Supermove formula, best-first solver & smart auto-move | [`games/solitaire/freecell/README.md`](games/solitaire/freecell/README.md) |
|
| **Solo** | **FreeCell** | Playable | *Standard*, 8 open cascades, 4 FreeCells, exact Supermove formula, best-first solver & smart auto-move | [`games/solitaire/freecell/README.md`](games/solitaire/freecell/README.md) |
|
||||||
| **Solo** | **Spider Solitaire** | Playable | *1 Suit*, *2 Suits* & *4 Suits*, 104 cards across 10 columns, strict deal rule, constructive deal generator & 8 run slots | [`games/solitaire/spider_solitaire/README.md`](games/solitaire/spider_solitaire/README.md) |
|
| **Solo** | **Spider Solitaire** | Playable | *1 Suit*, *2 Suits* & *4 Suits*, 104 cards across 10 columns, strict deal rule, constructive deal generator & 8 run slots | [`games/solitaire/spider_solitaire/README.md`](games/solitaire/spider_solitaire/README.md) |
|
||||||
|
|
@ -223,9 +237,21 @@ python3 build.py --target current
|
||||||
python3 build.py --target all
|
python3 build.py --target all
|
||||||
~~~
|
~~~
|
||||||
|
|
||||||
#### D. Static Core Database (`internal_base.db`)
|
#### D. Static Core Database (`internal_base.db`) & QA Scripts
|
||||||
`resources/code_res/internal_base.db` is **shipped ready-to-use** out of the box—no database setup step is needed.
|
`resources/code_res/internal_base.db` is **shipped ready-to-use** out of the box—no database setup step is needed to play.
|
||||||
The full seed script `internal_base.sql` is only required if you intentionally edited the static core data yourself or manually corrupted `internal_base.db` and wish to rebuild it from scratch:
|
When modifying localization keys or variants inside `resources/code_res/sql/*.sql`, you can rebuild the database and run full static verification via PowerShell:
|
||||||
~~~bash
|
~~~powershell
|
||||||
sqlite3 resources/code_res/internal_base.db < resources/code_res/internal_base.sql
|
# Rebuild internal_base.db & verify all t(...) keys (including nested constants & placeholders):
|
||||||
|
.\build_scripts\check_i18n.ps1 -RebuildDb
|
||||||
|
|
||||||
|
# Enforce the strict one-class-per-file rule across the entire codebase:
|
||||||
|
.\build_scripts\check_multi_class_files.ps1
|
||||||
~~~
|
~~~
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5. Architecture Guidelines
|
||||||
|
1. **Strict One-Class-Per-File Rule** for clean separation of concerns (verifiable via `check_multi_class_files.ps1`).
|
||||||
|
2. **Zero Hardcoding:** All localized strings (`DE`/`EN`) live in `base_i18n` (`resources/code_res/sql/`), SQL statements in `sql_queries.py`, and constants in `game_constants.py`.
|
||||||
|
3. **Plugin Entry Point:** Every game module exposes a `start.py` defining `GAME_TITLE_KEY`, `GAME_FOLDER_ID`, `GAME_CATEGORY`, and `start_game(context)` for automatic discovery by `GameLoader`.
|
||||||
|
4. **Line Endings:** `.gitattributes` enforces clean `LF` line endings across source and SQL files on all platforms.
|
||||||
|
|
@ -71,6 +71,12 @@ if "%DO_WIN%"=="0" if "%DO_UNIX%"=="0" if "%DO_OSX%"=="0" (
|
||||||
set "RAW_ARGS=--Win"
|
set "RAW_ARGS=--Win"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
REM --- Echte Lauf-Erfolgsflags initialisieren ---
|
||||||
|
set "WIN_OK=0"
|
||||||
|
set "UNIX_OK=0"
|
||||||
|
set "OSX_OK=0"
|
||||||
|
set "ANY_FAILED=0"
|
||||||
|
|
||||||
REM ----------------------------------------------------
|
REM ----------------------------------------------------
|
||||||
REM 0. RECHTE- & ABHAENGIGKEITS-PRUEFUNG (nur fuer --Win noetig!)
|
REM 0. RECHTE- & ABHAENGIGKEITS-PRUEFUNG (nur fuer --Win noetig!)
|
||||||
REM ----------------------------------------------------
|
REM ----------------------------------------------------
|
||||||
|
|
@ -136,75 +142,14 @@ REM ====================================================
|
||||||
if "%DO_WIN%"=="1" (
|
if "%DO_WIN%"=="1" (
|
||||||
echo.
|
echo.
|
||||||
echo ---^> [WIN] Baue Windows Single-File .exe...
|
echo ---^> [WIN] Baue Windows Single-File .exe...
|
||||||
call :FIND_PYTHON
|
if exist "%PROJECT_ROOT%\dist\windows" rmdir /s /q "%PROJECT_ROOT%\dist\windows"
|
||||||
if "!WIN_PY!"=="" (
|
call :BUILD_WIN_TARGET
|
||||||
echo [BOOTSTRAP] Installiere Python 3.11 via winget...
|
|
||||||
winget install -e --id Python.Python.3.11 --scope machine --accept-source-agreements --accept-package-agreements
|
|
||||||
for %%P in ("%ProgramFiles%\Python311" "%LocalAppData%\Programs\Python\Python311" "C:\Python311") do (
|
|
||||||
if exist "%%~P\python.exe" set "PATH=%%~P;%%~P\Scripts;!PATH!"
|
|
||||||
)
|
|
||||||
call :FIND_PYTHON
|
|
||||||
)
|
|
||||||
if "!WIN_PY!"=="" (
|
|
||||||
echo [ERROR] Python 3.11+ nicht gefunden!
|
|
||||||
exit /b 1
|
|
||||||
)
|
|
||||||
|
|
||||||
if "!DB_REBUILT!"=="0" (
|
|
||||||
call :REBUILD_INTERNAL_DB
|
|
||||||
if errorlevel 1 (
|
|
||||||
echo [ERROR] Erstellung von internal_base.db fehlgeschlagen!
|
|
||||||
if "%IS_ELEVATED%"=="1" pause
|
|
||||||
exit /b 1
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
!WIN_PY! -m pip --version >nul 2>nul
|
|
||||||
if errorlevel 1 !WIN_PY! -m ensurepip --upgrade
|
|
||||||
|
|
||||||
!WIN_PY! -c "import PIL, pygame, PyInstaller" >nul 2>nul
|
|
||||||
if errorlevel 1 (
|
if errorlevel 1 (
|
||||||
echo [BOOTSTRAP] Installiere Pillow, Pygame ^& PyInstaller...
|
set "WIN_OK=0"
|
||||||
!WIN_PY! -m pip install --upgrade pip pillow pygame pyinstaller
|
set "ANY_FAILED=1"
|
||||||
if errorlevel 1 exit /b 1
|
) else (
|
||||||
|
set "WIN_OK=1"
|
||||||
)
|
)
|
||||||
|
|
||||||
set "ICON_ARG="
|
|
||||||
if exist "%PROJECT_ROOT%\resources\images\game_icon.ico" (
|
|
||||||
set "ICON_ARG=--icon %PROJECT_ROOT%\resources\images\game_icon.ico"
|
|
||||||
)
|
|
||||||
|
|
||||||
!WIN_PY! -m PyInstaller ^
|
|
||||||
--noconfirm ^
|
|
||||||
--noconsole ^
|
|
||||||
--onefile ^
|
|
||||||
--clean ^
|
|
||||||
--distpath "%PROJECT_ROOT%\dist\windows" ^
|
|
||||||
--workpath "%PROJECT_ROOT%\build\windows" ^
|
|
||||||
--specpath "%PROJECT_ROOT%\build\windows" ^
|
|
||||||
!ICON_ARG! ^
|
|
||||||
--add-data "%PROJECT_ROOT%\resources;resources" ^
|
|
||||||
--add-data "%PROJECT_ROOT%\games;games" ^
|
|
||||||
--collect-submodules games ^
|
|
||||||
--collect-submodules controller ^
|
|
||||||
--collect-submodules models ^
|
|
||||||
--collect-submodules view ^
|
|
||||||
--collect-submodules resources ^
|
|
||||||
--hidden-import tkinter ^
|
|
||||||
--hidden-import tkinter.ttk ^
|
|
||||||
--hidden-import tkinter.font ^
|
|
||||||
--hidden-import sqlite3 ^
|
|
||||||
--hidden-import PIL._tkinter_finder ^
|
|
||||||
--name "%APP_NAME%" ^
|
|
||||||
"%PROJECT_ROOT%\main.py"
|
|
||||||
|
|
||||||
if errorlevel 1 (
|
|
||||||
echo [ERROR] Windows-Build fehlgeschlagen!
|
|
||||||
if "%IS_ELEVATED%"=="1" pause
|
|
||||||
exit /b 1
|
|
||||||
)
|
|
||||||
if exist "%PROJECT_ROOT%\build\windows" rmdir /s /q "%PROJECT_ROOT%\build\windows"
|
|
||||||
echo [OK] Windows-Build fertig: dist\windows\%APP_NAME%.exe
|
|
||||||
)
|
)
|
||||||
|
|
||||||
REM ====================================================
|
REM ====================================================
|
||||||
|
|
@ -213,7 +158,14 @@ REM ====================================================
|
||||||
if "%DO_UNIX%"=="1" (
|
if "%DO_UNIX%"=="1" (
|
||||||
echo.
|
echo.
|
||||||
echo ---^> [UNIX] Baue Linux Executable via VirtualBox VM "%UNIX_VM_NAME%"...
|
echo ---^> [UNIX] Baue Linux Executable via VirtualBox VM "%UNIX_VM_NAME%"...
|
||||||
|
if exist "%PROJECT_ROOT%\dist\linux" rmdir /s /q "%PROJECT_ROOT%\dist\linux"
|
||||||
call :RUN_UNIX_VM_BUILD
|
call :RUN_UNIX_VM_BUILD
|
||||||
|
if errorlevel 1 (
|
||||||
|
set "UNIX_OK=0"
|
||||||
|
set "ANY_FAILED=1"
|
||||||
|
) else (
|
||||||
|
set "UNIX_OK=1"
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
REM ====================================================
|
REM ====================================================
|
||||||
|
|
@ -222,34 +174,47 @@ REM ====================================================
|
||||||
if "%DO_OSX%"=="1" (
|
if "%DO_OSX%"=="1" (
|
||||||
echo.
|
echo.
|
||||||
echo ---^> [OSX] Baue macOS Binary via VirtualBox VM "%OSX_VM_NAME%"...
|
echo ---^> [OSX] Baue macOS Binary via VirtualBox VM "%OSX_VM_NAME%"...
|
||||||
|
if exist "%PROJECT_ROOT%\dist\macos" rmdir /s /q "%PROJECT_ROOT%\dist\macos"
|
||||||
call :RUN_OSX_VM_BUILD
|
call :RUN_OSX_VM_BUILD
|
||||||
|
if errorlevel 1 (
|
||||||
|
set "OSX_OK=0"
|
||||||
|
set "ANY_FAILED=1"
|
||||||
|
) else (
|
||||||
|
set "OSX_OK=1"
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
echo.
|
echo.
|
||||||
echo ====================================================
|
echo ====================================================
|
||||||
echo BUILD-ZUSAMMENFASSUNG ^(nur angeforderte Ziele^):
|
echo BUILD-ZUSAMMENFASSUNG ^(nur angeforderte Ziele^):
|
||||||
if "%DO_WIN%"=="1" (
|
if "%DO_WIN%"=="1" (
|
||||||
if exist "%PROJECT_ROOT%\dist\windows\%APP_NAME%.exe" (
|
if "!WIN_OK!"=="1" if exist "%PROJECT_ROOT%\dist\windows\%APP_NAME%.exe" (
|
||||||
echo [WIN] OK: dist\windows\%APP_NAME%.exe
|
echo [WIN] OK: dist\windows\%APP_NAME%.exe
|
||||||
) else (
|
) else (
|
||||||
echo [WIN] FEHLGESCHLAGEN
|
echo [WIN] FEHLGESCHLAGEN!
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if "%DO_UNIX%"=="1" (
|
if "%DO_UNIX%"=="1" (
|
||||||
if exist "%PROJECT_ROOT%\dist\linux\%APP_NAME%" (
|
if "!UNIX_OK!"=="1" if exist "%PROJECT_ROOT%\dist\linux\%APP_NAME%" (
|
||||||
echo [UNIX] OK: dist\linux\%APP_NAME% ^(+ %APP_NAME%_Linux.tar.gz^)
|
echo [UNIX] OK: dist\linux\%APP_NAME% ^(+ %APP_NAME%_Linux.tar.gz^)
|
||||||
) else (
|
) else (
|
||||||
echo [UNIX] FEHLGESCHLAGEN
|
echo [UNIX] FEHLGESCHLAGEN! ^(VM "%UNIX_VM_NAME%" nicht erreichbar oder Build abgebrochen^)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if "%DO_OSX%"=="1" (
|
if "%DO_OSX%"=="1" (
|
||||||
if exist "%PROJECT_ROOT%\dist\macos\%APP_NAME%" (
|
if "!OSX_OK!"=="1" if exist "%PROJECT_ROOT%\dist\macos\%APP_NAME%" (
|
||||||
echo [OSX] OK: dist\macos\%APP_NAME% ^(+ %APP_NAME%.app + %APP_NAME%_macOS.tar.gz^)
|
echo [OSX] OK: dist\macos\%APP_NAME% ^(+ %APP_NAME%.app + %APP_NAME%_macOS.tar.gz^)
|
||||||
) else (
|
) else (
|
||||||
echo [OSX] FEHLGESCHLAGEN
|
echo [OSX] FEHLGESCHLAGEN! ^(VM "%OSX_VM_NAME%" nicht erreichbar oder Build abgebrochen^)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
echo ====================================================
|
echo ====================================================
|
||||||
|
if "!ANY_FAILED!"=="1" (
|
||||||
|
echo [ERROR] Mindestens ein angefordertes Build-Ziel ist fehlgeschlagen!
|
||||||
|
if "%IS_ELEVATED%"=="1" pause
|
||||||
|
endlocal
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
if "%IS_ELEVATED%"=="1" pause
|
if "%IS_ELEVATED%"=="1" pause
|
||||||
endlocal
|
endlocal
|
||||||
exit /b 0
|
exit /b 0
|
||||||
|
|
@ -258,6 +223,84 @@ exit /b 0
|
||||||
REM ====================================================
|
REM ====================================================
|
||||||
REM HILFSROUTINEN
|
REM HILFSROUTINEN
|
||||||
REM ====================================================
|
REM ====================================================
|
||||||
|
:BUILD_WIN_TARGET
|
||||||
|
call :FIND_PYTHON
|
||||||
|
if "!WIN_PY!"=="" (
|
||||||
|
echo [BOOTSTRAP] Installiere Python 3.11 via winget...
|
||||||
|
winget install -e --id Python.Python.3.11 --scope machine --accept-source-agreements --accept-package-agreements
|
||||||
|
for %%P in ("%ProgramFiles%\Python311" "%LocalAppData%\Programs\Python\Python311" "C:\Python311") do (
|
||||||
|
if exist "%%~P\python.exe" set "PATH=%%~P;%%~P\Scripts;!PATH!"
|
||||||
|
)
|
||||||
|
call :FIND_PYTHON
|
||||||
|
)
|
||||||
|
if "!WIN_PY!"=="" (
|
||||||
|
echo [ERROR] Python 3.11+ nicht gefunden!
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
if "!DB_REBUILT!"=="0" (
|
||||||
|
call :REBUILD_INTERNAL_DB
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
!WIN_PY! -m pip --version >nul 2>nul
|
||||||
|
if errorlevel 1 !WIN_PY! -m ensurepip --upgrade
|
||||||
|
|
||||||
|
!WIN_PY! -c "import PIL, pygame, PyInstaller" >nul 2>nul
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo [BOOTSTRAP] Installiere Pillow, Pygame ^& PyInstaller...
|
||||||
|
!WIN_PY! -m pip install --upgrade pip pillow pygame pyinstaller
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
set "ICON_ARG="
|
||||||
|
if exist "%PROJECT_ROOT%\resources\images\game_icon.ico" (
|
||||||
|
set "ICON_ARG=--icon %PROJECT_ROOT%\resources\images\game_icon.ico"
|
||||||
|
)
|
||||||
|
|
||||||
|
set "VER_ARG="
|
||||||
|
if exist "%PROJECT_ROOT%\build_scripts\version_info.txt" (
|
||||||
|
set "VER_ARG=--version-file %PROJECT_ROOT%\build_scripts\version_info.txt"
|
||||||
|
)
|
||||||
|
|
||||||
|
!WIN_PY! -m PyInstaller ^
|
||||||
|
--noconfirm ^
|
||||||
|
--noconsole ^
|
||||||
|
--onefile ^
|
||||||
|
--noupx ^
|
||||||
|
--clean ^
|
||||||
|
--distpath "%PROJECT_ROOT%\dist\windows" ^
|
||||||
|
--workpath "%PROJECT_ROOT%\build\windows" ^
|
||||||
|
--specpath "%PROJECT_ROOT%\build\windows" ^
|
||||||
|
!ICON_ARG! ^
|
||||||
|
!VER_ARG! ^
|
||||||
|
--add-data "%PROJECT_ROOT%\resources;resources" ^
|
||||||
|
--add-data "%PROJECT_ROOT%\games;games" ^
|
||||||
|
--collect-submodules games ^
|
||||||
|
--collect-submodules controller ^
|
||||||
|
--collect-submodules models ^
|
||||||
|
--collect-submodules view ^
|
||||||
|
--collect-submodules resources ^
|
||||||
|
--hidden-import tkinter ^
|
||||||
|
--hidden-import tkinter.ttk ^
|
||||||
|
--hidden-import tkinter.font ^
|
||||||
|
--hidden-import sqlite3 ^
|
||||||
|
--hidden-import PIL._tkinter_finder ^
|
||||||
|
--name "%APP_NAME%" ^
|
||||||
|
"%PROJECT_ROOT%\main.py"
|
||||||
|
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo [ERROR] Windows-Build fehlgeschlagen!
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
if exist "%PROJECT_ROOT%\build\windows" rmdir /s /q "%PROJECT_ROOT%\build\windows"
|
||||||
|
if not exist "%PROJECT_ROOT%\dist\windows\%APP_NAME%.exe" (
|
||||||
|
echo [ERROR] Erwartete Datei dist\windows\%APP_NAME%.exe wurde nicht erzeugt!
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
echo [OK] Windows-Build fertig: dist\windows\%APP_NAME%.exe
|
||||||
|
exit /b 0
|
||||||
|
|
||||||
:REBUILD_INTERNAL_DB
|
:REBUILD_INTERNAL_DB
|
||||||
set "REBUILD_PY="
|
set "REBUILD_PY="
|
||||||
if exist "%PROJECT_ROOT%\build_scripts\rebuild_internal_db.py" (
|
if exist "%PROJECT_ROOT%\build_scripts\rebuild_internal_db.py" (
|
||||||
|
|
@ -266,11 +309,18 @@ if exist "%PROJECT_ROOT%\build_scripts\rebuild_internal_db.py" (
|
||||||
if exist "%PROJECT_ROOT%\rebuild_internal_db.py" (
|
if exist "%PROJECT_ROOT%\rebuild_internal_db.py" (
|
||||||
set "REBUILD_PY=%PROJECT_ROOT%\rebuild_internal_db.py"
|
set "REBUILD_PY=%PROJECT_ROOT%\rebuild_internal_db.py"
|
||||||
)
|
)
|
||||||
if not "!REBUILD_PY!"=="" if exist "%PROJECT_ROOT%\resources\code_res\sql" (
|
if not "!REBUILD_PY!"=="" (
|
||||||
echo ---^> [DB] Aktualisiere internal_base.db aus modularen SQL-Dateien...
|
if exist "%PROJECT_ROOT%\build_scripts\sql" (
|
||||||
!WIN_PY! "!REBUILD_PY!"
|
echo ---^> [DB] Aktualisiere internal_base.db aus modularen SQL-Dateien...
|
||||||
if errorlevel 1 exit /b 1
|
!WIN_PY! "!REBUILD_PY!"
|
||||||
set "DB_REBUILT=1"
|
if errorlevel 1 exit /b 1
|
||||||
|
set "DB_REBUILT=1"
|
||||||
|
) else if exist "%PROJECT_ROOT%\resources\code_res\sql" (
|
||||||
|
echo ---^> [DB] Aktualisiere internal_base.db aus modularen SQL-Dateien...
|
||||||
|
!WIN_PY! "!REBUILD_PY!"
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
set "DB_REBUILT=1"
|
||||||
|
)
|
||||||
)
|
)
|
||||||
exit /b 0
|
exit /b 0
|
||||||
|
|
||||||
|
|
@ -315,16 +365,25 @@ if "!VBOX_MANAGE!"=="" if exist "D:\Program Files\Oracle\VirtualBox\VBoxManage.e
|
||||||
)
|
)
|
||||||
exit /b 0
|
exit /b 0
|
||||||
|
|
||||||
|
:PRINT_AVAILABLE_VMS
|
||||||
|
echo [HINWEIS] Registrierte VirtualBox-VMs fuer Benutzer "%USERNAME%":
|
||||||
|
"!VBOX_MANAGE!" list vms
|
||||||
|
if "%IS_ADMIN%"=="1" (
|
||||||
|
echo [HINWEIS] Das Skript laeuft als Administrator ^(ggf. anderes VirtualBox-Benutzerverzeichnis^)!
|
||||||
|
)
|
||||||
|
exit /b 0
|
||||||
|
|
||||||
:RUN_UNIX_VM_BUILD
|
:RUN_UNIX_VM_BUILD
|
||||||
call :FIND_VBOX
|
call :FIND_VBOX
|
||||||
if "!VBOX_MANAGE!"=="" (
|
if "!VBOX_MANAGE!"=="" (
|
||||||
echo [SKIP] VBoxManage.exe nicht gefunden - ueberspringe Linux-VM-Build.
|
echo [ERROR] VBoxManage.exe nicht gefunden - Linux-VM-Build fehlgeschlagen!
|
||||||
exit /b 1
|
exit /b 1
|
||||||
)
|
)
|
||||||
|
|
||||||
"!VBOX_MANAGE!" showvminfo "%UNIX_VM_NAME%" >nul 2>nul
|
"!VBOX_MANAGE!" showvminfo "%UNIX_VM_NAME%" >nul 2>nul
|
||||||
if errorlevel 1 (
|
if errorlevel 1 (
|
||||||
echo [ERROR] VirtualBox-VM "%UNIX_VM_NAME%" nicht gefunden!
|
echo [ERROR] VirtualBox-VM "%UNIX_VM_NAME%" nicht gefunden!
|
||||||
|
call :PRINT_AVAILABLE_VMS
|
||||||
exit /b 1
|
exit /b 1
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -364,13 +423,17 @@ echo [UNIX-VM] Aktualisiere Projektquellen in "%UNIX_VM_NAME%"...
|
||||||
set "TMP_TAR_UNIX=%TEMP%\goth_unix_src.tar.gz"
|
set "TMP_TAR_UNIX=%TEMP%\goth_unix_src.tar.gz"
|
||||||
if exist "!TMP_TAR_UNIX!" del /q "!TMP_TAR_UNIX!"
|
if exist "!TMP_TAR_UNIX!" del /q "!TMP_TAR_UNIX!"
|
||||||
tar -czf "!TMP_TAR_UNIX!" --exclude=".git" --exclude="dist" --exclude="build" --exclude=".venv*" --exclude="__pycache__" -C "%PROJECT_ROOT%" .
|
tar -czf "!TMP_TAR_UNIX!" --exclude=".git" --exclude="dist" --exclude="build" --exclude=".venv*" --exclude="__pycache__" -C "%PROJECT_ROOT%" .
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
|
||||||
ssh -p %UNIX_SSH_PORT% %UNIX_SSH_USER%@%UNIX_SSH_HOST% "mkdir -p %UNIX_REMOTE_DIR% && find %UNIX_REMOTE_DIR% -mindepth 1 -maxdepth 1 ! -name '.venv' -exec rm -rf {} +"
|
ssh -p %UNIX_SSH_PORT% %UNIX_SSH_USER%@%UNIX_SSH_HOST% "mkdir -p %UNIX_REMOTE_DIR% && find %UNIX_REMOTE_DIR% -mindepth 1 -maxdepth 1 -not -name '.venv' -exec rm -rf {} +"
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
scp -P %UNIX_SSH_PORT% "!TMP_TAR_UNIX!" %UNIX_SSH_USER%@%UNIX_SSH_HOST%:%UNIX_REMOTE_DIR%/src.tar.gz
|
scp -P %UNIX_SSH_PORT% "!TMP_TAR_UNIX!" %UNIX_SSH_USER%@%UNIX_SSH_HOST%:%UNIX_REMOTE_DIR%/src.tar.gz
|
||||||
|
set "SCP_ERR=!ERRORLEVEL!"
|
||||||
del /q "!TMP_TAR_UNIX!" 2>nul
|
del /q "!TMP_TAR_UNIX!" 2>nul
|
||||||
|
if not "!SCP_ERR!"=="0" exit /b 1
|
||||||
|
|
||||||
echo [UNIX-VM] Kompiliere native Linux-ELF-Binary in der VM...
|
echo [UNIX-VM] Kompiliere native Linux-ELF-Binary in der VM...
|
||||||
ssh -t -p %UNIX_SSH_PORT% %UNIX_SSH_USER%@%UNIX_SSH_HOST% "cd %UNIX_REMOTE_DIR% && tar -xzf src.tar.gz && rm -f src.tar.gz && tr -d '\r' < build_scripts/build.sh > build_scripts/_unix.sh && mv build_scripts/_unix.sh build_scripts/build.sh && chmod +x build_scripts/build.sh && ( [ -d .venv ] || python3 -m venv .venv || (sudo apt-get update -qq && sudo apt-get install -y python3-venv python3-tk python3-pip libsdl2-dev libsdl2-image-dev libsdl2-mixer-dev libsdl2-ttf-dev libfreetype6-dev && python3 -m venv .venv) ) && ./build_scripts/build.sh --Unix && tar --warning=no-file-changed -czf dist/%APP_NAME%_Linux.tar.gz -C dist/linux ."
|
ssh -t -p %UNIX_SSH_PORT% %UNIX_SSH_USER%@%UNIX_SSH_HOST% "bash -lc 'set -e; cd %UNIX_REMOTE_DIR%; rm -rf dist build; tar -xzf src.tar.gz; rm -f src.tar.gz; tr -d \"\r\" < build_scripts/build.sh > build_scripts/_unix.sh; mv build_scripts/_unix.sh build_scripts/build.sh; chmod +x build_scripts/build.sh; if [ -d .venv ]; then :; else python3 -m venv .venv || (sudo apt-get update -qq && sudo apt-get install -y python3-venv python3-tk python3-pip libsdl2-dev libsdl2-image-dev libsdl2-mixer-dev libsdl2-ttf-dev libfreetype6-dev && python3 -m venv .venv); fi; ./build_scripts/build.sh --Unix; mkdir -p dist; rm -f dist/%APP_NAME%_Linux.tar.gz; tar --warning=no-file-changed -czf dist/%APP_NAME%_Linux.tar.gz -C dist/linux .'"
|
||||||
|
|
||||||
if errorlevel 1 (
|
if errorlevel 1 (
|
||||||
echo [ERROR] Linux-Build in der VM fehlgeschlagen!
|
echo [ERROR] Linux-Build in der VM fehlgeschlagen!
|
||||||
|
|
@ -378,9 +441,7 @@ if errorlevel 1 (
|
||||||
exit /b 1
|
exit /b 1
|
||||||
)
|
)
|
||||||
|
|
||||||
if exist "%PROJECT_ROOT%\dist\linux" rmdir /s /q "%PROJECT_ROOT%\dist\linux"
|
mkdir "%PROJECT_ROOT%\dist\linux" 2>nul
|
||||||
mkdir "%PROJECT_ROOT%\dist\linux"
|
|
||||||
|
|
||||||
echo [UNIX-VM] Lade fertiges Linux-Build nach dist\linux herunter...
|
echo [UNIX-VM] Lade fertiges Linux-Build nach dist\linux herunter...
|
||||||
scp -P %UNIX_SSH_PORT% %UNIX_SSH_USER%@%UNIX_SSH_HOST%:%UNIX_REMOTE_DIR%/dist/%APP_NAME%_Linux.tar.gz "%PROJECT_ROOT%\dist\linux\%APP_NAME%_Linux.tar.gz"
|
scp -P %UNIX_SSH_PORT% %UNIX_SSH_USER%@%UNIX_SSH_HOST%:%UNIX_REMOTE_DIR%/dist/%APP_NAME%_Linux.tar.gz "%PROJECT_ROOT%\dist\linux\%APP_NAME%_Linux.tar.gz"
|
||||||
if errorlevel 1 (
|
if errorlevel 1 (
|
||||||
|
|
@ -388,6 +449,10 @@ if errorlevel 1 (
|
||||||
exit /b 1
|
exit /b 1
|
||||||
)
|
)
|
||||||
tar -xzf "%PROJECT_ROOT%\dist\linux\%APP_NAME%_Linux.tar.gz" -C "%PROJECT_ROOT%\dist\linux"
|
tar -xzf "%PROJECT_ROOT%\dist\linux\%APP_NAME%_Linux.tar.gz" -C "%PROJECT_ROOT%\dist\linux"
|
||||||
|
if not exist "%PROJECT_ROOT%\dist\linux\%APP_NAME%" (
|
||||||
|
echo [ERROR] Linux-Binary dist\linux\%APP_NAME% fehlt nach dem Entpacken!
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
if "!UNIX_VM_WAS_RUNNING!"=="0" (
|
if "!UNIX_VM_WAS_RUNNING!"=="0" (
|
||||||
echo [UNIX-VM] Fahre Linux-VM wieder sauber herunter...
|
echo [UNIX-VM] Fahre Linux-VM wieder sauber herunter...
|
||||||
|
|
@ -399,13 +464,14 @@ exit /b 0
|
||||||
:RUN_OSX_VM_BUILD
|
:RUN_OSX_VM_BUILD
|
||||||
call :FIND_VBOX
|
call :FIND_VBOX
|
||||||
if "!VBOX_MANAGE!"=="" (
|
if "!VBOX_MANAGE!"=="" (
|
||||||
echo [SKIP] VBoxManage.exe nicht gefunden - ueberspringe macOS-VM-Build.
|
echo [ERROR] VBoxManage.exe nicht gefunden - macOS-VM-Build fehlgeschlagen!
|
||||||
exit /b 1
|
exit /b 1
|
||||||
)
|
)
|
||||||
|
|
||||||
"!VBOX_MANAGE!" showvminfo "%OSX_VM_NAME%" >nul 2>nul
|
"!VBOX_MANAGE!" showvminfo "%OSX_VM_NAME%" >nul 2>nul
|
||||||
if errorlevel 1 (
|
if errorlevel 1 (
|
||||||
echo [ERROR] VirtualBox-VM "%OSX_VM_NAME%" nicht gefunden!
|
echo [ERROR] VirtualBox-VM "%OSX_VM_NAME%" nicht gefunden!
|
||||||
|
call :PRINT_AVAILABLE_VMS
|
||||||
exit /b 1
|
exit /b 1
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -445,29 +511,35 @@ echo [OSX-VM] Aktualisiere Projektquellen in der macOS-VM ^(.venv_build_macos bl
|
||||||
set "TMP_TAR=%TEMP%\goth_osx_src.tar.gz"
|
set "TMP_TAR=%TEMP%\goth_osx_src.tar.gz"
|
||||||
if exist "!TMP_TAR!" del /q "!TMP_TAR!"
|
if exist "!TMP_TAR!" del /q "!TMP_TAR!"
|
||||||
tar -czf "!TMP_TAR!" --exclude=".git" --exclude="dist" --exclude="build" --exclude=".venv*" --exclude="__pycache__" -C "%PROJECT_ROOT%" .
|
tar -czf "!TMP_TAR!" --exclude=".git" --exclude="dist" --exclude="build" --exclude=".venv*" --exclude="__pycache__" -C "%PROJECT_ROOT%" .
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
|
||||||
ssh -p %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST% "mkdir -p %OSX_REMOTE_DIR% && find %OSX_REMOTE_DIR% -mindepth 1 -maxdepth 1 ! -name '.venv_build_macos' -exec rm -rf {} +"
|
ssh -p %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST% "mkdir -p %OSX_REMOTE_DIR% && find %OSX_REMOTE_DIR% -mindepth 1 -maxdepth 1 -not -name '.venv_build_macos' -exec rm -rf {} +"
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
scp -P %OSX_SSH_PORT% "!TMP_TAR!" %OSX_SSH_USER%@%OSX_SSH_HOST%:%OSX_REMOTE_DIR%/src.tar.gz
|
scp -P %OSX_SSH_PORT% "!TMP_TAR!" %OSX_SSH_USER%@%OSX_SSH_HOST%:%OSX_REMOTE_DIR%/src.tar.gz
|
||||||
|
set "SCP_OSX_ERR=!ERRORLEVEL!"
|
||||||
del /q "!TMP_TAR!" 2>nul
|
del /q "!TMP_TAR!" 2>nul
|
||||||
|
if not "!SCP_OSX_ERR!"=="0" exit /b 1
|
||||||
|
|
||||||
echo [OSX-VM] Kompiliere native macOS-Binary + .app Bundle in der VM...
|
echo [OSX-VM] Kompiliere native macOS-Binary + .app Bundle in der VM...
|
||||||
ssh -p %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST% "export PATH=/Library/Frameworks/Python.framework/Versions/3.11/bin:/opt/homebrew/bin:/usr/local/bin:$PATH; cd %OSX_REMOTE_DIR% && tar -xzf src.tar.gz && rm -f src.tar.gz && tr -d '\r' < build_scripts/build.sh > build_scripts/_osx.sh && mv build_scripts/_osx.sh build_scripts/build.sh && chmod +x build_scripts/build.sh && ./build_scripts/build.sh --OSX && tar -czf dist/macos/%APP_NAME%_macOS.tar.gz -C dist/macos ."
|
ssh -p %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST% "/bin/bash -lc 'set -e; export PATH=/Library/Frameworks/Python.framework/Versions/3.11/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH; cd %OSX_REMOTE_DIR%; rm -rf dist build; tar -xzf src.tar.gz; rm -f src.tar.gz; if [ -x .venv_build_macos/bin/python3 ]; then :; else rm -rf .venv_build_macos && python3 -m venv .venv_build_macos; fi; .venv_build_macos/bin/python3 -c \"import PIL, pygame, PyInstaller\" >/dev/null 2>&1 || .venv_build_macos/bin/python3 -m pip install --upgrade pip pillow pygame pyinstaller; ICON_ARGS=(); if [ -f \"$PWD/resources/images/game_icon.icns\" ]; then ICON_ARGS=(--icon \"$PWD/resources/images/game_icon.icns\"); elif [ -f \"$PWD/resources/images/game_icon.ico\" ]; then ICON_ARGS=(--icon \"$PWD/resources/images/game_icon.ico\"); fi; .venv_build_macos/bin/python3 -m PyInstaller --noconfirm --windowed --onefile --noupx --clean --osx-bundle-identifier de.kuro.thegothcardgamecollection --distpath \"$PWD/dist/macos\" --workpath \"$PWD/build/macos\" --specpath \"$PWD/build/macos\" \"${ICON_ARGS[@]}\" --add-data \"$PWD/resources:resources\" --add-data \"$PWD/games:games\" --collect-submodules games --collect-submodules controller --collect-submodules models --collect-submodules view --collect-submodules resources --hidden-import tkinter --hidden-import tkinter.ttk --hidden-import tkinter.font --hidden-import sqlite3 --hidden-import PIL._tkinter_finder --name %APP_NAME% \"$PWD/main.py\"; chmod +x dist/macos/%APP_NAME%; rm -rf build/macos; tar -czf dist/%APP_NAME%_macOS.tar.gz -C dist/macos .'"
|
||||||
if errorlevel 1 (
|
if errorlevel 1 (
|
||||||
echo [ERROR] macOS-Build in der VM fehlgeschlagen!
|
echo [ERROR] macOS-Build in der VM fehlgeschlagen!
|
||||||
if "!VM_WAS_RUNNING!"=="0" "!VBOX_MANAGE!" controlvm "%OSX_VM_NAME%" acpipowerbutton >nul 2>nul
|
if "!VM_WAS_RUNNING!"=="0" "!VBOX_MANAGE!" controlvm "%OSX_VM_NAME%" acpipowerbutton >nul 2>nul
|
||||||
exit /b 1
|
exit /b 1
|
||||||
)
|
)
|
||||||
|
|
||||||
if exist "%PROJECT_ROOT%\dist\macos" rmdir /s /q "%PROJECT_ROOT%\dist\macos"
|
mkdir "%PROJECT_ROOT%\dist\macos" 2>nul
|
||||||
mkdir "%PROJECT_ROOT%\dist\macos"
|
|
||||||
|
|
||||||
echo [OSX-VM] Lade fertiges macOS-Build nach dist\macos herunter...
|
echo [OSX-VM] Lade fertiges macOS-Build nach dist\macos herunter...
|
||||||
scp -P %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST%:%OSX_REMOTE_DIR%/dist/macos/%APP_NAME%_macOS.tar.gz "%PROJECT_ROOT%\dist\macos\%APP_NAME%_macOS.tar.gz"
|
scp -P %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST%:%OSX_REMOTE_DIR%/dist/%APP_NAME%_macOS.tar.gz "%PROJECT_ROOT%\dist\macos\%APP_NAME%_macOS.tar.gz"
|
||||||
if errorlevel 1 (
|
if errorlevel 1 (
|
||||||
echo [ERROR] Download des macOS-Artefakts fehlgeschlagen!
|
echo [ERROR] Download des macOS-Artefakts fehlgeschlagen!
|
||||||
exit /b 1
|
exit /b 1
|
||||||
)
|
)
|
||||||
tar -xzf "%PROJECT_ROOT%\dist\macos\%APP_NAME%_macOS.tar.gz" -C "%PROJECT_ROOT%\dist\macos"
|
tar -xzf "%PROJECT_ROOT%\dist\macos\%APP_NAME%_macOS.tar.gz" -C "%PROJECT_ROOT%\dist\macos"
|
||||||
|
if not exist "%PROJECT_ROOT%\dist\macos\%APP_NAME%" (
|
||||||
|
echo [ERROR] macOS-Binary dist\macos\%APP_NAME% fehlt nach dem Entpacken!
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
if "!VM_WAS_RUNNING!"=="0" (
|
if "!VM_WAS_RUNNING!"=="0" (
|
||||||
echo [OSX-VM] Fahre macOS-VM wieder sauber herunter...
|
echo [OSX-VM] Fahre macOS-VM wieder sauber herunter...
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
# Lokales Build-Skript (Linux / WSL / macOS-Zielsystem)
|
# Lokales Build-Skript (nur Linux & Windows via Wine)
|
||||||
# Ablageort: build_scripts/build.sh
|
# Ablageort: build_scripts/build.sh
|
||||||
# Targets: --Win | --Unix | --OSX | --current | --all | --clean
|
# Targets: --Win | --Unix | --current | --all | --clean
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
SCRIPT_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"
|
SCRIPT_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"
|
||||||
|
|
@ -11,17 +11,16 @@ cd "${PROJECT_ROOT}"
|
||||||
|
|
||||||
APP_NAME="TheGothCardgameCollection"
|
APP_NAME="TheGothCardgameCollection"
|
||||||
ICON_ICO="${PROJECT_ROOT}/resources/images/game_icon.ico"
|
ICON_ICO="${PROJECT_ROOT}/resources/images/game_icon.ico"
|
||||||
|
VERSION_TXT="${PROJECT_ROOT}/build_scripts/version_info.txt"
|
||||||
|
|
||||||
UNAME_OUT="$(uname -s)"
|
UNAME_OUT="$(uname -s)"
|
||||||
case "${UNAME_OUT}" in
|
case "${UNAME_OUT}" in
|
||||||
Linux*) HOST_OS="linux" ;;
|
Linux*) ;;
|
||||||
Darwin*) HOST_OS="macos" ;;
|
*) echo "❌ Dieses Skript unterstützt nur Linux-Systeme (gefunden: ${UNAME_OUT})."; exit 1 ;;
|
||||||
*) echo "❌ Unbekanntes System: ${UNAME_OUT}"; exit 1 ;;
|
|
||||||
esac
|
esac
|
||||||
|
|
||||||
DO_WIN=0
|
DO_WIN=0
|
||||||
DO_UNIX=0
|
DO_UNIX=0
|
||||||
DO_OSX=0
|
|
||||||
DO_CLEAN=0
|
DO_CLEAN=0
|
||||||
ORIG_ARGS=("$@")
|
ORIG_ARGS=("$@")
|
||||||
|
|
||||||
|
|
@ -31,16 +30,11 @@ for arg in "$@"; do
|
||||||
--clean) DO_CLEAN=1 ;;
|
--clean) DO_CLEAN=1 ;;
|
||||||
--win|--windows) DO_WIN=1 ;;
|
--win|--windows) DO_WIN=1 ;;
|
||||||
--unix|--linux) DO_UNIX=1 ;;
|
--unix|--linux) DO_UNIX=1 ;;
|
||||||
--osx|--macos) DO_OSX=1 ;;
|
--current) DO_UNIX=1 ;;
|
||||||
--current)
|
--all) DO_WIN=1; DO_UNIX=1 ;;
|
||||||
if [ "$HOST_OS" = "macos" ]; then DO_OSX=1; else DO_UNIX=1; fi
|
*)
|
||||||
;;
|
echo "❌ Unbekannte Option: $arg (Erlaubt: --Win | --Unix | --current | --all | --clean)"
|
||||||
--all)
|
exit 1
|
||||||
if [ "$HOST_OS" = "macos" ]; then
|
|
||||||
DO_OSX=1
|
|
||||||
else
|
|
||||||
DO_WIN=1; DO_UNIX=1
|
|
||||||
fi
|
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
done
|
done
|
||||||
|
|
@ -51,25 +45,24 @@ if [ "$DO_CLEAN" -eq 1 ]; then
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ "$DO_WIN" -eq 0 ] && [ "$DO_UNIX" -eq 0 ] && [ "$DO_OSX" -eq 0 ]; then
|
# Standardziel ohne Parameter: nativer Linux-Build
|
||||||
if [ "$HOST_OS" = "macos" ]; then DO_OSX=1; else DO_UNIX=1; fi
|
if [ "$DO_WIN" -eq 0 ] && [ "$DO_UNIX" -eq 0 ]; then
|
||||||
|
DO_UNIX=1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Root/Sudo Check unter Linux falls Systempakete fehlen
|
# Root/Sudo Check unter Linux falls Systempakete fehlen
|
||||||
NEEDS_SYS_INSTALL=0
|
NEEDS_SYS_INSTALL=0
|
||||||
if [ "$HOST_OS" = "linux" ]; then
|
if [ "$DO_UNIX" -eq 1 ]; then
|
||||||
if [ "$DO_UNIX" -eq 1 ]; then
|
if ! command -v python3 &>/dev/null || ! python3 -c "import tkinter" &>/dev/null || ! python3 -m pip --version &>/dev/null; then
|
||||||
if ! command -v python3 &>/dev/null || ! python3 -c "import tkinter" &>/dev/null || ! python3 -m pip --version &>/dev/null; then
|
|
||||||
NEEDS_SYS_INSTALL=1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
if [ "$DO_WIN" -eq 1 ] && ! command -v wine &>/dev/null; then
|
|
||||||
NEEDS_SYS_INSTALL=1
|
NEEDS_SYS_INSTALL=1
|
||||||
fi
|
fi
|
||||||
if [ "$NEEDS_SYS_INSTALL" -eq 1 ] && [ "${EUID:-$(id -u)}" -ne 0 ]; then
|
fi
|
||||||
echo "🔒 Fehlende Systempakete erkannt – fordere sudo an..."
|
if [ "$DO_WIN" -eq 1 ] && ! command -v wine &>/dev/null; then
|
||||||
exec sudo -E bash "$SCRIPT_PATH" "${ORIG_ARGS[@]}"
|
NEEDS_SYS_INSTALL=1
|
||||||
fi
|
fi
|
||||||
|
if [ "$NEEDS_SYS_INSTALL" -eq 1 ] && [ "${EUID:-$(id -u)}" -ne 0 ]; then
|
||||||
|
echo "🔒 Fehlende Systempakete erkannt – fordere sudo an..."
|
||||||
|
exec sudo -E bash "$SCRIPT_PATH" "${ORIG_ARGS[@]}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ "${EUID:-$(id -u)}" -eq 0 ] && [ -n "${SUDO_USER:-}" ]; then
|
if [ "${EUID:-$(id -u)}" -eq 0 ] && [ -n "${SUDO_USER:-}" ]; then
|
||||||
|
|
@ -113,8 +106,8 @@ rebuild_internal_db_if_present() {
|
||||||
|
|
||||||
DB_REBUILT=0
|
DB_REBUILT=0
|
||||||
|
|
||||||
# 1. LINUX BUILD
|
# 1. NATIVER LINUX BUILD (--Unix)
|
||||||
if [ "$DO_UNIX" -eq 1 ] && [ "$HOST_OS" = "linux" ]; then
|
if [ "$DO_UNIX" -eq 1 ]; then
|
||||||
echo "---> [UNIX] Baue Linux Executable..."
|
echo "---> [UNIX] Baue Linux Executable..."
|
||||||
if [ "$NEEDS_SYS_INSTALL" -eq 1 ]; then
|
if [ "$NEEDS_SYS_INSTALL" -eq 1 ]; then
|
||||||
if command -v apt-get &>/dev/null; then
|
if command -v apt-get &>/dev/null; then
|
||||||
|
|
@ -151,7 +144,7 @@ if [ "$DO_UNIX" -eq 1 ] && [ "$HOST_OS" = "linux" ]; then
|
||||||
[ -f "$ICON_ICO" ] && ICON_ARG=(--icon "$ICON_ICO")
|
[ -f "$ICON_ICO" ] && ICON_ARG=(--icon "$ICON_ICO")
|
||||||
|
|
||||||
"${USER_RUNNER[@]}" "$LINUX_PY" -m PyInstaller \
|
"${USER_RUNNER[@]}" "$LINUX_PY" -m PyInstaller \
|
||||||
--noconfirm --noconsole --onefile --clean \
|
--noconfirm --noconsole --onefile --noupx --clean \
|
||||||
--distpath "${PROJECT_ROOT}/dist/linux" \
|
--distpath "${PROJECT_ROOT}/dist/linux" \
|
||||||
--workpath "${PROJECT_ROOT}/build/linux" \
|
--workpath "${PROJECT_ROOT}/build/linux" \
|
||||||
--specpath "${PROJECT_ROOT}/build/linux" \
|
--specpath "${PROJECT_ROOT}/build/linux" \
|
||||||
|
|
@ -169,12 +162,12 @@ if [ "$DO_UNIX" -eq 1 ] && [ "$HOST_OS" = "linux" ]; then
|
||||||
echo "✔ Linux-Build fertig: dist/linux/${APP_NAME}"
|
echo "✔ Linux-Build fertig: dist/linux/${APP_NAME}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 2. WINDOWS BUILD VIA WINE (nur auf Linux)
|
# 2. WINDOWS BUILD VIA WINE (--Win)
|
||||||
if [ "$DO_WIN" -eq 1 ] && [ "$HOST_OS" = "linux" ]; then
|
if [ "$DO_WIN" -eq 1 ]; then
|
||||||
echo "---> [WIN] Baue Windows .exe (via Wine)..."
|
echo "---> [WIN] Baue Windows .exe (via Wine)..."
|
||||||
if ! command -v wine &>/dev/null; then
|
if ! command -v wine &>/dev/null; then
|
||||||
command -v apt-get &>/dev/null && dpkg --add-architecture amd64 2>/dev/null || true
|
command -v apt-get &>/dev/null && dpkg --add-architecture amd64 2>/dev/null || true
|
||||||
install_linux_pkgs wine wget
|
install_linux_pkgs wine wget curl
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ "$DB_REBUILT" -eq 0 ] && command -v python3 &>/dev/null; then
|
if [ "$DB_REBUILT" -eq 0 ] && command -v python3 &>/dev/null; then
|
||||||
|
|
@ -205,16 +198,24 @@ if [ "$DO_WIN" -eq 1 ] && [ "$HOST_OS" = "linux" ]; then
|
||||||
DB_REBUILT=1
|
DB_REBUILT=1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
"${USER_RUNNER[@]}" wine "$WINE_PY" -m pip install --upgrade pip pillow pygame pyinstaller
|
if ! "${USER_RUNNER[@]}" wine "$WINE_PY" -c "import PIL, pygame, PyInstaller" &>/dev/null; then
|
||||||
|
echo "---> [WIN] Installiere fehlende Python-Pakete in Wine..."
|
||||||
|
"${USER_RUNNER[@]}" wine "$WINE_PY" -m pip install --upgrade pip pillow pygame pyinstaller
|
||||||
|
fi
|
||||||
|
|
||||||
WINE_ICON_ARG=()
|
WINE_ICON_ARG=()
|
||||||
[ -f "$ICON_ICO" ] && WINE_ICON_ARG=(--icon "${WIN_ROOT}\\resources\\images\\game_icon.ico")
|
[ -f "$ICON_ICO" ] && WINE_ICON_ARG=(--icon "${WIN_ROOT}\\resources\\images\\game_icon.ico")
|
||||||
|
|
||||||
|
WINE_VER_ARG=()
|
||||||
|
[ -f "$VERSION_TXT" ] && WINE_VER_ARG=(--version-file "${WIN_ROOT}\\build_scripts\\version_info.txt")
|
||||||
|
|
||||||
"${USER_RUNNER[@]}" wine "$WINE_PY" -m PyInstaller \
|
"${USER_RUNNER[@]}" wine "$WINE_PY" -m PyInstaller \
|
||||||
--noconfirm --noconsole --onefile --clean \
|
--noconfirm --noconsole --onefile --noupx --clean \
|
||||||
--distpath "${WIN_ROOT}\\dist\\windows" \
|
--distpath "${WIN_ROOT}\\dist\\windows" \
|
||||||
--workpath "${WIN_ROOT}\\build\\windows" \
|
--workpath "${WIN_ROOT}\\build\\windows" \
|
||||||
--specpath "${WIN_ROOT}\\build\\windows" \
|
--specpath "${WIN_ROOT}\\build\\windows" \
|
||||||
"${WINE_ICON_ARG[@]}" \
|
"${WINE_ICON_ARG[@]}" \
|
||||||
|
"${WINE_VER_ARG[@]}" \
|
||||||
--add-data "${WIN_ROOT}\\resources;resources" \
|
--add-data "${WIN_ROOT}\\resources;resources" \
|
||||||
--add-data "${WIN_ROOT}\\games;games" \
|
--add-data "${WIN_ROOT}\\games;games" \
|
||||||
--collect-submodules games --collect-submodules controller \
|
--collect-submodules games --collect-submodules controller \
|
||||||
|
|
@ -227,49 +228,6 @@ if [ "$DO_WIN" -eq 1 ] && [ "$HOST_OS" = "linux" ]; then
|
||||||
echo "✔ Windows-Build fertig: dist/windows/${APP_NAME}.exe"
|
echo "✔ Windows-Build fertig: dist/windows/${APP_NAME}.exe"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 3. NATIVER MACOS BUILD (wird direkt in der macOS-VM ausgeführt)
|
|
||||||
if [ "$DO_OSX" -eq 1 ] && [ "$HOST_OS" = "macos" ]; then
|
|
||||||
echo "---> [OSX] Baue native macOS Binary + .app Bundle..."
|
|
||||||
export PATH="/Library/Frameworks/Python.framework/Versions/3.11/bin:/usr/local/bin:/opt/homebrew/bin:$PATH"
|
|
||||||
|
|
||||||
OSX_VENV="${PROJECT_ROOT}/.venv_build_macos"
|
|
||||||
if [ -d "$OSX_VENV" ] && [ ! -x "$OSX_VENV/bin/python3" ]; then rm -rf "$OSX_VENV"; fi
|
|
||||||
[ ! -d "$OSX_VENV" ] && python3 -m venv "$OSX_VENV"
|
|
||||||
|
|
||||||
if [ "$DB_REBUILT" -eq 0 ]; then
|
|
||||||
rebuild_internal_db_if_present "$OSX_VENV/bin/python3"
|
|
||||||
DB_REBUILT=1
|
|
||||||
fi
|
|
||||||
|
|
||||||
"$OSX_VENV/bin/python3" -m pip install --upgrade pip pillow pygame pyinstaller
|
|
||||||
|
|
||||||
OSX_ICON_ARG=()
|
|
||||||
if [ -f "${PROJECT_ROOT}/resources/images/game_icon.icns" ]; then
|
|
||||||
OSX_ICON_ARG=(--icon "${PROJECT_ROOT}/resources/images/game_icon.icns")
|
|
||||||
elif [ -f "$ICON_ICO" ]; then
|
|
||||||
OSX_ICON_ARG=(--icon "$ICON_ICO")
|
|
||||||
fi
|
|
||||||
|
|
||||||
"$OSX_VENV/bin/python3" -m PyInstaller \
|
|
||||||
--noconfirm --windowed --onefile --clean \
|
|
||||||
--osx-bundle-identifier "de.kuro.thegothcardgamecollection" \
|
|
||||||
--distpath "${PROJECT_ROOT}/dist/macos" \
|
|
||||||
--workpath "${PROJECT_ROOT}/build/macos" \
|
|
||||||
--specpath "${PROJECT_ROOT}/build/macos" \
|
|
||||||
"${OSX_ICON_ARG[@]}" \
|
|
||||||
--add-data "${PROJECT_ROOT}/resources:resources" \
|
|
||||||
--add-data "${PROJECT_ROOT}/games:games" \
|
|
||||||
--collect-submodules games --collect-submodules controller \
|
|
||||||
--collect-submodules models --collect-submodules view --collect-submodules resources \
|
|
||||||
--hidden-import tkinter --hidden-import tkinter.ttk --hidden-import tkinter.font \
|
|
||||||
--hidden-import sqlite3 --hidden-import PIL._tkinter_finder \
|
|
||||||
--name "${APP_NAME}" "${PROJECT_ROOT}/main.py"
|
|
||||||
|
|
||||||
chmod +x "${PROJECT_ROOT}/dist/macos/${APP_NAME}" 2>/dev/null || true
|
|
||||||
rm -rf "${PROJECT_ROOT}/build/macos"
|
|
||||||
echo "✔ macOS-Build fertig: dist/macos/${APP_NAME} (.app)"
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ "${EUID:-$(id -u)}" -eq 0 ] && [ -n "${SUDO_USER:-}" ]; then
|
if [ "${EUID:-$(id -u)}" -eq 0 ] && [ -n "${SUDO_USER:-}" ]; then
|
||||||
chown -R "$SUDO_USER:$SUDO_USER" "${PROJECT_ROOT}/dist" 2>/dev/null || true
|
chown -R "$SUDO_USER:$SUDO_USER" "${PROJECT_ROOT}/dist" 2>/dev/null || true
|
||||||
fi
|
fi
|
||||||
|
|
@ -0,0 +1,862 @@
|
||||||
|
#Requires -Version 5.1
|
||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Tiefen-Pruefung aller t(key, *args) i18n-Aufrufe im gesamten Projekt
|
||||||
|
inklusive verschachtelter Konstanten, Variablenketten, Modul-Importen,
|
||||||
|
Tupel/Dict-Unpacking, Funktionsparametern und f-Strings.
|
||||||
|
#>
|
||||||
|
param(
|
||||||
|
[switch]$RebuildDb,
|
||||||
|
[switch]$ShowDynamic
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
|
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
|
||||||
|
$ProjectRoot = (Resolve-Path (Join-Path $ScriptDir "..")).Path
|
||||||
|
|
||||||
|
function Find-PythonExe {
|
||||||
|
$venvPy = Join-Path $ProjectRoot ".venv\Scripts\python.exe"
|
||||||
|
if (Test-Path $venvPy) { return $venvPy }
|
||||||
|
|
||||||
|
foreach ($cmd in @("python", "python3")) {
|
||||||
|
$found = Get-Command $cmd -ErrorAction SilentlyContinue
|
||||||
|
if ($found) { return $found.Source }
|
||||||
|
}
|
||||||
|
foreach ($candidate in @(
|
||||||
|
"C:\Python311\python.exe",
|
||||||
|
"C:\Python312\python.exe",
|
||||||
|
"$env:LocalAppData\Programs\Python\Python311\python.exe",
|
||||||
|
"$env:ProgramFiles\Python311\python.exe"
|
||||||
|
)) {
|
||||||
|
if (Test-Path $candidate) { return $candidate }
|
||||||
|
}
|
||||||
|
throw "Keine Python-Installation gefunden!"
|
||||||
|
}
|
||||||
|
|
||||||
|
$PyExe = Find-PythonExe
|
||||||
|
|
||||||
|
if ($RebuildDb) {
|
||||||
|
$rebuildScript = Join-Path $ProjectRoot "build_scripts\rebuild_internal_db.py"
|
||||||
|
if (-not (Test-Path $rebuildScript)) {
|
||||||
|
$rebuildScript = Join-Path $ProjectRoot "rebuild_internal_db.py"
|
||||||
|
}
|
||||||
|
if (Test-Path $rebuildScript) {
|
||||||
|
Write-Host "---> Aktualisiere vorab internal_base.db..." -ForegroundColor Cyan
|
||||||
|
& $PyExe $rebuildScript
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$AnalyzerPy = @'
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
import ast
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(sys.argv[1]).resolve()
|
||||||
|
SHOW_DYNAMIC = "--show-dynamic" in sys.argv[2:]
|
||||||
|
|
||||||
|
EXCLUDE_DIRS = {".git", ".venv", ".venv_build_win", ".venv_build_macos", "build", "dist", "__pycache__"}
|
||||||
|
SQL_DIR = ROOT / "resources" / "code_res" / "sql"
|
||||||
|
DB_PATH = ROOT / "resources" / "code_res" / "internal_base.db"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 1. SQL & SQLite-DB Uebersetzungen einlesen
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def load_sql_translations(sql_dir: Path):
|
||||||
|
sql_map = {} # key -> {"DE": val, "EN": val}
|
||||||
|
variants = set()
|
||||||
|
if not sql_dir.is_dir():
|
||||||
|
return sql_map, variants
|
||||||
|
|
||||||
|
tuple_re = re.compile(
|
||||||
|
r"\(\s*'((?:''|[^'])*)'\s*,\s*'(DE|EN)'\s*,\s*'((?:''|[^'])*)'\s*\)"
|
||||||
|
)
|
||||||
|
var_re = re.compile(
|
||||||
|
r"\(\s*\d+\s*,\s*'[^']*'\s*,\s*'[^']*'\s*,\s*'([^']+)'\s*,"
|
||||||
|
)
|
||||||
|
for sql_file in sorted(sql_dir.glob("*.sql")):
|
||||||
|
content = sql_file.read_text(encoding="utf-8", errors="replace")
|
||||||
|
for m in tuple_re.finditer(content):
|
||||||
|
k = m.group(1).replace("''", "'")
|
||||||
|
lang = m.group(2)
|
||||||
|
val = m.group(3).replace("''", "'")
|
||||||
|
sql_map.setdefault(k, {})[lang] = val
|
||||||
|
for vm in var_re.finditer(content):
|
||||||
|
variants.add(vm.group(1))
|
||||||
|
return sql_map, variants
|
||||||
|
|
||||||
|
|
||||||
|
def load_db_translations(db_path: Path):
|
||||||
|
db_map = {}
|
||||||
|
if not db_path.is_file():
|
||||||
|
return db_map
|
||||||
|
conn = sqlite3.connect(f"{db_path.as_uri()}?mode=ro", uri=True)
|
||||||
|
try:
|
||||||
|
for k, lang, val in conn.execute("SELECT key, lang, val FROM base_i18n"):
|
||||||
|
db_map.setdefault(k, {})[lang] = val
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return db_map
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 2. Abstrakte Werte fuer tiefenverschachtelte Konstanten- & Datenfluss-Analyse
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class Val:
|
||||||
|
"""Repräsentiert mögliche String-Werte, Tupel/Listen, Dicts oder f-String-Muster."""
|
||||||
|
__slots__ = ("strings", "patterns", "items", "mapping")
|
||||||
|
|
||||||
|
def __init__(self, strings=None, patterns=None, items=None, mapping=None):
|
||||||
|
self.strings = set(strings) if strings else set()
|
||||||
|
self.patterns = set(patterns) if patterns else set()
|
||||||
|
self.items = list(items) if items else [] # list[Val] fuer Tuple/List
|
||||||
|
self.mapping = dict(mapping) if mapping else {} # dict[str, Val] fuer Dict
|
||||||
|
|
||||||
|
def copy(self):
|
||||||
|
return Val(
|
||||||
|
set(self.strings),
|
||||||
|
set(self.patterns),
|
||||||
|
[v.copy() for v in self.items],
|
||||||
|
{k: v.copy() for k, v in self.mapping.items()},
|
||||||
|
)
|
||||||
|
|
||||||
|
def merge(self, other: "Val") -> bool:
|
||||||
|
if other is None:
|
||||||
|
return False
|
||||||
|
changed = False
|
||||||
|
before_s = len(self.strings)
|
||||||
|
self.strings |= other.strings
|
||||||
|
if len(self.strings) != before_s:
|
||||||
|
changed = True
|
||||||
|
|
||||||
|
before_p = len(self.patterns)
|
||||||
|
self.patterns |= other.patterns
|
||||||
|
if len(self.patterns) != before_p:
|
||||||
|
changed = True
|
||||||
|
|
||||||
|
if len(other.items) > len(self.items):
|
||||||
|
for i in range(len(self.items), len(other.items)):
|
||||||
|
self.items.append(other.items[i].copy())
|
||||||
|
changed = True
|
||||||
|
for i in range(min(len(self.items), len(other.items))):
|
||||||
|
if self.items[i].merge(other.items[i]):
|
||||||
|
changed = True
|
||||||
|
|
||||||
|
for k, ov in other.mapping.items():
|
||||||
|
if k not in self.mapping:
|
||||||
|
self.mapping[k] = ov.copy()
|
||||||
|
changed = True
|
||||||
|
elif self.mapping[k].merge(ov):
|
||||||
|
changed = True
|
||||||
|
return changed
|
||||||
|
|
||||||
|
def all_leaf_strings(self) -> set:
|
||||||
|
out = set(self.strings)
|
||||||
|
for it in self.items:
|
||||||
|
out |= it.all_leaf_strings()
|
||||||
|
for mv in self.mapping.values():
|
||||||
|
out |= mv.all_leaf_strings()
|
||||||
|
return out
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_empty(self) -> bool:
|
||||||
|
return not (self.strings or self.patterns or self.items or self.mapping)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 3. Projektweite Python-Dateien parsen & Modulnamen bestimmen
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def collect_py_files(root: Path):
|
||||||
|
modules = {} # mod_name -> (Path, ast.Module)
|
||||||
|
for dirpath, dirnames, filenames in os.walk(root):
|
||||||
|
dirnames[:] = [d for d in dirnames if d not in EXCLUDE_DIRS]
|
||||||
|
for fn in sorted(filenames):
|
||||||
|
if not fn.endswith(".py"):
|
||||||
|
continue
|
||||||
|
fpath = Path(dirpath) / fn
|
||||||
|
rel = fpath.relative_to(root)
|
||||||
|
parts = list(rel.with_suffix("").parts)
|
||||||
|
if parts[-1] == "__init__":
|
||||||
|
parts = parts[:-1]
|
||||||
|
mod_name = ".".join(parts) if parts else "__root__"
|
||||||
|
try:
|
||||||
|
src = fpath.read_text(encoding="utf-8", errors="replace")
|
||||||
|
tree = ast.parse(src, filename=str(fpath))
|
||||||
|
modules[mod_name] = (fpath, tree)
|
||||||
|
except SyntaxError as exc:
|
||||||
|
print(f"[SYNTAX-WARNUNG] {rel}: {exc}")
|
||||||
|
return modules
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectAnalyzer:
|
||||||
|
def __init__(self, modules: dict):
|
||||||
|
self.modules = modules
|
||||||
|
# Globale Modul-Umgebungen: mod_name -> {var_name: Val}
|
||||||
|
self.mod_envs = {m: {} for m in modules}
|
||||||
|
# Klassen-Attribute & Instanz-Felder (self.xyz): (mod_name, cls_name) -> {attr: Val}
|
||||||
|
self.cls_attrs = {}
|
||||||
|
# Funktions-/Methoden-Parameter aus Aufrufen: func_key -> {param_name: Val}
|
||||||
|
self.func_param_envs = {}
|
||||||
|
# Funktions-Definitionen nach Schluessel fuer Call-Propagation
|
||||||
|
self.func_defs = {} # (mod_name, cls_name_or_None, func_name) -> ast.FunctionDef
|
||||||
|
# Import-Aliase fuer i18n.t pro Modul: mod_name -> (set_of_direct_t_names, set_of_i18n_mod_aliases)
|
||||||
|
self.t_aliases = {m: (set(), set()) for m in modules}
|
||||||
|
# Modul-Aliase (import foo.bar as fb): mod_name -> {alias: target_mod}
|
||||||
|
self.mod_imports = {m: {} for m in modules}
|
||||||
|
# From-Importe (from foo import BAR as B): mod_name -> {local_name: (target_mod, orig_name)}
|
||||||
|
self.sym_imports = {m: {} for m in modules}
|
||||||
|
|
||||||
|
self._index_definitions_and_imports()
|
||||||
|
|
||||||
|
def _resolve_import_target(self, cur_mod: str, module_str: str | None, level: int) -> str:
|
||||||
|
if level == 0:
|
||||||
|
return module_str or ""
|
||||||
|
cur_parts = cur_mod.split(".")[:-1]
|
||||||
|
up = max(0, level - 1)
|
||||||
|
base = cur_parts[: max(0, len(cur_parts) - up)]
|
||||||
|
if module_str:
|
||||||
|
base.extend(module_str.split("."))
|
||||||
|
return ".".join(base)
|
||||||
|
|
||||||
|
def _index_definitions_and_imports(self):
|
||||||
|
for mod_name, (_fpath, tree) in self.modules.items():
|
||||||
|
t_direct, t_mods = self.t_aliases[mod_name]
|
||||||
|
if mod_name.endswith(".i18n") or mod_name == "i18n":
|
||||||
|
t_direct.add("t")
|
||||||
|
|
||||||
|
for node in tree.body:
|
||||||
|
if isinstance(node, ast.Import):
|
||||||
|
for alias in node.names:
|
||||||
|
asname = alias.asname or alias.name.split(".")[0]
|
||||||
|
if alias.name in self.modules:
|
||||||
|
self.mod_imports[mod_name][asname] = alias.name
|
||||||
|
if alias.name.endswith(".i18n") or alias.name == "i18n":
|
||||||
|
t_mods.add(asname)
|
||||||
|
|
||||||
|
elif isinstance(node, ast.ImportFrom):
|
||||||
|
target_mod = self._resolve_import_target(mod_name, node.module, node.level)
|
||||||
|
is_i18n = target_mod.endswith(".i18n") or target_mod == "i18n"
|
||||||
|
for alias in node.names:
|
||||||
|
local = alias.asname or alias.name
|
||||||
|
if is_i18n and alias.name == "t":
|
||||||
|
t_direct.add(local)
|
||||||
|
full_submod = f"{target_mod}.{alias.name}" if target_mod else alias.name
|
||||||
|
if full_submod in self.modules:
|
||||||
|
self.mod_imports[mod_name][local] = full_submod
|
||||||
|
else:
|
||||||
|
self.sym_imports[mod_name][local] = (target_mod, alias.name)
|
||||||
|
|
||||||
|
elif isinstance(node, ast.FunctionDef):
|
||||||
|
self.func_defs[(mod_name, None, node.name)] = node
|
||||||
|
|
||||||
|
elif isinstance(node, ast.ClassDef):
|
||||||
|
self.cls_attrs.setdefault((mod_name, node.name), {})
|
||||||
|
for item in node.body:
|
||||||
|
if isinstance(item, ast.FunctionDef):
|
||||||
|
self.func_defs[(mod_name, node.name, item.name)] = item
|
||||||
|
|
||||||
|
def eval_expr(self, node, mod_name: str, local_env: dict, cur_cls: str | None = None) -> Val:
|
||||||
|
if node is None:
|
||||||
|
return Val()
|
||||||
|
|
||||||
|
# String- oder Zahlen-Literal
|
||||||
|
if isinstance(node, ast.Constant):
|
||||||
|
if isinstance(node.value, (str, int, float)) and not isinstance(node.value, bool):
|
||||||
|
return Val(strings={str(node.value)})
|
||||||
|
return Val()
|
||||||
|
|
||||||
|
# Variablen-Name (Lokal -> Klasse -> Modul -> Import)
|
||||||
|
if isinstance(node, ast.Name):
|
||||||
|
nm = node.id
|
||||||
|
if nm in local_env:
|
||||||
|
return local_env[nm].copy()
|
||||||
|
if cur_cls and nm in self.cls_attrs.get((mod_name, cur_cls), {}):
|
||||||
|
return self.cls_attrs[(mod_name, cur_cls)][nm].copy()
|
||||||
|
if nm in self.mod_envs.get(mod_name, {}):
|
||||||
|
return self.mod_envs[mod_name][nm].copy()
|
||||||
|
if nm in self.sym_imports.get(mod_name, {}):
|
||||||
|
t_mod, orig = self.sym_imports[mod_name][nm]
|
||||||
|
if t_mod in self.mod_envs and orig in self.mod_envs[t_mod]:
|
||||||
|
return self.mod_envs[t_mod][orig].copy()
|
||||||
|
return Val()
|
||||||
|
|
||||||
|
# Attribut-Zugriff: self.xyz oder modul.KONSTANTE oder Klasse.KONSTANTE
|
||||||
|
if isinstance(node, ast.Attribute):
|
||||||
|
if isinstance(node.value, ast.Name):
|
||||||
|
base = node.value.id
|
||||||
|
if base == "self" and cur_cls:
|
||||||
|
return self.cls_attrs.get((mod_name, cur_cls), {}).get(node.attr, Val()).copy()
|
||||||
|
if base in self.mod_imports.get(mod_name, {}):
|
||||||
|
t_mod = self.mod_imports[mod_name][base]
|
||||||
|
return self.mod_envs.get(t_mod, {}).get(node.attr, Val()).copy()
|
||||||
|
if (mod_name, base) in self.cls_attrs:
|
||||||
|
return self.cls_attrs[(mod_name, base)].get(node.attr, Val()).copy()
|
||||||
|
if base in self.sym_imports.get(mod_name, {}):
|
||||||
|
t_mod, orig_cls = self.sym_imports[mod_name][base]
|
||||||
|
if (t_mod, orig_cls) in self.cls_attrs:
|
||||||
|
return self.cls_attrs[(t_mod, orig_cls)].get(node.attr, Val()).copy()
|
||||||
|
return Val()
|
||||||
|
|
||||||
|
# Tupel / Liste / Set
|
||||||
|
if isinstance(node, (ast.Tuple, ast.List, ast.Set)):
|
||||||
|
elems = [self.eval_expr(e, mod_name, local_env, cur_cls) for e in node.elts]
|
||||||
|
v = Val(items=elems)
|
||||||
|
for el in elems:
|
||||||
|
v.strings |= el.strings
|
||||||
|
v.patterns |= el.patterns
|
||||||
|
return v
|
||||||
|
|
||||||
|
# Dict-Literal
|
||||||
|
if isinstance(node, ast.Dict):
|
||||||
|
mp = {}
|
||||||
|
all_s = set()
|
||||||
|
for k_node, v_node in zip(node.keys, node.values):
|
||||||
|
vv = self.eval_expr(v_node, mod_name, local_env, cur_cls)
|
||||||
|
all_s |= vv.strings
|
||||||
|
if k_node is not None:
|
||||||
|
kv = self.eval_expr(k_node, mod_name, local_env, cur_cls)
|
||||||
|
for ks in kv.strings:
|
||||||
|
mp.setdefault(ks, Val()).merge(vv)
|
||||||
|
return Val(strings=all_s, mapping=mp)
|
||||||
|
|
||||||
|
# Subscript: d[key] oder tup[0]
|
||||||
|
if isinstance(node, ast.Subscript):
|
||||||
|
container = self.eval_expr(node.value, mod_name, local_env, cur_cls)
|
||||||
|
idx_val = self.eval_expr(node.slice, mod_name, local_env, cur_cls)
|
||||||
|
out = Val()
|
||||||
|
if container.mapping:
|
||||||
|
if idx_val.strings:
|
||||||
|
for ks in idx_val.strings:
|
||||||
|
if ks in container.mapping:
|
||||||
|
out.merge(container.mapping[ks])
|
||||||
|
else:
|
||||||
|
for mv in container.mapping.values():
|
||||||
|
out.merge(mv)
|
||||||
|
if container.items:
|
||||||
|
matched_idx = False
|
||||||
|
for ks in idx_val.strings:
|
||||||
|
if ks.lstrip("-").isdigit():
|
||||||
|
i = int(ks)
|
||||||
|
if -len(container.items) <= i < len(container.items):
|
||||||
|
out.merge(container.items[i])
|
||||||
|
matched_idx = True
|
||||||
|
if not matched_idx and not container.mapping:
|
||||||
|
for it in container.items:
|
||||||
|
out.merge(it)
|
||||||
|
return out
|
||||||
|
|
||||||
|
# Ternary: a if cond else b
|
||||||
|
if isinstance(node, ast.IfExp):
|
||||||
|
res = self.eval_expr(node.body, mod_name, local_env, cur_cls)
|
||||||
|
res.merge(self.eval_expr(node.orelse, mod_name, local_env, cur_cls))
|
||||||
|
return res
|
||||||
|
|
||||||
|
# BoolOp: a or b
|
||||||
|
if isinstance(node, ast.BoolOp):
|
||||||
|
res = Val()
|
||||||
|
for v_node in node.values:
|
||||||
|
res.merge(self.eval_expr(v_node, mod_name, local_env, cur_cls))
|
||||||
|
return res
|
||||||
|
|
||||||
|
# String-Verkettung: "variant_" + key
|
||||||
|
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
|
||||||
|
lv = self.eval_expr(node.left, mod_name, local_env, cur_cls)
|
||||||
|
rv = self.eval_expr(node.right, mod_name, local_env, cur_cls)
|
||||||
|
return self._combine_parts([lv, rv])
|
||||||
|
|
||||||
|
# f-String: f"variant_{self.variant_key}"
|
||||||
|
if isinstance(node, ast.JoinedStr):
|
||||||
|
parts = []
|
||||||
|
for p in node.values:
|
||||||
|
if isinstance(p, ast.Constant) and isinstance(p.value, str):
|
||||||
|
parts.append(Val(strings={p.value}))
|
||||||
|
elif isinstance(p, ast.FormattedValue):
|
||||||
|
sub = self.eval_expr(p.value, mod_name, local_env, cur_cls)
|
||||||
|
if sub.strings:
|
||||||
|
parts.append(Val(strings=sub.strings))
|
||||||
|
else:
|
||||||
|
parts.append(Val(patterns={".*"}))
|
||||||
|
return self._combine_parts(parts)
|
||||||
|
|
||||||
|
# Aufrufe wie dict(STAT_GAME_GROUPS) oder my_dict.get(key, default)
|
||||||
|
if isinstance(node, ast.Call):
|
||||||
|
if isinstance(node.func, ast.Name) and node.func.id == "dict" and node.args:
|
||||||
|
arg0 = self.eval_expr(node.args[0], mod_name, local_env, cur_cls)
|
||||||
|
mp = {}
|
||||||
|
for pair in arg0.items:
|
||||||
|
if len(pair.items) >= 2:
|
||||||
|
for ks in pair.items[0].strings:
|
||||||
|
mp.setdefault(ks, Val()).merge(pair.items[1])
|
||||||
|
return Val(mapping=mp)
|
||||||
|
|
||||||
|
if isinstance(node.func, ast.Attribute) and node.func.attr == "get":
|
||||||
|
recv = self.eval_expr(node.func.value, mod_name, local_env, cur_cls)
|
||||||
|
out = Val()
|
||||||
|
if recv.mapping:
|
||||||
|
if node.args:
|
||||||
|
kv = self.eval_expr(node.args[0], mod_name, local_env, cur_cls)
|
||||||
|
if kv.strings:
|
||||||
|
for ks in kv.strings:
|
||||||
|
if ks in recv.mapping:
|
||||||
|
out.merge(recv.mapping[ks])
|
||||||
|
else:
|
||||||
|
for mv in recv.mapping.values():
|
||||||
|
out.merge(mv)
|
||||||
|
if len(node.args) >= 2:
|
||||||
|
out.merge(self.eval_expr(node.args[1], mod_name, local_env, cur_cls))
|
||||||
|
return out
|
||||||
|
|
||||||
|
return Val()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _combine_parts(parts: list) -> Val:
|
||||||
|
"""Kartesisches Produkt fuer f-Strings / '+'-Verkettung; faellt bei Unbekannten auf Regex-Muster zurueck."""
|
||||||
|
has_wildcard = any(bool(p.patterns) and not p.strings for p in parts)
|
||||||
|
if not has_wildcard:
|
||||||
|
acc = {""}
|
||||||
|
for p in parts:
|
||||||
|
if not p.strings:
|
||||||
|
return Val()
|
||||||
|
nxt = set()
|
||||||
|
for prefix in acc:
|
||||||
|
for s in p.strings:
|
||||||
|
if len(nxt) < 128:
|
||||||
|
nxt.add(prefix + s)
|
||||||
|
acc = nxt
|
||||||
|
return Val(strings=acc)
|
||||||
|
|
||||||
|
regex_pieces = []
|
||||||
|
for p in parts:
|
||||||
|
if p.strings and not p.patterns:
|
||||||
|
escaped = [re.escape(s) for s in sorted(p.strings)]
|
||||||
|
regex_pieces.append(f"(?:{'|'.join(escaped)})" if len(escaped) > 1 else escaped[0])
|
||||||
|
else:
|
||||||
|
regex_pieces.append(".+")
|
||||||
|
return Val(patterns={f"^{''.join(regex_pieces)}$"})
|
||||||
|
|
||||||
|
def _bind_target(self, target, val: Val, mod_name: str, env: dict, cur_cls: str | None, is_mod_scope: bool) -> bool:
|
||||||
|
changed = False
|
||||||
|
if isinstance(target, ast.Name):
|
||||||
|
dest = self.mod_envs[mod_name] if is_mod_scope else env
|
||||||
|
if target.id not in dest:
|
||||||
|
dest[target.id] = val.copy()
|
||||||
|
return not val.is_empty
|
||||||
|
return dest[target.id].merge(val)
|
||||||
|
|
||||||
|
if isinstance(target, ast.Attribute) and cur_cls:
|
||||||
|
if isinstance(target.value, ast.Name) and target.value.id == "self":
|
||||||
|
cdict = self.cls_attrs.setdefault((mod_name, cur_cls), {})
|
||||||
|
if target.attr not in cdict:
|
||||||
|
cdict[target.attr] = val.copy()
|
||||||
|
return not val.is_empty
|
||||||
|
return cdict[target.attr].merge(val)
|
||||||
|
|
||||||
|
if isinstance(target, (ast.Tuple, ast.List)):
|
||||||
|
for idx, sub_t in enumerate(target.elts):
|
||||||
|
sub_val = val.items[idx] if idx < len(val.items) else Val()
|
||||||
|
if self._bind_target(sub_t, sub_val, mod_name, env, cur_cls, is_mod_scope):
|
||||||
|
changed = True
|
||||||
|
return changed
|
||||||
|
|
||||||
|
def _propagate_call_args(self, call_node: ast.Call, mod_name: str, local_env: dict, cur_cls: str | None) -> bool:
|
||||||
|
"""Leitet Argument-Werte von Aufrufstellen an Funktions- und Konstruktor-Parameter weiter."""
|
||||||
|
target_key = None
|
||||||
|
is_method_or_init = False
|
||||||
|
|
||||||
|
if isinstance(call_node.func, ast.Name):
|
||||||
|
fn = call_node.func.id
|
||||||
|
if (mod_name, None, fn) in self.func_defs:
|
||||||
|
target_key = (mod_name, None, fn)
|
||||||
|
elif (mod_name, fn, "__init__") in self.func_defs:
|
||||||
|
target_key = (mod_name, fn, "__init__")
|
||||||
|
is_method_or_init = True
|
||||||
|
elif fn in self.sym_imports.get(mod_name, {}):
|
||||||
|
t_mod, orig = self.sym_imports[mod_name][fn]
|
||||||
|
if (t_mod, None, orig) in self.func_defs:
|
||||||
|
target_key = (t_mod, None, orig)
|
||||||
|
elif (t_mod, orig, "__init__") in self.func_defs:
|
||||||
|
target_key = (t_mod, orig, "__init__")
|
||||||
|
is_method_or_init = True
|
||||||
|
|
||||||
|
elif isinstance(call_node.func, ast.Attribute):
|
||||||
|
if isinstance(call_node.func.value, ast.Name) and call_node.func.value.id == "self" and cur_cls:
|
||||||
|
mname = call_node.func.attr
|
||||||
|
if (mod_name, cur_cls, mname) in self.func_defs:
|
||||||
|
target_key = (mod_name, cur_cls, mname)
|
||||||
|
is_method_or_init = True
|
||||||
|
|
||||||
|
if target_key is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
fdef = self.func_defs[target_key]
|
||||||
|
param_names = [a.arg for a in fdef.args.args]
|
||||||
|
if is_method_or_init and param_names and param_names[0] in ("self", "cls"):
|
||||||
|
param_names = param_names[1:]
|
||||||
|
|
||||||
|
penv = self.func_param_envs.setdefault(target_key, {})
|
||||||
|
changed = False
|
||||||
|
|
||||||
|
for i, arg_node in enumerate(call_node.args):
|
||||||
|
if i < len(param_names):
|
||||||
|
av = self.eval_expr(arg_node, mod_name, local_env, cur_cls)
|
||||||
|
if not av.is_empty:
|
||||||
|
pname = param_names[i]
|
||||||
|
if pname not in penv:
|
||||||
|
penv[pname] = av.copy()
|
||||||
|
changed = True
|
||||||
|
elif penv[pname].merge(av):
|
||||||
|
changed = True
|
||||||
|
|
||||||
|
for kw in call_node.keywords:
|
||||||
|
if kw.arg and kw.arg in param_names:
|
||||||
|
kv = self.eval_expr(kw.value, mod_name, local_env, cur_cls)
|
||||||
|
if not kv.is_empty:
|
||||||
|
if kw.arg not in penv:
|
||||||
|
penv[kw.arg] = kv.copy()
|
||||||
|
changed = True
|
||||||
|
elif penv[kw.arg].merge(kv):
|
||||||
|
changed = True
|
||||||
|
return changed
|
||||||
|
|
||||||
|
def _walk_statements(self, stmts, mod_name: str, env: dict, cur_cls: str | None, is_mod_scope: bool, collect_calls: list | None):
|
||||||
|
changed = False
|
||||||
|
for stmt in stmts:
|
||||||
|
if isinstance(stmt, ast.Assign):
|
||||||
|
val = self.eval_expr(stmt.value, mod_name, env, cur_cls)
|
||||||
|
for tgt in stmt.targets:
|
||||||
|
if self._bind_target(tgt, val, mod_name, env, cur_cls, is_mod_scope):
|
||||||
|
changed = True
|
||||||
|
elif isinstance(stmt, ast.AnnAssign) and stmt.value is not None:
|
||||||
|
val = self.eval_expr(stmt.value, mod_name, env, cur_cls)
|
||||||
|
if self._bind_target(stmt.target, val, mod_name, env, cur_cls, is_mod_scope):
|
||||||
|
changed = True
|
||||||
|
elif isinstance(stmt, ast.For):
|
||||||
|
iter_val = self._eval_iter_items(stmt.iter, mod_name, env, cur_cls)
|
||||||
|
for elem_val in iter_val:
|
||||||
|
if self._bind_target(stmt.target, elem_val, mod_name, env, cur_cls, False):
|
||||||
|
changed = True
|
||||||
|
if self._walk_statements(stmt.body, mod_name, env, cur_cls, False, collect_calls):
|
||||||
|
changed = True
|
||||||
|
if self._walk_statements(stmt.orelse, mod_name, env, cur_cls, False, collect_calls):
|
||||||
|
changed = True
|
||||||
|
elif isinstance(stmt, (ast.If, ast.While)):
|
||||||
|
if self._walk_statements(stmt.body, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
||||||
|
changed = True
|
||||||
|
if self._walk_statements(stmt.orelse, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
||||||
|
changed = True
|
||||||
|
elif isinstance(stmt, ast.With):
|
||||||
|
if self._walk_statements(stmt.body, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
||||||
|
changed = True
|
||||||
|
elif isinstance(stmt, ast.Try):
|
||||||
|
if self._walk_statements(stmt.body, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
||||||
|
changed = True
|
||||||
|
for h in stmt.handlers:
|
||||||
|
if self._walk_statements(h.body, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
||||||
|
changed = True
|
||||||
|
if self._walk_statements(stmt.orelse, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
||||||
|
changed = True
|
||||||
|
if self._walk_statements(stmt.finalbody, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
||||||
|
changed = True
|
||||||
|
elif isinstance(stmt, ast.ClassDef):
|
||||||
|
cls_env = {}
|
||||||
|
for c_stmt in stmt.body:
|
||||||
|
if isinstance(c_stmt, ast.Assign):
|
||||||
|
val = self.eval_expr(c_stmt.value, mod_name, cls_env, stmt.name)
|
||||||
|
for tgt in c_stmt.targets:
|
||||||
|
if isinstance(tgt, ast.Name):
|
||||||
|
cdict = self.cls_attrs.setdefault((mod_name, stmt.name), {})
|
||||||
|
if tgt.id not in cdict:
|
||||||
|
cdict[tgt.id] = val.copy()
|
||||||
|
changed = changed or (not val.is_empty)
|
||||||
|
elif cdict[tgt.id].merge(val):
|
||||||
|
changed = True
|
||||||
|
elif isinstance(c_stmt, ast.FunctionDef):
|
||||||
|
if self._analyze_function(c_stmt, mod_name, env, stmt.name, collect_calls):
|
||||||
|
changed = True
|
||||||
|
elif isinstance(stmt, ast.FunctionDef):
|
||||||
|
if self._analyze_function(stmt, mod_name, env, cur_cls, collect_calls):
|
||||||
|
changed = True
|
||||||
|
|
||||||
|
# Ausdruecke innerhalb des aktuellen Statements (ohne verschachtelte defs/classes) scannen
|
||||||
|
if not isinstance(stmt, (ast.FunctionDef, ast.ClassDef, ast.For, ast.If, ast.While, ast.With, ast.Try)):
|
||||||
|
if self._scan_expr_tree(stmt, mod_name, env, cur_cls, collect_calls):
|
||||||
|
changed = True
|
||||||
|
elif isinstance(stmt, (ast.If, ast.While)):
|
||||||
|
if self._scan_expr_tree(stmt.test, mod_name, env, cur_cls, collect_calls):
|
||||||
|
changed = True
|
||||||
|
return changed
|
||||||
|
|
||||||
|
def _eval_iter_items(self, iter_node, mod_name: str, env: dict, cur_cls: str | None) -> list:
|
||||||
|
"""Extrahiert Element-Werte aus Schleifen wie `for i, (a, b) in enumerate(STAT_FIELD_KEYS):`."""
|
||||||
|
if isinstance(iter_node, ast.Call) and isinstance(iter_node.func, ast.Name):
|
||||||
|
fn = iter_node.func.id
|
||||||
|
if fn == "enumerate" and iter_node.args:
|
||||||
|
sub_items = self._eval_iter_items(iter_node.args[0], mod_name, env, cur_cls)
|
||||||
|
return [Val(items=[Val(strings={str(i)}), it]) for i, it in enumerate(sub_items)]
|
||||||
|
if fn in ("reversed", "sorted", "list", "tuple") and iter_node.args:
|
||||||
|
return self._eval_iter_items(iter_node.args[0], mod_name, env, cur_cls)
|
||||||
|
if fn == "range":
|
||||||
|
nums = [self.eval_expr(a, mod_name, env, cur_cls) for a in iter_node.args]
|
||||||
|
if len(nums) == 1 and len(nums[0].strings) == 1 and list(nums[0].strings)[0].isdigit():
|
||||||
|
n = min(32, int(list(nums[0].strings)[0]))
|
||||||
|
return [Val(strings={str(i)}) for i in range(n)]
|
||||||
|
|
||||||
|
v = self.eval_expr(iter_node, mod_name, env, cur_cls)
|
||||||
|
if v.items:
|
||||||
|
return v.items
|
||||||
|
if v.strings:
|
||||||
|
return [Val(strings={s}) for s in v.strings]
|
||||||
|
return []
|
||||||
|
|
||||||
|
def _analyze_function(self, fnode: ast.FunctionDef, mod_name: str, outer_env: dict, cur_cls: str | None, collect_calls: list | None) -> bool:
|
||||||
|
f_env = {k: v.copy() for k, v in outer_env.items()}
|
||||||
|
fkey = (mod_name, cur_cls, fnode.name)
|
||||||
|
|
||||||
|
# Default-Parameterwerte binden
|
||||||
|
all_args = fnode.args.args
|
||||||
|
defaults = fnode.args.defaults
|
||||||
|
if defaults:
|
||||||
|
offset = len(all_args) - len(defaults)
|
||||||
|
for idx, d_node in enumerate(defaults):
|
||||||
|
pname = all_args[offset + idx].arg
|
||||||
|
f_env[pname] = self.eval_expr(d_node, mod_name, outer_env, cur_cls)
|
||||||
|
|
||||||
|
# Aus Aufrufstellen propagierte Parameterwerte einmischen
|
||||||
|
for pname, pval in self.func_param_envs.get(fkey, {}).items():
|
||||||
|
if pname in f_env:
|
||||||
|
f_env[pname].merge(pval)
|
||||||
|
else:
|
||||||
|
f_env[pname] = pval.copy()
|
||||||
|
|
||||||
|
return self._walk_statements(fnode.body, mod_name, f_env, cur_cls, False, collect_calls)
|
||||||
|
|
||||||
|
def _is_t_call(self, call_node: ast.Call, mod_name: str) -> bool:
|
||||||
|
t_direct, t_mods = self.t_aliases[mod_name]
|
||||||
|
if isinstance(call_node.func, ast.Name) and call_node.func.id in t_direct:
|
||||||
|
return True
|
||||||
|
if (
|
||||||
|
isinstance(call_node.func, ast.Attribute)
|
||||||
|
and call_node.func.attr == "t"
|
||||||
|
and isinstance(call_node.func.value, ast.Name)
|
||||||
|
and call_node.func.value.id in t_mods
|
||||||
|
):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _scan_expr_tree(self, root_node, mod_name: str, env: dict, cur_cls: str | None, collect_calls: list | None) -> bool:
|
||||||
|
changed = False
|
||||||
|
|
||||||
|
def visit(n, cur_env):
|
||||||
|
nonlocal changed
|
||||||
|
if n is None or isinstance(n, (ast.FunctionDef, ast.ClassDef)):
|
||||||
|
return
|
||||||
|
|
||||||
|
if isinstance(n, ast.Lambda):
|
||||||
|
l_env = {k: v.copy() for k, v in cur_env.items()}
|
||||||
|
l_args = n.args.args
|
||||||
|
l_defs = n.args.defaults
|
||||||
|
if l_defs:
|
||||||
|
off = len(l_args) - len(l_defs)
|
||||||
|
for i, dn in enumerate(l_defs):
|
||||||
|
l_env[l_args[off + i].arg] = self.eval_expr(dn, mod_name, cur_env, cur_cls)
|
||||||
|
visit(n.body, l_env)
|
||||||
|
return
|
||||||
|
|
||||||
|
if isinstance(n, (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp)):
|
||||||
|
c_env = {k: v.copy() for k, v in cur_env.items()}
|
||||||
|
for gen in n.generators:
|
||||||
|
visit(gen.iter, c_env)
|
||||||
|
for elem_v in self._eval_iter_items(gen.iter, mod_name, c_env, cur_cls):
|
||||||
|
self._bind_target(gen.target, elem_v, mod_name, c_env, cur_cls, False)
|
||||||
|
for if_n in gen.ifs:
|
||||||
|
visit(if_n, c_env)
|
||||||
|
if isinstance(n, ast.DictComp):
|
||||||
|
visit(n.key, c_env)
|
||||||
|
visit(n.value, c_env)
|
||||||
|
else:
|
||||||
|
visit(n.elt, c_env)
|
||||||
|
return
|
||||||
|
|
||||||
|
if isinstance(n, ast.Call):
|
||||||
|
if collect_calls is None:
|
||||||
|
if self._propagate_call_args(n, mod_name, cur_env, cur_cls):
|
||||||
|
changed = True
|
||||||
|
elif self._is_t_call(n, mod_name) and n.args:
|
||||||
|
key_node = n.args[0]
|
||||||
|
resolved = self.eval_expr(key_node, mod_name, cur_env, cur_cls)
|
||||||
|
has_star = any(isinstance(a, ast.Starred) for a in n.args[1:])
|
||||||
|
pos_argc = None if has_star else (len(n.args) - 1)
|
||||||
|
try:
|
||||||
|
expr_src = ast.unparse(key_node)
|
||||||
|
except Exception:
|
||||||
|
expr_src = "<expr>"
|
||||||
|
collect_calls.append({
|
||||||
|
"mod": mod_name,
|
||||||
|
"file": self.modules[mod_name][0],
|
||||||
|
"line": getattr(n, "lineno", 0),
|
||||||
|
"expr": expr_src,
|
||||||
|
"val": resolved,
|
||||||
|
"argc": pos_argc,
|
||||||
|
})
|
||||||
|
|
||||||
|
for child in ast.iter_child_nodes(n):
|
||||||
|
visit(child, cur_env)
|
||||||
|
|
||||||
|
visit(root_node, env)
|
||||||
|
return changed
|
||||||
|
|
||||||
|
def run_analysis(self, max_passes: int = 5):
|
||||||
|
for _ in range(max_passes):
|
||||||
|
any_change = False
|
||||||
|
for mod_name, (_fpath, tree) in self.modules.items():
|
||||||
|
if self._walk_statements(tree.body, mod_name, {}, None, True, collect_calls=None):
|
||||||
|
any_change = True
|
||||||
|
if not any_change:
|
||||||
|
break
|
||||||
|
|
||||||
|
calls = []
|
||||||
|
for mod_name, (_fpath, tree) in self.modules.items():
|
||||||
|
self._walk_statements(tree.body, mod_name, {}, None, True, collect_calls=calls)
|
||||||
|
return calls
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 4. Auswertung & Bericht
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
sql_map, sql_variants = load_sql_translations(SQL_DIR)
|
||||||
|
db_map = load_db_translations(DB_PATH)
|
||||||
|
ref_map = sql_map if sql_map else db_map
|
||||||
|
|
||||||
|
modules = collect_py_files(ROOT)
|
||||||
|
analyzer = ProjectAnalyzer(modules)
|
||||||
|
t_calls = analyzer.run_analysis()
|
||||||
|
|
||||||
|
missing_keys = [] # (key, rel_file, line, expr, missing_where)
|
||||||
|
incomplete_langs = [] # (key, missing_lang)
|
||||||
|
db_drift_keys = [] # Keys in SQL, aber noch nicht in internal_base.db
|
||||||
|
placeholder_issues = [] # (key, rel_file, line, lang, max_ph, given_argc)
|
||||||
|
unmatched_patterns = [] # (pattern, rel_file, line, expr)
|
||||||
|
unresolved_dynamic = [] # (rel_file, line, expr)
|
||||||
|
|
||||||
|
# 1. Alle SQL-Keys auf Vollständigkeit (DE & EN) und DB-Sync prüfen
|
||||||
|
for k in sorted(sql_map.keys()):
|
||||||
|
langs = sql_map[k]
|
||||||
|
if "DE" not in langs:
|
||||||
|
incomplete_langs.append((k, "DE fehlt in SQL"))
|
||||||
|
if "EN" not in langs:
|
||||||
|
incomplete_langs.append((k, "EN fehlt in SQL"))
|
||||||
|
if db_map and (k not in db_map or "DE" not in db_map[k] or "EN" not in db_map[k]):
|
||||||
|
db_drift_keys.append(k)
|
||||||
|
|
||||||
|
# Prüfen, ob jede registrierte Spielvariante ein 'variant_<key>' hat
|
||||||
|
for vk in sorted(sql_variants):
|
||||||
|
full_vk = f"variant_{vk}"
|
||||||
|
if full_vk not in ref_map:
|
||||||
|
missing_keys.append((full_vk, "resources/code_res/sql/*.sql", 0, f"game_variants.{vk}", "FEHLT in base_i18n"))
|
||||||
|
|
||||||
|
ph_re = re.compile(r"\{(\d+)\}")
|
||||||
|
checked_unique_keys = set()
|
||||||
|
|
||||||
|
for entry in t_calls:
|
||||||
|
rel_file = entry["file"].relative_to(ROOT).as_posix()
|
||||||
|
line = entry["line"]
|
||||||
|
expr = entry["expr"]
|
||||||
|
val: Val = entry["val"]
|
||||||
|
argc = entry["argc"]
|
||||||
|
|
||||||
|
if val.strings:
|
||||||
|
for k in sorted(val.strings):
|
||||||
|
checked_unique_keys.add(k)
|
||||||
|
in_sql = k in sql_map
|
||||||
|
in_db = (k in db_map) if db_map else in_sql
|
||||||
|
|
||||||
|
if not in_sql and not in_db:
|
||||||
|
missing_keys.append((k, rel_file, line, expr, "FEHLT in SQL & DB"))
|
||||||
|
elif not in_sql and in_db:
|
||||||
|
missing_keys.append((k, rel_file, line, expr, "Nur in DB, FEHLT in SQL-Dateien"))
|
||||||
|
else:
|
||||||
|
src_entry = sql_map.get(k) or db_map.get(k, {})
|
||||||
|
if argc is not None:
|
||||||
|
for lg in ("DE", "EN"):
|
||||||
|
txt = src_entry.get(lg, "")
|
||||||
|
idxs = [int(m.group(1)) for m in ph_re.finditer(txt)]
|
||||||
|
if idxs and max(idxs) >= argc:
|
||||||
|
placeholder_issues.append((k, rel_file, line, lg, max(idxs) + 1, argc))
|
||||||
|
|
||||||
|
elif val.patterns:
|
||||||
|
for pat in sorted(val.patterns):
|
||||||
|
rx = re.compile(pat)
|
||||||
|
matches = [k for k in ref_map if rx.match(k)]
|
||||||
|
if not matches:
|
||||||
|
unmatched_patterns.append((pat, rel_file, line, expr))
|
||||||
|
else:
|
||||||
|
checked_unique_keys.update(matches)
|
||||||
|
else:
|
||||||
|
unresolved_dynamic.append((rel_file, line, expr))
|
||||||
|
|
||||||
|
print("=" * 74)
|
||||||
|
print(" GOTH CARDGAME COLLECTION - i18n TIEFEN-PRUEFUNG (AST + KONSTANTEN)")
|
||||||
|
print("=" * 74)
|
||||||
|
print(f" Gepruefte Python-Module : {len(modules)}")
|
||||||
|
print(f" Gefundene t(...)-Aufrufe: {len(t_calls)} ({len(checked_unique_keys)} eindeutige Keys aufgeloest)")
|
||||||
|
print(f" Keys in SQL-Dateien : {len(sql_map)} | Keys in internal_base.db: {len(db_map)}")
|
||||||
|
print("-" * 74)
|
||||||
|
|
||||||
|
has_errors = False
|
||||||
|
|
||||||
|
if missing_keys:
|
||||||
|
has_errors = True
|
||||||
|
print(f"\n[FEHLER] {len(missing_keys)} fehlende i18n-Keys im Code gefunden:")
|
||||||
|
for k, rf, ln, ex, reason in missing_keys:
|
||||||
|
trace = f" (aus `{ex}`)" if ex not in (f"'{k}'", f'"{k}"') else ""
|
||||||
|
print(f" - '{k}' -> {rf}:{ln}{trace} [{reason}]")
|
||||||
|
|
||||||
|
if unmatched_patterns:
|
||||||
|
has_errors = True
|
||||||
|
print(f"\n[FEHLER] {len(unmatched_patterns)} f-String-Muster ohne jeglichen Treffer in SQL/DB:")
|
||||||
|
for pat, rf, ln, ex in unmatched_patterns:
|
||||||
|
print(f" - Muster {pat} aus `{ex}` -> {rf}:{ln}")
|
||||||
|
|
||||||
|
if incomplete_langs:
|
||||||
|
has_errors = True
|
||||||
|
print(f"\n[FEHLER] {len(incomplete_langs)} unvollstaendige Sprach-Paare (DE/EN):")
|
||||||
|
for k, msg in incomplete_langs:
|
||||||
|
print(f" - '{k}': {msg}")
|
||||||
|
|
||||||
|
if placeholder_issues:
|
||||||
|
has_errors = True
|
||||||
|
print(f"\n[WARNUNG] {len(placeholder_issues)} Platzhalter-Abweichungen ({{0}}, {{1}}, ...):")
|
||||||
|
for k, rf, ln, lg, need_n, got_n in placeholder_issues:
|
||||||
|
print(f" - '{k}' [{lg}] erwartet {need_n} Argument(e), Aufruf uebergibt {got_n} -> {rf}:{ln}")
|
||||||
|
|
||||||
|
if db_drift_keys:
|
||||||
|
print(f"\n[HINWEIS] {len(db_drift_keys)} Key(s) stehen in .sql, fehlen aber noch in internal_base.db:")
|
||||||
|
for k in db_drift_keys[:15]:
|
||||||
|
print(f" - '{k}'")
|
||||||
|
if len(db_drift_keys) > 15:
|
||||||
|
print(f" ... und {len(db_drift_keys) - 15} weitere.")
|
||||||
|
print(" -> Tipp: `python build_scripts/rebuild_internal_db.py` oder `-RebuildDb` ausfuehren!")
|
||||||
|
|
||||||
|
if SHOW_DYNAMIC and unresolved_dynamic:
|
||||||
|
print(f"\n[INFO] {len(unresolved_dynamic)} rein dynamische Laufzeit-Aufrufe:")
|
||||||
|
for rf, ln, ex in unresolved_dynamic:
|
||||||
|
print(f" - {rf}:{ln} -> t({ex})")
|
||||||
|
|
||||||
|
if not has_errors and not db_drift_keys:
|
||||||
|
print("\n[OK] Alles sauber! Alle aufgeloesten t(...)-Keys existieren vollstaendig in DE & EN.")
|
||||||
|
print("=" * 74)
|
||||||
|
|
||||||
|
sys.exit(1 if has_errors else 0)
|
||||||
|
'@
|
||||||
|
|
||||||
|
$extraArgs = @($ProjectRoot)
|
||||||
|
if ($ShowDynamic) { $extraArgs += "--show-dynamic" }
|
||||||
|
|
||||||
|
$AnalyzerPy | & $PyExe - @extraArgs
|
||||||
|
exit $LASTEXITCODE
|
||||||
|
|
@ -0,0 +1,116 @@
|
||||||
|
#Requires -Version 5.1
|
||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Prueft alle Python-Dateien im Projekt auf mehr als eine Klassendefinition
|
||||||
|
und gibt den vollen Dateipfad samt Klassennamen aus.
|
||||||
|
#>
|
||||||
|
param(
|
||||||
|
[string]$TargetDir = "",
|
||||||
|
[switch]$IncludeNested
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
|
if ([string]::IsNullOrWhiteSpace($TargetDir)) {
|
||||||
|
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
|
||||||
|
# Falls das Skript in build_scripts/ liegt, automatisch eine Ebene hoeher starten, sonst im aktuellen Ordner
|
||||||
|
if ((Split-Path -Leaf $ScriptDir) -ieq "build_scripts") {
|
||||||
|
$RootPath = (Resolve-Path (Join-Path $ScriptDir "..")).Path
|
||||||
|
} else {
|
||||||
|
$RootPath = (Resolve-Path $ScriptDir).Path
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$RootPath = (Resolve-Path $TargetDir).Path
|
||||||
|
}
|
||||||
|
|
||||||
|
$ExcludeDirs = @(".git", ".venv", ".venv_build_win", ".venv_build_macos", "build", "dist", "__pycache__")
|
||||||
|
|
||||||
|
# Versuche Python fuer 100% exaktes AST-Parsing zu finden, sonst Fallback auf Regex
|
||||||
|
$PyExe = $null
|
||||||
|
$venvPy = Join-Path $RootPath ".venv\Scripts\python.exe"
|
||||||
|
if (Test-Path $venvPy) {
|
||||||
|
$PyExe = $venvPy
|
||||||
|
} else {
|
||||||
|
foreach ($cmd in @("python", "python3")) {
|
||||||
|
$found = Get-Command $cmd -ErrorAction SilentlyContinue
|
||||||
|
if ($found) { $PyExe = $found.Source; break }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($PyExe) {
|
||||||
|
$PyScript = @'
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
import ast
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
root = Path(sys.argv[1]).resolve()
|
||||||
|
include_nested = "--nested" in sys.argv[2:]
|
||||||
|
exclude_dirs = {".git", ".venv", ".venv_build_win", ".venv_build_macos", "build", "dist", "__pycache__"}
|
||||||
|
|
||||||
|
def get_classes(tree: ast.AST, nested: bool) -> list[str]:
|
||||||
|
if not nested:
|
||||||
|
return [node.name for node in getattr(tree, "body", []) if isinstance(node, ast.ClassDef)]
|
||||||
|
found = []
|
||||||
|
def walk_node(n, prefix=""):
|
||||||
|
for child in ast.iter_child_nodes(n):
|
||||||
|
if isinstance(child, ast.ClassDef):
|
||||||
|
qual = f"{prefix}.{child.name}" if prefix else child.name
|
||||||
|
found.append(qual)
|
||||||
|
walk_node(child, qual)
|
||||||
|
else:
|
||||||
|
walk_node(child, prefix)
|
||||||
|
walk_node(tree)
|
||||||
|
return found
|
||||||
|
|
||||||
|
for dirpath, dirnames, filenames in os.walk(root):
|
||||||
|
dirnames[:] = sorted(d for d in dirnames if d not in exclude_dirs)
|
||||||
|
for fn in sorted(filenames):
|
||||||
|
if not fn.endswith(".py"):
|
||||||
|
continue
|
||||||
|
fpath = Path(dirpath) / fn
|
||||||
|
try:
|
||||||
|
src = fpath.read_text(encoding="utf-8", errors="replace")
|
||||||
|
tree = ast.parse(src, filename=str(fpath))
|
||||||
|
classes = get_classes(tree, include_nested)
|
||||||
|
if len(classes) > 1:
|
||||||
|
print(str(fpath))
|
||||||
|
for cls_name in classes:
|
||||||
|
print(f"- {cls_name}")
|
||||||
|
print("")
|
||||||
|
except SyntaxError:
|
||||||
|
pass
|
||||||
|
'@
|
||||||
|
$pyArgs = @($RootPath)
|
||||||
|
if ($IncludeNested) { $pyArgs += "--nested" }
|
||||||
|
$PyScript | & $PyExe - @pyArgs
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
# Reiner PowerShell-Fallback falls kein Python im PATH ist
|
||||||
|
$ClassRegex = if ($IncludeNested) { '^\s*class\s+([A-Za-z_][A-Za-z0-9_]*)\b' } else { '^class\s+([A-Za-z_][A-Za-z0-9_]*)\b' }
|
||||||
|
|
||||||
|
Get-ChildItem -Path $RootPath -Recurse -File -Filter "*.py" | Where-Object {
|
||||||
|
$full = $_.FullName
|
||||||
|
$skip = $false
|
||||||
|
foreach ($ex in $ExcludeDirs) {
|
||||||
|
if ($full -match ([regex]::Escape("\$ex\"))) { $skip = $true; break }
|
||||||
|
}
|
||||||
|
-not $skip
|
||||||
|
} | Sort-Object FullName | ForEach-Object {
|
||||||
|
$classes = New-Object System.Collections.Generic.List[string]
|
||||||
|
foreach ($line in [System.IO.File]::ReadLines($_.FullName)) {
|
||||||
|
if ($line -match $ClassRegex) {
|
||||||
|
$classes.Add($Matches[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($classes.Count -gt 1) {
|
||||||
|
Write-Output $_.FullName
|
||||||
|
foreach ($c in $classes) {
|
||||||
|
Write-Output "- $c"
|
||||||
|
}
|
||||||
|
Write-Output ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
VSVersionInfo(
|
||||||
|
ffi=FixedFileInfo(
|
||||||
|
filevers=(0, 6, 0, 0),
|
||||||
|
prodvers=(0, 6, 0, 0),
|
||||||
|
mask=0x3f,
|
||||||
|
flags=0x0,
|
||||||
|
OS=0x40004,
|
||||||
|
fileType=0x1,
|
||||||
|
subtype=0x0,
|
||||||
|
date=(0, 0)
|
||||||
|
),
|
||||||
|
kids=[
|
||||||
|
StringFileInfo([
|
||||||
|
StringTable(
|
||||||
|
'040704B0',
|
||||||
|
[
|
||||||
|
StringStruct('CompanyName', 'Kuro'),
|
||||||
|
StringStruct('FileDescription', 'The Goth Cardgame Collection'),
|
||||||
|
StringStruct('FileVersion', '0.6.0.0'),
|
||||||
|
StringStruct('InternalName', 'TheGothCardgameCollection'),
|
||||||
|
StringStruct('LegalCopyright', 'Copyright (C) 2026 Kuro'),
|
||||||
|
StringStruct('OriginalFilename', 'TheGothCardgameCollection.exe'),
|
||||||
|
StringStruct('ProductName', 'The Goth Cardgame Collection'),
|
||||||
|
StringStruct('ProductVersion', '0.6.0-beta')
|
||||||
|
]
|
||||||
|
)
|
||||||
|
]),
|
||||||
|
VarFileInfo([VarStruct('Translation', [1031, 1200])])
|
||||||
|
]
|
||||||
|
)
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -1,20 +1,25 @@
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
# controller/app_context.py
|
# controller/app_context.py
|
||||||
import tkinter as tk
|
from __future__ import annotations
|
||||||
|
|
||||||
from models.database import Database
|
from models.database import Database
|
||||||
from resources.code_res.game_constants import ACCENT_GOLD, ACCENT_GOTH, ERROR_FG, FG_COLOR, PANEL_BG, SUBTLE_BORDER
|
from view.unified_stats_view import UnifiedStatsView
|
||||||
from resources.code_res.i18n import t
|
from view.widgets.goth_dropdown import GothDropdown
|
||||||
from view.dialogs.audio_settings_dialog import AudioSettingsDialog
|
from view.widgets.goth_topbar import GothTopbar, format_compact_user_badge
|
||||||
from view.widgets.image_button import ImageButton
|
|
||||||
|
__all__ = ["AppContext", "GothTopbar", "UnifiedStatsView", "format_compact_user_badge"]
|
||||||
|
|
||||||
|
|
||||||
class AppContext:
|
class AppContext:
|
||||||
|
"""Schlanker Spiel-Kontext; Topbar, Einstellungen und Statistik laufen zentral."""
|
||||||
|
|
||||||
def __init__(self, controller, game_folder: str):
|
def __init__(self, controller, game_folder: str):
|
||||||
self._ctrl = controller
|
self._ctrl = controller
|
||||||
self.game_folder = game_folder
|
self.game_folder = game_folder
|
||||||
self.root = controller.view
|
self.root = controller.view
|
||||||
self.assets = controller.view.assets
|
self.assets = controller.view.assets
|
||||||
self.sounds = controller.sounds
|
self.sounds = controller.sounds
|
||||||
|
setattr(self.root, "_app_controller", controller)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def profile(self) -> dict:
|
def profile(self) -> dict:
|
||||||
|
|
@ -28,12 +33,28 @@ class AppContext:
|
||||||
return Database.get_game_progress(self.profile["id"], self.game_folder)
|
return Database.get_game_progress(self.profile["id"], self.game_folder)
|
||||||
|
|
||||||
def back_to_main_menu(self):
|
def back_to_main_menu(self):
|
||||||
|
GothDropdown.close_any_open_popup()
|
||||||
self._ctrl.show_main_menu()
|
self._ctrl.show_main_menu()
|
||||||
|
|
||||||
|
def open_settings(self, on_lang_refresh=None):
|
||||||
|
GothDropdown.close_any_open_popup()
|
||||||
|
self._ctrl.show_settings(
|
||||||
|
in_game_overlay=True,
|
||||||
|
on_ingame_lang_refresh=on_lang_refresh,
|
||||||
|
)
|
||||||
|
|
||||||
def open_audio_settings(self):
|
def open_audio_settings(self):
|
||||||
AudioSettingsDialog.open(self.root, self.assets, self.sounds)
|
self.open_settings(on_lang_refresh=None)
|
||||||
|
|
||||||
|
def open_stats(self, game_endpoint: str | None = None, on_back=None):
|
||||||
|
"""Öffnet die zentrale Statistik-Ansicht für `game_endpoint` (oder das aktive Spiel)."""
|
||||||
|
endpoint = self.game_folder if game_endpoint is None else game_endpoint
|
||||||
|
UnifiedStatsView.open(self, game_endpoint=endpoint, on_back=on_back)
|
||||||
|
|
||||||
|
open_global_stats = open_stats
|
||||||
|
|
||||||
def toggle_language(self, refresh_callback=None):
|
def toggle_language(self, refresh_callback=None):
|
||||||
|
GothDropdown.close_any_open_popup()
|
||||||
self._ctrl.toggle_language(refresh_callback)
|
self._ctrl.toggle_language(refresh_callback)
|
||||||
|
|
||||||
def record_result(
|
def record_result(
|
||||||
|
|
@ -63,74 +84,29 @@ class AppContext:
|
||||||
def build_game_topbar(
|
def build_game_topbar(
|
||||||
self,
|
self,
|
||||||
parent,
|
parent,
|
||||||
title: str,
|
title: str = "",
|
||||||
on_game_menu=None,
|
on_game_menu=None,
|
||||||
on_stats=None,
|
on_stats=None,
|
||||||
stats_enabled: bool = True,
|
stats_enabled: bool = True,
|
||||||
extra_right_text: str = "",
|
extra_right_text: str = "",
|
||||||
on_lang_refresh=None,
|
on_lang_refresh=None,
|
||||||
locked_exit: bool = False,
|
locked_exit: bool = False,
|
||||||
) -> tk.Frame:
|
stats_endpoint: str | None = None,
|
||||||
bar = tk.Frame(parent, bg=PANEL_BG, padx=12, pady=8, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
|
on_stats_back=None,
|
||||||
bar.pack(fill="x", side="top")
|
) -> GothTopbar:
|
||||||
|
"""Erstellt die universelle Topbar und verknüpft automatisch den Statistik-Endpunkt."""
|
||||||
stats_btn = None
|
bar = GothTopbar(
|
||||||
if locked_exit:
|
parent=parent,
|
||||||
tk.Label(
|
ctx=self,
|
||||||
bar, text=t("devils_deal_locked_badge"),
|
stats_endpoint=stats_endpoint if stats_endpoint is not None else self.game_folder,
|
||||||
font=("Helvetica", 10, "bold"), fg=ERROR_FG, bg=PANEL_BG
|
on_stats_back=on_stats_back,
|
||||||
).pack(side="left", padx=(4, 12))
|
stats_enabled=stats_enabled,
|
||||||
else:
|
on_lang_refresh=on_lang_refresh,
|
||||||
ImageButton(
|
locked_exit=locked_exit,
|
||||||
bar, t("btn_back_main"), self.assets.raw_sel, self.assets.raw_sel_active,
|
title=title,
|
||||||
self.back_to_main_menu, sound_mgr=self.sounds, width=135, height=36, font=("Helvetica", 10, "bold")
|
on_game_menu=on_game_menu,
|
||||||
).pack(side="left", padx=(0, 6))
|
on_stats=on_stats,
|
||||||
|
extra_right_text=extra_right_text,
|
||||||
if on_game_menu is not None:
|
|
||||||
ImageButton(
|
|
||||||
bar, t("btn_back_game_menu"), self.assets.raw_sel, self.assets.raw_sel_active,
|
|
||||||
on_game_menu, sound_mgr=self.sounds, width=135, height=36, font=("Helvetica", 10, "bold")
|
|
||||||
).pack(side="left", padx=(0, 6))
|
|
||||||
|
|
||||||
if on_stats is not None:
|
|
||||||
stats_btn = ImageButton(
|
|
||||||
bar, t("btn_stats"), self.assets.raw_sel, self.assets.raw_sel_active,
|
|
||||||
on_stats, sound_mgr=self.sounds, width=115, height=36,
|
|
||||||
font=("Helvetica", 10, "bold"), enabled=stats_enabled
|
|
||||||
)
|
|
||||||
stats_btn.pack(side="left")
|
|
||||||
|
|
||||||
title_lbl = tk.Label(bar, text=title, font=("Georgia", 15, "bold"), fg=FG_COLOR, bg=PANEL_BG)
|
|
||||||
title_lbl.pack(side="left", expand=True)
|
|
||||||
|
|
||||||
right_box = tk.Frame(bar, bg=PANEL_BG)
|
|
||||||
right_box.pack(side="right")
|
|
||||||
|
|
||||||
extra_lbl = tk.Label(right_box, text=extra_right_text, font=("Helvetica", 11, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG)
|
|
||||||
extra_lbl.pack(side="left", padx=(0, 14))
|
|
||||||
|
|
||||||
prof = self.profile
|
|
||||||
prog = self.game_progress
|
|
||||||
lvl_lbl = tk.Label(
|
|
||||||
right_box,
|
|
||||||
text=t("level_badge", prof["name"], prog["title"], prog["level"], prog["current_xp"], prog["needed_xp"]),
|
|
||||||
font=("Helvetica", 10, "bold"), fg=ACCENT_GOTH, bg=PANEL_BG
|
|
||||||
)
|
)
|
||||||
lvl_lbl.pack(side="left", padx=(0, 10))
|
bar.pack(fill="x", side="top")
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
right_box, t("btn_lang"), self.assets.raw_sel, self.assets.raw_sel_active,
|
|
||||||
lambda: self.toggle_language(on_lang_refresh),
|
|
||||||
sound_mgr=self.sounds, width=108, height=34, font=("Helvetica", 9, "bold")
|
|
||||||
).pack(side="left", padx=(0, 6))
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
right_box, t("btn_audio"), self.assets.raw_sel, self.assets.raw_sel_active,
|
|
||||||
self.open_audio_settings, sound_mgr=self.sounds, width=92, height=34, font=("Helvetica", 9, "bold")
|
|
||||||
).pack(side="left")
|
|
||||||
|
|
||||||
bar.title_label = title_lbl
|
|
||||||
bar.extra_label = extra_lbl
|
|
||||||
bar.level_label = lvl_lbl
|
|
||||||
bar.stats_btn = stats_btn
|
|
||||||
return bar
|
return bar
|
||||||
|
|
@ -1,12 +1,19 @@
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
# controller/app_controller.py
|
# controller/app_controller.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from controller.app_context import AppContext
|
from controller.app_context import AppContext
|
||||||
from controller.game_loader import GameLoader
|
from controller.game_loader import GameLoader
|
||||||
|
from games.solitaire.base.solitaire_tap_prefs import invalidate_tap_prefs_cache
|
||||||
from models.database import Database
|
from models.database import Database
|
||||||
|
from models.db_locator import DbLocator
|
||||||
|
from models.online_session import OnlineSessionClient
|
||||||
from models.sound_manager import SoundManager
|
from models.sound_manager import SoundManager
|
||||||
import resources.code_res.i18n as i18n
|
import resources.code_res.i18n as i18n
|
||||||
from resources.code_res.i18n import t
|
from resources.code_res.i18n import t
|
||||||
|
from view.widgets.image_button import set_button_hover_help_enabled
|
||||||
|
|
||||||
|
|
||||||
class AppController:
|
class AppController:
|
||||||
|
|
@ -17,16 +24,58 @@ class AppController:
|
||||||
i18n.set_lang(Database.load_setting("language", "DE"))
|
i18n.set_lang(Database.load_setting("language", "DE"))
|
||||||
self.loader = GameLoader(root_dir)
|
self.loader = GameLoader(root_dir)
|
||||||
self.sounds = SoundManager(root_dir / "resources" / "sounds")
|
self.sounds = SoundManager(root_dir / "resources" / "sounds")
|
||||||
self.active_profile = None
|
self.online_session = OnlineSessionClient()
|
||||||
|
self.is_online_mode: bool = False
|
||||||
|
self.active_profile: dict | None = None
|
||||||
self.view = None
|
self.view = None
|
||||||
|
|
||||||
def bind_view(self, view):
|
def bind_view(self, view):
|
||||||
self.view = view
|
self.view = view
|
||||||
|
self.view._app_controller = self
|
||||||
|
|
||||||
|
def can_modify_user_db(self) -> bool:
|
||||||
|
"""Sperrt das Laden/Umziehen der lokalen DB im Online-Modus oder während Devil's Deal."""
|
||||||
|
if self.is_online_mode:
|
||||||
|
return False
|
||||||
|
if self.active_profile and self.has_active_devils_lock():
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _reload_runtime_preferences_from_db(self):
|
||||||
|
"""Synchronisiert Sprache, Audio & Schalter-Settings nach einem Datenbank-Wechsel."""
|
||||||
|
lang = Database.load_setting("language", "DE")
|
||||||
|
i18n.set_lang(lang)
|
||||||
|
invalidate_tap_prefs_cache()
|
||||||
|
|
||||||
|
hover_raw = Database.load_setting("ui_button_hover_help", "")
|
||||||
|
if hover_raw != "":
|
||||||
|
set_button_hover_help_enabled(
|
||||||
|
str(hover_raw).strip().lower() in ("1", "true", "yes", "on"),
|
||||||
|
persist=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
amb_raw = Database.load_setting("ambiance_volume", "")
|
||||||
|
if amb_raw != "":
|
||||||
|
try:
|
||||||
|
self.sounds.set_ambiance_volume(float(amb_raw), persist=False)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
sfx_raw = Database.load_setting("menu_volume", "")
|
||||||
|
if sfx_raw != "":
|
||||||
|
try:
|
||||||
|
self.sounds.set_menu_volume(float(sfx_raw), persist=False)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if self.view is not None:
|
||||||
|
self.view.title(t("app_title"))
|
||||||
|
|
||||||
def toggle_language(self, custom_refresh=None):
|
def toggle_language(self, custom_refresh=None):
|
||||||
new_lang = i18n.next_lang()
|
new_lang = i18n.next_lang()
|
||||||
Database.save_setting("language", new_lang)
|
Database.save_setting("language", new_lang)
|
||||||
self.view.title(t("app_title"))
|
if self.view is not None:
|
||||||
|
self.view.title(t("app_title"))
|
||||||
if custom_refresh is not None:
|
if custom_refresh is not None:
|
||||||
custom_refresh()
|
custom_refresh()
|
||||||
elif self.active_profile:
|
elif self.active_profile:
|
||||||
|
|
@ -34,34 +83,134 @@ class AppController:
|
||||||
else:
|
else:
|
||||||
self.start()
|
self.start()
|
||||||
|
|
||||||
def start(self):
|
def start(self, status_msg: str = "", is_error: bool = False, login_mode: str = "local"):
|
||||||
self.sounds.play_menu_music()
|
self.sounds.play_menu_music()
|
||||||
profiles = Database.get_profiles()
|
profiles = Database.get_profiles()
|
||||||
last_prof = Database.load_setting("last_profile_name", "")
|
last_prof = Database.load_setting("last_profile_name", "")
|
||||||
self.view.show_login(profiles, preselect_name=last_prof)
|
self.view.show_login(
|
||||||
|
profiles,
|
||||||
|
preselect_name=last_prof,
|
||||||
|
status_msg=status_msg,
|
||||||
|
is_error=is_error,
|
||||||
|
login_mode=login_mode,
|
||||||
|
)
|
||||||
|
|
||||||
def do_login(self, name: str):
|
def do_login(self, name: str):
|
||||||
if not name:
|
if not name:
|
||||||
return
|
return
|
||||||
|
self.online_session.disconnect()
|
||||||
|
self.is_online_mode = False
|
||||||
Database.save_setting("last_profile_name", name)
|
Database.save_setting("last_profile_name", name)
|
||||||
self.active_profile = Database.get_or_create_profile(name)
|
self.active_profile = Database.get_or_create_profile(name)
|
||||||
self.show_main_menu()
|
self.show_main_menu()
|
||||||
|
|
||||||
def do_create_profile(self, name: str):
|
def do_create_profile(self, name: str, first_user_db_dir: str | None = None):
|
||||||
if not name:
|
clean_name = name.strip()
|
||||||
|
if not clean_name:
|
||||||
return
|
return
|
||||||
Database.save_setting("last_profile_name", name)
|
self.online_session.disconnect()
|
||||||
self.active_profile = Database.get_or_create_profile(name)
|
self.is_online_mode = False
|
||||||
|
|
||||||
|
if first_user_db_dir and len(Database.get_profiles()) == 0:
|
||||||
|
try:
|
||||||
|
Database.relocate_for_first_user(Path(first_user_db_dir))
|
||||||
|
except Exception as exc:
|
||||||
|
self.start(
|
||||||
|
status_msg=t("db_err_move_failed", str(exc)),
|
||||||
|
is_error=True,
|
||||||
|
login_mode="local",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
Database.save_setting("last_profile_name", clean_name)
|
||||||
|
self.active_profile = Database.get_or_create_profile(clean_name)
|
||||||
self.show_main_menu()
|
self.show_main_menu()
|
||||||
|
|
||||||
|
def do_online_login(
|
||||||
|
self,
|
||||||
|
addr_mode: str,
|
||||||
|
raw_url: str,
|
||||||
|
raw_ip: str,
|
||||||
|
raw_port: str,
|
||||||
|
username: str,
|
||||||
|
password: str,
|
||||||
|
) -> tuple[bool, str]:
|
||||||
|
clean_user = username.strip()
|
||||||
|
DbLocator.save_online_prefs(addr_mode, raw_url, raw_ip, raw_port, clean_user)
|
||||||
|
|
||||||
|
ok, err_msg = self.online_session.authenticate(
|
||||||
|
addr_mode=addr_mode,
|
||||||
|
raw_url=raw_url,
|
||||||
|
raw_ip=raw_ip,
|
||||||
|
raw_port=raw_port,
|
||||||
|
username=clean_user,
|
||||||
|
password=password,
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
return False, err_msg
|
||||||
|
|
||||||
|
self.is_online_mode = True
|
||||||
|
local_mirror = dict(Database.get_or_create_profile(clean_user))
|
||||||
|
local_mirror["is_online"] = True
|
||||||
|
local_mirror["online_endpoint"] = self.online_session.endpoint_label
|
||||||
|
self.active_profile = local_mirror
|
||||||
|
self.show_main_menu()
|
||||||
|
return True, ""
|
||||||
|
|
||||||
|
def load_user_data_from_file(self, db_file_path: str) -> tuple[bool, str]:
|
||||||
|
if not self.can_modify_user_db():
|
||||||
|
return False, t("db_err_locked_devils")
|
||||||
|
|
||||||
|
ok, info = Database.switch_user_database(Path(db_file_path))
|
||||||
|
if not ok:
|
||||||
|
msg = t("db_err_invalid_file") if info == "invalid_file" else t("db_err_move_failed", info)
|
||||||
|
return False, msg
|
||||||
|
|
||||||
|
self._reload_runtime_preferences_from_db()
|
||||||
|
self.online_session.disconnect()
|
||||||
|
self.is_online_mode = False
|
||||||
|
self.active_profile = None
|
||||||
|
|
||||||
|
profiles = Database.get_profiles()
|
||||||
|
last_prof = Database.load_setting("last_profile_name", "")
|
||||||
|
ok_msg = t("db_load_ok", info)
|
||||||
|
if self.view is not None:
|
||||||
|
self.view.show_login(profiles, preselect_name=last_prof, status_msg=ok_msg, is_error=False)
|
||||||
|
return True, ok_msg
|
||||||
|
|
||||||
|
def move_user_data_to_folder(self, target_dir_path: str) -> tuple[bool, str]:
|
||||||
|
if not self.can_modify_user_db():
|
||||||
|
return False, t("db_err_locked_devils")
|
||||||
|
|
||||||
|
ok, info = Database.move_user_database(Path(target_dir_path))
|
||||||
|
if not ok:
|
||||||
|
return False, t("db_err_move_failed", info)
|
||||||
|
|
||||||
|
if self.active_profile and not self.is_online_mode:
|
||||||
|
refreshed = Database.get_profile_by_id(self.active_profile["id"])
|
||||||
|
if refreshed:
|
||||||
|
self.active_profile = refreshed
|
||||||
|
return True, t("db_move_ok", info)
|
||||||
|
|
||||||
def logout_to_login(self):
|
def logout_to_login(self):
|
||||||
self.sounds.play_menu_music()
|
self.sounds.play_menu_music()
|
||||||
last_prof = self.active_profile["name"] if self.active_profile else Database.load_setting("last_profile_name", "")
|
last_prof = (
|
||||||
|
self.active_profile["name"]
|
||||||
|
if (self.active_profile and not self.is_online_mode)
|
||||||
|
else Database.load_setting("last_profile_name", "")
|
||||||
|
)
|
||||||
|
was_online = self.is_online_mode
|
||||||
|
self.online_session.disconnect()
|
||||||
|
self.is_online_mode = False
|
||||||
self.active_profile = None
|
self.active_profile = None
|
||||||
self.view.show_login(Database.get_profiles(), preselect_name=last_prof)
|
self.view.show_login(
|
||||||
|
Database.get_profiles(),
|
||||||
|
preselect_name=last_prof,
|
||||||
|
login_mode="online" if was_online else "local",
|
||||||
|
)
|
||||||
|
|
||||||
def get_locked_devils_game_folder(self) -> str | None:
|
def get_locked_devils_game_folder(self) -> str | None:
|
||||||
if not self.active_profile:
|
if not self.active_profile or self.is_online_mode:
|
||||||
return None
|
return None
|
||||||
pid = self.active_profile["id"]
|
pid = self.active_profile["id"]
|
||||||
if Database.get_active_devils_bj_account(pid) is not None:
|
if Database.get_active_devils_bj_account(pid) is not None:
|
||||||
|
|
@ -85,26 +234,69 @@ class AppController:
|
||||||
self.launch_game(g)
|
self.launch_game(g)
|
||||||
return
|
return
|
||||||
|
|
||||||
def show_main_menu(self):
|
def show_main_menu(self, category: str | None = None):
|
||||||
self.sounds.play_menu_music()
|
self.sounds.play_menu_music()
|
||||||
if self.active_profile:
|
if self.active_profile:
|
||||||
pid = self.active_profile["id"]
|
pid = self.active_profile["id"]
|
||||||
self.active_profile = Database.get_profile_by_id(pid)
|
fresh = Database.get_profile_by_id(pid)
|
||||||
|
if fresh:
|
||||||
|
fresh = dict(fresh)
|
||||||
|
fresh["overall_progress"] = Database.get_profile_overall_progress(pid)
|
||||||
|
if self.is_online_mode:
|
||||||
|
fresh["is_online"] = True
|
||||||
|
fresh["online_endpoint"] = self.online_session.endpoint_label
|
||||||
|
self.active_profile = fresh
|
||||||
|
|
||||||
if self.has_active_devils_lock():
|
if self.has_active_devils_lock():
|
||||||
self.view.show_main_menu(self.active_profile, [], devils_resume_only=True)
|
self.view.show_main_menu(self.active_profile, [], devils_resume_only=True)
|
||||||
else:
|
else:
|
||||||
games = self.loader.discover_games()
|
games = self.loader.discover_games()
|
||||||
for g in games:
|
for g in games:
|
||||||
g["progress"] = Database.get_game_progress(pid, g["folder"])
|
g["progress"] = Database.get_game_progress(pid, g["folder"])
|
||||||
self.view.show_main_menu(self.active_profile, games, devils_resume_only=False)
|
self.view.main_menu_view.show(
|
||||||
|
self.active_profile, games, devils_resume_only=False, category=category
|
||||||
|
)
|
||||||
|
|
||||||
def show_statistics(self):
|
def show_statistics(self):
|
||||||
if self.has_active_devils_lock():
|
if self.has_active_devils_lock() or not self.active_profile:
|
||||||
return
|
return
|
||||||
self.sounds.play_menu_music()
|
self.sounds.play_menu_music()
|
||||||
if self.active_profile:
|
fresh = Database.get_profile_by_id(self.active_profile["id"])
|
||||||
self.active_profile = Database.get_profile_by_id(self.active_profile["id"])
|
if fresh:
|
||||||
self.view.show_statistics(self.active_profile)
|
if self.is_online_mode:
|
||||||
|
fresh = dict(fresh)
|
||||||
|
fresh["is_online"] = True
|
||||||
|
fresh["online_endpoint"] = self.online_session.endpoint_label
|
||||||
|
self.active_profile = fresh
|
||||||
|
ctx = AppContext(self, game_folder="")
|
||||||
|
from view.unified_stats_view import UnifiedStatsView
|
||||||
|
UnifiedStatsView.open(ctx, game_endpoint=None, on_back=None)
|
||||||
|
|
||||||
|
def show_settings(
|
||||||
|
self,
|
||||||
|
on_back=None,
|
||||||
|
in_game_overlay: bool = False,
|
||||||
|
on_ingame_lang_refresh=None,
|
||||||
|
feedback_txt: str = "",
|
||||||
|
feedback_err: bool = False,
|
||||||
|
):
|
||||||
|
if not in_game_overlay:
|
||||||
|
self.sounds.play_menu_music()
|
||||||
|
if self.view is not None:
|
||||||
|
self.view.show_settings(
|
||||||
|
on_back=on_back,
|
||||||
|
in_game_overlay=in_game_overlay,
|
||||||
|
on_ingame_lang_refresh=on_ingame_lang_refresh,
|
||||||
|
feedback_txt=feedback_txt,
|
||||||
|
feedback_err=feedback_err,
|
||||||
|
)
|
||||||
|
|
||||||
|
def show_profile(self, on_back=None):
|
||||||
|
if self.has_active_devils_lock() or not self.active_profile:
|
||||||
|
return
|
||||||
|
self.sounds.play_menu_music()
|
||||||
|
if self.view is not None:
|
||||||
|
self.view.show_profile(on_back=on_back)
|
||||||
|
|
||||||
def launch_game(self, game_entry: dict):
|
def launch_game(self, game_entry: dict):
|
||||||
self.view.clear_window(apply_global_bg=True)
|
self.view.clear_window(apply_global_bg=True)
|
||||||
|
|
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,283 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/blackjack/views/blackjack_arena_renderer.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from games.blackjack.models.hand_evaluator import HandEvaluator
|
||||||
|
from games.blackjack.models.player_hand import PlayerHand
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
ACCENT_GOLD,
|
||||||
|
ACCENT_GOTH,
|
||||||
|
BJ_BOT_CARD_SIZE,
|
||||||
|
BJ_SPLIT_CARD_SIZE,
|
||||||
|
ERROR_FG,
|
||||||
|
FG_COLOR,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_BODY,
|
||||||
|
PLAYING_CARD_SIZE,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
|
||||||
|
BJ_DEALER_CARD_SIZE = (86, 125)
|
||||||
|
|
||||||
|
BJ_SEAT_LAYOUT_BY_COUNT = {
|
||||||
|
1: (2,),
|
||||||
|
2: (1, 2),
|
||||||
|
3: (1, 2, 3),
|
||||||
|
4: (0, 1, 2, 3),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class BlackjackArenaRenderer:
|
||||||
|
"""Zeichnet Dealer, Pot, Kultisten-Ecken und Spielerhände (inkl. Split) auf das Arena-Canvas."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def hand_state_suffix(hand: PlayerHand) -> str:
|
||||||
|
if hand.busted:
|
||||||
|
return t("bj_state_busted")
|
||||||
|
if hand.folded:
|
||||||
|
return t("bj_state_folded")
|
||||||
|
if hand.doubled or hand.cards_locked:
|
||||||
|
return t("bj_state_locked")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def draw_dealer_and_pot(
|
||||||
|
view,
|
||||||
|
table_rect: tuple[int, int, int, int],
|
||||||
|
player_top_y: int,
|
||||||
|
reveal_dealer: bool,
|
||||||
|
) -> None:
|
||||||
|
tx1, ty1, tx2, ty2 = table_rect
|
||||||
|
t_cx = (tx1 + tx2) // 2
|
||||||
|
t_h = max(260, ty2 - ty1)
|
||||||
|
|
||||||
|
felt_top = ty1 + max(36, int(t_h * 0.15))
|
||||||
|
felt_bot = min(ty2 - max(28, int(t_h * 0.12)), player_top_y - 12)
|
||||||
|
|
||||||
|
_dc_w, dc_h = BJ_DEALER_CARD_SIZE
|
||||||
|
avail_felt_h = max(170, felt_bot - felt_top)
|
||||||
|
d_cards_cy = felt_top + min(dc_h // 2 + 12, int(avail_felt_h * 0.34))
|
||||||
|
|
||||||
|
d_photos = []
|
||||||
|
for c_idx, card in enumerate(view.engine.dealer_hand):
|
||||||
|
photo = (
|
||||||
|
view.ctx.assets.get_card_back_photo(color=view.cfg["back_color"], size=BJ_DEALER_CARD_SIZE)
|
||||||
|
if c_idx == 1 and not reveal_dealer
|
||||||
|
else view.ctx.assets.get_card_photo(card.image_filename, size=BJ_DEALER_CARD_SIZE)
|
||||||
|
)
|
||||||
|
if photo:
|
||||||
|
view._photo_refs.append(photo)
|
||||||
|
d_photos.append(photo)
|
||||||
|
|
||||||
|
if d_photos:
|
||||||
|
view._draw_fanned_cards_on_canvas(
|
||||||
|
t_cx, d_cards_cy, d_photos, BJ_DEALER_CARD_SIZE, visible_step=38, max_width=340
|
||||||
|
)
|
||||||
|
|
||||||
|
pot_txt = t("bj_pot_banner", view.engine.pot).split("|")[0].strip()
|
||||||
|
pot_cy = min(
|
||||||
|
felt_bot - 22,
|
||||||
|
max(d_cards_cy + dc_h // 2 + 34, (d_cards_cy + dc_h // 2 + felt_bot) // 2),
|
||||||
|
)
|
||||||
|
pot_size = max(16, FONT_SIZE_BODY + 1)
|
||||||
|
pot_ph = view._make_goth_photo(pot_txt, size_px=pot_size, color=FONT_COLOR_TITLE_MAIN)
|
||||||
|
if pot_ph is not None:
|
||||||
|
bw, bh = max(230, pot_ph.width() + 64), max(40, pot_ph.height() + 18)
|
||||||
|
view._draw_framed_panel(t_cx, pot_cy, bw, bh, frame_style="gold")
|
||||||
|
view.arena_canvas.create_image(t_cx, pot_cy, image=pot_ph, anchor="center", tags="fg")
|
||||||
|
else:
|
||||||
|
view._draw_framed_panel(t_cx, pot_cy, 240, 40, frame_style="gold")
|
||||||
|
view._place_goth_photo_or_fallback(t_cx, pot_cy, None, pot_txt, pot_size, ACCENT_GOLD)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def draw_bots_at_corners(
|
||||||
|
view,
|
||||||
|
cw: int,
|
||||||
|
ch: int,
|
||||||
|
pad_x: int,
|
||||||
|
pad_top: int,
|
||||||
|
pad_bot: int,
|
||||||
|
table_rect: tuple[int, int, int, int],
|
||||||
|
reveal_opponents: bool,
|
||||||
|
) -> None:
|
||||||
|
if not view.bots:
|
||||||
|
return
|
||||||
|
|
||||||
|
tx1, ty1, tx2, ty2 = table_rect
|
||||||
|
bc_w, bc_h = BJ_BOT_CARD_SIZE
|
||||||
|
card_scale = 0.90 if ch < 560 else 1.0
|
||||||
|
cur_card_sz = (max(52, int(bc_w * card_scale)), max(76, int(bc_h * card_scale)))
|
||||||
|
base_box_w = max(198, cur_card_sz[0] + 114)
|
||||||
|
box_h = cur_card_sz[1] + 90
|
||||||
|
|
||||||
|
top_cy = max(pad_top + box_h // 2, ty1 + box_h // 2 - 4)
|
||||||
|
bot_cy = min(ch - pad_bot - box_h // 2, ty2 - box_h // 2 + 22)
|
||||||
|
if bot_cy - top_cy < box_h + 14:
|
||||||
|
mid_y = (top_cy + bot_cy) // 2
|
||||||
|
top_cy, bot_cy = mid_y - (box_h + 14) // 2, mid_y + (box_h + 14) // 2
|
||||||
|
|
||||||
|
slot_indices = BJ_SEAT_LAYOUT_BY_COUNT.get(len(view.bots), (0, 1, 2, 3))
|
||||||
|
name_sz, sub_sz = max(14, FONT_SIZE_BODY - 1), max(13, FONT_SIZE_BODY - 2)
|
||||||
|
|
||||||
|
for bot_i, bot in enumerate(view.bots):
|
||||||
|
coord_idx = slot_indices[bot_i]
|
||||||
|
is_left_side = coord_idx in (0, 1)
|
||||||
|
by = bot_cy if coord_idx in (0, 3) else top_cy
|
||||||
|
|
||||||
|
is_turn = (bot_i == view.active_bot_idx)
|
||||||
|
is_out = (bot.folded or bot.busted)
|
||||||
|
frame_style = "gold" if is_turn else "purple"
|
||||||
|
status_border = ERROR_FG if is_out else None
|
||||||
|
|
||||||
|
disp_name = t("bj_bot_rebuy", bot.name) if bot.rebought else bot.name
|
||||||
|
name_col = ACCENT_GOLD if is_turn else ACCENT_GOTH
|
||||||
|
gold_txt = t("bj_bot_gold_lbl", bot.gold)
|
||||||
|
|
||||||
|
if reveal_opponents and bot.hand:
|
||||||
|
b_val, _ = HandEvaluator.evaluate(bot.hand)
|
||||||
|
if bot.folded:
|
||||||
|
info_txt = t("bj_rank_folded", b_val)
|
||||||
|
elif bot.busted:
|
||||||
|
info_txt = t("bj_rank_busted", b_val)
|
||||||
|
else:
|
||||||
|
info_txt = t("bj_bot_showdown_val", b_val, bot.bet_in_pot)
|
||||||
|
elif bot.status_text:
|
||||||
|
info_txt = bot.status_text
|
||||||
|
elif bot.hand:
|
||||||
|
info_txt = t("bj_bot_cards_hidden", len(bot.hand), bot.bet_in_pot)
|
||||||
|
else:
|
||||||
|
info_txt = ""
|
||||||
|
|
||||||
|
info_col = ERROR_FG if is_out else FG_COLOR
|
||||||
|
name_ph = view._make_goth_photo(disp_name, name_sz, name_col, max_width=220)
|
||||||
|
gold_ph = view._make_goth_photo(gold_txt, sub_sz, ACCENT_GOLD)
|
||||||
|
info_ph = view._make_goth_photo(info_txt, sub_sz, info_col, max_width=220)
|
||||||
|
|
||||||
|
widest_txt = max((ph.width() for ph in (name_ph, gold_ph, info_ph) if ph), default=140)
|
||||||
|
box_w = max(base_box_w, min(268, widest_txt + 54))
|
||||||
|
|
||||||
|
bx = (
|
||||||
|
max(pad_x + box_w // 2, tx1 + int(box_w * 0.36))
|
||||||
|
if is_left_side else min(cw - pad_x - box_w // 2, tx2 - int(box_w * 0.36))
|
||||||
|
)
|
||||||
|
|
||||||
|
view._draw_framed_panel(bx, by, box_w, box_h, frame_style=frame_style, status_border=status_border)
|
||||||
|
top_y, bot_y = by - box_h // 2, by + box_h // 2
|
||||||
|
view._place_goth_photo_or_fallback(bx, top_y + 23, name_ph, disp_name, name_sz, name_col)
|
||||||
|
view._place_goth_photo_or_fallback(bx, top_y + 42, gold_ph, gold_txt, sub_sz, ACCENT_GOLD)
|
||||||
|
|
||||||
|
show_faces = reveal_opponents or bot.busted
|
||||||
|
bot_photos = []
|
||||||
|
for card in bot.hand:
|
||||||
|
photo = (
|
||||||
|
view.ctx.assets.get_card_photo(card.image_filename, size=cur_card_sz)
|
||||||
|
if show_faces else view.ctx.assets.get_card_back_photo(color=view.cfg["back_color"], size=cur_card_sz)
|
||||||
|
)
|
||||||
|
if photo:
|
||||||
|
view._photo_refs.append(photo)
|
||||||
|
bot_photos.append(photo)
|
||||||
|
|
||||||
|
if bot_photos:
|
||||||
|
view._draw_fanned_cards_on_canvas(
|
||||||
|
bx, by + 6, bot_photos, cur_card_sz, visible_step=25, max_width=box_w - 36
|
||||||
|
)
|
||||||
|
view._place_goth_photo_or_fallback(bx, bot_y - 21, info_ph, info_txt, sub_sz, info_col)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def draw_player_hands(cls, view, cw: int, player_zone_top: int, player_zone_bot: int) -> None:
|
||||||
|
hands = view.engine.player_hands
|
||||||
|
if not hands:
|
||||||
|
return
|
||||||
|
|
||||||
|
avail_h = max(140, player_zone_bot - player_zone_top)
|
||||||
|
zone_cy = (player_zone_top + player_zone_bot) // 2
|
||||||
|
|
||||||
|
if len(hands) == 1:
|
||||||
|
h = hands[0]
|
||||||
|
base_w, base_h = PLAYING_CARD_SIZE
|
||||||
|
scale = max(88, min(base_h, avail_h - 52)) / max(1, base_h)
|
||||||
|
card_sz = (max(60, int(round(base_w * scale))), int(round(base_h * scale)))
|
||||||
|
|
||||||
|
p_photos = []
|
||||||
|
for card in h.cards:
|
||||||
|
photo = view.ctx.assets.get_card_photo(card.image_filename, size=card_sz)
|
||||||
|
if photo:
|
||||||
|
view._photo_refs.append(photo)
|
||||||
|
p_photos.append(photo)
|
||||||
|
|
||||||
|
p_val, p_soft = HandEvaluator.evaluate(h.cards)
|
||||||
|
soft_hint = t("bj_soft_hint", p_val) if p_soft and p_val < 21 else ""
|
||||||
|
lbl_txt = t("bj_player_total", p_val, soft_hint, h.bet_in_pot, cls.hand_state_suffix(h))
|
||||||
|
|
||||||
|
is_player_turn = (view.engine.state == "ACTION_LOOP" and view.active_bot_idx == -1)
|
||||||
|
is_out = (h.busted or h.folded)
|
||||||
|
lbl_col = ERROR_FG if is_out else FONT_COLOR_TITLE_MAIN
|
||||||
|
lbl_sz = max(14, FONT_SIZE_BODY - 1)
|
||||||
|
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, lbl_col)
|
||||||
|
|
||||||
|
step = 36
|
||||||
|
fan_w = card_sz[0] + max(0, len(p_photos) - 1) * step
|
||||||
|
txt_w = lbl_ph.width() if lbl_ph is not None else 240
|
||||||
|
box_w = max(300, min(560, max(fan_w + 96, txt_w + 72)))
|
||||||
|
box_h = min(avail_h, card_sz[1] + 52)
|
||||||
|
|
||||||
|
view._draw_framed_panel(
|
||||||
|
cw // 2, zone_cy, box_w, box_h,
|
||||||
|
frame_style="gold" if is_player_turn and not is_out else "purple",
|
||||||
|
status_border=ERROR_FG if is_out else None,
|
||||||
|
)
|
||||||
|
if p_photos:
|
||||||
|
view._draw_fanned_cards_on_canvas(
|
||||||
|
cw // 2, zone_cy - 11, p_photos, card_sz, visible_step=step, max_width=box_w - 44
|
||||||
|
)
|
||||||
|
view._place_goth_photo_or_fallback(cw // 2, zone_cy + box_h // 2 - 20, lbl_ph, lbl_txt, lbl_sz, lbl_col)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Split-Hände nebeneinander
|
||||||
|
base_w, base_h = BJ_SPLIT_CARD_SIZE
|
||||||
|
scale = max(80, min(base_h, avail_h - 48)) / max(1, base_h)
|
||||||
|
card_sz = (max(54, int(round(base_w * scale))), int(round(base_h * scale)))
|
||||||
|
box_h = min(avail_h, card_sz[1] + 48)
|
||||||
|
lbl_sz = max(13, FONT_SIZE_BODY - 2)
|
||||||
|
|
||||||
|
prepared_splits = []
|
||||||
|
max_box_w = 228
|
||||||
|
for idx, h in enumerate(hands):
|
||||||
|
is_active = (
|
||||||
|
view.engine.state == "ACTION_LOOP"
|
||||||
|
and view.active_bot_idx == -1
|
||||||
|
and idx == view.active_hand_idx
|
||||||
|
)
|
||||||
|
is_out = (h.busted or h.folded)
|
||||||
|
p_val, p_soft = HandEvaluator.evaluate(h.cards)
|
||||||
|
soft_hint = t("bj_soft_hint", p_val) if p_soft and p_val < 21 else ""
|
||||||
|
lbl_txt = t("bj_hand_box_title", idx + 1, p_val, soft_hint, h.bet_in_pot, cls.hand_state_suffix(h))
|
||||||
|
lbl_col = ACCENT_GOLD if is_active else (ERROR_FG if is_out else FG_COLOR)
|
||||||
|
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, lbl_col)
|
||||||
|
txt_w = lbl_ph.width() if lbl_ph is not None else 180
|
||||||
|
sp_fan_w = card_sz[0] + max(0, len(h.cards) - 1) * 28
|
||||||
|
max_box_w = max(max_box_w, max(228, min(320, max(sp_fan_w + 64, txt_w + 60))))
|
||||||
|
prepared_splits.append((h, is_active, is_out, lbl_txt, lbl_col, lbl_ph))
|
||||||
|
|
||||||
|
n_hands = len(hands)
|
||||||
|
slot_gap = max(max_box_w + 14, min(310, (cw - 360) // max(1, n_hands)))
|
||||||
|
start_cx = cw // 2 - ((n_hands - 1) * slot_gap) // 2
|
||||||
|
|
||||||
|
for idx, (h, is_active, is_out, lbl_txt, lbl_col, lbl_ph) in enumerate(prepared_splits):
|
||||||
|
h_cx = start_cx + idx * slot_gap
|
||||||
|
view._draw_framed_panel(
|
||||||
|
h_cx, zone_cy, max_box_w, box_h,
|
||||||
|
frame_style="gold" if is_active else "purple",
|
||||||
|
status_border=ERROR_FG if is_out else None,
|
||||||
|
)
|
||||||
|
sp_photos = []
|
||||||
|
for card in h.cards:
|
||||||
|
photo = view.ctx.assets.get_card_photo(card.image_filename, size=card_sz)
|
||||||
|
if photo:
|
||||||
|
view._photo_refs.append(photo)
|
||||||
|
sp_photos.append(photo)
|
||||||
|
if sp_photos:
|
||||||
|
view._draw_fanned_cards_on_canvas(
|
||||||
|
h_cx, zone_cy - 10, sp_photos, card_sz, visible_step=28, max_width=max_box_w - 36
|
||||||
|
)
|
||||||
|
view._place_goth_photo_or_fallback(h_cx, zone_cy + box_h // 2 - 18, lbl_ph, lbl_txt, lbl_sz, lbl_col)
|
||||||
|
|
@ -1,449 +1,77 @@
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
# games/blackjack/views/blackjack_menu_view.py
|
# games/blackjack/views/blackjack_menu_view.py
|
||||||
import sqlite3
|
from __future__ import annotations
|
||||||
import tkinter as tk
|
|
||||||
from tkinter import ttk
|
|
||||||
|
|
||||||
from games.blackjack.views.blackjack_stats_view import BlackjackStatsView
|
|
||||||
from games.blackjack.views.blackjack_table_view import BlackjackTableView
|
from games.blackjack.views.blackjack_table_view import BlackjackTableView
|
||||||
from models.database import Database
|
from models.database import Database
|
||||||
from models.progression import Progression
|
|
||||||
from resources.code_res.game_constants import (
|
from resources.code_res.game_constants import (
|
||||||
ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BJ_INITIAL_ANTE, BJ_MAX_BOTS,
|
BJ_INITIAL_ANTE,
|
||||||
BJ_STARTING_GOLD, BJ_VARIANTS, BORDER_COLOR, CELL_BG,
|
BJ_MAX_BOTS,
|
||||||
DEVILS_DEAL_GOLD_REWARD, ERROR_FG, FG_COLOR, GOLD_MAX_ACCOUNTS,
|
BJ_STARTING_GOLD,
|
||||||
GOLD_MIN_TABLE_ENTRY, INPUT_BG, MUTED_FG, PANEL_BG,
|
BJ_VARIANTS,
|
||||||
SUBTLE_BORDER, XP_TO_GOLD_AMOUNT
|
GOLD_MAX_ACCOUNTS,
|
||||||
|
GOLD_MIN_TABLE_ENTRY,
|
||||||
|
XP_TO_GOLD_AMOUNT,
|
||||||
)
|
)
|
||||||
from resources.code_res.i18n import t
|
from resources.code_res.i18n import t
|
||||||
from view.widgets.bot_setup_widget import BotSetupWidget
|
from view.widgets.luck_pouch_menu_base import LuckPouchMenuBase
|
||||||
from view.widgets.image_button import ImageButton
|
|
||||||
|
|
||||||
GAME_FOLDER_ID = "blackjack"
|
GAME_FOLDER_ID = "blackjack"
|
||||||
|
|
||||||
|
|
||||||
class BlackjackMenuView:
|
class BlackjackMenuView(LuckPouchMenuBase):
|
||||||
def __init__(self, context):
|
GAME_FOLDER_ID = GAME_FOLDER_ID
|
||||||
self.ctx = context
|
LAST_ACC_SETTING_PREFIX = "last_bj_account"
|
||||||
self.bot_widget: BotSetupWidget | None = None
|
STARTING_GOLD = BJ_STARTING_GOLD
|
||||||
|
MAX_BOTS = BJ_MAX_BOTS
|
||||||
|
REQUIRES_MIN_ONE_BOT = False
|
||||||
|
DEVILS_DEFAULT_VARIANT = "bj_classic"
|
||||||
|
|
||||||
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
|
KEY_TOPBAR = "bj_menu_topbar"
|
||||||
pid = self.ctx.profile["id"]
|
KEY_HEADER_GOLD = "bj_header_gold"
|
||||||
|
KEY_SEC1_TITLE = "bj_sec1_title"
|
||||||
|
KEY_BOTS_TITLE = "bj_bots_sec_title"
|
||||||
|
KEY_SEC3_TITLE = "bj_sec3_title"
|
||||||
|
KEY_GOLD_DISPLAY = "bj_gold_display_lbl"
|
||||||
|
KEY_DEFAULT_ACC_NAME = "bj_default_acc_name"
|
||||||
|
KEY_ERR_DUPLICATE = "bj_err_duplicate_name"
|
||||||
|
|
||||||
# Aktiver Devil's Deal zwingt direkt an den Tisch
|
def _get_active_devils_account(self, pid: int):
|
||||||
devils_acc = Database.get_active_devils_bj_account(pid)
|
return Database.get_active_devils_bj_account(pid)
|
||||||
if devils_acc is not None:
|
|
||||||
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
|
|
||||||
if saved is not None:
|
|
||||||
BlackjackTableView(
|
|
||||||
self.ctx,
|
|
||||||
variant_key=saved["variant_key"],
|
|
||||||
bj_account_id=devils_acc["id"],
|
|
||||||
bot_configs=[],
|
|
||||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
|
|
||||||
resume_state_json=saved["state_json"],
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
self.ctx.sounds.play_menu_music()
|
def _get_accounts(self, pid: int):
|
||||||
self.ctx.root.clear_window(apply_global_bg=True)
|
return Database.get_blackjack_accounts(pid)
|
||||||
bj_prog = self.ctx.refresh_game_progress()
|
|
||||||
|
|
||||||
dyn_xp_cost = bj_prog["xp_exchange_cost"]
|
def _get_account(self, acc_id: int):
|
||||||
is_divine = bj_prog["is_divine_punishment"]
|
return Database.get_blackjack_account(acc_id)
|
||||||
at_floor = bj_prog["at_divine_floor"]
|
|
||||||
devils_deal_open = bj_prog["devils_deal_unlocked"]
|
|
||||||
|
|
||||||
setting_key = f"last_bj_account_{pid}"
|
def _create_account(self, pid: int, name: str):
|
||||||
accounts = Database.get_blackjack_accounts(pid)
|
return Database.create_blackjack_account(pid, name)
|
||||||
has_accounts = len(accounts) > 0
|
|
||||||
|
|
||||||
if preselect_id is None and has_accounts:
|
def _delete_account(self, acc_id: int):
|
||||||
saved_id_str = Database.load_setting(setting_key, "")
|
Database.delete_blackjack_account(acc_id)
|
||||||
if saved_id_str.isdigit():
|
|
||||||
preselect_id = int(saved_id_str)
|
|
||||||
|
|
||||||
# Im Dropdown stehen nur noch die sauberen Kontonamen; Gold wird prominent separat angezeigt!
|
def _exchange_xp(self, pid: int, acc_id: int):
|
||||||
acc_by_name = {a["account_name"]: a for a in accounts}
|
return Database.exchange_xp_for_bj_gold(pid, acc_id)
|
||||||
acc_names = list(acc_by_name.keys())
|
|
||||||
|
|
||||||
active_acc = None
|
def _variants_dict(self) -> dict[str, dict]:
|
||||||
if has_accounts:
|
return BJ_VARIANTS
|
||||||
active_acc = accounts[0]
|
|
||||||
if preselect_id is not None:
|
|
||||||
for a in accounts:
|
|
||||||
if a["id"] == preselect_id:
|
|
||||||
active_acc = a
|
|
||||||
break
|
|
||||||
Database.save_setting(setting_key, str(active_acc["id"]))
|
|
||||||
|
|
||||||
selected_name_var = tk.StringVar(
|
def _min_entry_for_variant(self, _v_key: str, _cfg: dict) -> int:
|
||||||
value=active_acc["account_name"] if active_acc else t("bj_no_account_item")
|
return GOLD_MIN_TABLE_ENTRY
|
||||||
|
|
||||||
|
def _format_variant_desc(self, _v_key: str, cfg: dict) -> str:
|
||||||
|
return t("bj_variant_desc", cfg["decks"], BJ_INITIAL_ANTE)
|
||||||
|
|
||||||
|
def _format_limit_info(self, dyn_xp_cost: int) -> str:
|
||||||
|
return t("bj_acc_limit_info", GOLD_MAX_ACCOUNTS, BJ_INITIAL_ANTE, dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
||||||
|
|
||||||
|
def _launch_table(self, variant_key: str, acc_id: int, bots: list, resume_json: str | None = None):
|
||||||
|
BlackjackTableView(
|
||||||
|
self.ctx,
|
||||||
|
variant_key=variant_key,
|
||||||
|
bj_account_id=acc_id,
|
||||||
|
bot_configs=bots,
|
||||||
|
on_back_to_menu=lambda aid, msg="": self.show(preselect_id=aid, status_msg=msg),
|
||||||
|
resume_state_json=resume_json,
|
||||||
)
|
)
|
||||||
feedback_var = tk.StringVar(value=status_msg)
|
|
||||||
|
|
||||||
def get_current_acc() -> dict | None:
|
|
||||||
return acc_by_name.get(selected_name_var.get())
|
|
||||||
|
|
||||||
def open_bj_stats():
|
|
||||||
cur = get_current_acc()
|
|
||||||
if cur is None:
|
|
||||||
return
|
|
||||||
if self.bot_widget is not None and has_accounts:
|
|
||||||
_, to_save = self.bot_widget.collect_configs()
|
|
||||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
|
||||||
BlackjackStatsView(
|
|
||||||
self.ctx,
|
|
||||||
on_back_to_bj_menu=lambda aid: self.show(preselect_id=aid)
|
|
||||||
).show(selected_acc_id=cur["id"])
|
|
||||||
|
|
||||||
def refresh_on_lang_switch():
|
|
||||||
cur = get_current_acc()
|
|
||||||
if self.bot_widget is not None and has_accounts:
|
|
||||||
_, to_save = self.bot_widget.collect_configs()
|
|
||||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
|
||||||
self.show(preselect_id=cur["id"] if cur else None)
|
|
||||||
|
|
||||||
topbar_gold_txt = (
|
|
||||||
t("bj_header_gold", active_acc["account_name"], active_acc["gold"])
|
|
||||||
if active_acc else ""
|
|
||||||
)
|
|
||||||
topbar = self.ctx.build_game_topbar(
|
|
||||||
self.ctx.root,
|
|
||||||
t("bj_menu_topbar"),
|
|
||||||
on_game_menu=None,
|
|
||||||
on_stats=open_bj_stats,
|
|
||||||
stats_enabled=has_accounts,
|
|
||||||
extra_right_text=topbar_gold_txt,
|
|
||||||
on_lang_refresh=refresh_on_lang_switch,
|
|
||||||
)
|
|
||||||
|
|
||||||
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=14)
|
|
||||||
container.place(relx=0.5, rely=0.52, anchor="center", relwidth=0.92, relheight=0.82)
|
|
||||||
|
|
||||||
main_card = tk.Frame(
|
|
||||||
container, bg=PANEL_BG, padx=24, pady=18,
|
|
||||||
highlightthickness=1, highlightbackground=BORDER_COLOR
|
|
||||||
)
|
|
||||||
main_card.pack(fill="x")
|
|
||||||
|
|
||||||
upper_split = tk.Frame(main_card, bg=PANEL_BG)
|
|
||||||
upper_split.pack(fill="x", pady=(0, 12))
|
|
||||||
upper_split.columnconfigure(0, weight=1, uniform="cols")
|
|
||||||
upper_split.columnconfigure(1, weight=1, uniform="cols")
|
|
||||||
|
|
||||||
# =====================================================================
|
|
||||||
# SPALTE 1: Goldkonto-Verwaltung (exaktes 3-Spalten-Grid für gleiche Breiten!)
|
|
||||||
# =====================================================================
|
|
||||||
left_col = tk.Frame(upper_split, bg=PANEL_BG)
|
|
||||||
left_col.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
left_col,
|
|
||||||
text=t("bj_sec1_title", len(accounts), GOLD_MAX_ACCOUNTS, BJ_STARTING_GOLD),
|
|
||||||
font=("Georgia", 12, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG
|
|
||||||
).pack(anchor="w", pady=(0, 6))
|
|
||||||
|
|
||||||
acc_box = tk.Frame(left_col, bg=CELL_BG, padx=14, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
|
|
||||||
acc_box.pack(fill="both", expand=True)
|
|
||||||
|
|
||||||
form_grid = tk.Frame(acc_box, bg=CELL_BG)
|
|
||||||
form_grid.pack(fill="x")
|
|
||||||
form_grid.columnconfigure(1, weight=1)
|
|
||||||
|
|
||||||
# --- Zeile 0: Aktives Konto (Dropdown + XP-Tausch Button) ---
|
|
||||||
tk.Label(
|
|
||||||
form_grid, text=t("bj_active_acc_lbl"),
|
|
||||||
font=("Helvetica", 10, "bold"), fg=FG_COLOR if has_accounts else MUTED_FG, bg=CELL_BG
|
|
||||||
).grid(row=0, column=0, sticky="w", padx=(0, 10), pady=4)
|
|
||||||
|
|
||||||
acc_cb = ttk.Combobox(
|
|
||||||
form_grid,
|
|
||||||
textvariable=selected_name_var,
|
|
||||||
values=acc_names if has_accounts else [t("bj_no_account_item")],
|
|
||||||
state="readonly" if has_accounts else "disabled",
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
style="Goth.TCombobox",
|
|
||||||
)
|
|
||||||
acc_cb.grid(row=0, column=1, sticky="ew", padx=(0, 10), pady=4, ipady=2)
|
|
||||||
|
|
||||||
def exchange_xp_action():
|
|
||||||
cur = get_current_acc()
|
|
||||||
if cur is None:
|
|
||||||
return
|
|
||||||
if self.bot_widget is not None:
|
|
||||||
_, to_save = self.bot_widget.collect_configs()
|
|
||||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
|
||||||
ok, msg = Database.exchange_xp_for_bj_gold(pid, cur["id"])
|
|
||||||
if ok and is_divine:
|
|
||||||
self.ctx.sounds.play("lose")
|
|
||||||
self.show(preselect_id=cur["id"], status_msg=msg, status_is_ok=ok)
|
|
||||||
|
|
||||||
can_afford_xp = is_divine or (bj_prog["total_points"] >= dyn_xp_cost)
|
|
||||||
can_exchange = has_accounts and (not at_floor) and can_afford_xp
|
|
||||||
|
|
||||||
ex_btn_txt = (
|
|
||||||
t("bj_exchange_divine_btn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
|
|
||||||
if is_divine else t("bj_exchange_btn", dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
|
||||||
)
|
|
||||||
exchange_btn = ImageButton(
|
|
||||||
form_grid, ex_btn_txt,
|
|
||||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
|
||||||
exchange_xp_action, sound_mgr=self.ctx.sounds,
|
|
||||||
width=185, height=34, font=("Helvetica", 9, "bold"),
|
|
||||||
enabled=can_exchange,
|
|
||||||
)
|
|
||||||
exchange_btn.grid(row=0, column=2, sticky="e", pady=4)
|
|
||||||
|
|
||||||
# --- Zeile 1: Prominente Gold-Anzeige + Konto löschen ---
|
|
||||||
gold_banner = tk.Frame(
|
|
||||||
acc_box, bg=PANEL_BG, padx=12, pady=8,
|
|
||||||
highlightthickness=1, highlightbackground=BORDER_COLOR if has_accounts else SUBTLE_BORDER
|
|
||||||
)
|
|
||||||
gold_banner.pack(fill="x", pady=(8, 8))
|
|
||||||
|
|
||||||
gold_var = tk.StringVar(
|
|
||||||
value=t("bj_gold_display_lbl", active_acc["gold"]) if active_acc else t("bj_gold_display_none")
|
|
||||||
)
|
|
||||||
gold_lbl = tk.Label(
|
|
||||||
gold_banner, textvariable=gold_var,
|
|
||||||
font=("Georgia", 13, "bold"),
|
|
||||||
fg=ACCENT_GOLD if active_acc else MUTED_FG,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
)
|
|
||||||
gold_lbl.pack(side="left")
|
|
||||||
|
|
||||||
def delete_selected_account():
|
|
||||||
cur = get_current_acc()
|
|
||||||
if cur is not None:
|
|
||||||
Database.delete_blackjack_account(cur["id"])
|
|
||||||
self.show()
|
|
||||||
|
|
||||||
delete_btn = ImageButton(
|
|
||||||
gold_banner, t("bj_delete_acc_btn"),
|
|
||||||
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
|
|
||||||
delete_selected_account, sound_mgr=self.ctx.sounds,
|
|
||||||
width=120, height=30, font=("Helvetica", 9, "bold"),
|
|
||||||
enabled=has_accounts,
|
|
||||||
)
|
|
||||||
delete_btn.pack(side="right")
|
|
||||||
|
|
||||||
# --- Zeile 2: Neues Konto anlegen (exakt gleiche Eingabefeld-Breite wie Dropdown oben!) ---
|
|
||||||
create_grid = tk.Frame(acc_box, bg=CELL_BG)
|
|
||||||
create_grid.pack(fill="x")
|
|
||||||
create_grid.columnconfigure(1, weight=1)
|
|
||||||
# Unsichtbarer Platzhalter hält Spalte 0 exakt so breit wie "Aktives Konto:" oben
|
|
||||||
lbl_w = max(len(t("bj_active_acc_lbl")), len(t("bj_new_acc_lbl")))
|
|
||||||
form_grid.grid_slaves(row=0, column=0)[0].configure(width=lbl_w, anchor="w")
|
|
||||||
|
|
||||||
can_create_more = len(accounts) < GOLD_MAX_ACCOUNTS
|
|
||||||
tk.Label(
|
|
||||||
create_grid, text=t("bj_new_acc_lbl"), width=lbl_w, anchor="w",
|
|
||||||
font=("Helvetica", 10, "bold" if not has_accounts else "normal"),
|
|
||||||
fg=ACCENT_GOLD if not has_accounts else (FG_COLOR if can_create_more else MUTED_FG),
|
|
||||||
bg=CELL_BG,
|
|
||||||
).grid(row=0, column=0, sticky="w", padx=(0, 10), pady=4)
|
|
||||||
|
|
||||||
next_idx = len(accounts) + 1
|
|
||||||
new_acc_var = tk.StringVar(
|
|
||||||
value=t("bj_default_acc_name", next_idx) if can_create_more else t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS)
|
|
||||||
)
|
|
||||||
new_entry = tk.Entry(
|
|
||||||
create_grid, textvariable=new_acc_var, font=("Helvetica", 10),
|
|
||||||
bg=INPUT_BG, fg=FG_COLOR, disabledbackground="#16141c", disabledforeground="#666070",
|
|
||||||
bd=0, highlightthickness=1, highlightbackground=ACCENT_GOLD if not has_accounts else BORDER_COLOR,
|
|
||||||
insertbackground="white", state="normal" if can_create_more else "disabled"
|
|
||||||
)
|
|
||||||
new_entry.grid(row=0, column=1, sticky="ew", padx=(0, 10), pady=4, ipady=5)
|
|
||||||
|
|
||||||
def create_new_account():
|
|
||||||
if not can_create_more:
|
|
||||||
return
|
|
||||||
name = new_acc_var.get().strip()
|
|
||||||
if not name:
|
|
||||||
feedback_var.set(t("bj_err_empty_name"))
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
if self.bot_widget is not None and has_accounts:
|
|
||||||
_, to_save = self.bot_widget.collect_configs()
|
|
||||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
|
||||||
created = Database.create_blackjack_account(pid, name)
|
|
||||||
Database.save_setting(setting_key, str(created["id"]))
|
|
||||||
self.show(preselect_id=created["id"])
|
|
||||||
except (sqlite3.IntegrityError, RuntimeError) as exc:
|
|
||||||
feedback_var.set(t("bj_err_duplicate_name") if isinstance(exc, sqlite3.IntegrityError) else str(exc))
|
|
||||||
|
|
||||||
if can_create_more:
|
|
||||||
new_entry.bind("<Return>", lambda _e: create_new_account())
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
create_grid, t("bj_create_acc_btn", BJ_STARTING_GOLD),
|
|
||||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
|
||||||
create_new_account, sound_mgr=self.ctx.sounds,
|
|
||||||
width=185, height=34, font=("Helvetica", 9, "bold"),
|
|
||||||
enabled=can_create_more,
|
|
||||||
).grid(row=0, column=2, sticky="e", pady=4)
|
|
||||||
|
|
||||||
# --- Info / Divine Punishment / The Devil's Deal ---
|
|
||||||
min_sac_lvl = Progression.get_devils_deal_min_level()
|
|
||||||
if devils_deal_open and has_accounts:
|
|
||||||
tk.Label(
|
|
||||||
acc_box,
|
|
||||||
text=t("bj_devils_deal_warn", min_sac_lvl, DEVILS_DEAL_GOLD_REWARD),
|
|
||||||
font=("Helvetica", 8, "bold"), fg=ERROR_FG, bg=CELL_BG, wraplength=480, justify="left"
|
|
||||||
).pack(anchor="w", pady=(6, 4))
|
|
||||||
|
|
||||||
sac_candidates = Database.get_sacrificeable_profiles(pid, GAME_FOLDER_ID)
|
|
||||||
if sac_candidates:
|
|
||||||
devil_row = tk.Frame(acc_box, bg=CELL_BG)
|
|
||||||
devil_row.pack(fill="x", pady=(2, 0))
|
|
||||||
sac_map = {f"{c['name']} ({c['title']} • Lv. {c['level']})": c["id"] for c in sac_candidates}
|
|
||||||
sac_var = tk.StringVar(value=next(iter(sac_map.keys())))
|
|
||||||
ttk.Combobox(
|
|
||||||
devil_row, textvariable=sac_var, values=list(sac_map.keys()),
|
|
||||||
state="readonly", font=("Helvetica", 9), width=26, style="Goth.TCombobox"
|
|
||||||
).pack(side="left", fill="x", expand=True, padx=(0, 8))
|
|
||||||
|
|
||||||
def seal_devils_deal():
|
|
||||||
cur = get_current_acc()
|
|
||||||
victim_id = sac_map.get(sac_var.get())
|
|
||||||
if cur is None or victim_id is None:
|
|
||||||
return
|
|
||||||
active_bots, to_save = self.bot_widget.collect_configs() if self.bot_widget else ([], {})
|
|
||||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
|
||||||
ok, _msg = Database.execute_devils_deal(pid, GAME_FOLDER_ID, victim_id, cur["id"])
|
|
||||||
if ok:
|
|
||||||
self.ctx.sounds.play("end_battle")
|
|
||||||
BlackjackTableView(
|
|
||||||
self.ctx,
|
|
||||||
variant_key="bj_classic",
|
|
||||||
bj_account_id=cur["id"],
|
|
||||||
bot_configs=active_bots,
|
|
||||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
|
|
||||||
)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
devil_row, t("bj_devils_deal_btn", DEVILS_DEAL_GOLD_REWARD),
|
|
||||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
|
||||||
seal_devils_deal, sound_mgr=None, width=185, height=32, font=("Helvetica", 9, "bold")
|
|
||||||
).pack(side="right")
|
|
||||||
else:
|
|
||||||
tk.Label(
|
|
||||||
acc_box, text=t("bj_devils_deal_none", min_sac_lvl),
|
|
||||||
font=("Helvetica", 8), fg=MUTED_FG, bg=CELL_BG
|
|
||||||
).pack(anchor="w")
|
|
||||||
else:
|
|
||||||
info_text = (
|
|
||||||
t("bj_divine_punishment_warn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
|
|
||||||
if is_divine
|
|
||||||
else t("bj_acc_limit_info", GOLD_MAX_ACCOUNTS, BJ_INITIAL_ANTE, dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
|
||||||
)
|
|
||||||
tk.Label(
|
|
||||||
acc_box, text=info_text,
|
|
||||||
font=("Helvetica", 8, "bold" if is_divine else "normal"),
|
|
||||||
fg=ERROR_FG if is_divine else MUTED_FG,
|
|
||||||
bg=CELL_BG, wraplength=480, justify="left"
|
|
||||||
).pack(anchor="w", pady=(6, 0))
|
|
||||||
|
|
||||||
# =====================================================================
|
|
||||||
# SPALTE 2: Gegner-Setup (inaktiv ausgegraut, solange kein Konto existiert)
|
|
||||||
# =====================================================================
|
|
||||||
right_col = tk.Frame(upper_split, bg=PANEL_BG)
|
|
||||||
right_col.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
right_col, text=t("bj_bots_sec_title"),
|
|
||||||
font=("Georgia", 12, "bold"), fg=ACCENT_GOTH if has_accounts else MUTED_FG, bg=PANEL_BG
|
|
||||||
).pack(anchor="w", pady=(0, 6))
|
|
||||||
|
|
||||||
saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID)
|
|
||||||
self.bot_widget = BotSetupWidget(right_col, saved_bots, max_bots=BJ_MAX_BOTS, enabled=has_accounts)
|
|
||||||
self.bot_widget.pack(fill="both", expand=True)
|
|
||||||
|
|
||||||
fb_lbl = tk.Label(
|
|
||||||
main_card, textvariable=feedback_var,
|
|
||||||
font=("Helvetica", 9, "bold"),
|
|
||||||
fg="#7be08a" if status_is_ok else ERROR_FG,
|
|
||||||
bg=PANEL_BG
|
|
||||||
)
|
|
||||||
fb_lbl.pack(anchor="w", pady=(2, 4))
|
|
||||||
|
|
||||||
# =====================================================================
|
|
||||||
# SEKTION 3: Spielvariante wählen (Buttons mit Graufilter, wenn Konto fehlt / < 10 Gold)
|
|
||||||
# =====================================================================
|
|
||||||
tk.Label(
|
|
||||||
main_card, text=t("bj_sec3_title"),
|
|
||||||
font=("Georgia", 12, "bold"), fg=ACCENT_GOTH if has_accounts else MUTED_FG, bg=PANEL_BG
|
|
||||||
).pack(anchor="w", pady=(2, 8))
|
|
||||||
|
|
||||||
def enter_table(v_key: str):
|
|
||||||
fb_lbl.configure(fg=ERROR_FG)
|
|
||||||
cur = get_current_acc()
|
|
||||||
if not cur:
|
|
||||||
return
|
|
||||||
acc = Database.get_blackjack_account(cur["id"])
|
|
||||||
if not acc:
|
|
||||||
return
|
|
||||||
Database.save_setting(setting_key, str(acc["id"]))
|
|
||||||
active_bots, configs_to_save = self.bot_widget.collect_configs()
|
|
||||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, configs_to_save)
|
|
||||||
|
|
||||||
cur_bj_prog = self.ctx.refresh_game_progress()
|
|
||||||
if acc["gold"] < GOLD_MIN_TABLE_ENTRY:
|
|
||||||
feedback_var.set(t(
|
|
||||||
"bj_err_not_enough_gold_entry",
|
|
||||||
acc["account_name"], GOLD_MIN_TABLE_ENTRY, acc["gold"],
|
|
||||||
cur_bj_prog["xp_exchange_cost"], XP_TO_GOLD_AMOUNT
|
|
||||||
))
|
|
||||||
return
|
|
||||||
|
|
||||||
BlackjackTableView(
|
|
||||||
self.ctx, v_key, acc["id"], active_bots,
|
|
||||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg)
|
|
||||||
)
|
|
||||||
|
|
||||||
variants_row = tk.Frame(main_card, bg=PANEL_BG)
|
|
||||||
variants_row.pack(fill="x")
|
|
||||||
for idx in range(len(BJ_VARIANTS)):
|
|
||||||
variants_row.columnconfigure(idx, weight=1)
|
|
||||||
|
|
||||||
table_buttons: list[ImageButton] = []
|
|
||||||
can_enter_now = bool(active_acc and active_acc["gold"] >= GOLD_MIN_TABLE_ENTRY)
|
|
||||||
|
|
||||||
for idx, (v_key, cfg) in enumerate(BJ_VARIANTS.items()):
|
|
||||||
card = tk.Frame(variants_row, bg=CELL_BG, padx=16, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
|
|
||||||
card.grid(row=0, column=idx, padx=(0, 8) if idx == 0 else (8, 0), sticky="nsew")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
card, text=t(f"variant_{v_key}"),
|
|
||||||
font=("Georgia", 12, "bold"), fg=FG_COLOR if has_accounts else MUTED_FG, bg=CELL_BG
|
|
||||||
).pack(anchor="w")
|
|
||||||
tk.Label(
|
|
||||||
card, text=t("bj_variant_desc", cfg["decks"], BJ_INITIAL_ANTE),
|
|
||||||
font=("Helvetica", 9), fg=MUTED_FG, bg=CELL_BG
|
|
||||||
).pack(anchor="w", pady=(4, 10))
|
|
||||||
|
|
||||||
t_btn = ImageButton(
|
|
||||||
card, t("bj_enter_table_btn"),
|
|
||||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
|
||||||
lambda k=v_key: enter_table(k),
|
|
||||||
sound_mgr=self.ctx.sounds, width=160, height=36,
|
|
||||||
font=("Helvetica", 10, "bold"), enabled=can_enter_now,
|
|
||||||
)
|
|
||||||
t_btn.pack(anchor="e")
|
|
||||||
table_buttons.append(t_btn)
|
|
||||||
|
|
||||||
# Live-Aktualisierung beim Konto-Wechsel im Dropdown
|
|
||||||
def on_account_switched(*_):
|
|
||||||
cur = get_current_acc()
|
|
||||||
if cur is not None:
|
|
||||||
fresh = Database.get_blackjack_account(cur["id"])
|
|
||||||
Database.save_setting(setting_key, str(fresh["id"]))
|
|
||||||
gold_var.set(t("bj_gold_display_lbl", fresh["gold"]))
|
|
||||||
topbar.extra_label.configure(text=t("bj_header_gold", fresh["account_name"], fresh["gold"]))
|
|
||||||
playable = fresh["gold"] >= GOLD_MIN_TABLE_ENTRY
|
|
||||||
for tb in table_buttons:
|
|
||||||
tb.set_enabled(playable)
|
|
||||||
feedback_var.set("")
|
|
||||||
|
|
||||||
acc_cb.bind("<<ComboboxSelected>>", on_account_switched)
|
|
||||||
|
|
@ -0,0 +1,307 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/blackjack/views/blackjack_showdown_presenter.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
from games.blackjack.models.bot_seat import BlackjackBotSeat
|
||||||
|
from games.blackjack.models.hand_evaluator import HandEvaluator
|
||||||
|
from models.card import Card
|
||||||
|
from models.database import Database
|
||||||
|
from models.progression import Progression
|
||||||
|
from resources.code_res.game_constants import GOLD_MIN_TABLE_ENTRY
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
|
||||||
|
|
||||||
|
class BlackjackShowdownPresenter:
|
||||||
|
"""Kapselt Showdown-Abrechnung, 7-7-7-Sofortsieg, XP-Vergabe und Popup-Aufbereitung."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def count_all_table_cards(view) -> None:
|
||||||
|
if len(view.engine.dealer_hand) >= 2:
|
||||||
|
for c in view.engine.dealer_hand[1:]:
|
||||||
|
view.bot_ai.observe_public_card(c)
|
||||||
|
for h in view.engine.player_hands:
|
||||||
|
for c in h.cards:
|
||||||
|
view.bot_ai.observe_public_card(c)
|
||||||
|
for b in view.bots:
|
||||||
|
for c in b.hand:
|
||||||
|
view.bot_ai.observe_public_card(c)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def resolve_devils_lock(view, outcome_type: str) -> None:
|
||||||
|
if not view.devils_locked:
|
||||||
|
view._clear_persisted_state()
|
||||||
|
return
|
||||||
|
updated_acc = Database.get_blackjack_account(view.bj_account["id"])
|
||||||
|
if not (outcome_type == "TIE" and updated_acc["gold"] == GOLD_MIN_TABLE_ENTRY):
|
||||||
|
Database.set_bj_devils_deal_active(view.bj_account["id"], False)
|
||||||
|
view.devils_locked = False
|
||||||
|
view._clear_persisted_state()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def award_xp_and_record(view, outcome_type: str, won_stat: bool | None) -> tuple[int, int | None]:
|
||||||
|
duration = max(0.5, time.time() - view.round_start_time)
|
||||||
|
prog_before = view.ctx.refresh_game_progress()
|
||||||
|
opp_levels = [b.ai_level for b in view.bots]
|
||||||
|
|
||||||
|
xp_gained = Progression.calculate_match_xp(
|
||||||
|
player_level=prog_before["level"],
|
||||||
|
opponent_levels=opp_levels,
|
||||||
|
outcome_type=outcome_type,
|
||||||
|
variant_mult=view.cfg["xp_mult"],
|
||||||
|
)
|
||||||
|
|
||||||
|
if won_stat is None:
|
||||||
|
Database.add_game_points(view.ctx.profile["id"], view.GAME_FOLDER_ID, xp_gained)
|
||||||
|
prog_after = view.ctx.refresh_game_progress()
|
||||||
|
view.ctx.sounds.play("end_battle")
|
||||||
|
new_lvl = prog_after["level"] if prog_after["level"] > prog_before["level"] else None
|
||||||
|
return xp_gained, new_lvl
|
||||||
|
|
||||||
|
old_lvl, new_lvl = view.ctx.record_result(
|
||||||
|
view.variant_key,
|
||||||
|
won=won_stat,
|
||||||
|
duration_sec=duration,
|
||||||
|
points_gained=xp_gained,
|
||||||
|
bj_account_id=view.bj_account["id"],
|
||||||
|
)
|
||||||
|
return xp_gained, (new_lvl if new_lvl > old_lvl else None)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def format_hand_rank_label(
|
||||||
|
cards, is_split: bool = False, busted: bool = False, folded: bool = False
|
||||||
|
) -> str:
|
||||||
|
val, _ = HandEvaluator.evaluate(cards)
|
||||||
|
if folded:
|
||||||
|
return t("bj_rank_folded", val)
|
||||||
|
if busted or val > 21:
|
||||||
|
return t("bj_rank_busted", val)
|
||||||
|
if HandEvaluator.is_triple_seven(cards):
|
||||||
|
return t("bj_rank_777")
|
||||||
|
if not is_split and HandEvaluator.is_natural_blackjack(cards):
|
||||||
|
return t("bj_rank_natural_bj")
|
||||||
|
if val == 21:
|
||||||
|
return t("bj_rank_split_21") if is_split else t("bj_rank_multi_21", len(cards))
|
||||||
|
return t("bj_rank_points", val, len(cards))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def collect_showdown_snapshot(view, instant_777_winner: str | None = None) -> list[dict]:
|
||||||
|
snapshot: list[dict] = []
|
||||||
|
d_cards = view.engine.dealer_hand
|
||||||
|
d_val, _ = HandEvaluator.evaluate(d_cards)
|
||||||
|
d_rank = view.engine._hand_rank(d_cards)
|
||||||
|
snapshot.append({
|
||||||
|
"role": "DEALER", "name": "", "hand_no": 0,
|
||||||
|
"card_images": [c.image_filename for c in d_cards],
|
||||||
|
"cards_raw": [[c.suit, c.rank] for c in d_cards],
|
||||||
|
"is_split": False, "busted": d_val > 21, "folded": False,
|
||||||
|
"rank_tuple": list(d_rank),
|
||||||
|
})
|
||||||
|
|
||||||
|
multi_p = len(view.engine.player_hands) > 1
|
||||||
|
for idx, h in enumerate(view.engine.player_hands):
|
||||||
|
hr = view.engine._hand_rank(h.cards, is_split=h.is_split_hand) if h.is_active_in_pot else (0, 0)
|
||||||
|
snapshot.append({
|
||||||
|
"role": "PLAYER", "name": "", "hand_no": (idx + 1) if multi_p else 0,
|
||||||
|
"card_images": [c.image_filename for c in h.cards],
|
||||||
|
"cards_raw": [[c.suit, c.rank] for c in h.cards],
|
||||||
|
"is_split": h.is_split_hand, "busted": h.busted, "folded": h.folded,
|
||||||
|
"rank_tuple": list(hr),
|
||||||
|
})
|
||||||
|
|
||||||
|
for b in view.bots:
|
||||||
|
br = view.engine._hand_rank(b.hand) if b.is_active_in_pot else (0, 0)
|
||||||
|
snapshot.append({
|
||||||
|
"role": "BOT", "name": b.name, "hand_no": 0,
|
||||||
|
"card_images": [c.image_filename for c in b.hand],
|
||||||
|
"cards_raw": [[c.suit, c.rank] for c in b.hand],
|
||||||
|
"is_split": False, "busted": b.busted, "folded": b.folded,
|
||||||
|
"rank_tuple": list(br),
|
||||||
|
})
|
||||||
|
|
||||||
|
if instant_777_winner is not None:
|
||||||
|
for s in snapshot:
|
||||||
|
s["is_winner"] = bool(
|
||||||
|
(instant_777_winner == "PLAYER" and s["role"] == "PLAYER" and s["rank_tuple"] == [3, 21])
|
||||||
|
or (s["role"] == "BOT" and s["name"] == instant_777_winner and s["rank_tuple"] == [3, 21])
|
||||||
|
)
|
||||||
|
return snapshot
|
||||||
|
|
||||||
|
contenders = [s for s in snapshot[1:] if not s["busted"] and not s["folded"]]
|
||||||
|
dealer_entry = snapshot[0]
|
||||||
|
if not contenders:
|
||||||
|
dealer_entry["is_winner"] = True
|
||||||
|
for s in snapshot[1:]:
|
||||||
|
s["is_winner"] = False
|
||||||
|
return snapshot
|
||||||
|
|
||||||
|
best_contender = max(tuple(s["rank_tuple"]) for s in contenders)
|
||||||
|
d_rnk = tuple(dealer_entry["rank_tuple"])
|
||||||
|
dealer_entry["is_winner"] = (d_rnk >= best_contender)
|
||||||
|
for s in snapshot[1:]:
|
||||||
|
s["is_winner"] = (
|
||||||
|
d_rnk <= best_contender
|
||||||
|
and not s["busted"]
|
||||||
|
and not s["folded"]
|
||||||
|
and tuple(s["rank_tuple"]) == best_contender
|
||||||
|
)
|
||||||
|
return snapshot
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def trigger_instant_777(
|
||||||
|
cls, view, winner_is_player: bool, winning_bot: BlackjackBotSeat | None
|
||||||
|
) -> dict:
|
||||||
|
view.engine.state = "SHOWDOWN"
|
||||||
|
cls.count_all_table_cards(view)
|
||||||
|
pot_total = view.engine.pot
|
||||||
|
total_p_bet = view.engine.total_player_bet
|
||||||
|
snap = cls.collect_showdown_snapshot(
|
||||||
|
view, instant_777_winner="PLAYER" if winner_is_player else winning_bot.name
|
||||||
|
)
|
||||||
|
|
||||||
|
if winner_is_player:
|
||||||
|
payout = pot_total + (total_p_bet if not view.bots else 0)
|
||||||
|
net = payout - total_p_bet
|
||||||
|
view.bj_account = Database.update_blackjack_gold(view.bj_account["id"], payout)
|
||||||
|
xp, leveled_to = cls.award_xp_and_record(view, "WIN_777", won_stat=True)
|
||||||
|
cls.resolve_devils_lock(view, "WIN_777")
|
||||||
|
return {
|
||||||
|
"winner_type": "PLAYER", "winner_names": [], "instant_777": "PLAYER",
|
||||||
|
"player_won": True, "player_net": net, "bank_gain": 0, "bot_gains": [],
|
||||||
|
"xp_gained": xp, "leveled_to": leveled_to, "showdown_snapshot": snap,
|
||||||
|
}
|
||||||
|
|
||||||
|
winning_bot.gold += pot_total
|
||||||
|
bot_net = pot_total - winning_bot.bet_in_pot
|
||||||
|
xp, leveled_to = cls.award_xp_and_record(view, "LOSE", won_stat=False)
|
||||||
|
cls.resolve_devils_lock(view, "LOSE")
|
||||||
|
return {
|
||||||
|
"winner_type": "BOT", "winner_names": [winning_bot.name], "instant_777": winning_bot.name,
|
||||||
|
"player_won": False, "player_net": -total_p_bet, "bank_gain": 0,
|
||||||
|
"bot_gains": [(winning_bot.name, bot_net)] if bot_net > 0 else [],
|
||||||
|
"xp_gained": xp, "leveled_to": leveled_to, "showdown_snapshot": snap,
|
||||||
|
}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def finalize_regular_showdown(cls, view) -> dict:
|
||||||
|
cls.count_all_table_cards(view)
|
||||||
|
res = view.engine.resolve_showdown(view.bots)
|
||||||
|
snap = cls.collect_showdown_snapshot(view, instant_777_winner=None)
|
||||||
|
|
||||||
|
if res["player_payout"] > 0:
|
||||||
|
view.bj_account = Database.update_blackjack_gold(view.bj_account["id"], res["player_payout"])
|
||||||
|
|
||||||
|
w_type = res["winner_type"]
|
||||||
|
if w_type == "PLAYER":
|
||||||
|
has_nat = any(
|
||||||
|
h.is_active_in_pot and not h.is_split_hand and HandEvaluator.is_natural_blackjack(h.cards)
|
||||||
|
for h in view.engine.player_hands
|
||||||
|
)
|
||||||
|
out_code, player_won_flag = ("WIN_BJ" if has_nat else "WIN"), True
|
||||||
|
xp, leveled_to = cls.award_xp_and_record(view, out_code, won_stat=True)
|
||||||
|
elif w_type == "TIE":
|
||||||
|
out_code, player_won_flag = "TIE", None
|
||||||
|
xp, leveled_to = cls.award_xp_and_record(view, "TIE", won_stat=None)
|
||||||
|
else:
|
||||||
|
out_code, player_won_flag = "LOSE", False
|
||||||
|
xp, leveled_to = cls.award_xp_and_record(view, "LOSE", won_stat=False)
|
||||||
|
|
||||||
|
cls.resolve_devils_lock(view, out_code)
|
||||||
|
return {
|
||||||
|
"winner_type": w_type, "winner_names": res["winner_names"], "instant_777": None,
|
||||||
|
"player_won": player_won_flag, "player_net": res["player_net"],
|
||||||
|
"bank_gain": res["bank_gain"], "bot_gains": res["bot_gains"],
|
||||||
|
"xp_gained": xp, "leveled_to": leveled_to, "showdown_snapshot": snap,
|
||||||
|
}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def build_localized_popup_data(cls, view, payload: dict) -> dict:
|
||||||
|
w_type = payload["winner_type"]
|
||||||
|
headline = (
|
||||||
|
t("bj_popup_bank_won") if w_type == "BANK"
|
||||||
|
else (t("bj_popup_player_won") if w_type == "PLAYER"
|
||||||
|
else (t("bj_popup_bot_won", ", ".join(payload["winner_names"])) if w_type == "BOT" else t("bj_popup_tie")))
|
||||||
|
)
|
||||||
|
|
||||||
|
showdown_hands = []
|
||||||
|
for s in payload.get("showdown_snapshot", []):
|
||||||
|
cards_obj = [Card(sr[0], sr[1]) for sr in s.get("cards_raw", [])]
|
||||||
|
owner_lbl = (
|
||||||
|
t("bj_showdown_seat_dealer") if s["role"] == "DEALER"
|
||||||
|
else ((t("bj_showdown_seat_you_hand", s["hand_no"]) if s.get("hand_no") else t("bj_showdown_seat_you"))
|
||||||
|
if s["role"] == "PLAYER" else s["name"])
|
||||||
|
)
|
||||||
|
showdown_hands.append({
|
||||||
|
"owner_label": owner_lbl, "is_dealer": (s["role"] == "DEALER"),
|
||||||
|
"is_winner": s.get("is_winner", False), "busted": s.get("busted", False),
|
||||||
|
"folded": s.get("folded", False), "card_images": s.get("card_images", []),
|
||||||
|
"rank_label": cls.format_hand_rank_label(
|
||||||
|
cards_obj, s.get("is_split", False), s.get("busted", False), s.get("folded", False)
|
||||||
|
),
|
||||||
|
"rank_tuple": tuple(s.get("rank_tuple", [0, 0])), "role": s["role"],
|
||||||
|
})
|
||||||
|
|
||||||
|
other_gains = []
|
||||||
|
if payload["bank_gain"] > 0:
|
||||||
|
other_gains.append(t("bj_popup_bank_gain", payload["bank_gain"]))
|
||||||
|
for b_name, b_gain in payload["bot_gains"]:
|
||||||
|
if b_gain > 0:
|
||||||
|
other_gains.append(t("bj_popup_bot_gain", b_name, b_gain))
|
||||||
|
|
||||||
|
lvl_to = payload["leveled_to"]
|
||||||
|
lvl_str = t("bj_popup_level_up", lvl_to, Progression.get_prestige_title(lvl_to)) if lvl_to is not None else None
|
||||||
|
cur_gold = Database.get_blackjack_account(view.bj_account["id"])["gold"]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"headline": headline,
|
||||||
|
"reason_text": cls._build_showdown_reason(payload, showdown_hands),
|
||||||
|
"showdown_hands": showdown_hands,
|
||||||
|
"player_won": payload["player_won"],
|
||||||
|
"player_net": payload["player_net"],
|
||||||
|
"other_gains": other_gains,
|
||||||
|
"xp_gained": payload["xp_gained"],
|
||||||
|
"new_level_title": lvl_str,
|
||||||
|
"can_continue": cur_gold >= GOLD_MIN_TABLE_ENTRY,
|
||||||
|
"can_leave_menu": not view.devils_locked,
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _build_showdown_reason(payload: dict, showdown_hands: list[dict]) -> str:
|
||||||
|
if not showdown_hands:
|
||||||
|
return ""
|
||||||
|
inst = payload.get("instant_777")
|
||||||
|
if inst:
|
||||||
|
return t("bj_reason_777_win", t("bj_showdown_seat_you") if inst == "PLAYER" else inst)
|
||||||
|
|
||||||
|
dealer = showdown_hands[0]
|
||||||
|
if not [h for h in showdown_hands[1:] if not h["busted"] and not h["folded"]]:
|
||||||
|
return t("bj_reason_all_out")
|
||||||
|
|
||||||
|
winners = [h for h in showdown_hands if h["is_winner"]]
|
||||||
|
if not winners:
|
||||||
|
return ""
|
||||||
|
if dealer["is_winner"] and len(winners) > 1:
|
||||||
|
return t("bj_reason_dealer_tie_push", dealer["rank_label"])
|
||||||
|
|
||||||
|
top_rank = winners[0]["rank_tuple"]
|
||||||
|
winner_names_str = ", ".join(dict.fromkeys(w["owner_label"] for w in winners if not w["is_dealer"]))
|
||||||
|
win_label = dealer["owner_label"] if dealer["is_winner"] else winner_names_str
|
||||||
|
losers_21 = [
|
||||||
|
h for h in showdown_hands
|
||||||
|
if not h["is_winner"] and not h["busted"] and not h["folded"] and h["rank_tuple"][1] == 21
|
||||||
|
]
|
||||||
|
if top_rank == (3, 21) and losers_21:
|
||||||
|
return t("bj_reason_777_beats_21", win_label)
|
||||||
|
if top_rank == (2, 21) and losers_21:
|
||||||
|
return t("bj_reason_nat_beats_reg21", win_label)
|
||||||
|
|
||||||
|
non_dealer_winners = [w for w in winners if not w["is_dealer"]]
|
||||||
|
if len(non_dealer_winners) > 1:
|
||||||
|
return t("bj_reason_split_pot", non_dealer_winners[0]["rank_label"], winner_names_str)
|
||||||
|
if dealer["busted"] and not dealer["is_winner"]:
|
||||||
|
return t("bj_reason_dealer_bust", dealer["rank_label"], win_label, winners[0]["rank_label"])
|
||||||
|
|
||||||
|
others_alive = [h for h in showdown_hands if not h["is_winner"] and not h["busted"] and not h["folded"]]
|
||||||
|
runner = max(others_alive, key=lambda x: x["rank_tuple"]) if others_alive else dealer
|
||||||
|
return t("bj_reason_higher_score", win_label, winners[0]["rank_label"], f"{runner['owner_label']}: {runner['rank_label']}")
|
||||||
|
|
@ -1,85 +0,0 @@
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
# games/blackjack/views/blackjack_stats_view.py
|
|
||||||
import tkinter as tk
|
|
||||||
from models.database import Database
|
|
||||||
from resources.code_res.game_constants import (
|
|
||||||
ACCENT_GOLD, BG_COLOR, BORDER_COLOR, PANEL_BG
|
|
||||||
)
|
|
||||||
from resources.code_res.i18n import t
|
|
||||||
from view.widgets.image_button import ImageButton
|
|
||||||
from view.widgets.stats_board_widget import StatsBoardWidget
|
|
||||||
|
|
||||||
GAME_FOLDER_ID = "blackjack"
|
|
||||||
|
|
||||||
|
|
||||||
class BlackjackStatsView:
|
|
||||||
"""Eigene Statistik-Ansicht für die einzelnen Blackjack-Goldbeutel."""
|
|
||||||
def __init__(self, context, on_back_to_bj_menu):
|
|
||||||
self.ctx = context
|
|
||||||
self.on_back_to_bj_menu = on_back_to_bj_menu
|
|
||||||
|
|
||||||
def show(self, selected_acc_id: int | None = None):
|
|
||||||
self.ctx.root.clear_window(apply_global_bg=True)
|
|
||||||
pid = self.ctx.profile["id"]
|
|
||||||
accounts = Database.get_blackjack_accounts(pid)
|
|
||||||
|
|
||||||
if not accounts:
|
|
||||||
self.on_back_to_bj_menu(None)
|
|
||||||
return
|
|
||||||
|
|
||||||
active_acc = accounts[0]
|
|
||||||
if selected_acc_id is not None:
|
|
||||||
for a in accounts:
|
|
||||||
if a["id"] == selected_acc_id:
|
|
||||||
active_acc = a
|
|
||||||
break
|
|
||||||
|
|
||||||
self.ctx.build_game_topbar(
|
|
||||||
self.ctx.root,
|
|
||||||
t("bj_stats_view_topbar"),
|
|
||||||
on_game_menu=lambda: self.on_back_to_bj_menu(active_acc["id"]),
|
|
||||||
extra_right_text=t("bj_header_gold", active_acc["account_name"], active_acc["gold"]),
|
|
||||||
on_lang_refresh=lambda: self.show(active_acc["id"]),
|
|
||||||
)
|
|
||||||
|
|
||||||
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=18)
|
|
||||||
container.place(relx=0.5, rely=0.54, anchor="center", relwidth=0.88, relheight=0.82)
|
|
||||||
|
|
||||||
selector_panel = tk.Frame(
|
|
||||||
container, bg=PANEL_BG, padx=18, pady=14,
|
|
||||||
highlightthickness=1, highlightbackground=BORDER_COLOR
|
|
||||||
)
|
|
||||||
selector_panel.pack(fill="x", pady=(0, 16))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
selector_panel, text=t("bj_stats_select_acc_lbl"),
|
|
||||||
font=("Georgia", 13, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG
|
|
||||||
).pack(anchor="w", pady=(0, 10))
|
|
||||||
|
|
||||||
tabs_row = tk.Frame(selector_panel, bg=PANEL_BG)
|
|
||||||
tabs_row.pack(fill="x")
|
|
||||||
|
|
||||||
for acc in accounts:
|
|
||||||
is_sel = (acc["id"] == active_acc["id"])
|
|
||||||
pil_norm = self.ctx.assets.raw_btn if is_sel else self.ctx.assets.raw_sel
|
|
||||||
pil_hov = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel_active
|
|
||||||
btn_lbl = f"{acc['account_name']} ({acc['gold']}g)"
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
tabs_row, btn_lbl, pil_norm, pil_hov,
|
|
||||||
lambda aid=acc["id"]: self.show(selected_acc_id=aid),
|
|
||||||
sound_mgr=self.ctx.sounds, width=185, height=38, font=("Helvetica", 9, "bold")
|
|
||||||
).pack(side="left", padx=(0, 8))
|
|
||||||
|
|
||||||
bj_variants = Database.get_variants_for_filter(folder_path=GAME_FOLDER_ID)
|
|
||||||
bj_filter_map = {t("bj_filter_all_tables"): None}
|
|
||||||
for v in bj_variants:
|
|
||||||
bj_filter_map[v["translated_name"]] = v["id"]
|
|
||||||
|
|
||||||
board = StatsBoardWidget(
|
|
||||||
container,
|
|
||||||
title=t("bj_stats_acc_title", active_acc["account_name"]),
|
|
||||||
filter_map=bj_filter_map,
|
|
||||||
fetch_callback=lambda vid: Database.get_bj_account_stats_overview(active_acc["id"], vid)
|
|
||||||
)
|
|
||||||
board.pack(fill="x")
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,244 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/blackjack/views/blackjack_turn_driver.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from games.blackjack.models.bot_seat import BlackjackBotSeat
|
||||||
|
from games.blackjack.models.hand_evaluator import HandEvaluator
|
||||||
|
from games.blackjack.views.blackjack_showdown_presenter import BlackjackShowdownPresenter
|
||||||
|
from models.database import Database
|
||||||
|
from resources.code_res.game_constants import BJ_BOT_TURN_DELAY_MS
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
|
||||||
|
STEP_MITGEHEN = "MITGEHEN"
|
||||||
|
STEP_ZIEHEN = "ZIEHEN"
|
||||||
|
STEP_ERHOEHEN = "ERHOEHEN"
|
||||||
|
|
||||||
|
|
||||||
|
class BlackjackTurnDriver:
|
||||||
|
"""Steuert die Aktions-Buttons des Spielers und die KI-Zugschleife der Bots am Blackjack-Tisch."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def render_tree_step(view) -> None:
|
||||||
|
view.bj_account = Database.get_blackjack_account(view.bj_account["id"])
|
||||||
|
wallet = view.bj_account["gold"]
|
||||||
|
hand = view.engine.player_hands[view.active_hand_idx]
|
||||||
|
|
||||||
|
btn_norm = view.ctx.assets.raw_btn_default
|
||||||
|
btn_purp = view.ctx.assets.raw_btn_purple
|
||||||
|
btn_fire = view.ctx.assets.raw_btn_fire or btn_purp
|
||||||
|
primary_btns: list[ImageButton] = []
|
||||||
|
overflow_btns: list[ImageButton] = []
|
||||||
|
|
||||||
|
if view.turn_step == STEP_MITGEHEN:
|
||||||
|
to_call = min(wallet, max(0, view.engine.highest_bet - hand.bet_in_pot))
|
||||||
|
primary_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, t("bj_tree_btn_call_yes", to_call),
|
||||||
|
btn_fire, btn_fire, lambda: view._on_step1_call_yes(to_call),
|
||||||
|
sound_mgr=view.ctx.sounds, width=162, height=30, style="fire",
|
||||||
|
hover_text=lambda: t("bj_tip_call_yes"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
overflow_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, t("bj_tree_btn_call_no_lose"),
|
||||||
|
btn_norm, btn_purp, view._on_fold_hand,
|
||||||
|
sound_mgr=view.ctx.sounds, width=162, height=30, style="amethyst",
|
||||||
|
hover_text=lambda: t("bj_tip_fold"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
view._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns)
|
||||||
|
return
|
||||||
|
|
||||||
|
if view.turn_step == STEP_ZIEHEN:
|
||||||
|
primary_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, t("bj_tree_btn_draw_yes"),
|
||||||
|
btn_fire, btn_fire, view._on_step2_draw_yes,
|
||||||
|
sound_mgr=view.ctx.sounds, width=138, height=30, style="fire",
|
||||||
|
hover_text=lambda: t("bj_tip_draw_yes"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if view.engine.can_double_down(view.active_hand_idx, wallet):
|
||||||
|
dd_cost = view.engine.get_double_down_cost(view.active_hand_idx)
|
||||||
|
primary_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, t("bj_double_btn", dd_cost),
|
||||||
|
btn_norm, btn_purp, view._on_step2_double_down,
|
||||||
|
sound_mgr=view.ctx.sounds, width=132, height=30,
|
||||||
|
style="amethyst", hover_text=lambda: t("bj_tip_double"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if view.engine.can_split_hand(view.active_hand_idx, wallet):
|
||||||
|
primary_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, t("bj_split_btn", view.engine.highest_bet),
|
||||||
|
btn_norm, btn_purp, view._on_step2_split,
|
||||||
|
sound_mgr=view.ctx.sounds, width=124, height=30,
|
||||||
|
style="amethyst", hover_text=lambda: t("bj_tip_split"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
overflow_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, t("bj_tree_btn_draw_no"),
|
||||||
|
btn_norm, btn_purp, view._on_step2_draw_no,
|
||||||
|
sound_mgr=None, width=134, height=30, style="amethyst",
|
||||||
|
hover_text=lambda: t("bj_tip_draw_no"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
overflow_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, t("bj_fold_btn"),
|
||||||
|
btn_norm, btn_purp, view._on_fold_hand,
|
||||||
|
sound_mgr=view.ctx.sounds, width=110, height=30, style="amethyst",
|
||||||
|
hover_text=lambda: t("bj_tip_fold"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
view._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns)
|
||||||
|
return
|
||||||
|
|
||||||
|
if view.turn_step == STEP_ERHOEHEN:
|
||||||
|
for chip in [c for c in view._get_current_level_chips() if wallet >= c]:
|
||||||
|
primary_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, f"+{chip}g",
|
||||||
|
btn_fire, btn_fire, lambda c=chip: view._on_step3_raise_yes(c),
|
||||||
|
sound_mgr=view.ctx.sounds, width=76, height=30, style="fire",
|
||||||
|
hover_text=lambda: t("bj_tip_raise_chip"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
overflow_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, t("bj_tree_btn_raise_no"),
|
||||||
|
btn_norm, btn_purp, view._finish_current_hand_turn,
|
||||||
|
sound_mgr=view.ctx.sounds, width=162, height=30, style="amethyst",
|
||||||
|
hover_text=lambda: t("bj_tip_raise_no"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
view._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def start_bots_cycle(cls, view) -> None:
|
||||||
|
view._set_bottom_buttons([])
|
||||||
|
if not view.bots or not view.engine.any_contender_alive(view.bots):
|
||||||
|
view._on_table_pass_completed()
|
||||||
|
return
|
||||||
|
view.active_bot_idx = 0
|
||||||
|
view._persist_state()
|
||||||
|
cls.step_next_bot(view)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def step_next_bot(cls, view) -> None:
|
||||||
|
if not view._canvas_alive():
|
||||||
|
return
|
||||||
|
while view.active_bot_idx < len(view.bots):
|
||||||
|
bot = view.bots[view.active_bot_idx]
|
||||||
|
if bot.is_active_in_pot and (
|
||||||
|
not view.settle_only_mode
|
||||||
|
or (bot.gold > 0 and bot.bet_in_pot < view.engine.highest_bet)
|
||||||
|
):
|
||||||
|
break
|
||||||
|
view.active_bot_idx += 1
|
||||||
|
|
||||||
|
if view.active_bot_idx >= len(view.bots):
|
||||||
|
view.active_bot_idx = -1
|
||||||
|
view._persist_state()
|
||||||
|
view._on_table_pass_completed()
|
||||||
|
return
|
||||||
|
|
||||||
|
bot = view.bots[view.active_bot_idx]
|
||||||
|
view._persist_state()
|
||||||
|
view._render_table(False, False)
|
||||||
|
view._turn_job = view.ctx.root.after(
|
||||||
|
BJ_BOT_TURN_DELAY_MS, lambda b=bot: cls.execute_bot_action(view, b)
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def execute_bot_action(cls, view, bot: BlackjackBotSeat) -> None:
|
||||||
|
if not view._canvas_alive():
|
||||||
|
return
|
||||||
|
upcard = view.engine.dealer_hand[0]
|
||||||
|
dyn_chips = view._get_current_level_chips()
|
||||||
|
rem_cards = view.engine.deck.remaining()
|
||||||
|
to_call = min(bot.gold, max(0, view.engine.highest_bet - bot.bet_in_pot))
|
||||||
|
|
||||||
|
if to_call > 0:
|
||||||
|
if not view.bot_ai.decide_step1_mitgehen(
|
||||||
|
bot, view.engine.highest_bet, upcard, rem_cards
|
||||||
|
):
|
||||||
|
bot.folded = bot.cards_locked = True
|
||||||
|
bot.status_text = t("bj_bot_action_fold")
|
||||||
|
cls._finish_bot_step(view)
|
||||||
|
return
|
||||||
|
view.ctx.sounds.play("click")
|
||||||
|
view.engine.bot_add_gold_to_pot(bot, to_call)
|
||||||
|
if view.settle_only_mode:
|
||||||
|
bot.status_text = t("bj_bot_action_call", to_call)
|
||||||
|
cls._finish_bot_step(view)
|
||||||
|
return
|
||||||
|
|
||||||
|
drew_card = False
|
||||||
|
if not bot.cards_locked and not bot.doubled:
|
||||||
|
if view.bot_ai.wants_double_down(
|
||||||
|
bot, upcard, view.engine.highest_bet, rem_cards
|
||||||
|
):
|
||||||
|
dd_cost = (
|
||||||
|
max(view.engine.highest_bet, bot.bet_in_pot) * 2 - bot.bet_in_pot
|
||||||
|
)
|
||||||
|
paid = view.engine.bot_add_gold_to_pot(bot, dd_cost)
|
||||||
|
view.ctx.sounds.play("click")
|
||||||
|
view.engine.bot_draw_card(bot)
|
||||||
|
bot.doubled = bot.cards_locked = True
|
||||||
|
if HandEvaluator.is_triple_seven(bot.hand):
|
||||||
|
view._conclude_with_payload(
|
||||||
|
BlackjackShowdownPresenter.trigger_instant_777(view, False, bot)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
b_val, _ = HandEvaluator.evaluate(bot.hand)
|
||||||
|
bot.status_text = (
|
||||||
|
t("bj_bot_action_bust", b_val)
|
||||||
|
if bot.busted
|
||||||
|
else t("bj_bot_action_double", paid)
|
||||||
|
)
|
||||||
|
cls._finish_bot_step(view)
|
||||||
|
return
|
||||||
|
|
||||||
|
if view.bot_ai.decide_step2_ziehen(bot, upcard, rem_cards):
|
||||||
|
view.ctx.sounds.play("click")
|
||||||
|
view.engine.bot_draw_card(bot)
|
||||||
|
drew_card = True
|
||||||
|
if HandEvaluator.is_triple_seven(bot.hand):
|
||||||
|
view._conclude_with_payload(
|
||||||
|
BlackjackShowdownPresenter.trigger_instant_777(view, False, bot)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
if bot.busted:
|
||||||
|
b_val, _ = HandEvaluator.evaluate(bot.hand)
|
||||||
|
bot.status_text = t("bj_bot_action_bust", b_val)
|
||||||
|
cls._finish_bot_step(view)
|
||||||
|
return
|
||||||
|
|
||||||
|
raise_amt = view.bot_ai.decide_step3_erhoehen(
|
||||||
|
bot, dyn_chips, rem_cards, upcard
|
||||||
|
)
|
||||||
|
if raise_amt > 0:
|
||||||
|
view.ctx.sounds.play("click")
|
||||||
|
view.engine.bot_add_gold_to_pot(bot, raise_amt)
|
||||||
|
bot.status_text = t("bj_bot_action_bet", raise_amt)
|
||||||
|
elif drew_card:
|
||||||
|
bot.status_text = t("bj_bot_action_hit", len(bot.hand))
|
||||||
|
elif to_call > 0:
|
||||||
|
bot.status_text = t("bj_bot_action_call", to_call)
|
||||||
|
else:
|
||||||
|
bot.status_text = t("bj_bot_action_ready", len(bot.hand))
|
||||||
|
cls._finish_bot_step(view)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _finish_bot_step(cls, view) -> None:
|
||||||
|
view.active_bot_idx += 1
|
||||||
|
view._persist_state()
|
||||||
|
view._render_table(False, False)
|
||||||
|
view._turn_job = view.ctx.root.after(
|
||||||
|
BJ_BOT_TURN_DELAY_MS, lambda: cls.step_next_bot(view)
|
||||||
|
)
|
||||||
|
|
@ -1,212 +1,130 @@
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
# games/blackjack/views/round_result_dialog.py
|
# games/blackjack/views/round_result_dialog.py
|
||||||
import tkinter as tk
|
from __future__ import annotations
|
||||||
|
|
||||||
from resources.code_res.game_constants import (
|
from resources.code_res.game_constants import (
|
||||||
ACCENT_GOLD, ACCENT_GOTH, CELL_BG, ERROR_FG,
|
FONT_COLOR_BODY_DEFAULT,
|
||||||
FG_COLOR, MODAL_BG, MUTED_FG, PANEL_BG, SUBTLE_BORDER
|
FONT_COLOR_BODY_MUTED,
|
||||||
|
FONT_COLOR_HEADING_SUB,
|
||||||
|
FONT_COLOR_STATUS_LOSS,
|
||||||
|
FONT_COLOR_STATUS_WIN,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_SMALL_MIN,
|
||||||
)
|
)
|
||||||
from resources.code_res.i18n import t
|
from resources.code_res.i18n import t
|
||||||
from view.widgets.image_button import ImageButton
|
from view.widgets.casino_result_dialog_base import CasinoResultDialogBase
|
||||||
|
|
||||||
SHOWDOWN_MINI_CARD_SIZE = (52, 76)
|
SHOWDOWN_MINI_CARD_SIZE = (48, 70)
|
||||||
|
|
||||||
|
|
||||||
class BlackjackResultDialog(tk.Frame):
|
class BlackjackResultDialog(CasinoResultDialogBase):
|
||||||
def __init__(
|
"""Gothic-Showdown-Overlay für Blackjack auf Basis von CasinoResultDialogBase."""
|
||||||
self,
|
|
||||||
parent,
|
def __init__(self, parent, assets, sounds, result_data: dict, on_next_round, on_back_to_menu):
|
||||||
assets,
|
hands_list = result_data.get("showdown_hands", [])
|
||||||
sounds,
|
cols = min(3, max(1, len(hands_list)))
|
||||||
result_data: dict,
|
rows = (len(hands_list) + 2) // 3 if hands_list else 0
|
||||||
on_next_round,
|
extra_lines = len(result_data.get("other_gains", []))
|
||||||
on_back_to_menu,
|
|
||||||
):
|
dlg_w = max(560, min(830, cols * 250 + 64))
|
||||||
super().__init__(
|
dlg_h = (
|
||||||
parent, bg=MODAL_BG, padx=26, pady=18,
|
58
|
||||||
highlightthickness=2, highlightbackground=ACCENT_GOTH
|
+ (48 if result_data.get("reason_text") else 8)
|
||||||
|
+ (rows * 140 + 28 if rows else 0)
|
||||||
|
+ 92 + min(2, extra_lines) * 20
|
||||||
|
+ (24 if result_data.get("new_level_title") else 0)
|
||||||
|
+ 62
|
||||||
)
|
)
|
||||||
self.assets = assets
|
super().__init__(parent, assets, sounds, result_data, dlg_w, dlg_h, on_next_round, on_back_to_menu)
|
||||||
self.sounds = sounds
|
|
||||||
self.data = result_data
|
|
||||||
self.on_next_round = on_next_round
|
|
||||||
self.on_back_to_menu = on_back_to_menu
|
|
||||||
self._gif_job = None
|
|
||||||
self._card_photos = []
|
|
||||||
|
|
||||||
self.place(relx=0.5, rely=0.5, anchor="center")
|
def _draw_showdown_middle(self, w: int, cx: int, cur_y: int) -> int:
|
||||||
self.lift()
|
|
||||||
self._build()
|
|
||||||
|
|
||||||
def _build(self):
|
|
||||||
# Kompaktere Kopfzeile (GIF + Headline), damit alle Karten sauber Platz haben
|
|
||||||
header_row = tk.Frame(self, bg=MODAL_BG)
|
|
||||||
header_row.pack(pady=(0, 6))
|
|
||||||
|
|
||||||
self.gif_lbl = tk.Label(header_row, bg=MODAL_BG, bd=0)
|
|
||||||
self.gif_lbl.pack(pady=(0, 4))
|
|
||||||
if self.data.get("player_won") is True:
|
|
||||||
self._start_gif("win_gif")
|
|
||||||
elif self.data.get("player_won") is False:
|
|
||||||
self._start_gif("lose_gif")
|
|
||||||
|
|
||||||
headline_color = ACCENT_GOLD if self.data.get("player_won") else (
|
|
||||||
MUTED_FG if self.data.get("player_won") is None else ERROR_FG
|
|
||||||
)
|
|
||||||
tk.Label(
|
|
||||||
header_row, text=self.data["headline"],
|
|
||||||
font=("Georgia", 17, "bold"), fg=headline_color, bg=MODAL_BG,
|
|
||||||
).pack()
|
|
||||||
|
|
||||||
# Klare Begründung (z. B. warum Natural BJ gegen 3-Karten-21 gewonnen hat)
|
|
||||||
reason_txt = self.data.get("reason_text", "")
|
reason_txt = self.data.get("reason_text", "")
|
||||||
if reason_txt:
|
if reason_txt:
|
||||||
reason_box = tk.Frame(
|
r_ph = self.assets.get_goth_text_photo(
|
||||||
self, bg=PANEL_BG, padx=14, pady=7,
|
reason_txt, FONT_SIZE_SMALL_MIN + 1, FONT_COLOR_HEADING_SUB, max_width=w - 92
|
||||||
highlightthickness=1, highlightbackground=ACCENT_GOLD
|
|
||||||
)
|
)
|
||||||
reason_box.pack(fill="x", pady=(2, 10))
|
self._photo_refs.append(r_ph)
|
||||||
tk.Label(
|
rb_h = max(36, r_ph.height() + 14)
|
||||||
reason_box, text=reason_txt,
|
rb_cy = cur_y + rb_h // 2
|
||||||
font=("Helvetica", 10, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG,
|
rb_box = self.assets.get_box_photo("box_gold_double", (w - 56, rb_h))
|
||||||
wraplength=760, justify="center"
|
if rb_box:
|
||||||
).pack()
|
self._photo_refs.append(rb_box)
|
||||||
|
self.create_image(cx, rb_cy, image=rb_box, anchor="center")
|
||||||
|
self.create_image(cx, rb_cy, image=r_ph, anchor="center")
|
||||||
|
cur_y += rb_h + 8
|
||||||
|
|
||||||
# =========================================================
|
|
||||||
# SHOWDOWN-KARTENANSICHT ALLER TEILNEHMER (Dealer, Du, Bots)
|
|
||||||
# =========================================================
|
|
||||||
hands_list = self.data.get("showdown_hands", [])
|
hands_list = self.data.get("showdown_hands", [])
|
||||||
if hands_list:
|
if not hands_list:
|
||||||
hands_outer = tk.Frame(
|
return cur_y
|
||||||
self, bg=CELL_BG, padx=12, pady=10,
|
|
||||||
highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
|
||||||
)
|
|
||||||
hands_outer.pack(fill="x", pady=(0, 10))
|
|
||||||
|
|
||||||
tk.Label(
|
sec_ph = self.assets.get_goth_text_photo(
|
||||||
hands_outer, text=t("bj_showdown_section_title"),
|
t("bj_showdown_section_title"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
|
||||||
font=("Georgia", 10, "bold"), fg=ACCENT_GOTH, bg=CELL_BG
|
|
||||||
).pack(anchor="w", pady=(0, 6))
|
|
||||||
|
|
||||||
cards_grid = tk.Frame(hands_outer, bg=CELL_BG)
|
|
||||||
cards_grid.pack()
|
|
||||||
|
|
||||||
max_cols = 3 if len(hands_list) <= 3 else 3
|
|
||||||
for idx, entry in enumerate(hands_list):
|
|
||||||
r_idx = idx // max_cols
|
|
||||||
c_idx = idx % max_cols
|
|
||||||
|
|
||||||
is_win = entry.get("is_winner", False)
|
|
||||||
is_dead = entry.get("busted", False) or entry.get("folded", False)
|
|
||||||
border_col = ACCENT_GOLD if is_win else (ERROR_FG if is_dead else SUBTLE_BORDER)
|
|
||||||
|
|
||||||
seat_card = tk.Frame(
|
|
||||||
cards_grid, bg=PANEL_BG, padx=10, pady=7,
|
|
||||||
highlightthickness=2 if is_win else 1, highlightbackground=border_col
|
|
||||||
)
|
|
||||||
seat_card.grid(row=r_idx, column=c_idx, padx=5, pady=4, sticky="nsew")
|
|
||||||
|
|
||||||
title_col = ACCENT_GOLD if is_win else (ACCENT_GOTH if entry.get("is_dealer") else FG_COLOR)
|
|
||||||
tk.Label(
|
|
||||||
seat_card, text=entry["owner_label"],
|
|
||||||
font=("Georgia", 10, "bold"), fg=title_col, bg=PANEL_BG
|
|
||||||
).pack()
|
|
||||||
|
|
||||||
c_row = tk.Frame(seat_card, bg=PANEL_BG)
|
|
||||||
c_row.pack(pady=4)
|
|
||||||
for img_name in entry.get("card_images", []):
|
|
||||||
photo = self.assets.get_card_photo(img_name, size=SHOWDOWN_MINI_CARD_SIZE)
|
|
||||||
if photo:
|
|
||||||
self._card_photos.append(photo)
|
|
||||||
tk.Label(c_row, image=photo, bg=PANEL_BG, bd=0).pack(side="left", padx=2)
|
|
||||||
|
|
||||||
badge_col = (
|
|
||||||
"#7be08a" if is_win else (ERROR_FG if is_dead else FG_COLOR)
|
|
||||||
)
|
|
||||||
tk.Label(
|
|
||||||
seat_card, text=entry["rank_label"],
|
|
||||||
font=("Helvetica", 9, "bold"), fg=badge_col, bg=PANEL_BG
|
|
||||||
).pack()
|
|
||||||
|
|
||||||
# =========================================================
|
|
||||||
# GOLD- & XP-ABRECHNUNG
|
|
||||||
# =========================================================
|
|
||||||
info_box = tk.Frame(
|
|
||||||
self, bg=CELL_BG, padx=18, pady=10,
|
|
||||||
highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
|
||||||
)
|
)
|
||||||
info_box.pack(fill="x", pady=(0, 10))
|
self._photo_refs.append(sec_ph)
|
||||||
|
self.create_image(32, cur_y + 10, image=sec_ph, anchor="w")
|
||||||
|
cur_y += 22
|
||||||
|
|
||||||
p_net = self.data["player_net"]
|
max_cols = 3
|
||||||
if p_net > 0:
|
rows = (len(hands_list) + max_cols - 1) // max_cols
|
||||||
own_txt, own_col = t("bj_popup_your_gain", p_net), "#7be08a"
|
seat_w = min(242, (w - 64 - (max_cols - 1) * 10) // max(1, min(max_cols, len(hands_list))))
|
||||||
elif p_net < 0:
|
seat_h = 128 if rows > 1 else 136
|
||||||
own_txt, own_col = t("bj_popup_your_loss", abs(p_net)), ERROR_FG
|
|
||||||
else:
|
|
||||||
own_txt, own_col = t("bj_popup_your_even"), FG_COLOR
|
|
||||||
|
|
||||||
tk.Label(info_box, text=own_txt, font=("Helvetica", 11, "bold"), fg=own_col, bg=CELL_BG).pack(pady=2)
|
win_box = self.assets.get_box_photo("box_gold_small", (seat_w, seat_h))
|
||||||
|
std_box = self.assets.get_box_photo("box_purple", (seat_w, seat_h))
|
||||||
|
if win_box:
|
||||||
|
self._photo_refs.append(win_box)
|
||||||
|
if std_box:
|
||||||
|
self._photo_refs.append(std_box)
|
||||||
|
|
||||||
for extra_line in self.data.get("other_gains", []):
|
for idx, entry in enumerate(hands_list):
|
||||||
tk.Label(info_box, text=extra_line, font=("Helvetica", 10), fg=MUTED_FG, bg=CELL_BG).pack(pady=1)
|
r_i, c_i = divmod(idx, max_cols)
|
||||||
|
in_row = min(max_cols, len(hands_list) - r_i * max_cols)
|
||||||
|
row_total_w = in_row * seat_w + (in_row - 1) * 10
|
||||||
|
sx = (w - row_total_w) // 2 + c_i * (seat_w + 10) + seat_w // 2
|
||||||
|
sy = cur_y + r_i * (seat_h + 6) + seat_h // 2
|
||||||
|
|
||||||
tk.Frame(info_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=6)
|
is_win = entry.get("is_winner", False)
|
||||||
|
is_dead = entry.get("busted", False) or entry.get("folded", False)
|
||||||
|
|
||||||
tk.Label(
|
frame_ph = win_box if is_win else std_box
|
||||||
info_box, text=t("bj_popup_xp_earned", self.data["xp_gained"]),
|
if frame_ph:
|
||||||
font=("Helvetica", 11, "bold"), fg=ACCENT_GOTH, bg=CELL_BG,
|
self.create_image(sx, sy, image=frame_ph, anchor="center")
|
||||||
).pack(pady=1)
|
|
||||||
|
|
||||||
if self.data.get("new_level_title"):
|
o_col = (
|
||||||
tk.Label(
|
FONT_COLOR_TITLE_MAIN if is_win
|
||||||
info_box, text=self.data["new_level_title"],
|
else (FONT_COLOR_HEADING_SUB if entry.get("is_dealer") else FONT_COLOR_BODY_DEFAULT)
|
||||||
font=("Georgia", 10, "bold"), fg=ACCENT_GOLD, bg=CELL_BG,
|
)
|
||||||
).pack(pady=(3, 0))
|
o_ph = self.assets.get_goth_text_photo(
|
||||||
|
entry["owner_label"], FONT_SIZE_SMALL_MIN + 1, o_col, max_width=seat_w - 24
|
||||||
|
)
|
||||||
|
self._photo_refs.append(o_ph)
|
||||||
|
self.create_image(sx, sy - seat_h // 2 + 20, image=o_ph, anchor="center")
|
||||||
|
|
||||||
btn_row = tk.Frame(self, bg=MODAL_BG)
|
c_photos = [
|
||||||
btn_row.pack(fill="x", pady=(4, 0))
|
ph for img_name in entry.get("card_images", [])
|
||||||
|
if (ph := self.assets.get_card_photo(img_name, size=SHOWDOWN_MINI_CARD_SIZE)) is not None
|
||||||
|
]
|
||||||
|
self._photo_refs.extend(c_photos)
|
||||||
|
|
||||||
if self.data.get("can_continue", True):
|
if c_photos:
|
||||||
ImageButton(
|
cw_c, ch_c = SHOWDOWN_MINI_CARD_SIZE
|
||||||
btn_row, t("bj_popup_next_round_btn"),
|
n_c = len(c_photos)
|
||||||
self.assets.raw_btn, self.assets.raw_btn_active,
|
step = 24
|
||||||
self._handle_next, sound_mgr=self.sounds, width=195, height=38, font=("Helvetica", 10, "bold")
|
if n_c > 1 and (cw_c + (n_c - 1) * step) > (seat_w - 28):
|
||||||
).pack(side="left", padx=(0, 10))
|
step = max(14, (seat_w - 28 - cw_c) // (n_c - 1))
|
||||||
|
fan_w = cw_c + (n_c - 1) * step if n_c > 1 else cw_c
|
||||||
|
start_cx, card_top = sx - fan_w // 2, sy - ch_c // 2 + 2
|
||||||
|
for ci, cph in enumerate(c_photos):
|
||||||
|
self.create_image(start_cx + ci * step, card_top, image=cph, anchor="nw")
|
||||||
|
|
||||||
if self.data.get("can_leave_menu", True):
|
rk_col = (
|
||||||
ImageButton(
|
FONT_COLOR_STATUS_WIN if is_win
|
||||||
btn_row, t("bj_popup_to_menu_btn"),
|
else (FONT_COLOR_STATUS_LOSS if is_dead else FONT_COLOR_BODY_DEFAULT)
|
||||||
self.assets.raw_sel, self.assets.raw_sel_active,
|
)
|
||||||
self._handle_menu, sound_mgr=self.sounds, width=165, height=38, font=("Helvetica", 10, "bold")
|
rk_ph = self.assets.get_goth_text_photo(
|
||||||
).pack(side="right")
|
entry["rank_label"], FONT_SIZE_SMALL_MIN, rk_col, max_width=seat_w - 22
|
||||||
|
)
|
||||||
|
self._photo_refs.append(rk_ph)
|
||||||
|
self.create_image(sx, sy + seat_h // 2 - 18, image=rk_ph, anchor="center")
|
||||||
|
|
||||||
def _start_gif(self, key: str):
|
return cur_y + rows * (seat_h + 6) + 6
|
||||||
frames = self.assets.get_gif_frames(key)
|
|
||||||
if not frames:
|
|
||||||
return
|
|
||||||
|
|
||||||
def _step(idx=0):
|
|
||||||
if not self.gif_lbl.winfo_exists():
|
|
||||||
return
|
|
||||||
self.gif_lbl.configure(image=frames[idx])
|
|
||||||
self._gif_job = self.after(90, _step, (idx + 1) % len(frames))
|
|
||||||
|
|
||||||
_step(0)
|
|
||||||
|
|
||||||
def close_dialog(self):
|
|
||||||
if self._gif_job:
|
|
||||||
try:
|
|
||||||
self.after_cancel(self._gif_job)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
self._gif_job = None
|
|
||||||
self._card_photos.clear()
|
|
||||||
if self.winfo_exists():
|
|
||||||
self.destroy()
|
|
||||||
|
|
||||||
def _handle_next(self):
|
|
||||||
self.close_dialog()
|
|
||||||
self.on_next_round()
|
|
||||||
|
|
||||||
def _handle_menu(self):
|
|
||||||
self.close_dialog()
|
|
||||||
self.on_back_to_menu()
|
|
||||||
|
|
@ -0,0 +1,265 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/watten/models/watten_ai.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import random
|
||||||
|
|
||||||
|
from games.party.watten.models.watten_engine import WattenEngine, WattenSeat
|
||||||
|
from games.party.watten.models.watten_rules import (
|
||||||
|
NATURAL_STRENGTH,
|
||||||
|
WATTEN_RANKS_32,
|
||||||
|
evaluate_trick_winner,
|
||||||
|
is_guade,
|
||||||
|
is_kritische,
|
||||||
|
is_schlag,
|
||||||
|
is_trump_card,
|
||||||
|
trick_card_power,
|
||||||
|
)
|
||||||
|
from models.bavarian_deck import BavarianCard
|
||||||
|
from resources.code_res.game_constants import BAVARIAN_SUITS
|
||||||
|
|
||||||
|
|
||||||
|
class WattenBotAI:
|
||||||
|
"""2v2-Team-KI (Stufen 0..6) für Oberbayerisches Watten."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _hand_raw_strength(hand: list[BavarianCard]) -> float:
|
||||||
|
pts = 0.0
|
||||||
|
rank_counts: dict[str, int] = {}
|
||||||
|
suit_counts: dict[str, int] = {}
|
||||||
|
for c in hand:
|
||||||
|
if is_kritische(c):
|
||||||
|
pts += 3.2
|
||||||
|
elif c.rank == "A":
|
||||||
|
pts += 1.2
|
||||||
|
rank_counts[c.rank] = rank_counts.get(c.rank, 0) + 1
|
||||||
|
suit_counts[c.suit] = suit_counts.get(c.suit, 0) + 1
|
||||||
|
pts += max(rank_counts.values(), default=0) * 1.1
|
||||||
|
pts += max(suit_counts.values(), default=0) * 0.8
|
||||||
|
return pts
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def should_ask_schoenere(
|
||||||
|
cls, bot: WattenSeat, rng: random.Random | None = None
|
||||||
|
) -> bool:
|
||||||
|
r = rng or random
|
||||||
|
if bot.ai_level == 0:
|
||||||
|
return r.random() < 0.20
|
||||||
|
return cls._hand_raw_strength(bot.hand) < 4.3 and r.random() < 0.75
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def should_accept_schoenere(
|
||||||
|
cls, bot: WattenSeat, rng: random.Random | None = None
|
||||||
|
) -> bool:
|
||||||
|
r = rng or random
|
||||||
|
if bot.ai_level == 0:
|
||||||
|
return r.random() < 0.50
|
||||||
|
# Geber stimmt nur zu, wenn seine eigene Hand ebenfalls schwach ist
|
||||||
|
return cls._hand_raw_strength(bot.hand) < 5.0
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def choose_schlag(
|
||||||
|
cls, bot: WattenSeat, rng: random.Random | None = None
|
||||||
|
) -> str:
|
||||||
|
r = rng or random
|
||||||
|
if bot.ai_level == 0:
|
||||||
|
return r.choice(WATTEN_RANKS_32)
|
||||||
|
|
||||||
|
scores: dict[str, float] = {rk: 0.0 for rk in WATTEN_RANKS_32}
|
||||||
|
for card in bot.hand:
|
||||||
|
if is_kritische(card):
|
||||||
|
continue
|
||||||
|
scores[card.rank] += 3.0
|
||||||
|
# Hohe Beikarten derselben Farbe machen eine potenzielle Guade wahrscheinlicher
|
||||||
|
same_suit = sum(1 for x in bot.hand if x.suit == card.suit)
|
||||||
|
scores[card.rank] += same_suit * 0.35
|
||||||
|
|
||||||
|
ranked = sorted(
|
||||||
|
WATTEN_RANKS_32,
|
||||||
|
key=lambda rk: (scores[rk], r.random()),
|
||||||
|
reverse=True,
|
||||||
|
)
|
||||||
|
if bot.ai_level <= 2 and r.random() < 0.25 and len(ranked) > 1:
|
||||||
|
return ranked[1]
|
||||||
|
return ranked[0]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def choose_trumpf(
|
||||||
|
cls,
|
||||||
|
bot: WattenSeat,
|
||||||
|
schlag_rank: str,
|
||||||
|
rng: random.Random | None = None,
|
||||||
|
) -> str:
|
||||||
|
r = rng or random
|
||||||
|
if bot.ai_level == 0:
|
||||||
|
return r.choice(BAVARIAN_SUITS)
|
||||||
|
|
||||||
|
scores: dict[str, float] = {s: 0.0 for s in BAVARIAN_SUITS}
|
||||||
|
for card in bot.hand:
|
||||||
|
if is_kritische(card):
|
||||||
|
continue
|
||||||
|
if card.rank == schlag_rank:
|
||||||
|
# Hält der Geber diese Karte selbst -> durch Wahl dieser Farbe hat er sofort die GUADE!
|
||||||
|
scores[card.suit] += 4.8
|
||||||
|
else:
|
||||||
|
scores[card.suit] += 1.6 + NATURAL_STRENGTH[card.rank] * 0.15
|
||||||
|
|
||||||
|
ranked = sorted(
|
||||||
|
BAVARIAN_SUITS,
|
||||||
|
key=lambda s: (scores[s], r.random()),
|
||||||
|
reverse=True,
|
||||||
|
)
|
||||||
|
return ranked[0]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _post_ansage_hand_power(engine: WattenEngine, bot: WattenSeat) -> float:
|
||||||
|
sr, ts = engine.schlag_rank, engine.trump_suit
|
||||||
|
power = 0.0
|
||||||
|
for c in bot.hand:
|
||||||
|
if is_kritische(c):
|
||||||
|
power += 2.2
|
||||||
|
elif is_guade(c, sr, ts):
|
||||||
|
power += 2.0
|
||||||
|
elif is_schlag(c, sr, ts):
|
||||||
|
power += 1.5
|
||||||
|
elif ts and c.suit == ts:
|
||||||
|
power += 0.95 + (0.25 if c.rank == "A" else 0.0)
|
||||||
|
elif c.rank == "A":
|
||||||
|
power += 0.55
|
||||||
|
return power
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def should_ausschaffen(
|
||||||
|
cls,
|
||||||
|
engine: WattenEngine,
|
||||||
|
bot: WattenSeat,
|
||||||
|
rng: random.Random | None = None,
|
||||||
|
) -> bool:
|
||||||
|
if not engine.can_seat_ausschaffen(bot.seat_id):
|
||||||
|
return False
|
||||||
|
r = rng or random
|
||||||
|
lvl = bot.ai_level
|
||||||
|
if lvl == 0:
|
||||||
|
return r.random() < 0.12
|
||||||
|
|
||||||
|
my_team = bot.team_id
|
||||||
|
my_tricks = engine.team_tricks[my_team]
|
||||||
|
opp_tricks = engine.team_tricks[1 - my_team]
|
||||||
|
hand_pow = cls._post_ansage_hand_power(engine, bot)
|
||||||
|
effective = hand_pow + my_tricks * 1.45 - opp_tricks * 1.15
|
||||||
|
|
||||||
|
# Gelegentlicher Wirtshaus-Bluff auf höheren KI-Stufen!
|
||||||
|
if lvl >= 4 and my_tricks >= 1 and r.random() < 0.10:
|
||||||
|
return True
|
||||||
|
|
||||||
|
threshold = 3.55 if engine.current_stake == 2 else 4.25
|
||||||
|
return effective >= threshold and r.random() < (0.45 + lvl * 0.07)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def should_hold_ausschaffen(
|
||||||
|
cls,
|
||||||
|
engine: WattenEngine,
|
||||||
|
bot: WattenSeat,
|
||||||
|
rng: random.Random | None = None,
|
||||||
|
) -> bool:
|
||||||
|
r = rng or random
|
||||||
|
my_team = bot.team_id
|
||||||
|
opp_team = 1 - my_team
|
||||||
|
|
||||||
|
# Wenn der Gegner durch Weglaufen ohnehin den Satz (>= 11) gewinnen würde -> IMMER halten!
|
||||||
|
if engine.team_points[opp_team] + engine.current_stake >= 11:
|
||||||
|
return True
|
||||||
|
|
||||||
|
partner_id = (bot.seat_id + 2) % 4
|
||||||
|
# Fair: Bot kennt seine eigene Hand + bisherige Stiche (+ auf hohen Levels grobe Einschätzung)
|
||||||
|
own_pow = cls._post_ansage_hand_power(engine, bot)
|
||||||
|
my_tricks = engine.team_tricks[my_team]
|
||||||
|
opp_tricks = engine.team_tricks[opp_team]
|
||||||
|
|
||||||
|
score = own_pow + my_tricks * 1.5 - opp_tricks * 1.0
|
||||||
|
if bot.ai_level >= 5:
|
||||||
|
# Leichte Heuristik ob Partner Ansager/Geber war
|
||||||
|
if partner_id in (engine.ansager_seat, engine.dealer_seat):
|
||||||
|
score += 0.55
|
||||||
|
return score >= 2.25 or (r.random() < 0.22)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def choose_card(
|
||||||
|
cls,
|
||||||
|
engine: WattenEngine,
|
||||||
|
bot: WattenSeat,
|
||||||
|
rng: random.Random | None = None,
|
||||||
|
) -> BavarianCard:
|
||||||
|
legal = engine.get_playable_cards(bot.seat_id)
|
||||||
|
assert legal, "Bot muss mindestens 1 spielbare Karte haben"
|
||||||
|
if len(legal) == 1:
|
||||||
|
return legal[0]
|
||||||
|
|
||||||
|
r = rng or random
|
||||||
|
lvl = bot.ai_level
|
||||||
|
sr, ts = engine.schlag_rank or "O", engine.trump_suit or "H"
|
||||||
|
|
||||||
|
if lvl == 0 or (lvl <= 2 and r.random() < 0.25):
|
||||||
|
return r.choice(legal)
|
||||||
|
|
||||||
|
trick = engine.current_trick
|
||||||
|
# 1. Ausspiel (erster im Stich)
|
||||||
|
if not trick:
|
||||||
|
# Ansager im 1. Stich mit Guade/Schlag + weiteren Trümpfen -> Trümpfe ziehen!
|
||||||
|
if engine.trick_index == 0 and bot.seat_id == engine.ansager_seat:
|
||||||
|
pulls = [
|
||||||
|
c for c in legal if is_guade(c, sr, ts) or is_schlag(c, sr, ts)
|
||||||
|
]
|
||||||
|
trumps_total = sum(1 for c in bot.hand if is_trump_card(c, sr, ts))
|
||||||
|
if pulls and trumps_total >= 2:
|
||||||
|
return pulls[0]
|
||||||
|
|
||||||
|
# Starke sichere Karte (Kritische / Ass) oder kleinste Fehlfarbe anspielen
|
||||||
|
krits = [c for c in legal if is_kritische(c)]
|
||||||
|
if krits and (engine.team_tricks[bot.team_id] == 2 or lvl >= 4):
|
||||||
|
return krits[0]
|
||||||
|
|
||||||
|
aces = [c for c in legal if c.rank == "A" and not is_trump_card(c, sr, ts)]
|
||||||
|
if aces:
|
||||||
|
return aces[0]
|
||||||
|
|
||||||
|
return min(
|
||||||
|
legal,
|
||||||
|
key=lambda c: (
|
||||||
|
1 if is_trump_card(c, sr, ts) else 0,
|
||||||
|
NATURAL_STRENGTH[c.rank],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2. Zugeben / Stechen im laufenden Stich
|
||||||
|
cur_winner = evaluate_trick_winner(trick, sr, ts)
|
||||||
|
partner_winning = engine.team_of(cur_winner) == bot.team_id
|
||||||
|
led_suit = trick[0][1].suit
|
||||||
|
|
||||||
|
# Hält der Partner den Stich bereits (besonders als Letzter am Stich oder mit hohem Trumpf) -> kleinste Karte abwerfen!
|
||||||
|
cur_best_pow = max(
|
||||||
|
trick_card_power(c, led_suit, i, sr, ts) for i, (_s, c) in enumerate(trick)
|
||||||
|
)
|
||||||
|
if partner_winning and (len(trick) == 3 or cur_best_pow[0] >= 96):
|
||||||
|
return min(
|
||||||
|
legal,
|
||||||
|
key=lambda c: trick_card_power(c, led_suit, len(trick), sr, ts),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Sonst: Günstigste Karte suchen, die den Stich aktuell erobert!
|
||||||
|
winning_cards = [
|
||||||
|
c
|
||||||
|
for c in legal
|
||||||
|
if trick_card_power(c, led_suit, len(trick), sr, ts) > cur_best_pow
|
||||||
|
]
|
||||||
|
if winning_cards:
|
||||||
|
return min(
|
||||||
|
winning_cards,
|
||||||
|
key=lambda c: trick_card_power(c, led_suit, len(trick), sr, ts),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Kann nicht überstechen -> wertloseste Karte abwerfen
|
||||||
|
return min(
|
||||||
|
legal,
|
||||||
|
key=lambda c: trick_card_power(c, led_suit, len(trick), sr, ts),
|
||||||
|
)
|
||||||
|
|
@ -0,0 +1,344 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/watten/models/watten_engine.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
import random
|
||||||
|
|
||||||
|
from games.party.watten.models.watten_rules import (
|
||||||
|
WATTEN_RANKS_32,
|
||||||
|
evaluate_trick_winner,
|
||||||
|
get_legal_cards_for_trick,
|
||||||
|
is_trump_card,
|
||||||
|
)
|
||||||
|
from models.bavarian_deck import BavarianCard, create_bavarian_deck
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
BAVARIAN_SUITS,
|
||||||
|
WT_GESPANNT_POINTS,
|
||||||
|
WT_HAND_SIZE,
|
||||||
|
WT_NUM_PLAYERS,
|
||||||
|
WT_WIN_POINTS,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Phasen einer einzelnen Watten-Hand innerhalb des Satzes (bis 11 Punkte)
|
||||||
|
PHASE_SCHOENERE_ASK = "schoenere_ask" # Vorhand darf "Schönere?" fragen oder Schlag ansagen
|
||||||
|
PHASE_SCHOENERE_REPLY = "schoenere_reply" # Geber antwortet auf "Schönere?" (Ja = neu geben / Nein = Pflicht)
|
||||||
|
PHASE_ANSAGE_SCHLAG = "ansage_schlag" # Vorhand (Ansager) bestimmt den Schlag (7..A)
|
||||||
|
PHASE_ANSAGE_TRUMPF = "ansage_trumpf" # Geber bestimmt die Trumpffarbe (E/B/H/S)
|
||||||
|
PHASE_TRICK_PLAY = "trick_play" # Ausspielen der bis zu 5 Stiche (oder Ausschaffen!)
|
||||||
|
PHASE_AUSSCHAFFEN_REPLY = "ausschaffen_reply" # Gegner-Team entscheidet: Halten (+1) oder Gehen!
|
||||||
|
PHASE_HAND_DONE = "hand_done" # Einzelhand beendet (3 Stiche erreicht oder Aufgabe)
|
||||||
|
PHASE_MATCH_DONE = "match_done" # Gesamtsatz beendet (>= 11 Punkte erreicht)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class WattenSeat:
|
||||||
|
seat_id: int
|
||||||
|
name: str
|
||||||
|
team_id: int # Team 0 = Sitz 0 (Du) & Sitz 2 (Partner Nord); Team 1 = Sitz 1 (West) & Sitz 3 (Ost)
|
||||||
|
is_human: bool = False
|
||||||
|
ai_level: int = 2
|
||||||
|
hand: list[BavarianCard] = field(default_factory=list)
|
||||||
|
status_text: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
class WattenEngine:
|
||||||
|
"""
|
||||||
|
Oberbayerisches Watten (32 Karten, 2v2 über Kreuz bis 11 Gewinnpunkte):
|
||||||
|
- Team 0: Sitz 0 (Spieler Süd) + Sitz 2 (Partner Nord)
|
||||||
|
- Team 1: Sitz 1 (Gegner West) + Sitz 3 (Gegner Ost)
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.seats: list[WattenSeat] = []
|
||||||
|
self.team_points: list[int] = [0, 0]
|
||||||
|
self.team_tricks: list[int] = [0, 0]
|
||||||
|
|
||||||
|
self.dealer_seat: int = -1
|
||||||
|
self.ansager_seat: int = 0
|
||||||
|
self.turn_seat: int = 0
|
||||||
|
|
||||||
|
self.phase: str = PHASE_ANSAGE_SCHLAG
|
||||||
|
self.schoenere_used: bool = False
|
||||||
|
self.schlag_rank: str | None = None
|
||||||
|
self.trump_suit: str | None = None
|
||||||
|
|
||||||
|
self.current_stake: int = 2
|
||||||
|
self.proposed_stake: int = 3
|
||||||
|
self.last_raising_team: int | None = None
|
||||||
|
self.responder_seat: int = 0
|
||||||
|
self._saved_turn_before_raise: int = 0
|
||||||
|
|
||||||
|
self.trick_index: int = 0
|
||||||
|
self.current_trick: list[tuple[int, BavarianCard]] = []
|
||||||
|
self.last_completed_trick: list[tuple[int, BavarianCard]] = []
|
||||||
|
self.last_trick_winner: int | None = None
|
||||||
|
|
||||||
|
self.hand_winner_team: int | None = None
|
||||||
|
self.hand_points_awarded: int = 0
|
||||||
|
self.match_winner_team: int | None = None
|
||||||
|
self.hands_played: int = 0
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def team_of(seat_id: int) -> int:
|
||||||
|
return seat_id % 2
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_match_over(self) -> bool:
|
||||||
|
return self.match_winner_team is not None
|
||||||
|
|
||||||
|
def is_team_gespannt(self, team_id: int) -> bool:
|
||||||
|
return self.team_points[team_id] >= WT_GESPANNT_POINTS
|
||||||
|
|
||||||
|
def configure_seats(
|
||||||
|
self, human_name: str, bot_configs: list[tuple[int, str]]
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Sitz 0: Spieler (Team 0)
|
||||||
|
Sitz 1: Gegner Links / West (Team 1) <- bot_configs[0]
|
||||||
|
Sitz 2: Partner Oben / Nord (Team 0) <- bot_configs[1]
|
||||||
|
Sitz 3: Gegner Rechts / Ost (Team 1) <- bot_configs[2]
|
||||||
|
"""
|
||||||
|
self.seats = [WattenSeat(seat_id=0, name=human_name, team_id=0, is_human=True)]
|
||||||
|
for seat_id in range(1, WT_NUM_PLAYERS):
|
||||||
|
cfg_idx = seat_id - 1
|
||||||
|
lvl, b_name = (
|
||||||
|
bot_configs[cfg_idx]
|
||||||
|
if cfg_idx < len(bot_configs)
|
||||||
|
else (2, f"Bot {seat_id}")
|
||||||
|
)
|
||||||
|
self.seats.append(
|
||||||
|
WattenSeat(
|
||||||
|
seat_id=seat_id,
|
||||||
|
name=b_name,
|
||||||
|
team_id=self.team_of(seat_id),
|
||||||
|
is_human=False,
|
||||||
|
ai_level=lvl,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def start_new_match(self, rng: random.Random | None = None) -> None:
|
||||||
|
self.team_points = [0, 0]
|
||||||
|
self.match_winner_team = None
|
||||||
|
self.hands_played = 0
|
||||||
|
self.dealer_seat = (rng or random).randrange(WT_NUM_PLAYERS)
|
||||||
|
self.start_new_hand(rotate_dealer=False, rng=rng)
|
||||||
|
|
||||||
|
def start_new_hand(
|
||||||
|
self, rotate_dealer: bool = True, rng: random.Random | None = None
|
||||||
|
) -> None:
|
||||||
|
if rotate_dealer or self.dealer_seat < 0:
|
||||||
|
self.dealer_seat = (self.dealer_seat + 1) % WT_NUM_PLAYERS
|
||||||
|
self.ansager_seat = (self.dealer_seat + 1) % WT_NUM_PLAYERS
|
||||||
|
self.schoenere_used = False
|
||||||
|
self._deal_cards_internal(rng)
|
||||||
|
|
||||||
|
def _deal_cards_internal(self, rng: random.Random | None = None) -> None:
|
||||||
|
r = rng or random
|
||||||
|
deck = create_bavarian_deck(include_six=False, shuffle=True, rng=r)
|
||||||
|
suit_order = {s: i for i, s in enumerate(BAVARIAN_SUITS)}
|
||||||
|
|
||||||
|
for idx, seat in enumerate(self.seats):
|
||||||
|
chunk = deck[idx * WT_HAND_SIZE : (idx + 1) * WT_HAND_SIZE]
|
||||||
|
chunk.sort(key=lambda c: (suit_order[c.suit], c.order_index))
|
||||||
|
seat.hand = chunk
|
||||||
|
seat.status_text = ""
|
||||||
|
|
||||||
|
self.team_tricks = [0, 0]
|
||||||
|
self.schlag_rank = None
|
||||||
|
self.trump_suit = None
|
||||||
|
self.trick_index = 0
|
||||||
|
self.current_trick = []
|
||||||
|
self.last_completed_trick = []
|
||||||
|
self.last_trick_winner = None
|
||||||
|
self.hand_winner_team = None
|
||||||
|
self.hand_points_awarded = 0
|
||||||
|
|
||||||
|
# Ist mindestens ein Team gespannt (>= 9), zählt jede Hand automatisch 3 Punkte!
|
||||||
|
either_gespannt = self.is_team_gespannt(0) or self.is_team_gespannt(1)
|
||||||
|
self.current_stake = 3 if either_gespannt else 2
|
||||||
|
self.proposed_stake = self.current_stake + 1
|
||||||
|
self.last_raising_team = None
|
||||||
|
|
||||||
|
self.turn_seat = self.ansager_seat
|
||||||
|
# "Schönere?" ist erlaubt, solange keines der Teams gespannt ist und noch nicht neu gegeben wurde
|
||||||
|
if not either_gespannt and not self.schoenere_used:
|
||||||
|
self.phase = PHASE_SCHOENERE_ASK
|
||||||
|
else:
|
||||||
|
self.phase = PHASE_ANSAGE_SCHLAG
|
||||||
|
|
||||||
|
def sort_hands_for_ansage(self) -> None:
|
||||||
|
"""Sortiert nach erfolgter Ansage alle Trümpfe übersichtlich nach links auf die Hand."""
|
||||||
|
if not self.schlag_rank or not self.trump_suit:
|
||||||
|
return
|
||||||
|
suit_order = {s: i for i, s in enumerate(BAVARIAN_SUITS)}
|
||||||
|
for seat in self.seats:
|
||||||
|
seat.hand.sort(
|
||||||
|
key=lambda c: (
|
||||||
|
0 if is_trump_card(c, self.schlag_rank, self.trump_suit) else 1,
|
||||||
|
suit_order[c.suit],
|
||||||
|
c.order_index,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
# --- 1. Schönere? & Ansagen (Schlag + Trumpf) ---
|
||||||
|
def ask_schoenere(self, seat_id: int) -> bool:
|
||||||
|
if self.phase != PHASE_SCHOENERE_ASK or seat_id != self.ansager_seat:
|
||||||
|
return False
|
||||||
|
self.phase = PHASE_SCHOENERE_REPLY
|
||||||
|
self.turn_seat = self.dealer_seat
|
||||||
|
return True
|
||||||
|
|
||||||
|
def skip_schoenere(self, seat_id: int) -> bool:
|
||||||
|
if self.phase != PHASE_SCHOENERE_ASK or seat_id != self.ansager_seat:
|
||||||
|
return False
|
||||||
|
self.phase = PHASE_ANSAGE_SCHLAG
|
||||||
|
self.turn_seat = self.ansager_seat
|
||||||
|
return True
|
||||||
|
|
||||||
|
def reply_schoenere(
|
||||||
|
self, seat_id: int, accept_redeal: bool, rng: random.Random | None = None
|
||||||
|
) -> bool:
|
||||||
|
if self.phase != PHASE_SCHOENERE_REPLY or seat_id != self.dealer_seat:
|
||||||
|
return False
|
||||||
|
self.schoenere_used = True
|
||||||
|
if accept_redeal:
|
||||||
|
self._deal_cards_internal(rng)
|
||||||
|
else:
|
||||||
|
self.phase = PHASE_ANSAGE_SCHLAG
|
||||||
|
self.turn_seat = self.ansager_seat
|
||||||
|
return True
|
||||||
|
|
||||||
|
def declare_schlag(self, seat_id: int, rank: str) -> bool:
|
||||||
|
if self.phase not in (PHASE_SCHOENERE_ASK, PHASE_ANSAGE_SCHLAG):
|
||||||
|
return False
|
||||||
|
if seat_id != self.ansager_seat or rank not in WATTEN_RANKS_32:
|
||||||
|
return False
|
||||||
|
self.schlag_rank = rank
|
||||||
|
self.phase = PHASE_ANSAGE_TRUMPF
|
||||||
|
self.turn_seat = self.dealer_seat
|
||||||
|
return True
|
||||||
|
|
||||||
|
def declare_trumpf(self, seat_id: int, suit: str) -> bool:
|
||||||
|
if self.phase != PHASE_ANSAGE_TRUMPF or seat_id != self.dealer_seat:
|
||||||
|
return False
|
||||||
|
if suit not in BAVARIAN_SUITS:
|
||||||
|
return False
|
||||||
|
self.trump_suit = suit
|
||||||
|
self.sort_hands_for_ansage()
|
||||||
|
self.phase = PHASE_TRICK_PLAY
|
||||||
|
self.turn_seat = self.ansager_seat
|
||||||
|
return True
|
||||||
|
|
||||||
|
# --- 2. Ausschaffen (Erhöhen) & Halten / Gehen ---
|
||||||
|
def can_seat_ausschaffen(self, seat_id: int) -> bool:
|
||||||
|
if self.phase != PHASE_TRICK_PLAY or seat_id != self.turn_seat:
|
||||||
|
return False
|
||||||
|
my_team = self.team_of(seat_id)
|
||||||
|
if self.is_team_gespannt(my_team):
|
||||||
|
return False
|
||||||
|
if self.last_raising_team == my_team:
|
||||||
|
return False
|
||||||
|
# Sinnvolle Obergrenze: sobald aktueller Einsatz ohnehin zum Match-Sieg beider Teams reicht
|
||||||
|
opp_team = 1 - my_team
|
||||||
|
if (
|
||||||
|
self.team_points[my_team] + self.current_stake >= WT_WIN_POINTS
|
||||||
|
and self.team_points[opp_team] + self.current_stake >= WT_WIN_POINTS
|
||||||
|
):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
def initiate_ausschaffen(self, seat_id: int) -> bool:
|
||||||
|
if not self.can_seat_ausschaffen(seat_id):
|
||||||
|
return False
|
||||||
|
my_team = self.team_of(seat_id)
|
||||||
|
opp_team = 1 - my_team
|
||||||
|
self._saved_turn_before_raise = self.turn_seat
|
||||||
|
self.proposed_stake = self.current_stake + 1
|
||||||
|
self.last_raising_team = my_team
|
||||||
|
|
||||||
|
# Wenn der menschliche Spieler im Gegner-Team sitzt (opp_team == 0), antwortet IMMER der Mensch!
|
||||||
|
if opp_team == 0:
|
||||||
|
self.responder_seat = 0
|
||||||
|
else:
|
||||||
|
# Sonst antwortet der nächste aktive Gegner im Uhrzeigersinn
|
||||||
|
cand = (seat_id + 1) % WT_NUM_PLAYERS
|
||||||
|
self.responder_seat = cand if self.team_of(cand) == opp_team else (cand + 2) % WT_NUM_PLAYERS
|
||||||
|
|
||||||
|
self.phase = PHASE_AUSSCHAFFEN_REPLY
|
||||||
|
self.turn_seat = self.responder_seat
|
||||||
|
return True
|
||||||
|
|
||||||
|
def respond_ausschaffen(self, seat_id: int, accept_hold: bool) -> bool:
|
||||||
|
if self.phase != PHASE_AUSSCHAFFEN_REPLY or seat_id != self.responder_seat:
|
||||||
|
return False
|
||||||
|
if accept_hold:
|
||||||
|
self.current_stake = self.proposed_stake
|
||||||
|
self.phase = PHASE_TRICK_PLAY
|
||||||
|
self.turn_seat = self._saved_turn_before_raise
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Gegner geht ("Aufgabe der Hand") -> ausschaffendes Team erhält den bisherigen Einsatz!
|
||||||
|
winner_team = 1 - self.team_of(seat_id)
|
||||||
|
self._award_hand_to_team(winner_team, self.current_stake)
|
||||||
|
return True
|
||||||
|
|
||||||
|
# --- 3. Stich-Ausspiel ---
|
||||||
|
def get_playable_cards(self, seat_id: int) -> list[BavarianCard]:
|
||||||
|
if self.phase != PHASE_TRICK_PLAY or seat_id != self.turn_seat:
|
||||||
|
return []
|
||||||
|
assert self.schlag_rank is not None and self.trump_suit is not None
|
||||||
|
return get_legal_cards_for_trick(
|
||||||
|
self.seats[seat_id].hand,
|
||||||
|
self.current_trick,
|
||||||
|
self.trick_index,
|
||||||
|
self.ansager_seat,
|
||||||
|
self.schlag_rank,
|
||||||
|
self.trump_suit,
|
||||||
|
)
|
||||||
|
|
||||||
|
def play_card(self, seat_id: int, card: BavarianCard) -> str:
|
||||||
|
"""
|
||||||
|
Spielt eine Karte in den aktuellen Stich.
|
||||||
|
Rückgabe: 'invalid' | 'played' | 'trick_completed' | 'hand_completed' | 'match_completed'
|
||||||
|
"""
|
||||||
|
legal = self.get_playable_cards(seat_id)
|
||||||
|
if card not in legal:
|
||||||
|
return "invalid"
|
||||||
|
|
||||||
|
self.seats[seat_id].hand.remove(card)
|
||||||
|
self.current_trick.append((seat_id, card))
|
||||||
|
|
||||||
|
if len(self.current_trick) < WT_NUM_PLAYERS:
|
||||||
|
self.turn_seat = (self.turn_seat + 1) % WT_NUM_PLAYERS
|
||||||
|
return "played"
|
||||||
|
|
||||||
|
assert self.schlag_rank is not None and self.trump_suit is not None
|
||||||
|
win_seat = evaluate_trick_winner(
|
||||||
|
self.current_trick, self.schlag_rank, self.trump_suit
|
||||||
|
)
|
||||||
|
win_team = self.team_of(win_seat)
|
||||||
|
self.team_tricks[win_team] += 1
|
||||||
|
self.last_completed_trick = list(self.current_trick)
|
||||||
|
self.last_trick_winner = win_seat
|
||||||
|
self.current_trick = []
|
||||||
|
self.trick_index += 1
|
||||||
|
|
||||||
|
# Wer zuerst 3 Stiche hat, gewinnt die Hand sofort!
|
||||||
|
if self.team_tricks[win_team] >= 3:
|
||||||
|
self._award_hand_to_team(win_team, self.current_stake)
|
||||||
|
return "match_completed" if self.is_match_over else "hand_completed"
|
||||||
|
|
||||||
|
self.turn_seat = win_seat
|
||||||
|
return "trick_completed"
|
||||||
|
|
||||||
|
def _award_hand_to_team(self, winner_team: int, pts: int) -> None:
|
||||||
|
self.hand_winner_team = winner_team
|
||||||
|
self.hand_points_awarded = pts
|
||||||
|
self.team_points[winner_team] += pts
|
||||||
|
self.hands_played += 1
|
||||||
|
if self.team_points[winner_team] >= WT_WIN_POINTS:
|
||||||
|
self.match_winner_team = winner_team
|
||||||
|
self.phase = PHASE_MATCH_DONE
|
||||||
|
else:
|
||||||
|
self.phase = PHASE_HAND_DONE
|
||||||
|
|
@ -0,0 +1,156 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/watten/models/watten_rules.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from models.bavarian_deck import BavarianCard
|
||||||
|
|
||||||
|
# Natürliche Rangstärke beim Watten innerhalb einer Farbe: 7 < 8 < 9 < 10 < U < O < K < A
|
||||||
|
WATTEN_RANKS_32: tuple[str, ...] = ("7", "8", "9", "10", "U", "O", "K", "A")
|
||||||
|
NATURAL_STRENGTH: dict[str, int] = {
|
||||||
|
rank: idx for idx, rank in enumerate(WATTEN_RANKS_32)
|
||||||
|
}
|
||||||
|
|
||||||
|
# Die 3 Kritischen (unveränderliche höchste Trümpfe in jedem Spiel!)
|
||||||
|
KRIT_MAX = BavarianCard("H", "K") # 1. Herz-König ("Max")
|
||||||
|
KRIT_BELLI = BavarianCard("S", "7") # 2. Schellen-7 ("Belli")
|
||||||
|
KRIT_SPITZ = BavarianCard("E", "7") # 3. Eichel-7 ("Spitz")
|
||||||
|
KRITISCHE = (KRIT_MAX, KRIT_BELLI, KRIT_SPITZ)
|
||||||
|
|
||||||
|
|
||||||
|
def is_kritische(card: BavarianCard) -> bool:
|
||||||
|
return card in KRITISCHE
|
||||||
|
|
||||||
|
|
||||||
|
def is_guade(card: BavarianCard, schlag_rank: str | None, trump_suit: str | None) -> bool:
|
||||||
|
"""Die 'Guade' (Rechte) vereint Schlag-Rang + Trumpffarbe (sofern sie keine Kritische ist)."""
|
||||||
|
if not schlag_rank or not trump_suit or is_kritische(card):
|
||||||
|
return False
|
||||||
|
return card.rank == schlag_rank and card.suit == trump_suit
|
||||||
|
|
||||||
|
|
||||||
|
def is_schlag(card: BavarianCard, schlag_rank: str | None, trump_suit: str | None) -> bool:
|
||||||
|
"""Einer der 'Blinden' (Hauptschläge) = angesagter Rang in Nicht-Trumpffarbe (ohne Kritische)."""
|
||||||
|
if not schlag_rank or is_kritische(card) or is_guade(card, schlag_rank, trump_suit):
|
||||||
|
return False
|
||||||
|
return card.rank == schlag_rank
|
||||||
|
|
||||||
|
|
||||||
|
def is_trump_card(
|
||||||
|
card: BavarianCard, schlag_rank: str | None, trump_suit: str | None
|
||||||
|
) -> bool:
|
||||||
|
"""Beim Watten zählen Kritische, Guade, alle Schläge UND die Trumpffarbe als Trumpf!"""
|
||||||
|
if is_kritische(card):
|
||||||
|
return True
|
||||||
|
if schlag_rank and card.rank == schlag_rank:
|
||||||
|
return True
|
||||||
|
if trump_suit and card.suit == trump_suit:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def card_role_badge_key(
|
||||||
|
card: BavarianCard, schlag_rank: str | None, trump_suit: str | None
|
||||||
|
) -> str | None:
|
||||||
|
"""Liefert ein optionales Kurz-Label für UI-Hervorhebungen (Max, Belli, Spitz, Guade, Schlag, Trumpf)."""
|
||||||
|
if card == KRIT_MAX:
|
||||||
|
return "wt_role_max"
|
||||||
|
if card == KRIT_BELLI:
|
||||||
|
return "wt_role_belli"
|
||||||
|
if card == KRIT_SPITZ:
|
||||||
|
return "wt_role_spitz"
|
||||||
|
if is_guade(card, schlag_rank, trump_suit):
|
||||||
|
return "wt_role_guade"
|
||||||
|
if is_schlag(card, schlag_rank, trump_suit):
|
||||||
|
return "wt_role_schlag"
|
||||||
|
if trump_suit and card.suit == trump_suit:
|
||||||
|
return "wt_role_trump"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def trick_card_power(
|
||||||
|
card: BavarianCard,
|
||||||
|
led_suit: str,
|
||||||
|
play_order: int,
|
||||||
|
schlag_rank: str,
|
||||||
|
trump_suit: str,
|
||||||
|
) -> tuple[int, int]:
|
||||||
|
"""
|
||||||
|
Berechnet die exakte Stich-Stärke (Kategorie, Feinwert).
|
||||||
|
Bei gleichrangigen 'Blinden' (Hauptschlägen) gewinnt die ZUERST gespielte Karte (-play_order)!
|
||||||
|
"""
|
||||||
|
if card == KRIT_MAX:
|
||||||
|
return (100, 0)
|
||||||
|
if card == KRIT_BELLI:
|
||||||
|
return (99, 0)
|
||||||
|
if card == KRIT_SPITZ:
|
||||||
|
return (98, 0)
|
||||||
|
if is_guade(card, schlag_rank, trump_suit):
|
||||||
|
return (97, 0)
|
||||||
|
if is_schlag(card, schlag_rank, trump_suit):
|
||||||
|
return (96, -play_order)
|
||||||
|
if card.suit == trump_suit:
|
||||||
|
return (80, NATURAL_STRENGTH[card.rank])
|
||||||
|
if card.suit == led_suit:
|
||||||
|
return (40, NATURAL_STRENGTH[card.rank])
|
||||||
|
return (0, -play_order)
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_trick_winner(
|
||||||
|
trick: list[tuple[int, BavarianCard]],
|
||||||
|
schlag_rank: str,
|
||||||
|
trump_suit: str,
|
||||||
|
) -> int:
|
||||||
|
"""Gibt die seat_id (0..3) des Stich-Gewinners zurück."""
|
||||||
|
assert trick, "Stich darf nicht leer sein"
|
||||||
|
led_suit = trick[0][1].suit
|
||||||
|
best_seat = trick[0][0]
|
||||||
|
best_score = (-1, -99)
|
||||||
|
for order_idx, (seat_id, card) in enumerate(trick):
|
||||||
|
sc = trick_card_power(card, led_suit, order_idx, schlag_rank, trump_suit)
|
||||||
|
if sc > best_score:
|
||||||
|
best_score = sc
|
||||||
|
best_seat = seat_id
|
||||||
|
return best_seat
|
||||||
|
|
||||||
|
|
||||||
|
def get_legal_cards_for_trick(
|
||||||
|
hand: list[BavarianCard],
|
||||||
|
trick: list[tuple[int, BavarianCard]],
|
||||||
|
trick_index: int,
|
||||||
|
ansager_seat: int,
|
||||||
|
schlag_rank: str,
|
||||||
|
trump_suit: str,
|
||||||
|
) -> list[BavarianCard]:
|
||||||
|
"""
|
||||||
|
Beim Watten herrscht KEIN allgemeiner Farbzwang!
|
||||||
|
Einzige Pflicht-Ausnahme (Oberbayerische Hauptschlag-Regel):
|
||||||
|
Spielt der Ansager im 1. Stich (trick_index == 0) die Guade oder einen Schlag an,
|
||||||
|
muss jeder Spieler, der Trumpf hält, Trumpf zugeben – AUSSER er besitzt als einzige
|
||||||
|
Trümpfe nur Kritische oder die Guade (diese dürfen geschont werden).
|
||||||
|
"""
|
||||||
|
if not hand or not trick or trick_index != 0:
|
||||||
|
return list(hand)
|
||||||
|
|
||||||
|
lead_seat, lead_card = trick[0]
|
||||||
|
led_hauptschlag = (lead_seat == ansager_seat) and (
|
||||||
|
is_guade(lead_card, schlag_rank, trump_suit)
|
||||||
|
or is_schlag(lead_card, schlag_rank, trump_suit)
|
||||||
|
)
|
||||||
|
if not led_hauptschlag:
|
||||||
|
return list(hand)
|
||||||
|
|
||||||
|
all_trumps = [c for c in hand if is_trump_card(c, schlag_rank, trump_suit)]
|
||||||
|
if not all_trumps:
|
||||||
|
return list(hand)
|
||||||
|
|
||||||
|
# Hat der Spieler mindestens einen normalen Trumpf oder normalen Schlag -> strenge Trumpfpflicht!
|
||||||
|
non_protected_trumps = [
|
||||||
|
c
|
||||||
|
for c in all_trumps
|
||||||
|
if not is_kritische(c) and not is_guade(c, schlag_rank, trump_suit)
|
||||||
|
]
|
||||||
|
if non_protected_trumps:
|
||||||
|
return all_trumps
|
||||||
|
|
||||||
|
# Hält er ausschließlich Kritische / Guade als Trumpf -> er darf sie schonen (freie Kartenwahl)!
|
||||||
|
return list(hand)
|
||||||
|
|
@ -0,0 +1,181 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/watten/models/watten_tutorials.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from view.tutorial.tutorial_models import TutorialStep, TutorialUnit
|
||||||
|
|
||||||
|
|
||||||
|
def build_watten_tutorial_units() -> list[TutorialUnit]:
|
||||||
|
"""Liefert die 4 geführten Praxis-Lektionen für Oberbayerisches Watten."""
|
||||||
|
unit_1 = TutorialUnit(
|
||||||
|
unit_id="u1_basics_kritische",
|
||||||
|
title_key="wt_tut_u1_title",
|
||||||
|
subtitle_key="wt_tut_u1_sub",
|
||||||
|
badge_text="I",
|
||||||
|
steps=[
|
||||||
|
TutorialStep(
|
||||||
|
title_key="wt_tut_u1_s1_title",
|
||||||
|
body_key="wt_tut_u1_s1_body",
|
||||||
|
mode="info",
|
||||||
|
my_hand=[("E", "A"), ("B", "10"), ("H", "K"), ("S", "7"), ("E", "7")],
|
||||||
|
team_points=(0, 0),
|
||||||
|
current_stake=2,
|
||||||
|
),
|
||||||
|
TutorialStep(
|
||||||
|
title_key="wt_tut_u1_s2_title",
|
||||||
|
body_key="wt_tut_u1_s2_body",
|
||||||
|
mode="card",
|
||||||
|
my_hand=[("E", "A"), ("B", "10"), ("H", "K"), ("S", "7"), ("E", "7")],
|
||||||
|
highlight_cards=[("H", "K"), ("S", "7"), ("E", "7")],
|
||||||
|
allowed_cards=[("H", "K")],
|
||||||
|
wrong_hint_key="wt_tut_u1_s2_wrong",
|
||||||
|
),
|
||||||
|
TutorialStep(
|
||||||
|
title_key="wt_tut_u1_s3_title",
|
||||||
|
body_key="wt_tut_u1_s3_body",
|
||||||
|
mode="card",
|
||||||
|
my_hand=[("E", "A"), ("B", "10"), ("S", "7"), ("E", "7"), ("H", "9")],
|
||||||
|
trick_cards=[(1, "E", "7")],
|
||||||
|
allowed_cards=[("S", "7")],
|
||||||
|
schlag_rank="O",
|
||||||
|
trump_suit="B",
|
||||||
|
wrong_hint_key="wt_tut_u1_s3_wrong",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
unit_2 = TutorialUnit(
|
||||||
|
unit_id="u2_schlag_trumpf_guade",
|
||||||
|
title_key="wt_tut_u2_title",
|
||||||
|
subtitle_key="wt_tut_u2_sub",
|
||||||
|
badge_text="II",
|
||||||
|
steps=[
|
||||||
|
TutorialStep(
|
||||||
|
title_key="wt_tut_u2_s1_title",
|
||||||
|
body_key="wt_tut_u2_s1_body",
|
||||||
|
mode="choice",
|
||||||
|
my_hand=[("B", "O"), ("E", "O"), ("B", "A"), ("B", "9"), ("H", "8")],
|
||||||
|
highlight_cards=[("B", "O"), ("E", "O")],
|
||||||
|
choices=[
|
||||||
|
("ask_o", "wt_tut_choice_ober", True),
|
||||||
|
("ask_8", "wt_tut_choice_acht", False),
|
||||||
|
],
|
||||||
|
wrong_hint_key="wt_tut_u2_s1_wrong",
|
||||||
|
),
|
||||||
|
TutorialStep(
|
||||||
|
title_key="wt_tut_u2_s2_title",
|
||||||
|
body_key="wt_tut_u2_s2_body",
|
||||||
|
mode="card",
|
||||||
|
my_hand=[("B", "O"), ("E", "O"), ("B", "A"), ("B", "9"), ("H", "8")],
|
||||||
|
highlight_cards=[("B", "O")],
|
||||||
|
allowed_cards=[("B", "O")],
|
||||||
|
schlag_rank="O",
|
||||||
|
trump_suit="B",
|
||||||
|
wrong_hint_key="wt_tut_u2_s2_wrong",
|
||||||
|
),
|
||||||
|
TutorialStep(
|
||||||
|
title_key="wt_tut_u2_s3_title",
|
||||||
|
body_key="wt_tut_u2_s3_body",
|
||||||
|
mode="info",
|
||||||
|
my_hand=[("B", "O"), ("E", "O"), ("B", "A"), ("B", "9"), ("H", "8")],
|
||||||
|
highlight_cards=[("B", "O"), ("E", "O"), ("B", "A"), ("B", "9")],
|
||||||
|
schlag_rank="O",
|
||||||
|
trump_suit="B",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
unit_3 = TutorialUnit(
|
||||||
|
unit_id="u3_first_round_trumps",
|
||||||
|
title_key="wt_tut_u3_title",
|
||||||
|
subtitle_key="wt_tut_u3_sub",
|
||||||
|
badge_text="III",
|
||||||
|
steps=[
|
||||||
|
TutorialStep(
|
||||||
|
title_key="wt_tut_u3_s1_title",
|
||||||
|
body_key="wt_tut_u3_s1_body",
|
||||||
|
mode="card",
|
||||||
|
my_hand=[("E", "8"), ("E", "9"), ("H", "A"), ("B", "U"), ("S", "10")],
|
||||||
|
trick_cards=[(1, "E", "A"), (2, "H", "10"), (3, "E", "K")],
|
||||||
|
allowed_cards=[("B", "U")],
|
||||||
|
schlag_rank="10",
|
||||||
|
trump_suit="B",
|
||||||
|
wrong_hint_key="wt_tut_u3_s1_wrong",
|
||||||
|
),
|
||||||
|
TutorialStep(
|
||||||
|
title_key="wt_tut_u3_s2_title",
|
||||||
|
body_key="wt_tut_u3_s2_body",
|
||||||
|
mode="card",
|
||||||
|
my_hand=[("H", "8"), ("H", "9"), ("B", "8"), ("S", "A"), ("E", "K")],
|
||||||
|
trick_cards=[(1, "H", "O")],
|
||||||
|
allowed_cards=[("B", "8")],
|
||||||
|
schlag_rank="O",
|
||||||
|
trump_suit="B",
|
||||||
|
wrong_hint_key="wt_tut_u3_s2_wrong",
|
||||||
|
),
|
||||||
|
TutorialStep(
|
||||||
|
title_key="wt_tut_u3_s3_title",
|
||||||
|
body_key="wt_tut_u3_s3_body",
|
||||||
|
mode="card",
|
||||||
|
my_hand=[("H", "K"), ("E", "8"), ("S", "9"), ("H", "10"), ("E", "U")],
|
||||||
|
trick_cards=[(1, "S", "O")],
|
||||||
|
allowed_cards=[("E", "8"), ("S", "9"), ("H", "10"), ("E", "U")],
|
||||||
|
highlight_cards=[("E", "8")],
|
||||||
|
schlag_rank="O",
|
||||||
|
trump_suit="B",
|
||||||
|
wrong_hint_key="wt_tut_u3_s3_wrong",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
unit_4 = TutorialUnit(
|
||||||
|
unit_id="u4_ausschaffen_gespannt",
|
||||||
|
title_key="wt_tut_u4_title",
|
||||||
|
subtitle_key="wt_tut_u4_sub",
|
||||||
|
badge_text="IV",
|
||||||
|
steps=[
|
||||||
|
TutorialStep(
|
||||||
|
title_key="wt_tut_u4_s1_title",
|
||||||
|
body_key="wt_tut_u4_s1_body",
|
||||||
|
mode="choice",
|
||||||
|
my_hand=[("H", "K"), ("S", "7"), ("B", "O"), ("B", "A"), ("E", "A")],
|
||||||
|
highlight_cards=[("H", "K"), ("S", "7"), ("B", "O")],
|
||||||
|
schlag_rank="O",
|
||||||
|
trump_suit="B",
|
||||||
|
team_points=(4, 4),
|
||||||
|
current_stake=2,
|
||||||
|
choices=[
|
||||||
|
("raise", "wt_btn_ausschaffen_ tutorial", True),
|
||||||
|
("quiet", "wt_tut_choice_stay_2", False),
|
||||||
|
],
|
||||||
|
wrong_hint_key="wt_tut_u4_s1_wrong",
|
||||||
|
),
|
||||||
|
TutorialStep(
|
||||||
|
title_key="wt_tut_u4_s2_title",
|
||||||
|
body_key="wt_tut_u4_s2_body",
|
||||||
|
mode="choice",
|
||||||
|
my_hand=[("E", "8"), ("E", "9"), ("S", "8"), ("H", "7"), ("H", "9")],
|
||||||
|
schlag_rank="K",
|
||||||
|
trump_suit="B",
|
||||||
|
team_points=(6, 4),
|
||||||
|
current_stake=2,
|
||||||
|
choices=[
|
||||||
|
("fold", "wt_btn_fold_hand", True),
|
||||||
|
("hold", "wt_tut_choice_hold_bad", False),
|
||||||
|
],
|
||||||
|
wrong_hint_key="wt_tut_u4_s2_wrong",
|
||||||
|
),
|
||||||
|
TutorialStep(
|
||||||
|
title_key="wt_tut_u4_s3_title",
|
||||||
|
body_key="wt_tut_u4_s3_body",
|
||||||
|
mode="info",
|
||||||
|
my_hand=[("H", "K"), ("B", "A"), ("E", "10"), ("S", "O"), ("H", "A")],
|
||||||
|
schlag_rank="O",
|
||||||
|
trump_suit="B",
|
||||||
|
team_points=(9, 7),
|
||||||
|
current_stake=3,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
return [unit_1, unit_2, unit_3, unit_4]
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/watten/start.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from games.party.watten.views.watten_menu_view import WattenMenuView
|
||||||
|
from resources.code_res.game_constants import CAT_PARTY_OFFLINE
|
||||||
|
|
||||||
|
GAME_FOLDER_ID = "party/watten"
|
||||||
|
GAME_TITLE_KEY = "game_title_watten"
|
||||||
|
GAME_CATEGORY = CAT_PARTY_OFFLINE
|
||||||
|
|
||||||
|
|
||||||
|
def start_game(context) -> None:
|
||||||
|
WattenMenuView(context).show()
|
||||||
|
|
@ -0,0 +1,351 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/watten/views/watten_arena_renderer.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from games.party.watten.models.watten_engine import PHASE_TRICK_PLAY
|
||||||
|
from games.party.watten.models.watten_rules import card_role_badge_key
|
||||||
|
from models.bavarian_deck import BavarianCard
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
ACCENT_GOLD,
|
||||||
|
ACCENT_GOTH,
|
||||||
|
BAVARIAN_CARD_THEME,
|
||||||
|
BORDER_COLOR,
|
||||||
|
ERROR_FG,
|
||||||
|
FG_COLOR,
|
||||||
|
FONT_COLOR_STATUS_WIN,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_BODY,
|
||||||
|
FONT_SIZE_SMALL_MIN,
|
||||||
|
MUTED_FG,
|
||||||
|
PLAYING_CARD_SIZE,
|
||||||
|
SUBTLE_BORDER,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
|
||||||
|
WT_BOT_BACK_SIZE = (40, 58)
|
||||||
|
WT_TRICK_CARD_SIZE = (84, 122)
|
||||||
|
WT_MAX_HAND_CARD_H = 182
|
||||||
|
WT_HAND_TOP_EXTEND_PX = 20
|
||||||
|
|
||||||
|
|
||||||
|
class WattenArenaRenderer:
|
||||||
|
"""Rendert Partner/Gegner, das Ansage- & Stichzentrum sowie die Spielerhand mit Rollen-Badges."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def draw_other_seats(
|
||||||
|
view,
|
||||||
|
cw: int,
|
||||||
|
pad_x: int,
|
||||||
|
pad_top: int,
|
||||||
|
table_rect: tuple[int, int, int, int],
|
||||||
|
) -> tuple[int, int, int]:
|
||||||
|
tx1, ty1, tx2, ty2 = table_rect
|
||||||
|
eng = view.engine
|
||||||
|
if len(eng.seats) < 4:
|
||||||
|
return ty1 + 20, tx1 + 60, tx2 - 60
|
||||||
|
|
||||||
|
box_w, box_h = 232, 92
|
||||||
|
mid_side_y = (ty1 + ty2) // 2 - 14
|
||||||
|
top_cy = max(pad_top + box_h // 2 - 4, ty1 + int(box_h * 0.30))
|
||||||
|
left_cx = max(pad_x + box_w // 2 - 10, tx1 + int(box_w * 0.24))
|
||||||
|
right_cx = min(cw - pad_x - box_w // 2 + 10, tx2 - int(box_w * 0.24))
|
||||||
|
|
||||||
|
# Sitz 1 = West (Gegner), Sitz 2 = Nord (Partner!), Sitz 3 = Ost (Gegner)
|
||||||
|
seat_specs = [
|
||||||
|
(eng.seats[1], left_cx, mid_side_y, False),
|
||||||
|
(eng.seats[2], cw // 2, top_cy, True),
|
||||||
|
(eng.seats[3], right_cx, mid_side_y, False),
|
||||||
|
]
|
||||||
|
|
||||||
|
back_ph = view.ctx.assets.get_card_back_photo(
|
||||||
|
size=WT_BOT_BACK_SIZE, theme=BAVARIAN_CARD_THEME
|
||||||
|
)
|
||||||
|
if back_ph is not None:
|
||||||
|
view._photo_refs.append(back_ph)
|
||||||
|
|
||||||
|
name_sz = max(14, FONT_SIZE_BODY - 1)
|
||||||
|
sub_sz = max(12, FONT_SIZE_SMALL_MIN)
|
||||||
|
|
||||||
|
for seat, bx, by, is_partner in seat_specs:
|
||||||
|
is_turn = not eng.is_match_over and eng.turn_seat == seat.seat_id
|
||||||
|
n_cards = len(seat.hand)
|
||||||
|
|
||||||
|
role_tags: list[str] = []
|
||||||
|
if seat.seat_id == eng.dealer_seat:
|
||||||
|
role_tags.append(t("wt_tag_dealer"))
|
||||||
|
elif seat.seat_id == eng.ansager_seat:
|
||||||
|
role_tags.append(t("wt_tag_ansager"))
|
||||||
|
if is_partner:
|
||||||
|
role_tags.insert(0, t("wt_tag_partner"))
|
||||||
|
role_line = " • ".join(role_tags) if role_tags else t("wt_tag_opponent")
|
||||||
|
|
||||||
|
view._draw_framed_panel(
|
||||||
|
bx,
|
||||||
|
by,
|
||||||
|
box_w,
|
||||||
|
box_h,
|
||||||
|
frame_style="gold" if is_turn else "purple",
|
||||||
|
status_border=FONT_COLOR_STATUS_WIN if is_partner else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
if back_ph is not None and n_cards > 0:
|
||||||
|
step_b = 8
|
||||||
|
bx0 = bx - box_w // 2 + 12
|
||||||
|
by0 = by - WT_BOT_BACK_SIZE[1] // 2
|
||||||
|
for bi in range(n_cards):
|
||||||
|
view.arena_canvas.create_image(
|
||||||
|
bx0 + bi * step_b, by0, image=back_ph, anchor="nw", tags="fg"
|
||||||
|
)
|
||||||
|
txt_cx = bx + 28
|
||||||
|
max_tw = box_w - 92
|
||||||
|
else:
|
||||||
|
txt_cx = bx
|
||||||
|
max_tw = box_w - 24
|
||||||
|
|
||||||
|
n_col = (
|
||||||
|
ACCENT_GOLD
|
||||||
|
if is_turn
|
||||||
|
else (FONT_COLOR_STATUS_WIN if is_partner else ACCENT_GOTH)
|
||||||
|
)
|
||||||
|
act_txt = seat.status_text or "-"
|
||||||
|
|
||||||
|
n_ph = view._make_goth_photo(seat.name, name_sz, n_col, max_tw)
|
||||||
|
r_ph = view._make_goth_photo(role_line, sub_sz - 1, MUTED_FG, max_tw)
|
||||||
|
a_ph = view._make_goth_photo(act_txt, sub_sz, FG_COLOR, max_tw)
|
||||||
|
|
||||||
|
view._place_goth_photo_or_fallback(txt_cx, by - 23, n_ph, seat.name, name_sz, n_col)
|
||||||
|
view._place_goth_photo_or_fallback(txt_cx, by - 1, r_ph, role_line, sub_sz - 1, MUTED_FG)
|
||||||
|
view._place_goth_photo_or_fallback(txt_cx, by + 22, a_ph, act_txt, sub_sz, FG_COLOR)
|
||||||
|
|
||||||
|
return (top_cy + box_h // 2, left_cx + box_w // 2, right_cx - box_w // 2)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def draw_center_trick_area(
|
||||||
|
view,
|
||||||
|
cw: int,
|
||||||
|
table_rect: tuple[int, int, int, int],
|
||||||
|
bot_bounds: tuple[int, int, int],
|
||||||
|
player_top_y: int,
|
||||||
|
) -> None:
|
||||||
|
tx1, ty1, tx2, ty2 = table_rect
|
||||||
|
top_obs_y, left_obs_x, right_obs_x = bot_bounds
|
||||||
|
eng = view.engine
|
||||||
|
|
||||||
|
felt_top = max(ty1 + 12, top_obs_y + 10)
|
||||||
|
felt_bot = min(ty2 - 12, player_top_y - WT_HAND_TOP_EXTEND_PX - 10)
|
||||||
|
center_cy = (felt_top + felt_bot) // 2 + 12
|
||||||
|
center_cx = cw // 2
|
||||||
|
|
||||||
|
# 1. Ansage- & Stich-Infotafel oben links auf dem Tischfilz
|
||||||
|
schlag_txt = t(f"bav_rank_{eng.schlag_rank}") if eng.schlag_rank else "?"
|
||||||
|
trump_txt = t(f"bav_suit_{eng.trump_suit}") if eng.trump_suit else "?"
|
||||||
|
info_x = max(left_obs_x + 112, tx1 + 148)
|
||||||
|
info_y = felt_top + 42
|
||||||
|
|
||||||
|
view._draw_framed_panel(info_x, info_y, 206, 78, frame_style="purple")
|
||||||
|
l1 = f"{t('wt_lbl_schlag')}: {schlag_txt}"
|
||||||
|
l2 = f"{t('wt_lbl_trumpf')}: {trump_txt}"
|
||||||
|
l3 = t("wt_lbl_tricks_pair", eng.team_tricks[0], eng.team_tricks[1])
|
||||||
|
for dy, txt, col in (
|
||||||
|
(-21, l1, ACCENT_GOLD),
|
||||||
|
(0, l2, FONT_COLOR_TITLE_MAIN),
|
||||||
|
(21, l3, FONT_COLOR_STATUS_WIN if eng.team_tricks[0] >= eng.team_tricks[1] else FG_COLOR),
|
||||||
|
):
|
||||||
|
ph = view._make_goth_photo(txt, FONT_SIZE_SMALL_MIN, col, 186)
|
||||||
|
view._place_goth_photo_or_fallback(info_x, info_y + dy, ph, txt, FONT_SIZE_SMALL_MIN, col)
|
||||||
|
|
||||||
|
# 2. Punktestand- & Einsatz-Tafel oben rechts auf dem Tischfilz
|
||||||
|
score_x = min(right_obs_x - 112, tx2 - 148)
|
||||||
|
score_y = felt_top + 42
|
||||||
|
gesp_0 = eng.is_team_gespannt(0)
|
||||||
|
gesp_1 = eng.is_team_gespannt(1)
|
||||||
|
view._draw_framed_panel(
|
||||||
|
score_x,
|
||||||
|
score_y,
|
||||||
|
206,
|
||||||
|
78,
|
||||||
|
frame_style="gold" if (gesp_0 or gesp_1) else "purple",
|
||||||
|
)
|
||||||
|
s1 = t("wt_lbl_match_pts", eng.team_points[0], eng.team_points[1])
|
||||||
|
s2 = t("wt_lbl_cur_stake", eng.current_stake)
|
||||||
|
s3 = (
|
||||||
|
t("wt_lbl_gespannt_warn")
|
||||||
|
if (gesp_0 or gesp_1)
|
||||||
|
else t("wt_lbl_target_11")
|
||||||
|
)
|
||||||
|
for dy, txt, col in (
|
||||||
|
(-21, s1, FONT_COLOR_TITLE_MAIN),
|
||||||
|
(0, s2, ACCENT_GOLD),
|
||||||
|
(21, s3, ERROR_FG if (gesp_0 or gesp_1) else MUTED_FG),
|
||||||
|
):
|
||||||
|
ph = view._make_goth_photo(txt, FONT_SIZE_SMALL_MIN, col, 186)
|
||||||
|
view._place_goth_photo_or_fallback(score_x, score_y + dy, ph, txt, FONT_SIZE_SMALL_MIN, col)
|
||||||
|
|
||||||
|
# 3. 4 Stich-Ablageplätze kreuzförmig in der Tischmitte (Süd=0, West=1, Nord=2, Ost=3)
|
||||||
|
tw, th = WT_TRICK_CARD_SIZE
|
||||||
|
slot_offsets = {
|
||||||
|
0: (0, 32), # Spieler (unten)
|
||||||
|
1: (-86, 0), # Gegner West (links)
|
||||||
|
2: (0, -32), # Partner Nord (oben)
|
||||||
|
3: (86, 0), # Gegner Ost (rechts)
|
||||||
|
}
|
||||||
|
|
||||||
|
active_cards = (
|
||||||
|
view._visible_completed_trick
|
||||||
|
if view._visible_completed_trick
|
||||||
|
else eng.current_trick
|
||||||
|
)
|
||||||
|
if not active_cards:
|
||||||
|
view.arena_canvas.create_oval(
|
||||||
|
center_cx - 64,
|
||||||
|
center_cy - 44,
|
||||||
|
center_cx + 64,
|
||||||
|
center_cy + 44,
|
||||||
|
outline=SUBTLE_BORDER,
|
||||||
|
width=2,
|
||||||
|
dash=(4, 4),
|
||||||
|
tags="fg",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
win_seat = (
|
||||||
|
eng.last_trick_winner if view._visible_completed_trick else None
|
||||||
|
)
|
||||||
|
for seat_id, card in active_cards:
|
||||||
|
dx, dy = slot_offsets.get(seat_id, (0, 0))
|
||||||
|
cx, cy = center_cx + dx, center_cy + dy
|
||||||
|
ph = view.ctx.assets.get_card_photo(
|
||||||
|
card.image_filename, size=WT_TRICK_CARD_SIZE, theme=BAVARIAN_CARD_THEME
|
||||||
|
)
|
||||||
|
if ph is not None:
|
||||||
|
view._photo_refs.append(ph)
|
||||||
|
view.arena_canvas.create_image(cx, cy, image=ph, anchor="center", tags="fg")
|
||||||
|
border_c = ACCENT_GOLD if seat_id == win_seat else BORDER_COLOR
|
||||||
|
border_w = 3 if seat_id == win_seat else 1
|
||||||
|
view.arena_canvas.create_rectangle(
|
||||||
|
cx - tw // 2 - 2,
|
||||||
|
cy - th // 2 - 2,
|
||||||
|
cx + tw // 2 + 2,
|
||||||
|
cy + th // 2 + 2,
|
||||||
|
outline=border_c,
|
||||||
|
width=border_w,
|
||||||
|
tags="fg",
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def draw_human_hand(
|
||||||
|
view, cw: int, player_zone_top: int, player_zone_bot: int
|
||||||
|
) -> list[tuple[BavarianCard, int, int, int, int]]:
|
||||||
|
eng = view.engine
|
||||||
|
human = eng.seats[0]
|
||||||
|
eff_top = max(230, player_zone_top - WT_HAND_TOP_EXTEND_PX)
|
||||||
|
avail_h = max(168, player_zone_bot - eff_top)
|
||||||
|
zone_cy = (eff_top + player_zone_bot) // 2
|
||||||
|
|
||||||
|
base_w, base_h = PLAYING_CARD_SIZE
|
||||||
|
target_h = max(116, min(WT_MAX_HAND_CARD_H, avail_h - 44))
|
||||||
|
scale = target_h / max(1, base_h)
|
||||||
|
card_w = max(78, int(round(base_w * scale)))
|
||||||
|
card_h = int(round(base_h * scale))
|
||||||
|
card_sz = (card_w, card_h)
|
||||||
|
|
||||||
|
is_my_play_turn = (
|
||||||
|
eng.phase == PHASE_TRICK_PLAY
|
||||||
|
and eng.turn_seat == 0
|
||||||
|
and not view._visible_completed_trick
|
||||||
|
)
|
||||||
|
playable_set = set(eng.get_playable_cards(0)) if is_my_play_turn else set()
|
||||||
|
|
||||||
|
n_cards = len(human.hand)
|
||||||
|
step = card_w + 14
|
||||||
|
span_w = card_w + max(0, n_cards - 1) * step if n_cards else card_w
|
||||||
|
|
||||||
|
my_role = ""
|
||||||
|
if eng.dealer_seat == 0:
|
||||||
|
my_role = f" ({t('wt_tag_dealer')})"
|
||||||
|
elif eng.ansager_seat == 0:
|
||||||
|
my_role = f" ({t('wt_tag_ansager')})"
|
||||||
|
lbl_txt = f"{t('wt_your_hand_lbl')}{my_role}"
|
||||||
|
lbl_sz = max(13, FONT_SIZE_BODY - 2)
|
||||||
|
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, FONT_COLOR_TITLE_MAIN)
|
||||||
|
txt_w = lbl_ph.width() if lbl_ph is not None else 280
|
||||||
|
|
||||||
|
box_w = max(420, min(cw - 72, max(span_w + 80, txt_w + 68)))
|
||||||
|
box_h = min(avail_h + 6, card_h + 48)
|
||||||
|
box_cx = cw // 2
|
||||||
|
|
||||||
|
view._draw_framed_panel(
|
||||||
|
box_cx,
|
||||||
|
zone_cy,
|
||||||
|
box_w,
|
||||||
|
box_h,
|
||||||
|
frame_style="gold" if eng.turn_seat == 0 else "purple",
|
||||||
|
)
|
||||||
|
|
||||||
|
hit_rects: list[tuple[BavarianCard, int, int, int, int]] = []
|
||||||
|
start_x = box_cx - span_w // 2
|
||||||
|
base_top = (zone_cy - 8) - card_h // 2
|
||||||
|
|
||||||
|
for idx, card in enumerate(human.hand):
|
||||||
|
is_playable = card in playable_set
|
||||||
|
cx_left = start_x + idx * step
|
||||||
|
cy_top = base_top - (9 if is_playable else 0)
|
||||||
|
|
||||||
|
ph = view.ctx.assets.get_card_photo(
|
||||||
|
card.image_filename, size=card_sz, theme=BAVARIAN_CARD_THEME
|
||||||
|
)
|
||||||
|
if ph is not None:
|
||||||
|
view._photo_refs.append(ph)
|
||||||
|
view.arena_canvas.create_image(
|
||||||
|
cx_left, cy_top, image=ph, anchor="nw", tags="fg"
|
||||||
|
)
|
||||||
|
if is_playable:
|
||||||
|
view.arena_canvas.create_rectangle(
|
||||||
|
cx_left - 2,
|
||||||
|
cy_top - 2,
|
||||||
|
cx_left + card_w + 2,
|
||||||
|
cy_top + card_h + 2,
|
||||||
|
outline=ACCENT_GOLD,
|
||||||
|
width=2,
|
||||||
|
tags="fg",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Dezentes Rollen-Badge oben auf der Karte (Max, Belli, Spitz, Guade, Schlag, Trumpf)
|
||||||
|
badge_key = card_role_badge_key(card, eng.schlag_rank, eng.trump_suit)
|
||||||
|
if badge_key:
|
||||||
|
b_txt = t(badge_key)
|
||||||
|
b_col = (
|
||||||
|
ACCENT_GOLD
|
||||||
|
if badge_key in ("wt_role_max", "wt_role_belli", "wt_role_spitz", "wt_role_guade")
|
||||||
|
else ACCENT_GOTH
|
||||||
|
)
|
||||||
|
view.arena_canvas.create_rectangle(
|
||||||
|
cx_left + 4,
|
||||||
|
cy_top + card_h - 21,
|
||||||
|
cx_left + card_w - 4,
|
||||||
|
cy_top + card_h - 4,
|
||||||
|
fill="#0d0914",
|
||||||
|
outline=b_col,
|
||||||
|
width=1,
|
||||||
|
tags="fg",
|
||||||
|
)
|
||||||
|
view.arena_canvas.create_text(
|
||||||
|
cx_left + card_w // 2,
|
||||||
|
cy_top + card_h - 12,
|
||||||
|
text=b_txt,
|
||||||
|
font=("Georgia", 8, "bold"),
|
||||||
|
fill=b_col,
|
||||||
|
tags="fg",
|
||||||
|
)
|
||||||
|
|
||||||
|
hit_rects.append((card, cx_left, cy_top, cx_left + card_w, cy_top + card_h))
|
||||||
|
|
||||||
|
view._place_goth_photo_or_fallback(
|
||||||
|
box_cx,
|
||||||
|
zone_cy + box_h // 2 - 14,
|
||||||
|
lbl_ph,
|
||||||
|
lbl_txt,
|
||||||
|
lbl_sz,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
)
|
||||||
|
return hit_rects
|
||||||
|
|
@ -0,0 +1,296 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/watten/views/watten_menu_view.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
from games.party.watten.models.watten_tutorials import build_watten_tutorial_units
|
||||||
|
from games.party.watten.views.watten_table_view import WattenTableView
|
||||||
|
from models.database import Database
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
BAVARIAN_CARD_THEME,
|
||||||
|
BOT_LEVEL_COUNT,
|
||||||
|
FONT_COLOR_BODY_DEFAULT,
|
||||||
|
FONT_COLOR_BODY_MUTED,
|
||||||
|
FONT_COLOR_HEADING_SUB,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_BODY,
|
||||||
|
FONT_SIZE_HEADING,
|
||||||
|
FONT_SIZE_SMALL_MIN,
|
||||||
|
FONT_SIZE_TITLE_LG,
|
||||||
|
WT_BOT_COUNT,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from view.tutorial.tutorial_hub_view import TutorialHubView
|
||||||
|
from view.tutorial.tutorial_models import TutorialProgressRepo, TutorialUnit
|
||||||
|
from view.tutorial.tutorial_runner_view import TutorialRunnerView
|
||||||
|
from view.widgets.goth_dropdown import GothDropdown
|
||||||
|
from view.widgets.goth_entry import GothEntry
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
from view.widgets.menu_body_canvas import MenuBodyCanvas
|
||||||
|
|
||||||
|
GAME_FOLDER_ID = "party/watten"
|
||||||
|
GAME_TITLE_KEY = "game_title_watten"
|
||||||
|
|
||||||
|
|
||||||
|
class WattenMenuView:
|
||||||
|
"""Vorauswahl-Menü für Oberbayerisches Watten inkl. interaktivem 4-Kapitel-Tutorial."""
|
||||||
|
|
||||||
|
def __init__(self, context):
|
||||||
|
self.ctx = context
|
||||||
|
self._photo_refs: list = []
|
||||||
|
self._bot_entries: list[GothEntry] = []
|
||||||
|
self._bot_lvl_vars: list[tk.StringVar] = []
|
||||||
|
self._bot_dds: list[GothDropdown] = []
|
||||||
|
|
||||||
|
def _collect_and_save_bots(self) -> list[tuple[int, str]]:
|
||||||
|
pid = self.ctx.profile["id"]
|
||||||
|
lvl_by_label = {t(f"bot_level_{i}"): i for i in range(BOT_LEVEL_COUNT)}
|
||||||
|
active_bots: list[tuple[int, str]] = []
|
||||||
|
to_save: dict[int, tuple[str, int]] = {}
|
||||||
|
|
||||||
|
for idx in range(WT_BOT_COUNT):
|
||||||
|
raw_name = (
|
||||||
|
self._bot_entries[idx].get().strip()
|
||||||
|
if idx < len(self._bot_entries)
|
||||||
|
else ""
|
||||||
|
)
|
||||||
|
b_name = raw_name or t("bot_default_name", idx + 1)
|
||||||
|
lvl = lvl_by_label.get(
|
||||||
|
self._bot_lvl_vars[idx].get(), min(BOT_LEVEL_COUNT - 1, idx + 1)
|
||||||
|
)
|
||||||
|
active_bots.append((lvl, b_name))
|
||||||
|
to_save[idx] = (b_name, lvl)
|
||||||
|
|
||||||
|
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||||
|
return active_bots
|
||||||
|
|
||||||
|
def _open_tutorial_hub(self):
|
||||||
|
if self._bot_entries:
|
||||||
|
self._collect_and_save_bots()
|
||||||
|
units = build_watten_tutorial_units()
|
||||||
|
|
||||||
|
def open_hub():
|
||||||
|
TutorialHubView(
|
||||||
|
self.ctx,
|
||||||
|
game_folder_id=GAME_FOLDER_ID,
|
||||||
|
game_title_key=GAME_TITLE_KEY,
|
||||||
|
units=units,
|
||||||
|
on_start_unit=start_unit,
|
||||||
|
on_back_to_game_menu=self.show,
|
||||||
|
).show()
|
||||||
|
|
||||||
|
def start_unit(unit: TutorialUnit):
|
||||||
|
TutorialRunnerView(
|
||||||
|
self.ctx,
|
||||||
|
game_folder_id=GAME_FOLDER_ID,
|
||||||
|
unit=unit,
|
||||||
|
on_finish_to_hub=open_hub,
|
||||||
|
card_theme=BAVARIAN_CARD_THEME,
|
||||||
|
)
|
||||||
|
|
||||||
|
open_hub()
|
||||||
|
|
||||||
|
def show(self):
|
||||||
|
pid = self.ctx.profile["id"]
|
||||||
|
self.ctx.sounds.play_menu_music()
|
||||||
|
self.ctx.root.clear_window(apply_global_bg=True)
|
||||||
|
self._photo_refs.clear()
|
||||||
|
self._bot_entries.clear()
|
||||||
|
self._bot_lvl_vars.clear()
|
||||||
|
self._bot_dds.clear()
|
||||||
|
self.ctx.refresh_game_progress()
|
||||||
|
|
||||||
|
def refresh_menu():
|
||||||
|
if self._bot_entries:
|
||||||
|
self._collect_and_save_bots()
|
||||||
|
self.show()
|
||||||
|
|
||||||
|
self.ctx.build_game_topbar(
|
||||||
|
self.ctx.root,
|
||||||
|
t("wt_menu_topbar"),
|
||||||
|
stats_endpoint=GAME_FOLDER_ID,
|
||||||
|
stats_enabled=True,
|
||||||
|
on_stats_back=refresh_menu,
|
||||||
|
on_lang_refresh=refresh_menu,
|
||||||
|
)
|
||||||
|
|
||||||
|
cv = MenuBodyCanvas(self.ctx)
|
||||||
|
btn_norm = self.ctx.assets.raw_btn_default
|
||||||
|
btn_purp = self.ctx.assets.raw_btn_purple
|
||||||
|
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
|
||||||
|
|
||||||
|
units = build_watten_tutorial_units()
|
||||||
|
done_cnt = len(TutorialProgressRepo.get_completed_units(pid, GAME_FOLDER_ID))
|
||||||
|
tut_unseen = done_cnt == 0
|
||||||
|
tut_btn = ImageButton(
|
||||||
|
cv,
|
||||||
|
t("wt_btn_open_tutorial", done_cnt, len(units)),
|
||||||
|
btn_fire if tut_unseen else btn_norm,
|
||||||
|
btn_fire if tut_unseen else btn_purp,
|
||||||
|
self._open_tutorial_hub,
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=226,
|
||||||
|
height=38,
|
||||||
|
style="fire" if tut_unseen else "amethyst",
|
||||||
|
)
|
||||||
|
|
||||||
|
saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID)
|
||||||
|
ai_labels = [t(f"bot_level_{i}") for i in range(BOT_LEVEL_COUNT)]
|
||||||
|
|
||||||
|
for i in range(WT_BOT_COUNT):
|
||||||
|
def_name = t("bot_default_name", i + 1)
|
||||||
|
def_lvl = 2
|
||||||
|
if i in saved_bots:
|
||||||
|
s_name, s_lvl = saved_bots[i]
|
||||||
|
b_name = s_name or def_name
|
||||||
|
b_lvl = max(0, min(BOT_LEVEL_COUNT - 1, int(s_lvl)))
|
||||||
|
else:
|
||||||
|
b_name, b_lvl = def_name, def_lvl
|
||||||
|
|
||||||
|
entry = GothEntry(
|
||||||
|
cv,
|
||||||
|
self.ctx.assets,
|
||||||
|
width=230,
|
||||||
|
height=36,
|
||||||
|
textvariable=tk.StringVar(value=b_name),
|
||||||
|
)
|
||||||
|
l_var = tk.StringVar(value=t(f"bot_level_{b_lvl}"))
|
||||||
|
dd = GothDropdown(
|
||||||
|
cv,
|
||||||
|
self.ctx.assets,
|
||||||
|
values=ai_labels,
|
||||||
|
textvariable=l_var,
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=270,
|
||||||
|
height=36,
|
||||||
|
)
|
||||||
|
self._bot_entries.append(entry)
|
||||||
|
self._bot_lvl_vars.append(l_var)
|
||||||
|
self._bot_dds.append(dd)
|
||||||
|
|
||||||
|
def start_match():
|
||||||
|
bots = self._collect_and_save_bots()
|
||||||
|
WattenTableView(
|
||||||
|
self.ctx,
|
||||||
|
variant_key="watten_std",
|
||||||
|
bot_configs=bots,
|
||||||
|
on_back_to_menu=self.show,
|
||||||
|
)
|
||||||
|
|
||||||
|
start_btn = ImageButton(
|
||||||
|
cv,
|
||||||
|
t("wt_start_btn"),
|
||||||
|
btn_fire,
|
||||||
|
btn_fire,
|
||||||
|
start_match,
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=210,
|
||||||
|
height=40,
|
||||||
|
style="fire",
|
||||||
|
)
|
||||||
|
|
||||||
|
seat_role_keys = (
|
||||||
|
"wt_menu_seat_west", # idx 0 -> Sitz 1 (Gegner Links)
|
||||||
|
"wt_menu_seat_partner", # idx 1 -> Sitz 2 (Partner Oben!)
|
||||||
|
"wt_menu_seat_east", # idx 2 -> Sitz 3 (Gegner Rechts)
|
||||||
|
)
|
||||||
|
|
||||||
|
def draw_layout(w: int, h: int):
|
||||||
|
cv.sync_bg(w, h)
|
||||||
|
cv.delete("fg")
|
||||||
|
self._photo_refs.clear()
|
||||||
|
|
||||||
|
box_w = min(940, w - 120)
|
||||||
|
cx = w // 2
|
||||||
|
x_left = cx - box_w // 2
|
||||||
|
cur_y = max(20, int(h * 0.045))
|
||||||
|
|
||||||
|
title_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left"
|
||||||
|
)
|
||||||
|
sub_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("wt_menu_subtitle"),
|
||||||
|
FONT_SIZE_BODY,
|
||||||
|
FONT_COLOR_BODY_MUTED,
|
||||||
|
max_width=box_w,
|
||||||
|
align="left",
|
||||||
|
)
|
||||||
|
self._photo_refs.extend([title_ph, sub_ph])
|
||||||
|
cv.create_image(x_left, cur_y, image=title_ph, anchor="nw", tags="fg")
|
||||||
|
cur_y += title_ph.height() + 4
|
||||||
|
cv.create_image(x_left, cur_y, image=sub_ph, anchor="nw", tags="fg")
|
||||||
|
cur_y += sub_ph.height() + 16
|
||||||
|
|
||||||
|
# 1. Regelwerk & Lehrmeister-Tutorial-Box
|
||||||
|
s1_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("wt_rules_sec_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_HEADING_SUB, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.append(s1_ph)
|
||||||
|
cv.create_image(x_left + 6, cur_y, image=s1_ph, anchor="nw", tags="fg")
|
||||||
|
cur_y += s1_ph.height() + 6
|
||||||
|
|
||||||
|
r_box_h = 84
|
||||||
|
r_cy = cur_y + r_box_h // 2
|
||||||
|
r_box = self.ctx.assets.get_box_photo("box_gold_double", (box_w, r_box_h))
|
||||||
|
if r_box:
|
||||||
|
self._photo_refs.append(r_box)
|
||||||
|
cv.create_image(cx, r_cy, image=r_box, anchor="center", tags="fg")
|
||||||
|
|
||||||
|
v_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("variant_watten_std"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
|
||||||
|
)
|
||||||
|
d_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("wt_rule_summary"),
|
||||||
|
FONT_SIZE_SMALL_MIN,
|
||||||
|
FONT_COLOR_BODY_DEFAULT,
|
||||||
|
max_width=box_w - 285,
|
||||||
|
align="left",
|
||||||
|
)
|
||||||
|
self._photo_refs.extend([v_ph, d_ph])
|
||||||
|
cv.create_image(x_left + 26, r_cy - 16, image=v_ph, anchor="w", tags="fg")
|
||||||
|
cv.create_image(x_left + 26, r_cy + 16, image=d_ph, anchor="w", tags="fg")
|
||||||
|
cv.create_window(
|
||||||
|
x_left + box_w - 24, r_cy, window=tut_btn, anchor="e", tags="fg"
|
||||||
|
)
|
||||||
|
cur_y += r_box_h + 16
|
||||||
|
|
||||||
|
# 2. Partner & Gegner konfigurieren
|
||||||
|
s2_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("wt_bots_sec_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_HEADING_SUB, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.append(s2_ph)
|
||||||
|
cv.create_image(x_left + 6, cur_y, image=s2_ph, anchor="nw", tags="fg")
|
||||||
|
cur_y += s2_ph.height() + 6
|
||||||
|
|
||||||
|
b_box_h = 236
|
||||||
|
b_cy = cur_y + b_box_h // 2
|
||||||
|
b_box = self.ctx.assets.get_box_photo("box_big", (box_w, b_box_h))
|
||||||
|
if b_box:
|
||||||
|
self._photo_refs.append(b_box)
|
||||||
|
cv.create_image(cx, b_cy, image=b_box, anchor="center", tags="fg")
|
||||||
|
|
||||||
|
dd_w = max(210, box_w - 460)
|
||||||
|
for idx in range(WT_BOT_COUNT):
|
||||||
|
ry = cur_y + 38 + idx * 50
|
||||||
|
seat_lbl = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t(seat_role_keys[idx]), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.append(seat_lbl)
|
||||||
|
cv.create_image(x_left + 28, ry, image=seat_lbl, anchor="w", tags="fg")
|
||||||
|
cv.create_window(x_left + 168, ry, window=self._bot_entries[idx], anchor="w", tags="fg")
|
||||||
|
|
||||||
|
dd = self._bot_dds[idx]
|
||||||
|
if dd._width != dd_w:
|
||||||
|
dd._width = dd_w
|
||||||
|
dd.configure(width=dd_w)
|
||||||
|
dd._render_closed()
|
||||||
|
cv.create_window(x_left + 416, ry, window=dd, anchor="w", tags="fg")
|
||||||
|
|
||||||
|
cv.create_window(
|
||||||
|
x_left + box_w - 32, cur_y + b_box_h - 36, window=start_btn, anchor="e", tags="fg"
|
||||||
|
)
|
||||||
|
|
||||||
|
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
|
||||||
|
self.ctx.root.update_idletasks()
|
||||||
|
draw_layout(max(900, cv.winfo_width()), max(620, cv.winfo_height()))
|
||||||
|
|
@ -0,0 +1,150 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/watten/views/watten_result_dialog.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from PIL import Image, ImageTk
|
||||||
|
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
FONT_COLOR_BODY_DEFAULT,
|
||||||
|
FONT_COLOR_HEADING_SUB,
|
||||||
|
FONT_COLOR_STATUS_LOSS,
|
||||||
|
FONT_COLOR_STATUS_WIN,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_BODY,
|
||||||
|
FONT_SIZE_HEADING,
|
||||||
|
SUBTLE_BORDER,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from view.widgets.casino_result_dialog_base import CasinoResultDialogBase
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
|
||||||
|
|
||||||
|
class WattenResultDialog(CasinoResultDialogBase):
|
||||||
|
"""Satz-Abschlussdialog für Watten (Endstand bis 11 Punkte, gespielte Hände & XP)."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self, parent, assets, sounds, result_data: dict, on_next_round, on_back_to_menu
|
||||||
|
):
|
||||||
|
dlg_w = 640
|
||||||
|
dlg_h = 356 + (22 if result_data.get("new_level_title") else 0)
|
||||||
|
super().__init__(
|
||||||
|
parent, assets, sounds, result_data, dlg_w, dlg_h, on_next_round, on_back_to_menu
|
||||||
|
)
|
||||||
|
|
||||||
|
def _build_scene(self):
|
||||||
|
w, h = self._dlg_w, self._dlg_h
|
||||||
|
cx = w // 2
|
||||||
|
self._photo_refs.clear()
|
||||||
|
|
||||||
|
bg_src = (
|
||||||
|
self.assets.raw_bg_vertical
|
||||||
|
or self.assets.raw_bg_horizontal
|
||||||
|
or self.assets.raw_bg
|
||||||
|
)
|
||||||
|
if bg_src is not None:
|
||||||
|
bg_ph = ImageTk.PhotoImage(bg_src.resize((w, h), Image.Resampling.LANCZOS))
|
||||||
|
self._photo_refs.append(bg_ph)
|
||||||
|
self.create_image(0, 0, image=bg_ph, anchor="nw")
|
||||||
|
|
||||||
|
outer_box = self.assets.get_box_photo("box_big", (w - 6, h - 6))
|
||||||
|
if outer_box:
|
||||||
|
self._photo_refs.append(outer_box)
|
||||||
|
self.create_image(cx, h // 2, image=outer_box, anchor="center")
|
||||||
|
|
||||||
|
p_won = bool(self.data.get("player_won"))
|
||||||
|
hl_ph = self.assets.get_goth_text_photo(
|
||||||
|
self.data["headline"],
|
||||||
|
24,
|
||||||
|
FONT_COLOR_TITLE_MAIN if p_won else FONT_COLOR_STATUS_LOSS,
|
||||||
|
max_width=w - 64,
|
||||||
|
)
|
||||||
|
self._photo_refs.append(hl_ph)
|
||||||
|
cur_y = 30
|
||||||
|
self.create_image(cx, cur_y + hl_ph.height() // 2, image=hl_ph, anchor="center")
|
||||||
|
cur_y += hl_ph.height() + 16
|
||||||
|
|
||||||
|
# Team-Vergleichsboxen (Dein Team vs. Gegner-Team)
|
||||||
|
box_w_sm, box_h_sm = (w - 92) // 2, 118
|
||||||
|
teams = [
|
||||||
|
(
|
||||||
|
self.data["team0_names"],
|
||||||
|
self.data["team0_pts"],
|
||||||
|
p_won,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
self.data["team1_names"],
|
||||||
|
self.data["team1_pts"],
|
||||||
|
not p_won,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
for idx, (names_str, pts, is_w) in enumerate(teams):
|
||||||
|
tx = 38 + idx * (box_w_sm + 16) + box_w_sm // 2
|
||||||
|
ty = cur_y + box_h_sm // 2
|
||||||
|
f_ph = self.assets.get_box_photo(
|
||||||
|
"box_gold_small" if is_w else "box_purple", (box_w_sm, box_h_sm)
|
||||||
|
)
|
||||||
|
if f_ph:
|
||||||
|
self._photo_refs.append(f_ph)
|
||||||
|
self.create_image(tx, ty, image=f_ph, anchor="center")
|
||||||
|
|
||||||
|
n_ph = self.assets.get_goth_text_photo(
|
||||||
|
names_str,
|
||||||
|
FONT_SIZE_BODY - 1,
|
||||||
|
FONT_COLOR_TITLE_MAIN if is_w else FONT_COLOR_HEADING_SUB,
|
||||||
|
max_width=box_w_sm - 24,
|
||||||
|
)
|
||||||
|
p_ph = self.assets.get_goth_text_photo(
|
||||||
|
t("wt_popup_team_pts", pts),
|
||||||
|
FONT_SIZE_HEADING,
|
||||||
|
FONT_COLOR_STATUS_WIN if is_w else FONT_COLOR_BODY_DEFAULT,
|
||||||
|
max_width=box_w_sm - 24,
|
||||||
|
)
|
||||||
|
self._photo_refs.extend([n_ph, p_ph])
|
||||||
|
self.create_image(tx, ty - 22, image=n_ph, anchor="center")
|
||||||
|
self.create_image(tx, ty + 20, image=p_ph, anchor="center")
|
||||||
|
|
||||||
|
cur_y += box_h_sm + 18
|
||||||
|
self.create_line(36, cur_y, w - 36, cur_y, fill=SUBTLE_BORDER, width=1)
|
||||||
|
cur_y += 14
|
||||||
|
|
||||||
|
xp_line = t("bj_popup_xp_earned", self.data["xp_gained"])
|
||||||
|
if self.data.get("new_level_title"):
|
||||||
|
xp_line = f"{xp_line} | {self.data['new_level_title']}"
|
||||||
|
xp_ph = self.assets.get_goth_text_photo(
|
||||||
|
xp_line,
|
||||||
|
FONT_SIZE_BODY + 1,
|
||||||
|
FONT_COLOR_TITLE_MAIN if self.data.get("new_level_title") else FONT_COLOR_HEADING_SUB,
|
||||||
|
max_width=w - 72,
|
||||||
|
)
|
||||||
|
self._photo_refs.append(xp_ph)
|
||||||
|
self.create_image(cx, cur_y + xp_ph.height() // 2, image=xp_ph, anchor="center")
|
||||||
|
|
||||||
|
btn_norm = self.assets.raw_btn_default
|
||||||
|
btn_purp = self.assets.raw_btn_purple
|
||||||
|
btn_fire = self.assets.raw_btn_fire or btn_purp
|
||||||
|
btn_y = h - 36
|
||||||
|
|
||||||
|
b_next = ImageButton(
|
||||||
|
self,
|
||||||
|
t("wt_popup_new_match_btn"),
|
||||||
|
btn_fire,
|
||||||
|
btn_fire,
|
||||||
|
self._handle_next,
|
||||||
|
sound_mgr=self.sounds,
|
||||||
|
width=205,
|
||||||
|
height=38,
|
||||||
|
style="fire",
|
||||||
|
)
|
||||||
|
b_menu = ImageButton(
|
||||||
|
self,
|
||||||
|
t("bj_popup_to_menu_btn"),
|
||||||
|
btn_norm,
|
||||||
|
btn_purp,
|
||||||
|
self._handle_menu,
|
||||||
|
sound_mgr=self.sounds,
|
||||||
|
width=175,
|
||||||
|
height=38,
|
||||||
|
style="amethyst",
|
||||||
|
)
|
||||||
|
self.create_window(42, btn_y, window=b_next, anchor="w")
|
||||||
|
self.create_window(w - 42, btn_y, window=b_menu, anchor="e")
|
||||||
|
|
@ -0,0 +1,565 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/watten/views/watten_table_view.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
from games.party.watten.models.watten_ai import WattenBotAI
|
||||||
|
from games.party.watten.models.watten_engine import (
|
||||||
|
PHASE_ANSAGE_SCHLAG,
|
||||||
|
PHASE_ANSAGE_TRUMPF,
|
||||||
|
PHASE_AUSSCHAFFEN_REPLY,
|
||||||
|
PHASE_HAND_DONE,
|
||||||
|
PHASE_MATCH_DONE,
|
||||||
|
PHASE_SCHOENERE_ASK,
|
||||||
|
PHASE_SCHOENERE_REPLY,
|
||||||
|
PHASE_TRICK_PLAY,
|
||||||
|
WattenEngine,
|
||||||
|
)
|
||||||
|
from games.party.watten.models.watten_rules import WATTEN_RANKS_32
|
||||||
|
from games.party.watten.views.watten_arena_renderer import WattenArenaRenderer
|
||||||
|
from games.party.watten.views.watten_result_dialog import WattenResultDialog
|
||||||
|
from models.bavarian_deck import BavarianCard
|
||||||
|
from models.progression import Progression
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
BAVARIAN_SUITS,
|
||||||
|
WT_BOT_TURN_DELAY_MS,
|
||||||
|
WT_TRICK_CLEAR_DELAY_MS,
|
||||||
|
WT_VARIANTS,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from view.widgets.casino_arena_base import CasinoArenaBase
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
|
||||||
|
GAME_FOLDER_ID = "party/watten"
|
||||||
|
|
||||||
|
|
||||||
|
class WattenTableView(CasinoArenaBase):
|
||||||
|
GAME_FOLDER_ID = GAME_FOLDER_ID
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
context,
|
||||||
|
variant_key: str,
|
||||||
|
bot_configs: list[tuple[int, str]],
|
||||||
|
on_back_to_menu,
|
||||||
|
):
|
||||||
|
v_key = variant_key if variant_key in WT_VARIANTS else "watten_std"
|
||||||
|
cfg = WT_VARIANTS[v_key]
|
||||||
|
self._init_arena_state(context, v_key, cfg, on_back_to_menu)
|
||||||
|
|
||||||
|
self._bot_configs = list(bot_configs)
|
||||||
|
self.engine = WattenEngine()
|
||||||
|
self.engine.configure_seats(self.ctx.profile["name"], self._bot_configs)
|
||||||
|
|
||||||
|
self.match_start_time: float = time.time()
|
||||||
|
self._hand_hit_rects: list[tuple[BavarianCard, int, int, int, int]] = []
|
||||||
|
self._visible_completed_trick: list[tuple[int, BavarianCard]] = []
|
||||||
|
self._trick_pause_job: str | None = None
|
||||||
|
self._last_popup_payload: dict | None = None
|
||||||
|
|
||||||
|
self.ctx.sounds.play_ingame_music()
|
||||||
|
self._build_ui()
|
||||||
|
self._start_new_match()
|
||||||
|
|
||||||
|
def _cancel_jobs(self):
|
||||||
|
if self._trick_pause_job is not None:
|
||||||
|
try:
|
||||||
|
self.ctx.root.after_cancel(self._trick_pause_job)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._trick_pause_job = None
|
||||||
|
super()._cancel_jobs()
|
||||||
|
|
||||||
|
def _build_ui(self):
|
||||||
|
self._build_arena_shell(on_lang_refresh=self._on_language_switched)
|
||||||
|
self.arena_canvas.bind("<ButtonPress-1>", self._on_canvas_click)
|
||||||
|
|
||||||
|
btn_norm = self.ctx.assets.raw_btn_default
|
||||||
|
btn_purp = self.ctx.assets.raw_btn_purple
|
||||||
|
self._menu_btn = ImageButton(
|
||||||
|
self.bottom_bar,
|
||||||
|
t("bj_popup_to_menu_btn"),
|
||||||
|
btn_norm,
|
||||||
|
btn_purp,
|
||||||
|
lambda: self._cleanup_and_go(self.on_back_to_menu),
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=150,
|
||||||
|
height=30,
|
||||||
|
style="amethyst",
|
||||||
|
)
|
||||||
|
|
||||||
|
def _on_arena_resize_redraw(self):
|
||||||
|
self._render_table()
|
||||||
|
|
||||||
|
def _on_language_switched(self):
|
||||||
|
ImageButton.close_active_hover_tip()
|
||||||
|
self._cancel_fx_overlay()
|
||||||
|
self._build_ui()
|
||||||
|
self._render_table()
|
||||||
|
if self.engine.is_match_over and self._last_popup_payload is not None:
|
||||||
|
self._open_result_popup(
|
||||||
|
self._localize_popup(self._last_popup_payload), play_fx=False
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._sync_turn_controls()
|
||||||
|
|
||||||
|
def _refresh_header(self):
|
||||||
|
eng = self.engine
|
||||||
|
schlag_s = t(f"bav_rank_{eng.schlag_rank}") if eng.schlag_rank else "?"
|
||||||
|
trump_s = t(f"bav_suit_{eng.trump_suit}") if eng.trump_suit else "?"
|
||||||
|
self._set_hud_segments(
|
||||||
|
t("wt_hud_score", eng.team_points[0], eng.team_points[1], eng.current_stake),
|
||||||
|
t("wt_hud_ansage", schlag_s, trump_s),
|
||||||
|
t("wt_hud_tricks", eng.team_tricks[0], eng.team_tricks[1]),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _start_new_match(self):
|
||||||
|
self._cancel_jobs()
|
||||||
|
if self._result_dialog is not None:
|
||||||
|
self._result_dialog.close_dialog()
|
||||||
|
self._result_dialog = None
|
||||||
|
self._visible_completed_trick.clear()
|
||||||
|
self._last_popup_payload = None
|
||||||
|
self.match_start_time = time.time()
|
||||||
|
|
||||||
|
self.engine.start_new_match()
|
||||||
|
self.ctx.sounds.play("deal")
|
||||||
|
if not self._canvas_alive():
|
||||||
|
self._build_ui()
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
|
||||||
|
def _start_next_hand(self):
|
||||||
|
self._cancel_jobs()
|
||||||
|
self._visible_completed_trick.clear()
|
||||||
|
self.engine.start_new_hand(rotate_dealer=True)
|
||||||
|
self.ctx.sounds.play("deal")
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
|
||||||
|
def _render_table(self):
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
cw, _ch, pad_x, pad_top, _pad_bot, p_top, p_bot, table_rect = (
|
||||||
|
self._prepare_arena_surface()
|
||||||
|
)
|
||||||
|
bot_bounds = WattenArenaRenderer.draw_other_seats(
|
||||||
|
self, cw, pad_x, pad_top, table_rect
|
||||||
|
)
|
||||||
|
WattenArenaRenderer.draw_center_trick_area(
|
||||||
|
self, cw, table_rect, bot_bounds, p_top
|
||||||
|
)
|
||||||
|
self._hand_hit_rects = WattenArenaRenderer.draw_human_hand(
|
||||||
|
self, cw, p_top, p_bot
|
||||||
|
)
|
||||||
|
if self.arena_canvas.find_withtag("modal_dim_veil"):
|
||||||
|
self.arena_canvas.tag_raise("modal_dim_veil")
|
||||||
|
self._refresh_header()
|
||||||
|
if self._result_dialog is not None and self._result_dialog.winfo_exists():
|
||||||
|
tk.Widget.tkraise(self._result_dialog)
|
||||||
|
|
||||||
|
# --- Steuerung & Phasen-Buttons für den menschlichen Spieler (Sitz 0) ---
|
||||||
|
def _sync_turn_controls(self):
|
||||||
|
if not hasattr(self, "bottom_bar") or not self.bottom_bar.winfo_exists():
|
||||||
|
return
|
||||||
|
eng = self.engine
|
||||||
|
btn_norm = self.ctx.assets.raw_btn_default
|
||||||
|
btn_purp = self.ctx.assets.raw_btn_purple
|
||||||
|
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
|
||||||
|
|
||||||
|
if eng.phase == PHASE_MATCH_DONE:
|
||||||
|
self.status_var.set("")
|
||||||
|
self._set_bottom_buttons([])
|
||||||
|
return
|
||||||
|
|
||||||
|
if eng.phase == PHASE_HAND_DONE:
|
||||||
|
w_team = eng.hand_winner_team or 0
|
||||||
|
msg_key = "wt_status_hand_won" if w_team == 0 else "wt_status_hand_lost"
|
||||||
|
self.status_var.set(t(msg_key, eng.hand_points_awarded))
|
||||||
|
nxt_btn = ImageButton(
|
||||||
|
self.bottom_bar,
|
||||||
|
t("wt_btn_next_hand"),
|
||||||
|
btn_fire,
|
||||||
|
btn_fire,
|
||||||
|
self._start_next_hand,
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=188,
|
||||||
|
height=32,
|
||||||
|
style="fire",
|
||||||
|
)
|
||||||
|
self._set_bottom_buttons([nxt_btn], overflow_buttons=[self._menu_btn])
|
||||||
|
return
|
||||||
|
|
||||||
|
if self._visible_completed_trick or eng.turn_seat != 0:
|
||||||
|
if not self._visible_completed_trick:
|
||||||
|
actor = eng.seats[eng.turn_seat].name
|
||||||
|
self.status_var.set(t("wt_status_waiting_for", actor))
|
||||||
|
self._set_bottom_buttons([], overflow_buttons=[self._menu_btn])
|
||||||
|
return
|
||||||
|
|
||||||
|
# Menschlicher Spieler ist am Zug:
|
||||||
|
if eng.phase in (PHASE_SCHOENERE_ASK, PHASE_ANSAGE_SCHLAG):
|
||||||
|
self.status_var.set(t("wt_status_pick_schlag"))
|
||||||
|
rank_btns = [
|
||||||
|
ImageButton(
|
||||||
|
self.bottom_bar,
|
||||||
|
rk,
|
||||||
|
btn_norm,
|
||||||
|
btn_purp,
|
||||||
|
lambda r=rk: self._on_human_schlag(r),
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=54,
|
||||||
|
height=30,
|
||||||
|
style="amethyst",
|
||||||
|
)
|
||||||
|
for rk in WATTEN_RANKS_32
|
||||||
|
]
|
||||||
|
ovf = [self._menu_btn]
|
||||||
|
if eng.phase == PHASE_SCHOENERE_ASK:
|
||||||
|
ovf.insert(
|
||||||
|
0,
|
||||||
|
ImageButton(
|
||||||
|
self.bottom_bar,
|
||||||
|
t("wt_btn_ask_schoenere"),
|
||||||
|
btn_fire,
|
||||||
|
btn_fire,
|
||||||
|
self._on_human_ask_schoenere,
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=136,
|
||||||
|
height=30,
|
||||||
|
style="fire",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
self._set_bottom_buttons(rank_btns, overflow_buttons=ovf)
|
||||||
|
return
|
||||||
|
|
||||||
|
if eng.phase == PHASE_SCHOENERE_REPLY:
|
||||||
|
self.status_var.set(t("wt_status_reply_schoenere", eng.seats[eng.ansager_seat].name))
|
||||||
|
b_yes = ImageButton(
|
||||||
|
self.bottom_bar, t("wt_btn_schoenere_yes"), btn_fire, btn_fire,
|
||||||
|
lambda: self._on_human_reply_schoenere(True),
|
||||||
|
sound_mgr=self.ctx.sounds, width=164, height=32, style="fire",
|
||||||
|
)
|
||||||
|
b_no = ImageButton(
|
||||||
|
self.bottom_bar, t("wt_btn_schoenere_no"), btn_norm, btn_purp,
|
||||||
|
lambda: self._on_human_reply_schoenere(False),
|
||||||
|
sound_mgr=self.ctx.sounds, width=164, height=32, style="amethyst",
|
||||||
|
)
|
||||||
|
self._set_bottom_buttons([b_yes, b_no], overflow_buttons=[self._menu_btn])
|
||||||
|
return
|
||||||
|
|
||||||
|
if eng.phase == PHASE_ANSAGE_TRUMPF:
|
||||||
|
self.status_var.set(t("wt_status_pick_trumpf", t(f"bav_rank_{eng.schlag_rank}")))
|
||||||
|
suit_btns = [
|
||||||
|
ImageButton(
|
||||||
|
self.bottom_bar,
|
||||||
|
t(f"bav_suit_{s}"),
|
||||||
|
btn_fire,
|
||||||
|
btn_fire,
|
||||||
|
lambda su=s: self._on_human_trumpf(su),
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=116,
|
||||||
|
height=32,
|
||||||
|
style="fire",
|
||||||
|
)
|
||||||
|
for s in BAVARIAN_SUITS
|
||||||
|
]
|
||||||
|
self._set_bottom_buttons(suit_btns, overflow_buttons=[self._menu_btn])
|
||||||
|
return
|
||||||
|
|
||||||
|
if eng.phase == PHASE_AUSSCHAFFEN_REPLY:
|
||||||
|
self.status_var.set(t("wt_status_opp_raised", eng.proposed_stake, eng.current_stake))
|
||||||
|
b_hold = ImageButton(
|
||||||
|
self.bottom_bar,
|
||||||
|
t("wt_btn_hold_stake", eng.proposed_stake),
|
||||||
|
btn_fire,
|
||||||
|
btn_fire,
|
||||||
|
lambda: self._on_human_reply_ausschaffen(True),
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=176,
|
||||||
|
height=32,
|
||||||
|
style="fire",
|
||||||
|
)
|
||||||
|
b_fold = ImageButton(
|
||||||
|
self.bottom_bar,
|
||||||
|
t("wt_btn_fold_hand"),
|
||||||
|
btn_norm,
|
||||||
|
btn_purp,
|
||||||
|
lambda: self._on_human_reply_ausschaffen(False),
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=168,
|
||||||
|
height=32,
|
||||||
|
style="amethyst",
|
||||||
|
)
|
||||||
|
self._set_bottom_buttons([b_hold, b_fold], overflow_buttons=[self._menu_btn])
|
||||||
|
return
|
||||||
|
|
||||||
|
if eng.phase == PHASE_TRICK_PLAY:
|
||||||
|
playable = eng.get_playable_cards(0)
|
||||||
|
if len(playable) < len(eng.seats[0].hand):
|
||||||
|
self.status_var.set(t("wt_status_trump_compulsion"))
|
||||||
|
else:
|
||||||
|
self.status_var.set(t("wt_status_your_turn_card"))
|
||||||
|
|
||||||
|
prim: list[ImageButton] = []
|
||||||
|
if eng.can_seat_ausschaffen(0):
|
||||||
|
prim.append(
|
||||||
|
ImageButton(
|
||||||
|
self.bottom_bar,
|
||||||
|
t("wt_btn_ausschaffen", eng.current_stake + 1),
|
||||||
|
btn_fire,
|
||||||
|
btn_fire,
|
||||||
|
self._on_human_ausschaffen,
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=186,
|
||||||
|
height=32,
|
||||||
|
style="fire",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self._set_bottom_buttons(prim, overflow_buttons=[self._menu_btn])
|
||||||
|
|
||||||
|
# --- Menschliche Klick-Aktionen ---
|
||||||
|
def _on_human_ask_schoenere(self):
|
||||||
|
if self.engine.ask_schoenere(0):
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
|
||||||
|
def _on_human_reply_schoenere(self, accept: bool):
|
||||||
|
if self.engine.reply_schoenere(0, accept):
|
||||||
|
if accept:
|
||||||
|
self.ctx.sounds.play("deal")
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
|
||||||
|
def _on_human_schlag(self, rank: str):
|
||||||
|
if self.engine.declare_schlag(0, rank):
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
|
||||||
|
def _on_human_trumpf(self, suit: str):
|
||||||
|
if self.engine.declare_trumpf(0, suit):
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
|
||||||
|
def _on_human_ausschaffen(self):
|
||||||
|
if self.engine.initiate_ausschaffen(0):
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
|
||||||
|
def _on_human_reply_ausschaffen(self, hold: bool):
|
||||||
|
if self.engine.respond_ausschaffen(0, hold):
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
|
||||||
|
def _on_canvas_click(self, event):
|
||||||
|
if (
|
||||||
|
self._fx_overlay is not None
|
||||||
|
or self._result_dialog is not None
|
||||||
|
or self._visible_completed_trick
|
||||||
|
or self.engine.phase != PHASE_TRICK_PLAY
|
||||||
|
or self.engine.turn_seat != 0
|
||||||
|
):
|
||||||
|
return
|
||||||
|
|
||||||
|
for card, x1, y1, x2, y2 in reversed(self._hand_hit_rects):
|
||||||
|
if x1 <= event.x <= x2 and y1 <= event.y <= y2:
|
||||||
|
res = self.engine.play_card(0, card)
|
||||||
|
if res == "invalid":
|
||||||
|
self.ctx.sounds.play("lose")
|
||||||
|
self.status_var.set(t("wt_status_trump_compulsion"))
|
||||||
|
return
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
self._handle_post_card_play(res)
|
||||||
|
return
|
||||||
|
|
||||||
|
# --- Spielfluss & KI-Züge ---
|
||||||
|
def _handle_post_card_play(self, res: str):
|
||||||
|
if res in ("trick_completed", "hand_completed", "match_completed"):
|
||||||
|
self._visible_completed_trick = list(self.engine.last_completed_trick)
|
||||||
|
win_id = self.engine.last_trick_winner
|
||||||
|
if win_id is not None:
|
||||||
|
self.status_var.set(
|
||||||
|
t("wt_status_trick_winner", self.engine.seats[win_id].name)
|
||||||
|
)
|
||||||
|
self._render_table()
|
||||||
|
self._sync_turn_controls()
|
||||||
|
self._trick_pause_job = self.ctx.root.after(
|
||||||
|
WT_TRICK_CLEAR_DELAY_MS, self._after_trick_pause
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
|
||||||
|
def _after_trick_pause(self):
|
||||||
|
self._trick_pause_job = None
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
self._visible_completed_trick.clear()
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
|
||||||
|
def _advance_flow(self):
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
if self.engine.phase == PHASE_MATCH_DONE:
|
||||||
|
self._finalize_match()
|
||||||
|
return
|
||||||
|
self._sync_turn_controls()
|
||||||
|
if self.engine.phase != PHASE_HAND_DONE and self.engine.turn_seat != 0:
|
||||||
|
self._turn_job = self.ctx.root.after(
|
||||||
|
WT_BOT_TURN_DELAY_MS, self._execute_bot_step
|
||||||
|
)
|
||||||
|
|
||||||
|
def _execute_bot_step(self):
|
||||||
|
self._turn_job = None
|
||||||
|
if not self._canvas_alive() or self.engine.turn_seat == 0:
|
||||||
|
return
|
||||||
|
eng = self.engine
|
||||||
|
bot = eng.seats[eng.turn_seat]
|
||||||
|
|
||||||
|
if eng.phase == PHASE_SCHOENERE_ASK:
|
||||||
|
if WattenBotAI.should_ask_schoenere(bot):
|
||||||
|
bot.status_text = t("wt_act_asked_schoenere")
|
||||||
|
eng.ask_schoenere(bot.seat_id)
|
||||||
|
else:
|
||||||
|
eng.skip_schoenere(bot.seat_id)
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
return
|
||||||
|
|
||||||
|
if eng.phase == PHASE_SCHOENERE_REPLY:
|
||||||
|
accept = WattenBotAI.should_accept_schoenere(bot)
|
||||||
|
bot.status_text = (
|
||||||
|
t("wt_act_schoenere_yes") if accept else t("wt_act_schoenere_no")
|
||||||
|
)
|
||||||
|
eng.reply_schoenere(bot.seat_id, accept)
|
||||||
|
if accept:
|
||||||
|
self.ctx.sounds.play("deal")
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
return
|
||||||
|
|
||||||
|
if eng.phase == PHASE_ANSAGE_SCHLAG:
|
||||||
|
rk = WattenBotAI.choose_schlag(bot)
|
||||||
|
bot.status_text = f"{t('wt_lbl_schlag')}: {t(f'bav_rank_{rk}')}"
|
||||||
|
eng.declare_schlag(bot.seat_id, rk)
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
return
|
||||||
|
|
||||||
|
if eng.phase == PHASE_ANSAGE_TRUMPF:
|
||||||
|
su = WattenBotAI.choose_trumpf(bot, eng.schlag_rank or "O")
|
||||||
|
bot.status_text = f"{t('wt_lbl_trumpf')}: {t(f'bav_suit_{su}')}"
|
||||||
|
eng.declare_trumpf(bot.seat_id, su)
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
return
|
||||||
|
|
||||||
|
if eng.phase == PHASE_AUSSCHAFFEN_REPLY:
|
||||||
|
hold = WattenBotAI.should_hold_ausschaffen(eng, bot)
|
||||||
|
bot.status_text = (
|
||||||
|
t("wt_act_held", eng.proposed_stake)
|
||||||
|
if hold
|
||||||
|
else t("wt_act_folded")
|
||||||
|
)
|
||||||
|
eng.respond_ausschaffen(bot.seat_id, hold)
|
||||||
|
self.ctx.sounds.play("click" if hold else "stand")
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
return
|
||||||
|
|
||||||
|
if eng.phase == PHASE_TRICK_PLAY:
|
||||||
|
if WattenBotAI.should_ausschaffen(eng, bot):
|
||||||
|
bot.status_text = t("wt_act_raised", eng.current_stake + 1)
|
||||||
|
eng.initiate_ausschaffen(bot.seat_id)
|
||||||
|
self.ctx.sounds.play("stand")
|
||||||
|
self._render_table()
|
||||||
|
self._advance_flow()
|
||||||
|
return
|
||||||
|
|
||||||
|
chosen = WattenBotAI.choose_card(eng, bot)
|
||||||
|
bot.status_text = f"{t(f'bav_suit_{chosen.suit}')} {chosen.rank}"
|
||||||
|
res = eng.play_card(bot.seat_id, chosen)
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
self._handle_post_card_play(res)
|
||||||
|
|
||||||
|
# --- Match-Abschluss & XP ---
|
||||||
|
def _finalize_match(self):
|
||||||
|
self._set_bottom_buttons([])
|
||||||
|
self.status_var.set("")
|
||||||
|
|
||||||
|
human_won = self.engine.match_winner_team == 0
|
||||||
|
duration = max(1.0, time.time() - self.match_start_time)
|
||||||
|
|
||||||
|
prog_before = self.ctx.refresh_game_progress()
|
||||||
|
opp_levels = [self.engine.seats[1].ai_level, self.engine.seats[3].ai_level]
|
||||||
|
xp_gained = Progression.calculate_match_xp(
|
||||||
|
player_level=prog_before["level"],
|
||||||
|
opponent_levels=opp_levels,
|
||||||
|
outcome_type="WIN" if human_won else "LOSE",
|
||||||
|
variant_mult=self.cfg["xp_mult"],
|
||||||
|
)
|
||||||
|
|
||||||
|
old_lvl, new_lvl = self.ctx.record_result(
|
||||||
|
self.variant_key,
|
||||||
|
won=human_won,
|
||||||
|
duration_sec=duration,
|
||||||
|
points_gained=xp_gained,
|
||||||
|
)
|
||||||
|
self.topbar.update_level_xp_text()
|
||||||
|
self.ctx.sounds.play("win" if human_won else "lose")
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"player_won": human_won,
|
||||||
|
"team0_names": f"{self.engine.seats[0].name} & {self.engine.seats[2].name}",
|
||||||
|
"team1_names": f"{self.engine.seats[1].name} & {self.engine.seats[3].name}",
|
||||||
|
"team0_pts": self.engine.team_points[0],
|
||||||
|
"team1_pts": self.engine.team_points[1],
|
||||||
|
"xp_gained": xp_gained,
|
||||||
|
"leveled_to": new_lvl if new_lvl > old_lvl else None,
|
||||||
|
}
|
||||||
|
self._last_popup_payload = payload
|
||||||
|
self._open_result_popup(self._localize_popup(payload), play_fx=True)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _localize_popup(payload: dict) -> dict:
|
||||||
|
p_won = payload["player_won"]
|
||||||
|
lvl_to = payload["leveled_to"]
|
||||||
|
return {
|
||||||
|
"headline": t("wt_popup_match_won") if p_won else t("wt_popup_match_lost"),
|
||||||
|
"player_won": p_won,
|
||||||
|
"team0_names": payload["team0_names"],
|
||||||
|
"team1_names": payload["team1_names"],
|
||||||
|
"team0_pts": payload["team0_pts"],
|
||||||
|
"team1_pts": payload["team1_pts"],
|
||||||
|
"xp_gained": payload["xp_gained"],
|
||||||
|
"new_level_title": (
|
||||||
|
t("bj_popup_level_up", lvl_to, Progression.get_prestige_title(lvl_to))
|
||||||
|
if lvl_to is not None
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _show_result_dialog_now(self, popup_data: dict):
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
self._result_dialog = WattenResultDialog(
|
||||||
|
parent=self.arena_canvas,
|
||||||
|
assets=self.ctx.assets,
|
||||||
|
sounds=self.ctx.sounds,
|
||||||
|
result_data=popup_data,
|
||||||
|
on_next_round=self._start_new_match,
|
||||||
|
on_back_to_menu=lambda: self._cleanup_and_go(self.on_back_to_menu),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _open_result_popup(self, popup_data: dict, play_fx: bool = True):
|
||||||
|
self._play_outcome_fx_then(
|
||||||
|
popup_data.get("player_won"),
|
||||||
|
play_fx,
|
||||||
|
lambda: self._show_result_dialog_now(popup_data),
|
||||||
|
)
|
||||||
|
|
@ -0,0 +1,79 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/zehner_raus/models/zehner_raus_ai.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import random
|
||||||
|
|
||||||
|
from games.party.zehner_raus.models.zehner_raus_engine import (
|
||||||
|
ZehnerRausEngine,
|
||||||
|
ZehnerRausSeat,
|
||||||
|
)
|
||||||
|
from models.bavarian_deck import TEN_ORDER_INDEX, BavarianCard
|
||||||
|
|
||||||
|
|
||||||
|
class ZehnerRausBotAI:
|
||||||
|
"""KI-Entscheidungslogik (Stufen 0..6) für '10er raus'."""
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def choose_card(
|
||||||
|
cls,
|
||||||
|
engine: ZehnerRausEngine,
|
||||||
|
bot: ZehnerRausSeat,
|
||||||
|
rng: random.Random | None = None,
|
||||||
|
) -> BavarianCard | None:
|
||||||
|
playable = engine.get_playable_cards(bot.seat_id)
|
||||||
|
if not playable:
|
||||||
|
return None
|
||||||
|
if len(playable) == 1:
|
||||||
|
return playable[0]
|
||||||
|
|
||||||
|
r = rng or random
|
||||||
|
lvl = max(0, min(6, int(bot.ai_level)))
|
||||||
|
|
||||||
|
if lvl == 0:
|
||||||
|
return r.choice(playable)
|
||||||
|
|
||||||
|
mistake_chance = {1: 0.45, 2: 0.25, 3: 0.12, 4: 0.05, 5: 0.0, 6: 0.0}[lvl]
|
||||||
|
if mistake_chance > 0.0 and r.random() < mistake_chance:
|
||||||
|
return r.choice(playable)
|
||||||
|
|
||||||
|
scored = [
|
||||||
|
(cls._evaluate_move(card, bot.hand, lvl), r.random(), card)
|
||||||
|
for card in playable
|
||||||
|
]
|
||||||
|
scored.sort(key=lambda item: (item[0], item[1]), reverse=True)
|
||||||
|
return scored[0][2]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _evaluate_move(
|
||||||
|
card: BavarianCard, hand: list[BavarianCard], ai_level: int
|
||||||
|
) -> float:
|
||||||
|
suit_indices = {c.order_index for c in hand if c.suit == card.suit}
|
||||||
|
idx = card.order_index
|
||||||
|
|
||||||
|
if idx == TEN_ORDER_INDEX:
|
||||||
|
own_rest = [i for i in suit_indices if i != TEN_ORDER_INDEX]
|
||||||
|
extremity_sum = sum(abs(i - TEN_ORDER_INDEX) for i in own_rest)
|
||||||
|
score = len(own_rest) * 3.2 + extremity_sum * 1.4
|
||||||
|
if not own_rest and ai_level >= 4:
|
||||||
|
score -= 6.5
|
||||||
|
return score
|
||||||
|
|
||||||
|
if idx > TEN_ORDER_INDEX:
|
||||||
|
own_above = [i for i in suit_indices if i > idx]
|
||||||
|
remaining_for_others = (8 - idx) - len(own_above)
|
||||||
|
score = len(own_above) * 4.5 + (idx - TEN_ORDER_INDEX) * 0.6
|
||||||
|
if idx == 8:
|
||||||
|
score += 2.0
|
||||||
|
elif not own_above and ai_level >= 3:
|
||||||
|
score -= remaining_for_others * (1.8 if ai_level >= 5 else 1.1)
|
||||||
|
return score
|
||||||
|
|
||||||
|
own_below = [i for i in suit_indices if i < idx]
|
||||||
|
remaining_for_others = idx - len(own_below)
|
||||||
|
score = len(own_below) * 4.5 + (TEN_ORDER_INDEX - idx) * 0.6
|
||||||
|
if idx == 0:
|
||||||
|
score += 2.0
|
||||||
|
elif not own_below and ai_level >= 3:
|
||||||
|
score -= remaining_for_others * (1.8 if ai_level >= 5 else 1.1)
|
||||||
|
return score
|
||||||
|
|
@ -0,0 +1,166 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/zehner_raus/models/zehner_raus_engine.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
import random
|
||||||
|
|
||||||
|
from models.bavarian_deck import (
|
||||||
|
BAVARIAN_RANKS,
|
||||||
|
TEN_ORDER_INDEX,
|
||||||
|
BavarianCard,
|
||||||
|
create_bavarian_deck,
|
||||||
|
)
|
||||||
|
from resources.code_res.game_constants import BAVARIAN_SUITS, ZR_NUM_PLAYERS
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ZehnerRausSeat:
|
||||||
|
seat_id: int
|
||||||
|
name: str
|
||||||
|
is_human: bool = False
|
||||||
|
ai_level: int = 1
|
||||||
|
hand: list[BavarianCard] = field(default_factory=list)
|
||||||
|
status_text: str = ""
|
||||||
|
passed_turns: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
class ZehnerRausEngine:
|
||||||
|
"""
|
||||||
|
Regelwerk für '10er raus' (36 bayerische Karten, exakt 4 Spieler = je 9 Karten):
|
||||||
|
- Beliebiger Startspieler (rotiert nach der ersten Runde), es wird weitergeschoben
|
||||||
|
bis der erste einen 10er herauslegen kann.
|
||||||
|
- Von jedem gelegten 10er wächst die Farbreihe nach oben (U->O->K->A) und unten (9->8->7->6).
|
||||||
|
- Strikter Zugzwang: Wer eine passende Karte hat, MUSS legen; Passen ist nur ohne Zug erlaubt.
|
||||||
|
- Sobald der erste Spieler seine letzte Karte ablegt, endet die Runde sofort mit seinem Sieg!
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.seats: list[ZehnerRausSeat] = []
|
||||||
|
self.lanes: dict[str, tuple[int, int] | None] = {
|
||||||
|
s: None for s in BAVARIAN_SUITS
|
||||||
|
}
|
||||||
|
self.turn_seat: int = 0
|
||||||
|
self.starter_seat: int = -1
|
||||||
|
self.winner_seat: int | None = None
|
||||||
|
self.turns_played: int = 0
|
||||||
|
self.last_played_card: BavarianCard | None = None
|
||||||
|
self.last_played_by: int | None = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def human_seat(self) -> ZehnerRausSeat:
|
||||||
|
return self.seats[0]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_finished(self) -> bool:
|
||||||
|
return self.winner_seat is not None
|
||||||
|
|
||||||
|
def configure_seats(
|
||||||
|
self, human_name: str, bot_configs: list[tuple[int, str]]
|
||||||
|
) -> None:
|
||||||
|
self.seats = [ZehnerRausSeat(seat_id=0, name=human_name, is_human=True)]
|
||||||
|
for idx in range(1, ZR_NUM_PLAYERS):
|
||||||
|
if idx - 1 < len(bot_configs):
|
||||||
|
lvl, b_name = bot_configs[idx - 1]
|
||||||
|
else:
|
||||||
|
lvl, b_name = idx, f"Bot {idx}"
|
||||||
|
self.seats.append(
|
||||||
|
ZehnerRausSeat(
|
||||||
|
seat_id=idx, name=b_name, is_human=False, ai_level=lvl
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def start_new_round(self, rng: random.Random | None = None) -> int:
|
||||||
|
r = rng or random
|
||||||
|
deck = create_bavarian_deck(include_six=True, shuffle=True, rng=r)
|
||||||
|
self.lanes = {s: None for s in BAVARIAN_SUITS}
|
||||||
|
self.winner_seat = None
|
||||||
|
self.turns_played = 0
|
||||||
|
self.last_played_card = None
|
||||||
|
self.last_played_by = None
|
||||||
|
|
||||||
|
suit_sort = {s: i for i, s in enumerate(BAVARIAN_SUITS)}
|
||||||
|
for idx, seat in enumerate(self.seats):
|
||||||
|
chunk = deck[idx * 9 : (idx + 1) * 9]
|
||||||
|
chunk.sort(key=lambda c: (suit_sort[c.suit], c.order_index))
|
||||||
|
seat.hand = chunk
|
||||||
|
seat.status_text = ""
|
||||||
|
seat.passed_turns = 0
|
||||||
|
|
||||||
|
if self.starter_seat < 0:
|
||||||
|
self.starter_seat = r.randrange(ZR_NUM_PLAYERS)
|
||||||
|
else:
|
||||||
|
self.starter_seat = (self.starter_seat + 1) % ZR_NUM_PLAYERS
|
||||||
|
|
||||||
|
self.turn_seat = self.starter_seat
|
||||||
|
return self.turn_seat
|
||||||
|
|
||||||
|
def is_card_playable(self, card: BavarianCard) -> bool:
|
||||||
|
if self.is_finished:
|
||||||
|
return False
|
||||||
|
bounds = self.lanes[card.suit]
|
||||||
|
idx = card.order_index
|
||||||
|
if bounds is None:
|
||||||
|
return idx == TEN_ORDER_INDEX
|
||||||
|
low_idx, high_idx = bounds
|
||||||
|
return idx == low_idx - 1 or idx == high_idx + 1
|
||||||
|
|
||||||
|
def get_playable_cards(self, seat_id: int) -> list[BavarianCard]:
|
||||||
|
if self.is_finished or not (0 <= seat_id < len(self.seats)):
|
||||||
|
return []
|
||||||
|
return [c for c in self.seats[seat_id].hand if self.is_card_playable(c)]
|
||||||
|
|
||||||
|
def can_seat_pass(self, seat_id: int) -> bool:
|
||||||
|
return len(self.get_playable_cards(seat_id)) == 0
|
||||||
|
|
||||||
|
def play_card(self, seat_id: int, card: BavarianCard) -> bool:
|
||||||
|
if self.is_finished or seat_id != self.turn_seat:
|
||||||
|
return False
|
||||||
|
seat = self.seats[seat_id]
|
||||||
|
if card not in seat.hand or not self.is_card_playable(card):
|
||||||
|
return False
|
||||||
|
|
||||||
|
seat.hand.remove(card)
|
||||||
|
bounds = self.lanes[card.suit]
|
||||||
|
idx = card.order_index
|
||||||
|
if bounds is None:
|
||||||
|
self.lanes[card.suit] = (TEN_ORDER_INDEX, TEN_ORDER_INDEX)
|
||||||
|
else:
|
||||||
|
low_idx, high_idx = bounds
|
||||||
|
if idx < low_idx:
|
||||||
|
self.lanes[card.suit] = (idx, high_idx)
|
||||||
|
else:
|
||||||
|
self.lanes[card.suit] = (low_idx, idx)
|
||||||
|
|
||||||
|
self.last_played_card = card
|
||||||
|
self.last_played_by = seat_id
|
||||||
|
self.turns_played += 1
|
||||||
|
|
||||||
|
if not seat.hand:
|
||||||
|
self.winner_seat = seat_id
|
||||||
|
else:
|
||||||
|
self.turn_seat = (self.turn_seat + 1) % ZR_NUM_PLAYERS
|
||||||
|
return True
|
||||||
|
|
||||||
|
def pass_turn(self, seat_id: int) -> bool:
|
||||||
|
if self.is_finished or seat_id != self.turn_seat:
|
||||||
|
return False
|
||||||
|
if not self.can_seat_pass(seat_id):
|
||||||
|
return False
|
||||||
|
self.seats[seat_id].passed_turns += 1
|
||||||
|
self.turns_played += 1
|
||||||
|
self.turn_seat = (self.turn_seat + 1) % ZR_NUM_PLAYERS
|
||||||
|
return True
|
||||||
|
|
||||||
|
def lane_snapshot_ranks(self, suit: str) -> dict[str, str | int | None]:
|
||||||
|
bounds = self.lanes[suit]
|
||||||
|
if bounds is None:
|
||||||
|
return {"low": None, "ten": None, "high": None}
|
||||||
|
low_i, high_i = bounds
|
||||||
|
return {
|
||||||
|
"low": BAVARIAN_RANKS[low_i] if low_i < TEN_ORDER_INDEX else None,
|
||||||
|
"ten": "10",
|
||||||
|
"high": BAVARIAN_RANKS[high_i] if high_i > TEN_ORDER_INDEX else None,
|
||||||
|
"low_idx": low_i,
|
||||||
|
"high_idx": high_i,
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/zehner_raus/start.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from games.party.zehner_raus.views.zehner_raus_menu_view import ZehnerRausMenuView
|
||||||
|
from resources.code_res.game_constants import CAT_PARTY_OFFLINE
|
||||||
|
|
||||||
|
GAME_FOLDER_ID = "party/zehner_raus"
|
||||||
|
GAME_TITLE_KEY = "game_title_zehner_raus"
|
||||||
|
GAME_CATEGORY = CAT_PARTY_OFFLINE
|
||||||
|
|
||||||
|
|
||||||
|
def start_game(context) -> None:
|
||||||
|
ZehnerRausMenuView(context).show()
|
||||||
|
|
@ -0,0 +1,394 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/zehner_raus/views/zehner_raus_arena_renderer.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from models.bavarian_deck import BAVARIAN_RANKS, TEN_ORDER_INDEX, BavarianCard
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
ACCENT_GOLD,
|
||||||
|
ACCENT_GOTH,
|
||||||
|
BAVARIAN_CARD_THEME,
|
||||||
|
BORDER_COLOR,
|
||||||
|
ERROR_FG,
|
||||||
|
FG_COLOR,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_BODY,
|
||||||
|
FONT_SIZE_SMALL_MIN,
|
||||||
|
MUTED_FG,
|
||||||
|
PLAYING_CARD_SIZE,
|
||||||
|
SUBTLE_BORDER,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
|
||||||
|
ZR_BOT_BACK_SIZE = (42, 62)
|
||||||
|
ZR_MAX_HAND_CARD_H = 186
|
||||||
|
ZR_HAND_TOP_EXTEND_PX = 22
|
||||||
|
|
||||||
|
# Festes 2x2-Raster: Oben Eichel & Blatt, unten Herz & Schellen
|
||||||
|
ZR_GRID_SUITS = (
|
||||||
|
("E", 0, 0), # Oben links: Eichel
|
||||||
|
("B", 0, 1), # Oben rechts: Blatt
|
||||||
|
("H", 1, 0), # Unten links: Herz
|
||||||
|
("S", 1, 1), # Unten rechts: Schellen
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ZehnerRausArenaRenderer:
|
||||||
|
"""
|
||||||
|
Rendert für 10er raus:
|
||||||
|
- Außen links, oben und rechts die 3 Kultisten-Gegner
|
||||||
|
- Auf dem Tischfilz ein 2x2-Raster mit Mittelkreuz:
|
||||||
|
Oben: Eichel | Blatt
|
||||||
|
Unten: Herz | Schellen
|
||||||
|
- Unten die vergrößerte Spielerhand mit Gold-Highlight für legbare Karten.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def draw_bots(
|
||||||
|
view,
|
||||||
|
cw: int,
|
||||||
|
ch: int,
|
||||||
|
pad_x: int,
|
||||||
|
pad_top: int,
|
||||||
|
table_rect: tuple[int, int, int, int],
|
||||||
|
) -> tuple[int, int, int]:
|
||||||
|
"""Zeichnet die 3 Bots und gibt (top_bot_bottom_y, left_bot_right_x, right_bot_left_x) zurück."""
|
||||||
|
tx1, ty1, tx2, ty2 = table_rect
|
||||||
|
bots = view.engine.seats[1:]
|
||||||
|
if len(bots) < 3:
|
||||||
|
return ty1 + 20, tx1 + 60, tx2 - 60
|
||||||
|
|
||||||
|
box_w, box_h = 220, 90
|
||||||
|
mid_side_y = (ty1 + ty2) // 2 - 18
|
||||||
|
top_cy = max(pad_top + box_h // 2 - 6, ty1 + int(box_h * 0.30))
|
||||||
|
left_cx = max(pad_x + box_w // 2 - 10, tx1 + int(box_w * 0.24))
|
||||||
|
right_cx = min(cw - pad_x - box_w // 2 + 10, tx2 - int(box_w * 0.24))
|
||||||
|
|
||||||
|
coords = [
|
||||||
|
(left_cx, mid_side_y), # Sitz 1: Links
|
||||||
|
(cw // 2, top_cy), # Sitz 2: Oben Mitte
|
||||||
|
(right_cx, mid_side_y), # Sitz 3: Rechts
|
||||||
|
]
|
||||||
|
|
||||||
|
name_sz = max(14, FONT_SIZE_BODY - 1)
|
||||||
|
sub_sz = max(12, FONT_SIZE_SMALL_MIN)
|
||||||
|
back_ph = view.ctx.assets.get_card_back_photo(
|
||||||
|
size=ZR_BOT_BACK_SIZE, theme=BAVARIAN_CARD_THEME
|
||||||
|
)
|
||||||
|
if back_ph is not None:
|
||||||
|
view._photo_refs.append(back_ph)
|
||||||
|
|
||||||
|
for idx, seat in enumerate(bots[:3]):
|
||||||
|
bx, by = coords[idx]
|
||||||
|
is_turn = not view.engine.is_finished and view.engine.turn_seat == seat.seat_id
|
||||||
|
n_cards = len(seat.hand)
|
||||||
|
warn_last = n_cards == 1
|
||||||
|
|
||||||
|
view._draw_framed_panel(
|
||||||
|
bx,
|
||||||
|
by,
|
||||||
|
box_w,
|
||||||
|
box_h,
|
||||||
|
frame_style="gold" if is_turn else "purple",
|
||||||
|
status_border=ERROR_FG if warn_last else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
if back_ph is not None and n_cards > 0:
|
||||||
|
vis_backs = min(5, n_cards)
|
||||||
|
step_b = 9
|
||||||
|
bx0 = bx - box_w // 2 + 14
|
||||||
|
by0 = by - ZR_BOT_BACK_SIZE[1] // 2
|
||||||
|
for bi in range(vis_backs):
|
||||||
|
view.arena_canvas.create_image(
|
||||||
|
bx0 + bi * step_b, by0, image=back_ph, anchor="nw", tags="fg"
|
||||||
|
)
|
||||||
|
txt_cx = bx + 30
|
||||||
|
max_tw = box_w - 96
|
||||||
|
else:
|
||||||
|
txt_cx = bx
|
||||||
|
max_tw = box_w - 28
|
||||||
|
|
||||||
|
n_col = ACCENT_GOLD if is_turn else ACCENT_GOTH
|
||||||
|
cnt_txt = (
|
||||||
|
t("zr_bot_one_card_left")
|
||||||
|
if warn_last
|
||||||
|
else t("zr_bot_cards_left", n_cards)
|
||||||
|
)
|
||||||
|
cnt_col = ERROR_FG if warn_last else ACCENT_GOLD
|
||||||
|
act_txt = seat.status_text or "-"
|
||||||
|
|
||||||
|
n_ph = view._make_goth_photo(seat.name, name_sz, n_col, max_tw)
|
||||||
|
c_ph = view._make_goth_photo(cnt_txt, sub_sz, cnt_col, max_tw)
|
||||||
|
a_ph = view._make_goth_photo(act_txt, sub_sz, FG_COLOR, max_tw)
|
||||||
|
|
||||||
|
view._place_goth_photo_or_fallback(txt_cx, by - 22, n_ph, seat.name, name_sz, n_col)
|
||||||
|
view._place_goth_photo_or_fallback(txt_cx, by, c_ph, cnt_txt, sub_sz, cnt_col)
|
||||||
|
view._place_goth_photo_or_fallback(txt_cx, by + 22, a_ph, act_txt, sub_sz, FG_COLOR)
|
||||||
|
|
||||||
|
return (
|
||||||
|
top_cy + box_h // 2,
|
||||||
|
left_cx + box_w // 2,
|
||||||
|
right_cx - box_w // 2,
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def draw_bavarian_lanes(
|
||||||
|
view,
|
||||||
|
table_rect: tuple[int, int, int, int],
|
||||||
|
bot_bounds: tuple[int, int, int],
|
||||||
|
player_top_y: int,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Zeichnet die 4 Farben kompakt in einem 2x2-Raster direkt auf den Tischfilz
|
||||||
|
(ohne Hintergrundkasten, nur getrennt durch ein sauberes Mittelkreuz):
|
||||||
|
Oben: Eichel | Blatt
|
||||||
|
Unten: Herz | Schellen
|
||||||
|
"""
|
||||||
|
tx1, ty1, tx2, ty2 = table_rect
|
||||||
|
top_obs_y, left_obs_x, right_obs_x = bot_bounds
|
||||||
|
|
||||||
|
hand_real_top = player_top_y - ZR_HAND_TOP_EXTEND_PX
|
||||||
|
felt_top = max(ty1 + 14, top_obs_y + 8)
|
||||||
|
felt_bot = min(ty2 - 12, hand_real_top - 10)
|
||||||
|
avail_h = max(170, felt_bot - felt_top)
|
||||||
|
|
||||||
|
felt_left = max(tx1 + 48, left_obs_x + 16)
|
||||||
|
felt_right = min(tx2 - 48, right_obs_x - 16)
|
||||||
|
avail_w = max(440, felt_right - felt_left)
|
||||||
|
|
||||||
|
grid_w = min(avail_w, 840)
|
||||||
|
grid_h = min(avail_h, 268)
|
||||||
|
gx1 = (felt_left + felt_right - grid_w) // 2
|
||||||
|
gy1 = felt_top + max(0, (avail_h - grid_h) // 2)
|
||||||
|
gx2 = gx1 + grid_w
|
||||||
|
gy2 = gy1 + grid_h
|
||||||
|
mid_x = (gx1 + gx2) // 2
|
||||||
|
mid_y = (gy1 + gy2) // 2
|
||||||
|
|
||||||
|
# Nur das freistehende Mittelkreuz direkt auf dem Tischfilz (kein Kasten in den Ecken!)
|
||||||
|
view.arena_canvas.create_line(
|
||||||
|
mid_x, gy1 + 4, mid_x, gy2 - 4,
|
||||||
|
fill=BORDER_COLOR,
|
||||||
|
width=2,
|
||||||
|
tags="fg",
|
||||||
|
)
|
||||||
|
view.arena_canvas.create_line(
|
||||||
|
gx1 + 12, mid_y, gx2 - 12, mid_y,
|
||||||
|
fill=BORDER_COLOR,
|
||||||
|
width=2,
|
||||||
|
tags="fg",
|
||||||
|
)
|
||||||
|
|
||||||
|
quad_w = grid_w // 2
|
||||||
|
quad_h = grid_h // 2
|
||||||
|
hdr_h = 24
|
||||||
|
pad_qx = 14
|
||||||
|
|
||||||
|
base_w, base_h = PLAYING_CARD_SIZE
|
||||||
|
card_h = max(62, min(94, quad_h - hdr_h - 14))
|
||||||
|
card_w = max(43, int(round(base_w * (card_h / max(1, base_h)))))
|
||||||
|
card_sz = (card_w, card_h)
|
||||||
|
|
||||||
|
inner_cards_w = max(160, quad_w - 2 * pad_qx)
|
||||||
|
step_x = min(card_w + 3, max(19, (inner_cards_w - card_w) // 8))
|
||||||
|
span_cards_w = card_w + 8 * step_x
|
||||||
|
|
||||||
|
last_card = view.engine.last_played_card
|
||||||
|
|
||||||
|
for suit, r_idx, c_idx in ZR_GRID_SUITS:
|
||||||
|
qx1 = gx1 + c_idx * quad_w
|
||||||
|
qy1 = gy1 + r_idx * quad_h
|
||||||
|
q_cx = qx1 + quad_w // 2
|
||||||
|
|
||||||
|
bounds = view.engine.lanes[suit]
|
||||||
|
is_done = bounds is not None and bounds[0] == 0 and bounds[1] == 8
|
||||||
|
|
||||||
|
# Untere Zeile bekommt minimal Abstand zur horizontalen Kreuzlinie
|
||||||
|
lbl_y = qy1 + (15 if r_idx == 1 else 11)
|
||||||
|
suit_lbl = t(f"bav_suit_{suit}")
|
||||||
|
if is_done:
|
||||||
|
suit_lbl = f"{suit_lbl} ✓"
|
||||||
|
s_col = ACCENT_GOLD if is_done else FONT_COLOR_TITLE_MAIN
|
||||||
|
s_ph = view._make_goth_photo(suit_lbl, FONT_SIZE_SMALL_MIN, s_col, quad_w - 24)
|
||||||
|
view._place_goth_photo_or_fallback(
|
||||||
|
q_cx, lbl_y, s_ph, suit_lbl, FONT_SIZE_SMALL_MIN, s_col
|
||||||
|
)
|
||||||
|
|
||||||
|
cards_x0 = q_cx - span_cards_w // 2
|
||||||
|
row_top = qy1 + hdr_h + max(3, (quad_h - hdr_h - card_h) // 2)
|
||||||
|
row_cy = row_top + card_h // 2
|
||||||
|
|
||||||
|
ten_x = cards_x0 + TEN_ORDER_INDEX * step_x
|
||||||
|
if bounds is None:
|
||||||
|
view.arena_canvas.create_rectangle(
|
||||||
|
ten_x,
|
||||||
|
row_top,
|
||||||
|
ten_x + card_w,
|
||||||
|
row_top + card_h,
|
||||||
|
fill="",
|
||||||
|
outline=SUBTLE_BORDER,
|
||||||
|
width=2,
|
||||||
|
tags="fg",
|
||||||
|
)
|
||||||
|
view.arena_canvas.create_text(
|
||||||
|
ten_x + card_w // 2,
|
||||||
|
row_cy,
|
||||||
|
text="10",
|
||||||
|
font=("Georgia", max(11, card_w // 3), "bold"),
|
||||||
|
fill=MUTED_FG,
|
||||||
|
tags="fg",
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
low_idx, high_idx = bounds
|
||||||
|
|
||||||
|
if low_idx > 0:
|
||||||
|
nx_low = cards_x0 + (low_idx - 1) * step_x
|
||||||
|
ZehnerRausArenaRenderer._draw_next_hint_slot(
|
||||||
|
view, nx_low, row_top, card_w, card_h, BAVARIAN_RANKS[low_idx - 1]
|
||||||
|
)
|
||||||
|
if high_idx < 8:
|
||||||
|
nx_high = cards_x0 + (high_idx + 1) * step_x
|
||||||
|
ZehnerRausArenaRenderer._draw_next_hint_slot(
|
||||||
|
view, nx_high, row_top, card_w, card_h, BAVARIAN_RANKS[high_idx + 1]
|
||||||
|
)
|
||||||
|
|
||||||
|
for r_i in range(low_idx, high_idx + 1):
|
||||||
|
cx_card = cards_x0 + r_i * step_x
|
||||||
|
ZehnerRausArenaRenderer._draw_lane_card(
|
||||||
|
view,
|
||||||
|
BavarianCard(suit, BAVARIAN_RANKS[r_i]),
|
||||||
|
cx_card,
|
||||||
|
row_top,
|
||||||
|
card_sz,
|
||||||
|
last_card,
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _draw_next_hint_slot(
|
||||||
|
view, x: int, y: int, card_w: int, card_h: int, rank_txt: str
|
||||||
|
) -> None:
|
||||||
|
view.arena_canvas.create_rectangle(
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
x + card_w,
|
||||||
|
y + card_h,
|
||||||
|
fill="#120e1b",
|
||||||
|
outline="#2d2340",
|
||||||
|
dash=(3, 3),
|
||||||
|
width=1,
|
||||||
|
tags="fg",
|
||||||
|
)
|
||||||
|
view.arena_canvas.create_text(
|
||||||
|
x + card_w // 2,
|
||||||
|
y + card_h // 2,
|
||||||
|
text=rank_txt,
|
||||||
|
font=("Georgia", max(10, card_w // 4)),
|
||||||
|
fill="#5a4c73",
|
||||||
|
tags="fg",
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _draw_lane_card(
|
||||||
|
view,
|
||||||
|
card: BavarianCard,
|
||||||
|
x: int,
|
||||||
|
y: int,
|
||||||
|
card_sz: tuple[int, int],
|
||||||
|
last_card: BavarianCard | None,
|
||||||
|
) -> None:
|
||||||
|
cw, ch = card_sz
|
||||||
|
if card.order_index == TEN_ORDER_INDEX:
|
||||||
|
view.arena_canvas.create_rectangle(
|
||||||
|
x - 2, y - 2, x + cw + 2, y + ch + 2,
|
||||||
|
outline=ACCENT_GOTH, width=1, tags="fg",
|
||||||
|
)
|
||||||
|
ph = view.ctx.assets.get_card_photo(
|
||||||
|
card.image_filename, size=card_sz, theme=BAVARIAN_CARD_THEME
|
||||||
|
)
|
||||||
|
if ph is not None:
|
||||||
|
view._photo_refs.append(ph)
|
||||||
|
view.arena_canvas.create_image(x, y, image=ph, anchor="nw", tags="fg")
|
||||||
|
if last_card == card:
|
||||||
|
view.arena_canvas.create_rectangle(
|
||||||
|
x - 2, y - 2, x + cw + 2, y + ch + 2,
|
||||||
|
outline=ACCENT_GOLD, width=2, tags="fg",
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def draw_human_hand(
|
||||||
|
view, cw: int, player_zone_top: int, player_zone_bot: int
|
||||||
|
) -> list[tuple[BavarianCard, int, int, int, int]]:
|
||||||
|
human = view.engine.human_seat
|
||||||
|
eff_top = max(230, player_zone_top - ZR_HAND_TOP_EXTEND_PX)
|
||||||
|
avail_h = max(170, player_zone_bot - eff_top)
|
||||||
|
zone_cy = (eff_top + player_zone_bot) // 2
|
||||||
|
|
||||||
|
base_w, base_h = PLAYING_CARD_SIZE
|
||||||
|
target_h = max(118, min(ZR_MAX_HAND_CARD_H, avail_h - 42))
|
||||||
|
scale = target_h / max(1, base_h)
|
||||||
|
card_w = max(80, int(round(base_w * scale)))
|
||||||
|
card_h = int(round(base_h * scale))
|
||||||
|
card_sz = (card_w, card_h)
|
||||||
|
|
||||||
|
is_my_turn = not view.engine.is_finished and view.engine.turn_seat == 0
|
||||||
|
playable_set = (
|
||||||
|
set(view.engine.get_playable_cards(0)) if is_my_turn else set()
|
||||||
|
)
|
||||||
|
|
||||||
|
n_cards = len(human.hand)
|
||||||
|
max_hand_w = max(380, cw - 180)
|
||||||
|
step = min(card_w + 10, max(44, (max_hand_w - card_w) // max(1, n_cards - 1)))
|
||||||
|
span_w = card_w + max(0, n_cards - 1) * step if n_cards else card_w
|
||||||
|
|
||||||
|
lbl_txt = t("zr_player_hand_lbl", n_cards)
|
||||||
|
lbl_sz = max(13, FONT_SIZE_BODY - 2)
|
||||||
|
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, FONT_COLOR_TITLE_MAIN)
|
||||||
|
txt_w = lbl_ph.width() if lbl_ph is not None else 280
|
||||||
|
|
||||||
|
box_w = max(380, min(cw - 72, max(span_w + 76, txt_w + 68)))
|
||||||
|
box_h = min(avail_h + 6, card_h + 44)
|
||||||
|
box_cx = cw // 2
|
||||||
|
|
||||||
|
view._draw_framed_panel(
|
||||||
|
box_cx,
|
||||||
|
zone_cy,
|
||||||
|
box_w,
|
||||||
|
box_h,
|
||||||
|
frame_style="gold" if is_my_turn else "purple",
|
||||||
|
)
|
||||||
|
|
||||||
|
hit_rects: list[tuple[BavarianCard, int, int, int, int]] = []
|
||||||
|
start_x = box_cx - span_w // 2
|
||||||
|
base_top = (zone_cy - 10) - card_h // 2
|
||||||
|
|
||||||
|
for idx, card in enumerate(human.hand):
|
||||||
|
is_playable = card in playable_set
|
||||||
|
cx_left = start_x + idx * step
|
||||||
|
cy_top = base_top - (10 if is_playable else 0)
|
||||||
|
|
||||||
|
ph = view.ctx.assets.get_card_photo(
|
||||||
|
card.image_filename, size=card_sz, theme=BAVARIAN_CARD_THEME
|
||||||
|
)
|
||||||
|
if ph is not None:
|
||||||
|
view._photo_refs.append(ph)
|
||||||
|
view.arena_canvas.create_image(
|
||||||
|
cx_left, cy_top, image=ph, anchor="nw", tags="fg"
|
||||||
|
)
|
||||||
|
if is_playable:
|
||||||
|
view.arena_canvas.create_rectangle(
|
||||||
|
cx_left - 2,
|
||||||
|
cy_top - 2,
|
||||||
|
cx_left + card_w + 2,
|
||||||
|
cy_top + card_h + 2,
|
||||||
|
outline=ACCENT_GOLD,
|
||||||
|
width=2,
|
||||||
|
tags="fg",
|
||||||
|
)
|
||||||
|
|
||||||
|
hit_right = (cx_left + card_w) if idx == n_cards - 1 else (cx_left + step)
|
||||||
|
hit_rects.append((card, cx_left, cy_top, hit_right, cy_top + card_h))
|
||||||
|
|
||||||
|
view._place_goth_photo_or_fallback(
|
||||||
|
box_cx, zone_cy + box_h // 2 - 15, lbl_ph, lbl_txt, lbl_sz, FONT_COLOR_TITLE_MAIN
|
||||||
|
)
|
||||||
|
return hit_rects
|
||||||
|
|
@ -0,0 +1,237 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/zehner_raus/views/zehner_raus_menu_view.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
from games.party.zehner_raus.views.zehner_raus_table_view import ZehnerRausTableView
|
||||||
|
from models.database import Database
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
BOT_LEVEL_COUNT,
|
||||||
|
FONT_COLOR_BODY_DEFAULT,
|
||||||
|
FONT_COLOR_BODY_MUTED,
|
||||||
|
FONT_COLOR_HEADING_SUB,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_BODY,
|
||||||
|
FONT_SIZE_HEADING,
|
||||||
|
FONT_SIZE_SMALL_MIN,
|
||||||
|
FONT_SIZE_TITLE_LG,
|
||||||
|
ZR_BOT_COUNT,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from view.widgets.goth_dropdown import GothDropdown
|
||||||
|
from view.widgets.goth_entry import GothEntry
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
from view.widgets.menu_body_canvas import MenuBodyCanvas
|
||||||
|
|
||||||
|
GAME_FOLDER_ID = "party/zehner_raus"
|
||||||
|
GAME_TITLE_KEY = "game_title_zehner_raus"
|
||||||
|
|
||||||
|
|
||||||
|
class ZehnerRausMenuView:
|
||||||
|
"""Vorauswahl-Menü für 10er raus mit 3 festen Pflicht-Mitspielern (ohne Goldbeutel)."""
|
||||||
|
|
||||||
|
def __init__(self, context):
|
||||||
|
self.ctx = context
|
||||||
|
self._photo_refs: list = []
|
||||||
|
self._bot_entries: list[GothEntry] = []
|
||||||
|
self._bot_lvl_vars: list[tk.StringVar] = []
|
||||||
|
self._bot_dds: list[GothDropdown] = []
|
||||||
|
|
||||||
|
def _collect_and_save_bots(self) -> list[tuple[int, str]]:
|
||||||
|
pid = self.ctx.profile["id"]
|
||||||
|
lvl_by_label = {t(f"bot_level_{i}"): i for i in range(BOT_LEVEL_COUNT)}
|
||||||
|
active_bots: list[tuple[int, str]] = []
|
||||||
|
to_save: dict[int, tuple[str, int]] = {}
|
||||||
|
|
||||||
|
for idx in range(ZR_BOT_COUNT):
|
||||||
|
raw_name = (
|
||||||
|
self._bot_entries[idx].get().strip()
|
||||||
|
if idx < len(self._bot_entries)
|
||||||
|
else ""
|
||||||
|
)
|
||||||
|
b_name = raw_name or t("bot_default_name", idx + 1)
|
||||||
|
lvl = lvl_by_label.get(
|
||||||
|
self._bot_lvl_vars[idx].get(), min(BOT_LEVEL_COUNT - 1, idx + 1)
|
||||||
|
)
|
||||||
|
active_bots.append((lvl, b_name))
|
||||||
|
to_save[idx] = (b_name, lvl)
|
||||||
|
|
||||||
|
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||||
|
return active_bots
|
||||||
|
|
||||||
|
def show(self):
|
||||||
|
pid = self.ctx.profile["id"]
|
||||||
|
self.ctx.sounds.play_menu_music()
|
||||||
|
self.ctx.root.clear_window(apply_global_bg=True)
|
||||||
|
self._photo_refs.clear()
|
||||||
|
self._bot_entries.clear()
|
||||||
|
self._bot_lvl_vars.clear()
|
||||||
|
self._bot_dds.clear()
|
||||||
|
self.ctx.refresh_game_progress()
|
||||||
|
|
||||||
|
def refresh_menu():
|
||||||
|
if self._bot_entries:
|
||||||
|
self._collect_and_save_bots()
|
||||||
|
self.show()
|
||||||
|
|
||||||
|
self.ctx.build_game_topbar(
|
||||||
|
self.ctx.root,
|
||||||
|
t("zr_menu_topbar"),
|
||||||
|
stats_endpoint=GAME_FOLDER_ID,
|
||||||
|
stats_enabled=True,
|
||||||
|
on_stats_back=refresh_menu,
|
||||||
|
on_lang_refresh=refresh_menu,
|
||||||
|
)
|
||||||
|
|
||||||
|
cv = MenuBodyCanvas(self.ctx)
|
||||||
|
btn_fire = self.ctx.assets.raw_btn_fire or self.ctx.assets.raw_btn_purple
|
||||||
|
|
||||||
|
saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID)
|
||||||
|
ai_labels = [t(f"bot_level_{i}") for i in range(BOT_LEVEL_COUNT)]
|
||||||
|
|
||||||
|
for i in range(ZR_BOT_COUNT):
|
||||||
|
def_name = t("bot_default_name", i + 1)
|
||||||
|
def_lvl = min(BOT_LEVEL_COUNT - 1, i + 1)
|
||||||
|
if i in saved_bots:
|
||||||
|
s_name, s_lvl = saved_bots[i]
|
||||||
|
b_name = s_name or def_name
|
||||||
|
b_lvl = (
|
||||||
|
max(0, min(BOT_LEVEL_COUNT - 1, int(s_lvl)))
|
||||||
|
if int(s_lvl) >= 0
|
||||||
|
else def_lvl
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
b_name, b_lvl = def_name, def_lvl
|
||||||
|
|
||||||
|
entry = GothEntry(
|
||||||
|
cv,
|
||||||
|
self.ctx.assets,
|
||||||
|
width=240,
|
||||||
|
height=36,
|
||||||
|
textvariable=tk.StringVar(value=b_name),
|
||||||
|
)
|
||||||
|
l_var = tk.StringVar(value=t(f"bot_level_{b_lvl}"))
|
||||||
|
dd = GothDropdown(
|
||||||
|
cv,
|
||||||
|
self.ctx.assets,
|
||||||
|
values=ai_labels,
|
||||||
|
textvariable=l_var,
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=270,
|
||||||
|
height=36,
|
||||||
|
)
|
||||||
|
self._bot_entries.append(entry)
|
||||||
|
self._bot_lvl_vars.append(l_var)
|
||||||
|
self._bot_dds.append(dd)
|
||||||
|
|
||||||
|
def start_round():
|
||||||
|
bots = self._collect_and_save_bots()
|
||||||
|
ZehnerRausTableView(
|
||||||
|
self.ctx,
|
||||||
|
variant_key="zehner_raus_std",
|
||||||
|
bot_configs=bots,
|
||||||
|
on_back_to_menu=self.show,
|
||||||
|
)
|
||||||
|
|
||||||
|
start_btn = ImageButton(
|
||||||
|
cv,
|
||||||
|
t("zr_start_btn"),
|
||||||
|
btn_fire,
|
||||||
|
btn_fire,
|
||||||
|
start_round,
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=210,
|
||||||
|
height=40,
|
||||||
|
style="fire",
|
||||||
|
)
|
||||||
|
|
||||||
|
def draw_layout(w: int, h: int):
|
||||||
|
cv.sync_bg(w, h)
|
||||||
|
cv.delete("fg")
|
||||||
|
self._photo_refs.clear()
|
||||||
|
|
||||||
|
box_w = min(940, w - 120)
|
||||||
|
cx = w // 2
|
||||||
|
x_left = cx - box_w // 2
|
||||||
|
cur_y = max(22, int(h * 0.05))
|
||||||
|
|
||||||
|
title_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left"
|
||||||
|
)
|
||||||
|
sub_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("zr_menu_subtitle"),
|
||||||
|
FONT_SIZE_BODY,
|
||||||
|
FONT_COLOR_BODY_MUTED,
|
||||||
|
max_width=box_w,
|
||||||
|
align="left",
|
||||||
|
)
|
||||||
|
self._photo_refs.extend([title_ph, sub_ph])
|
||||||
|
cv.create_image(x_left, cur_y, image=title_ph, anchor="nw", tags="fg")
|
||||||
|
cur_y += title_ph.height() + 4
|
||||||
|
cv.create_image(x_left, cur_y, image=sub_ph, anchor="nw", tags="fg")
|
||||||
|
cur_y += sub_ph.height() + 18
|
||||||
|
|
||||||
|
s1_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("zr_rules_sec_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_HEADING_SUB, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.append(s1_ph)
|
||||||
|
cv.create_image(x_left + 6, cur_y, image=s1_ph, anchor="nw", tags="fg")
|
||||||
|
cur_y += s1_ph.height() + 6
|
||||||
|
|
||||||
|
r_box_h = 74
|
||||||
|
r_cy = cur_y + r_box_h // 2
|
||||||
|
r_box = self.ctx.assets.get_box_photo("box_gold_double", (box_w, r_box_h))
|
||||||
|
if r_box:
|
||||||
|
self._photo_refs.append(r_box)
|
||||||
|
cv.create_image(cx, r_cy, image=r_box, anchor="center", tags="fg")
|
||||||
|
|
||||||
|
v_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("variant_zehner_raus_std"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
|
||||||
|
)
|
||||||
|
d_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("zr_rule_summary"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_DEFAULT, max_width=box_w - 56, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.extend([v_ph, d_ph])
|
||||||
|
cv.create_image(x_left + 28, r_cy - 14, image=v_ph, anchor="w", tags="fg")
|
||||||
|
cv.create_image(x_left + 28, r_cy + 15, image=d_ph, anchor="w", tags="fg")
|
||||||
|
cur_y += r_box_h + 18
|
||||||
|
|
||||||
|
s2_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("zr_bots_sec_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_HEADING_SUB, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.append(s2_ph)
|
||||||
|
cv.create_image(x_left + 6, cur_y, image=s2_ph, anchor="nw", tags="fg")
|
||||||
|
cur_y += s2_ph.height() + 6
|
||||||
|
|
||||||
|
b_box_h = 236
|
||||||
|
b_cy = cur_y + b_box_h // 2
|
||||||
|
b_box = self.ctx.assets.get_box_photo("box_big", (box_w, b_box_h))
|
||||||
|
if b_box:
|
||||||
|
self._photo_refs.append(b_box)
|
||||||
|
cv.create_image(cx, b_cy, image=b_box, anchor="center", tags="fg")
|
||||||
|
|
||||||
|
dd_w = max(220, box_w - 430)
|
||||||
|
for idx in range(ZR_BOT_COUNT):
|
||||||
|
ry = cur_y + 38 + idx * 50
|
||||||
|
seat_lbl = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("zr_seat_lbl", idx + 2), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.append(seat_lbl)
|
||||||
|
cv.create_image(x_left + 32, ry, image=seat_lbl, anchor="w", tags="fg")
|
||||||
|
cv.create_window(x_left + 130, ry, window=self._bot_entries[idx], anchor="w", tags="fg")
|
||||||
|
|
||||||
|
dd = self._bot_dds[idx]
|
||||||
|
if dd._width != dd_w:
|
||||||
|
dd._width = dd_w
|
||||||
|
dd.configure(width=dd_w)
|
||||||
|
dd._render_closed()
|
||||||
|
cv.create_window(x_left + 390, ry, window=dd, anchor="w", tags="fg")
|
||||||
|
|
||||||
|
cv.create_window(
|
||||||
|
x_left + box_w - 32, cur_y + b_box_h - 36, window=start_btn, anchor="e", tags="fg"
|
||||||
|
)
|
||||||
|
|
||||||
|
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
|
||||||
|
self.ctx.root.update_idletasks()
|
||||||
|
draw_layout(max(900, cv.winfo_width()), max(620, cv.winfo_height()))
|
||||||
|
|
@ -0,0 +1,178 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/zehner_raus/views/zehner_raus_result_dialog.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
BAVARIAN_CARD_THEME,
|
||||||
|
FONT_COLOR_BODY_DEFAULT,
|
||||||
|
FONT_COLOR_BODY_MUTED,
|
||||||
|
FONT_COLOR_HEADING_SUB,
|
||||||
|
FONT_COLOR_STATUS_LOSS,
|
||||||
|
FONT_COLOR_STATUS_WIN,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_BODY,
|
||||||
|
FONT_SIZE_SMALL_MIN,
|
||||||
|
SUBTLE_BORDER,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from view.widgets.casino_result_dialog_base import CasinoResultDialogBase
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
|
||||||
|
MINI_BAV_CARD_SIZE = (40, 58)
|
||||||
|
|
||||||
|
|
||||||
|
class ZehnerRausResultDialog(CasinoResultDialogBase):
|
||||||
|
"""Ergebnis-Overlay für 10er raus (ohne Goldbeutel-Zeilen, mit Restkarten-Übersicht)."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self, parent, assets, sounds, result_data: dict, on_next_round, on_back_to_menu
|
||||||
|
):
|
||||||
|
dlg_w = 736
|
||||||
|
dlg_h = 494 + (22 if result_data.get("new_level_title") else 0)
|
||||||
|
super().__init__(
|
||||||
|
parent, assets, sounds, result_data, dlg_w, dlg_h, on_next_round, on_back_to_menu
|
||||||
|
)
|
||||||
|
|
||||||
|
def _build_scene(self):
|
||||||
|
"""Überschreibt den Gold-Fußbereich durch einen luftigen XP- & Level-Abschluss."""
|
||||||
|
from PIL import Image, ImageTk
|
||||||
|
|
||||||
|
w, h = self._dlg_w, self._dlg_h
|
||||||
|
cx = w // 2
|
||||||
|
self._photo_refs.clear()
|
||||||
|
|
||||||
|
bg_src = (
|
||||||
|
self.assets.raw_bg_vertical
|
||||||
|
or self.assets.raw_bg_horizontal
|
||||||
|
or self.assets.raw_bg
|
||||||
|
)
|
||||||
|
if bg_src is not None:
|
||||||
|
bg_ph = ImageTk.PhotoImage(bg_src.resize((w, h), Image.Resampling.LANCZOS))
|
||||||
|
self._photo_refs.append(bg_ph)
|
||||||
|
self.create_image(0, 0, image=bg_ph, anchor="nw")
|
||||||
|
|
||||||
|
outer_box = self.assets.get_box_photo("box_big", (w - 6, h - 6))
|
||||||
|
if outer_box:
|
||||||
|
self._photo_refs.append(outer_box)
|
||||||
|
self.create_image(cx, h // 2, image=outer_box, anchor="center")
|
||||||
|
|
||||||
|
p_won = bool(self.data.get("player_won"))
|
||||||
|
hl_ph = self.assets.get_goth_text_photo(
|
||||||
|
self.data["headline"],
|
||||||
|
24,
|
||||||
|
FONT_COLOR_TITLE_MAIN if p_won else FONT_COLOR_STATUS_LOSS,
|
||||||
|
max_width=w - 64,
|
||||||
|
)
|
||||||
|
self._photo_refs.append(hl_ph)
|
||||||
|
cur_y = 26
|
||||||
|
self.create_image(cx, cur_y + hl_ph.height() // 2, image=hl_ph, anchor="center")
|
||||||
|
cur_y += hl_ph.height() + 10
|
||||||
|
|
||||||
|
cur_y = self._draw_showdown_middle(w, cx, cur_y)
|
||||||
|
|
||||||
|
self.create_line(36, cur_y, w - 36, cur_y, fill=SUBTLE_BORDER, width=1)
|
||||||
|
cur_y += 12
|
||||||
|
|
||||||
|
xp_line = t("bj_popup_xp_earned", self.data["xp_gained"])
|
||||||
|
if self.data.get("new_level_title"):
|
||||||
|
xp_line = f"{xp_line} | {self.data['new_level_title']}"
|
||||||
|
xp_ph = self.assets.get_goth_text_photo(
|
||||||
|
xp_line,
|
||||||
|
FONT_SIZE_BODY + 1,
|
||||||
|
FONT_COLOR_TITLE_MAIN if self.data.get("new_level_title") else FONT_COLOR_HEADING_SUB,
|
||||||
|
max_width=w - 72,
|
||||||
|
)
|
||||||
|
self._photo_refs.append(xp_ph)
|
||||||
|
self.create_image(cx, cur_y + xp_ph.height() // 2, image=xp_ph, anchor="center")
|
||||||
|
|
||||||
|
btn_norm = self.assets.raw_btn_default
|
||||||
|
btn_purp = self.assets.raw_btn_purple
|
||||||
|
btn_fire = self.assets.raw_btn_fire or btn_purp
|
||||||
|
btn_y = h - 38
|
||||||
|
|
||||||
|
b_next = ImageButton(
|
||||||
|
self, t("bj_popup_next_round_btn"), btn_fire, btn_fire,
|
||||||
|
self._handle_next, sound_mgr=self.sounds, width=205, height=38, style="fire",
|
||||||
|
)
|
||||||
|
b_menu = ImageButton(
|
||||||
|
self, t("bj_popup_to_menu_btn"), btn_norm, btn_purp,
|
||||||
|
self._handle_menu, sound_mgr=self.sounds, width=175, height=38, style="amethyst",
|
||||||
|
)
|
||||||
|
self.create_window(42, btn_y, window=b_next, anchor="w")
|
||||||
|
self.create_window(w - 42, btn_y, window=b_menu, anchor="e")
|
||||||
|
|
||||||
|
def _draw_showdown_middle(self, w: int, cx: int, cur_y: int) -> int:
|
||||||
|
hdr_ph = self.assets.get_goth_text_photo(
|
||||||
|
t("zr_popup_remaining_hdr"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.append(hdr_ph)
|
||||||
|
self.create_image(36, cur_y + 10, image=hdr_ph, anchor="w")
|
||||||
|
cur_y += 26
|
||||||
|
|
||||||
|
seats = self.data.get("seats_summary", [])
|
||||||
|
cols = 2
|
||||||
|
gap_x, gap_y = 14, 10
|
||||||
|
card_w = (w - 72 - gap_x) // cols
|
||||||
|
card_h = 128
|
||||||
|
|
||||||
|
win_box = self.assets.get_box_photo("box_gold_small", (card_w, card_h))
|
||||||
|
std_box = self.assets.get_box_photo("box_purple", (card_w, card_h))
|
||||||
|
if win_box:
|
||||||
|
self._photo_refs.append(win_box)
|
||||||
|
if std_box:
|
||||||
|
self._photo_refs.append(std_box)
|
||||||
|
|
||||||
|
for idx, entry in enumerate(seats):
|
||||||
|
r_i, c_i = divmod(idx, cols)
|
||||||
|
sx = 36 + c_i * (card_w + gap_x) + card_w // 2
|
||||||
|
sy = cur_y + r_i * (card_h + gap_y) + card_h // 2
|
||||||
|
is_win = entry["is_winner"]
|
||||||
|
|
||||||
|
frame_ph = win_box if is_win else std_box
|
||||||
|
if frame_ph:
|
||||||
|
self.create_image(sx, sy, image=frame_ph, anchor="center")
|
||||||
|
|
||||||
|
n_ph = self.assets.get_goth_text_photo(
|
||||||
|
entry["name"],
|
||||||
|
FONT_SIZE_SMALL_MIN + 2,
|
||||||
|
FONT_COLOR_TITLE_MAIN if is_win else FONT_COLOR_HEADING_SUB,
|
||||||
|
max_width=card_w - 28,
|
||||||
|
)
|
||||||
|
rem_txt = (
|
||||||
|
t("zr_popup_cards_zero")
|
||||||
|
if is_win
|
||||||
|
else t("zr_popup_cards_rem", len(entry["cards"]))
|
||||||
|
)
|
||||||
|
r_ph = self.assets.get_goth_text_photo(
|
||||||
|
rem_txt,
|
||||||
|
FONT_SIZE_SMALL_MIN - 1,
|
||||||
|
FONT_COLOR_STATUS_WIN if is_win else FONT_COLOR_BODY_DEFAULT,
|
||||||
|
max_width=card_w - 28,
|
||||||
|
)
|
||||||
|
self._photo_refs.extend([n_ph, r_ph])
|
||||||
|
|
||||||
|
# Erst Mini-Karten in die Mitte legen, danach Name (oben) & Anzahl (unten) sauber darüber!
|
||||||
|
c_photos = [
|
||||||
|
ph
|
||||||
|
for img_name in entry["cards"]
|
||||||
|
if (
|
||||||
|
ph := self.assets.get_card_photo(
|
||||||
|
img_name, size=MINI_BAV_CARD_SIZE, theme=BAVARIAN_CARD_THEME
|
||||||
|
)
|
||||||
|
)
|
||||||
|
]
|
||||||
|
self._photo_refs.extend(c_photos)
|
||||||
|
if c_photos:
|
||||||
|
cw_m, ch_m = MINI_BAV_CARD_SIZE
|
||||||
|
n_c = len(c_photos)
|
||||||
|
step = min(22, max(12, (card_w - 36 - cw_m) // max(1, n_c - 1)))
|
||||||
|
span = cw_m + (n_c - 1) * step
|
||||||
|
x0 = sx - span // 2
|
||||||
|
cards_top_y = sy - ch_m // 2 - 2
|
||||||
|
for ci, cph in enumerate(c_photos):
|
||||||
|
self.create_image(x0 + ci * step, cards_top_y, image=cph, anchor="nw")
|
||||||
|
|
||||||
|
self.create_image(sx, sy - card_h // 2 + 19, image=n_ph, anchor="center")
|
||||||
|
self.create_image(sx, sy + card_h // 2 - 17, image=r_ph, anchor="center")
|
||||||
|
|
||||||
|
return cur_y + 2 * (card_h + gap_y) + 6
|
||||||
|
|
@ -0,0 +1,314 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/party/zehner_raus/views/zehner_raus_table_view.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
from games.party.zehner_raus.models.zehner_raus_ai import ZehnerRausBotAI
|
||||||
|
from games.party.zehner_raus.models.zehner_raus_engine import ZehnerRausEngine
|
||||||
|
from games.party.zehner_raus.views.zehner_raus_arena_renderer import (
|
||||||
|
ZehnerRausArenaRenderer,
|
||||||
|
)
|
||||||
|
from games.party.zehner_raus.views.zehner_raus_result_dialog import (
|
||||||
|
ZehnerRausResultDialog,
|
||||||
|
)
|
||||||
|
from models.bavarian_deck import BavarianCard
|
||||||
|
from models.progression import Progression
|
||||||
|
from resources.code_res.game_constants import ZR_BOT_TURN_DELAY_MS, ZR_VARIANTS
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from view.widgets.casino_arena_base import CasinoArenaBase
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
|
||||||
|
GAME_FOLDER_ID = "party/zehner_raus"
|
||||||
|
|
||||||
|
|
||||||
|
class ZehnerRausTableView(CasinoArenaBase):
|
||||||
|
GAME_FOLDER_ID = GAME_FOLDER_ID
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
context,
|
||||||
|
variant_key: str,
|
||||||
|
bot_configs: list[tuple[int, str]],
|
||||||
|
on_back_to_menu,
|
||||||
|
):
|
||||||
|
v_key = variant_key if variant_key in ZR_VARIANTS else "zehner_raus_std"
|
||||||
|
cfg = ZR_VARIANTS[v_key]
|
||||||
|
self._init_arena_state(context, v_key, cfg, on_back_to_menu)
|
||||||
|
|
||||||
|
self._bot_configs = list(bot_configs)
|
||||||
|
self.engine = ZehnerRausEngine()
|
||||||
|
self.engine.configure_seats(self.ctx.profile["name"], self._bot_configs)
|
||||||
|
self.round_start_time: float = time.time()
|
||||||
|
self._hand_hit_rects: list[tuple[BavarianCard, int, int, int, int]] = []
|
||||||
|
self._last_popup_payload: dict | None = None
|
||||||
|
|
||||||
|
self.ctx.sounds.play_ingame_music()
|
||||||
|
self._build_ui()
|
||||||
|
self._start_new_round()
|
||||||
|
|
||||||
|
def _build_ui(self):
|
||||||
|
self._build_arena_shell(on_lang_refresh=self._on_language_switched)
|
||||||
|
self.arena_canvas.bind("<ButtonPress-1>", self._on_canvas_click)
|
||||||
|
|
||||||
|
btn_norm = self.ctx.assets.raw_btn_default
|
||||||
|
btn_purp = self.ctx.assets.raw_btn_purple
|
||||||
|
self._menu_btn = ImageButton(
|
||||||
|
self.bottom_bar,
|
||||||
|
t("bj_popup_to_menu_btn"),
|
||||||
|
btn_norm,
|
||||||
|
btn_purp,
|
||||||
|
lambda: self._cleanup_and_go(self.on_back_to_menu),
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=156,
|
||||||
|
height=30,
|
||||||
|
style="amethyst",
|
||||||
|
)
|
||||||
|
|
||||||
|
def _on_arena_resize_redraw(self):
|
||||||
|
self._render_table()
|
||||||
|
|
||||||
|
def _on_language_switched(self):
|
||||||
|
ImageButton.close_active_hover_tip()
|
||||||
|
self._cancel_fx_overlay()
|
||||||
|
self._build_ui()
|
||||||
|
self._render_table()
|
||||||
|
if self.engine.is_finished and self._last_popup_payload is not None:
|
||||||
|
self._open_result_popup(
|
||||||
|
self._localize_popup(self._last_popup_payload), play_fx=False
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._sync_turn_controls()
|
||||||
|
|
||||||
|
def _refresh_header(self):
|
||||||
|
turn_name = (
|
||||||
|
self.engine.seats[self.engine.turn_seat].name
|
||||||
|
if not self.engine.is_finished
|
||||||
|
else "-"
|
||||||
|
)
|
||||||
|
hud_line = t(
|
||||||
|
"zr_hud_round_info",
|
||||||
|
turn_name,
|
||||||
|
len(self.engine.human_seat.hand),
|
||||||
|
self.engine.turns_played,
|
||||||
|
)
|
||||||
|
self._set_hud_segments(*hud_line.split("|"))
|
||||||
|
|
||||||
|
def _start_new_round(self):
|
||||||
|
self._cancel_jobs()
|
||||||
|
if self._result_dialog is not None:
|
||||||
|
self._result_dialog.close_dialog()
|
||||||
|
self._result_dialog = None
|
||||||
|
ImageButton.close_active_hover_tip()
|
||||||
|
|
||||||
|
self._last_popup_payload = None
|
||||||
|
self.round_start_time = time.time()
|
||||||
|
self.engine.start_new_round()
|
||||||
|
self.ctx.sounds.play("deal")
|
||||||
|
|
||||||
|
if not self._canvas_alive():
|
||||||
|
self._build_ui()
|
||||||
|
self._render_table()
|
||||||
|
self._process_turn()
|
||||||
|
|
||||||
|
def _render_table(self):
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
cw, ch, pad_x, pad_top, _pad_bot, p_top, p_bot, table_rect = (
|
||||||
|
self._prepare_arena_surface()
|
||||||
|
)
|
||||||
|
top_obs = ZehnerRausArenaRenderer.draw_bots(
|
||||||
|
self, cw, ch, pad_x, pad_top, table_rect
|
||||||
|
)
|
||||||
|
bot_bounds = ZehnerRausArenaRenderer.draw_bots(
|
||||||
|
self, cw, ch, pad_x, pad_top, table_rect
|
||||||
|
)
|
||||||
|
ZehnerRausArenaRenderer.draw_bavarian_lanes(
|
||||||
|
self, table_rect, bot_bounds, p_top
|
||||||
|
)
|
||||||
|
self._hand_hit_rects = ZehnerRausArenaRenderer.draw_human_hand(
|
||||||
|
self, cw, p_top, p_bot
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.arena_canvas.find_withtag("modal_dim_veil"):
|
||||||
|
self.arena_canvas.tag_raise("modal_dim_veil")
|
||||||
|
self._refresh_header()
|
||||||
|
if self._result_dialog is not None and self._result_dialog.winfo_exists():
|
||||||
|
tk.Widget.tkraise(self._result_dialog)
|
||||||
|
|
||||||
|
def _sync_turn_controls(self):
|
||||||
|
if not hasattr(self, "bottom_bar") or not self.bottom_bar.winfo_exists():
|
||||||
|
return
|
||||||
|
if self.engine.is_finished:
|
||||||
|
self.status_var.set("")
|
||||||
|
self._set_bottom_buttons([])
|
||||||
|
return
|
||||||
|
|
||||||
|
if self.engine.turn_seat != 0:
|
||||||
|
self.status_var.set("")
|
||||||
|
self._set_bottom_buttons([], overflow_buttons=[self._menu_btn])
|
||||||
|
return
|
||||||
|
|
||||||
|
playable = self.engine.get_playable_cards(0)
|
||||||
|
if playable:
|
||||||
|
self.status_var.set(t("zr_status_your_turn_play", len(playable)))
|
||||||
|
self._set_bottom_buttons([], overflow_buttons=[self._menu_btn])
|
||||||
|
else:
|
||||||
|
self.status_var.set(t("zr_status_your_turn_pass"))
|
||||||
|
btn_fire = self.ctx.assets.raw_btn_fire or self.ctx.assets.raw_btn_purple
|
||||||
|
pass_btn = ImageButton(
|
||||||
|
self.bottom_bar,
|
||||||
|
t("zr_btn_pass"),
|
||||||
|
btn_fire,
|
||||||
|
btn_fire,
|
||||||
|
self._on_human_pass,
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=184,
|
||||||
|
height=30,
|
||||||
|
style="fire",
|
||||||
|
hover_text=lambda: t("zr_tip_pass"),
|
||||||
|
)
|
||||||
|
self._set_bottom_buttons([pass_btn], overflow_buttons=[self._menu_btn])
|
||||||
|
|
||||||
|
def _process_turn(self):
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
if self.engine.is_finished:
|
||||||
|
self._finalize_round()
|
||||||
|
return
|
||||||
|
|
||||||
|
self._sync_turn_controls()
|
||||||
|
if self.engine.turn_seat != 0:
|
||||||
|
self._turn_job = self.ctx.root.after(
|
||||||
|
ZR_BOT_TURN_DELAY_MS, self._execute_bot_turn
|
||||||
|
)
|
||||||
|
|
||||||
|
def _on_canvas_click(self, event):
|
||||||
|
if (
|
||||||
|
self._fx_overlay is not None
|
||||||
|
or self._result_dialog is not None
|
||||||
|
or self.engine.is_finished
|
||||||
|
or self.engine.turn_seat != 0
|
||||||
|
):
|
||||||
|
return
|
||||||
|
|
||||||
|
for card, x1, y1, x2, y2 in reversed(self._hand_hit_rects):
|
||||||
|
if x1 <= event.x <= x2 and y1 <= event.y <= y2:
|
||||||
|
if self.engine.play_card(0, card):
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
self._render_table()
|
||||||
|
self._process_turn()
|
||||||
|
return
|
||||||
|
|
||||||
|
def _on_human_pass(self):
|
||||||
|
if self.engine.pass_turn(0):
|
||||||
|
self.ctx.sounds.play("stand")
|
||||||
|
self._render_table()
|
||||||
|
self._process_turn()
|
||||||
|
|
||||||
|
def _execute_bot_turn(self):
|
||||||
|
self._turn_job = None
|
||||||
|
if not self._canvas_alive() or self.engine.is_finished:
|
||||||
|
return
|
||||||
|
seat_id = self.engine.turn_seat
|
||||||
|
if seat_id == 0:
|
||||||
|
return
|
||||||
|
|
||||||
|
bot = self.engine.seats[seat_id]
|
||||||
|
chosen = ZehnerRausBotAI.choose_card(self.engine, bot)
|
||||||
|
if chosen is not None and self.engine.play_card(seat_id, chosen):
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
bot.status_text = t(
|
||||||
|
"zr_act_played", t(f"bav_suit_{chosen.suit}"), chosen.rank
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.engine.pass_turn(seat_id)
|
||||||
|
bot.status_text = t("zr_act_passed")
|
||||||
|
|
||||||
|
self._render_table()
|
||||||
|
self._process_turn()
|
||||||
|
|
||||||
|
def _finalize_round(self):
|
||||||
|
self._set_bottom_buttons([])
|
||||||
|
self.status_var.set("")
|
||||||
|
|
||||||
|
winner_id = self.engine.winner_seat
|
||||||
|
human_won = winner_id == 0
|
||||||
|
duration = max(1.0, time.time() - self.round_start_time)
|
||||||
|
|
||||||
|
prog_before = self.ctx.refresh_game_progress()
|
||||||
|
opp_levels = [s.ai_level for s in self.engine.seats[1:]]
|
||||||
|
xp_gained = Progression.calculate_match_xp(
|
||||||
|
player_level=prog_before["level"],
|
||||||
|
opponent_levels=opp_levels,
|
||||||
|
outcome_type="WIN" if human_won else "LOSE",
|
||||||
|
variant_mult=self.cfg["xp_mult"],
|
||||||
|
)
|
||||||
|
|
||||||
|
old_lvl, new_lvl = self.ctx.record_result(
|
||||||
|
self.variant_key,
|
||||||
|
won=human_won,
|
||||||
|
duration_sec=duration,
|
||||||
|
points_gained=xp_gained,
|
||||||
|
)
|
||||||
|
self.topbar.update_level_xp_text()
|
||||||
|
self.ctx.sounds.play("win" if human_won else "lose")
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"player_won": human_won,
|
||||||
|
"winner_name": self.engine.seats[winner_id].name if winner_id is not None else "",
|
||||||
|
"xp_gained": xp_gained,
|
||||||
|
"leveled_to": new_lvl if new_lvl > old_lvl else None,
|
||||||
|
"seats_summary": [
|
||||||
|
{
|
||||||
|
"name": s.name,
|
||||||
|
"is_winner": s.seat_id == winner_id,
|
||||||
|
"cards": [c.image_filename for c in s.hand],
|
||||||
|
}
|
||||||
|
for s in self.engine.seats
|
||||||
|
],
|
||||||
|
}
|
||||||
|
self._last_popup_payload = payload
|
||||||
|
self._open_result_popup(self._localize_popup(payload), play_fx=True)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _localize_popup(payload: dict) -> dict:
|
||||||
|
p_won = payload["player_won"]
|
||||||
|
headline = (
|
||||||
|
t("zr_popup_you_won")
|
||||||
|
if p_won
|
||||||
|
else t("zr_popup_bot_won", payload["winner_name"])
|
||||||
|
)
|
||||||
|
lvl_to = payload["leveled_to"]
|
||||||
|
lvl_str = (
|
||||||
|
t("bj_popup_level_up", lvl_to, Progression.get_prestige_title(lvl_to))
|
||||||
|
if lvl_to is not None
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"headline": headline,
|
||||||
|
"player_won": p_won,
|
||||||
|
"xp_gained": payload["xp_gained"],
|
||||||
|
"new_level_title": lvl_str,
|
||||||
|
"seats_summary": payload["seats_summary"],
|
||||||
|
}
|
||||||
|
|
||||||
|
def _show_result_dialog_now(self, popup_data: dict):
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
self._result_dialog = ZehnerRausResultDialog(
|
||||||
|
parent=self.arena_canvas,
|
||||||
|
assets=self.ctx.assets,
|
||||||
|
sounds=self.ctx.sounds,
|
||||||
|
result_data=popup_data,
|
||||||
|
on_next_round=self._start_new_round,
|
||||||
|
on_back_to_menu=lambda: self._cleanup_and_go(self.on_back_to_menu),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _open_result_popup(self, popup_data: dict, play_fx: bool = True):
|
||||||
|
self._play_outcome_fx_then(
|
||||||
|
popup_data.get("player_won"),
|
||||||
|
play_fx,
|
||||||
|
lambda: self._show_result_dialog_now(popup_data),
|
||||||
|
)
|
||||||
|
|
@ -10,7 +10,7 @@
|
||||||
Das Modul `games/poker/` implementiert **6-Max No-Limit Texas Hold'em** innerhalb der Kategorie **Glück**. Es besitzt eine **vollständig autarke Ökonomie** (`poker_accounts` & `poker_account_stats`) sowie eine eigene Erfahrungs- und Rang-Kurve (`game_folder = 'poker'`), strikt getrennt von Blackjack.
|
Das Modul `games/poker/` implementiert **6-Max No-Limit Texas Hold'em** innerhalb der Kategorie **Glück**. Es besitzt eine **vollständig autarke Ökonomie** (`poker_accounts` & `poker_account_stats`) sowie eine eigene Erfahrungs- und Rang-Kurve (`game_folder = 'poker'`), strikt getrennt von Blackjack.
|
||||||
|
|
||||||
### 2. Spielregeln & Tischablauf
|
### 2. Spielregeln & Tischablauf
|
||||||
* **6-Max Tisch (`poker_table.jpg`):** Du spielst gegen **1 bis maximal 5 KI-Gegner** rund um einen dynamisch skalierenden gotischen Pokertisch.
|
* **6-Max Tisch (`poker_table.png`):** Du spielst gegen **1 bis maximal 5 KI-Gegner** rund um einen dynamisch skalierenden gotischen Pokertisch.
|
||||||
* **Einheitlicher Grundeinsatz (Ante) statt asymmetrischer Blinds:** Beim Start einer Hand zahlt jeder aktive Sitz automatisch denselben Grundeinsatz in den Pot (`10 Gold` bei *Klassisch*, `20 Gold` bei *Hoher Einsatz*). Der Dealer-Button `[D]` rotiert jede Runde im Uhrzeigersinn weiter und bestimmt die Zugreihenfolge.
|
* **Einheitlicher Grundeinsatz (Ante) statt asymmetrischer Blinds:** Beim Start einer Hand zahlt jeder aktive Sitz automatisch denselben Grundeinsatz in den Pot (`10 Gold` bei *Klassisch*, `20 Gold` bei *Hoher Einsatz*). Der Dealer-Button `[D]` rotiert jede Runde im Uhrzeigersinn weiter und bestimmt die Zugreihenfolge.
|
||||||
* **Setzrunden (Streets):** `Pre-Flop` (2 Hole Cards) $\rightarrow$ `Flop` (3 Gemeinschaftskarten) $\rightarrow$ `Turn` (4. Karte) $\rightarrow$ `River` (5. Karte) $\rightarrow$ `Showdown`.
|
* **Setzrunden (Streets):** `Pre-Flop` (2 Hole Cards) $\rightarrow$ `Flop` (3 Gemeinschaftskarten) $\rightarrow$ `Turn` (4. Karte) $\rightarrow$ `River` (5. Karte) $\rightarrow$ `Showdown`.
|
||||||
* **No-Limit, All-In & Side-Pots:** Jederzeit **All-In** möglich. Bei unterschiedlich hohen Stacks berechnet die `PokerEngine` automatisch exakte Haupt- und **Side-Pots**.
|
* **No-Limit, All-In & Side-Pots:** Jederzeit **All-In** möglich. Bei unterschiedlich hohen Stacks berechnet die `PokerEngine` automatisch exakte Haupt- und **Side-Pots**.
|
||||||
|
|
@ -29,7 +29,7 @@ Das Modul `games/poker/` implementiert **6-Max No-Limit Texas Hold'em** innerhal
|
||||||
The `games/poker/` module implements **6-Max No-Limit Texas Hold'em** under the **Luck** category with a **standalone economy** (`poker_accounts`, `poker_account_stats`) and isolated XP progression (`game_folder = 'poker'`).
|
The `games/poker/` module implements **6-Max No-Limit Texas Hold'em** under the **Luck** category with a **standalone economy** (`poker_accounts`, `poker_account_stats`) and isolated XP progression (`game_folder = 'poker'`).
|
||||||
|
|
||||||
### 2. Rules & Table Features
|
### 2. Rules & Table Features
|
||||||
* **6-Max Arena (`poker_table.jpg`):** Play against **1 to 5 AI opponents** arranged around a dynamically scaling Gothic poker table.
|
* **6-Max Arena (`poker_table.png`):** Play against **1 to 5 AI opponents** arranged around a dynamically scaling Gothic poker table.
|
||||||
* **Equal Entry Ante:** At the start of each hand, every active seat automatically posts the table's base ante (`10 Gold` in *Classic*, `20 Gold` in *High Stakes*) before starting in **Pre-Flop**, while the Dealer button `[D]` rotates clockwise.
|
* **Equal Entry Ante:** At the start of each hand, every active seat automatically posts the table's base ante (`10 Gold` in *Classic*, `20 Gold` in *High Stakes*) before starting in **Pre-Flop**, while the Dealer button `[D]` rotates clockwise.
|
||||||
* **Streets & Side Pots:** Full `Pre-Flop` $\rightarrow$ `Flop` $\rightarrow$ `Turn` $\rightarrow$ `River` $\rightarrow$ `Showdown` flow with automatic multi-way **Side Pot** resolution on uneven All-Ins.
|
* **Streets & Side Pots:** Full `Pre-Flop` $\rightarrow$ `Flop` $\rightarrow$ `Turn` $\rightarrow$ `River` $\rightarrow$ `Showdown` flow with automatic multi-way **Side Pot** resolution on uneven All-Ins.
|
||||||
* **Visual Hand Reference & `ⓘ` Tooltips:** Static 2-column mini-card cheat sheet (no hand spoilers during play) paired with hover/click `ⓘ` (`InfoBadge`) explanations for all 10 hand rankings and betting actions.
|
* **Visual Hand Reference & `ⓘ` Tooltips:** Static 2-column mini-card cheat sheet (no hand spoilers during play) paired with hover/click `ⓘ` (`InfoBadge`) explanations for all 10 hand rankings and betting actions.
|
||||||
|
|
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,324 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/poker/views/poker_arena_renderer.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
ACCENT_GOLD,
|
||||||
|
ACCENT_GOTH,
|
||||||
|
ERROR_FG,
|
||||||
|
FG_COLOR,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_BODY,
|
||||||
|
MUTED_FG,
|
||||||
|
PLAYING_CARD_SIZE,
|
||||||
|
SUBTLE_BORDER,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from games.poker.models.poker_evaluator import PokerEvaluator
|
||||||
|
from models.database import Database
|
||||||
|
from models.progression import Progression
|
||||||
|
|
||||||
|
PK_OVAL_BOARD_CARD = (78, 114)
|
||||||
|
PK_BOT_SHOWDOWN_CARD = (42, 62)
|
||||||
|
|
||||||
|
SEAT_LAYOUT_BY_COUNT = {
|
||||||
|
1: (2,),
|
||||||
|
2: (1, 3),
|
||||||
|
3: (1, 2, 3),
|
||||||
|
4: (0, 1, 3, 4),
|
||||||
|
5: (0, 1, 2, 3, 4),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class PokerArenaRenderer:
|
||||||
|
"""Zeichnet die 6-Max-Tischszene für Texas Hold'em auf das Arena-Canvas."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def role_badge(eng, seat_idx: int) -> str:
|
||||||
|
badges = []
|
||||||
|
if seat_idx == eng.dealer_pos:
|
||||||
|
badges.append(t("pk_role_dealer"))
|
||||||
|
if seat_idx == eng.sb_pos:
|
||||||
|
badges.append(t("pk_role_sb"))
|
||||||
|
if seat_idx == eng.bb_pos:
|
||||||
|
badges.append(t("pk_role_bb"))
|
||||||
|
return "".join(badges)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def draw_bots(
|
||||||
|
cls,
|
||||||
|
view,
|
||||||
|
cw: int,
|
||||||
|
ch: int,
|
||||||
|
pad_x: int,
|
||||||
|
pad_top: int,
|
||||||
|
pad_bot: int,
|
||||||
|
table_rect: tuple[int, int, int, int],
|
||||||
|
) -> int:
|
||||||
|
bot_seats = view.engine.seats[1:]
|
||||||
|
if not bot_seats:
|
||||||
|
return table_rect[1] + 24
|
||||||
|
|
||||||
|
tx1, ty1, tx2, ty2 = table_rect
|
||||||
|
is_showdown = (view.engine.street == "SHOWDOWN")
|
||||||
|
box_h = 98 if is_showdown else 88
|
||||||
|
base_box_w = 216 if is_showdown else 204
|
||||||
|
|
||||||
|
top_cy = max(pad_top + box_h // 2, ty1 + box_h // 2 - 4)
|
||||||
|
bot_cy = min(ch - pad_bot - box_h // 2, ty2 - box_h // 2 + 22)
|
||||||
|
if bot_cy - top_cy < box_h + 16:
|
||||||
|
mid_y = (top_cy + bot_cy) // 2
|
||||||
|
top_cy, bot_cy = mid_y - (box_h + 16) // 2, mid_y + (box_h + 16) // 2
|
||||||
|
|
||||||
|
top_center_cy = max(pad_top + box_h // 2, ty1 + int(box_h * 0.42))
|
||||||
|
top_center_bottom = ty1 + 24
|
||||||
|
|
||||||
|
slot_indices = SEAT_LAYOUT_BY_COUNT.get(len(bot_seats), (0, 1, 2, 3, 4))
|
||||||
|
name_sz, sub_sz = max(14, FONT_SIZE_BODY - 1), max(13, FONT_SIZE_BODY - 2)
|
||||||
|
|
||||||
|
for bot_i, seat in enumerate(bot_seats):
|
||||||
|
coord_idx = slot_indices[bot_i]
|
||||||
|
is_turn = (not is_showdown and view.engine.turn_pos == seat.seat_id)
|
||||||
|
show_bot_cards = is_showdown and bool(seat.hole_cards) and (not seat.folded)
|
||||||
|
|
||||||
|
frame_style = "gold" if is_turn else "purple"
|
||||||
|
status_border = ERROR_FG if seat.folded else (ACCENT_GOTH if seat.all_in else None)
|
||||||
|
|
||||||
|
base_name = t("bj_bot_rebuy", seat.name) if seat.rebought else seat.name
|
||||||
|
title_txt = f"{base_name}{cls.role_badge(view.engine, seat.seat_id)}"
|
||||||
|
title_col = MUTED_FG if seat.folded else (ACCENT_GOLD if is_turn else ACCENT_GOTH)
|
||||||
|
|
||||||
|
stack_txt = t("pk_bot_stack_lbl", seat.stack, seat.street_bet)
|
||||||
|
st_txt = seat.status_text or "-"
|
||||||
|
st_col = ERROR_FG if seat.folded else (ACCENT_GOLD if is_turn else FG_COLOR)
|
||||||
|
|
||||||
|
max_txt_w = 176 if show_bot_cards else 230
|
||||||
|
title_ph = view._make_goth_photo(title_txt, name_sz, title_col, max_txt_w)
|
||||||
|
stack_ph = view._make_goth_photo(stack_txt, sub_sz, ACCENT_GOLD, max_txt_w)
|
||||||
|
st_ph = view._make_goth_photo(st_txt, sub_sz, st_col, max_txt_w)
|
||||||
|
|
||||||
|
widest_txt = max((ph.width() for ph in (title_ph, stack_ph, st_ph) if ph), default=140)
|
||||||
|
extra_cards_w = (PK_BOT_SHOWDOWN_CARD[0] + 38) if show_bot_cards else 0
|
||||||
|
box_w = max(base_box_w, min(296, widest_txt + extra_cards_w + 46))
|
||||||
|
|
||||||
|
if coord_idx == 2:
|
||||||
|
bx, by = cw // 2, top_center_cy
|
||||||
|
top_center_bottom = max(top_center_bottom, by + box_h // 2)
|
||||||
|
elif coord_idx in (0, 1):
|
||||||
|
bx = max(pad_x + box_w // 2, tx1 + int(box_w * 0.36))
|
||||||
|
by = bot_cy if coord_idx == 0 else top_cy
|
||||||
|
else:
|
||||||
|
bx = min(cw - pad_x - box_w // 2, tx2 - int(box_w * 0.36))
|
||||||
|
by = top_cy if coord_idx == 3 else bot_cy
|
||||||
|
|
||||||
|
view._draw_framed_panel(bx, by, box_w, box_h, frame_style=frame_style, status_border=status_border)
|
||||||
|
|
||||||
|
if show_bot_cards:
|
||||||
|
c_w, c_h = PK_BOT_SHOWDOWN_CARD
|
||||||
|
step_x = 22
|
||||||
|
fan_left, fan_top = bx - box_w // 2 + 16, by - c_h // 2
|
||||||
|
for ci, c_obj in enumerate(seat.hole_cards[:2]):
|
||||||
|
c_ph = view.ctx.assets.get_card_photo(c_obj.image_filename, size=PK_BOT_SHOWDOWN_CARD)
|
||||||
|
if c_ph is not None:
|
||||||
|
view._photo_refs.append(c_ph)
|
||||||
|
view.arena_canvas.create_image(fan_left + ci * step_x, fan_top, image=c_ph, anchor="nw", tags="fg")
|
||||||
|
txt_cx = bx + (c_w + step_x) // 2 + 4
|
||||||
|
view._place_goth_photo_or_fallback(txt_cx, by - 24, title_ph, title_txt, name_sz, title_col)
|
||||||
|
view._place_goth_photo_or_fallback(txt_cx, by, stack_ph, stack_txt, sub_sz, ACCENT_GOLD)
|
||||||
|
view._place_goth_photo_or_fallback(txt_cx, by + 24, st_ph, st_txt, sub_sz, st_col)
|
||||||
|
else:
|
||||||
|
view._place_goth_photo_or_fallback(bx, by - 23, title_ph, title_txt, name_sz, title_col)
|
||||||
|
view._place_goth_photo_or_fallback(bx, by, stack_ph, stack_txt, sub_sz, ACCENT_GOLD)
|
||||||
|
view._place_goth_photo_or_fallback(bx, by + 23, st_ph, st_txt, sub_sz, st_col)
|
||||||
|
|
||||||
|
return top_center_bottom
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def draw_board_and_pot(
|
||||||
|
view, table_rect: tuple[int, int, int, int], top_obstacle_y: int, player_top_y: int
|
||||||
|
) -> None:
|
||||||
|
tx1, ty1, tx2, ty2 = table_rect
|
||||||
|
t_cx = (tx1 + tx2) // 2
|
||||||
|
t_h = max(260, ty2 - ty1)
|
||||||
|
|
||||||
|
felt_top = max(ty1 + max(32, int(t_h * 0.14)), top_obstacle_y + 12)
|
||||||
|
felt_bot = min(ty2 - max(24, int(t_h * 0.10)), player_top_y - 10)
|
||||||
|
avail_h = max(148, felt_bot - felt_top)
|
||||||
|
|
||||||
|
base_cw, base_ch = PK_OVAL_BOARD_CARD
|
||||||
|
scale = max(84, min(base_ch, avail_h - 58)) / max(1, base_ch)
|
||||||
|
card_w, card_h = max(58, int(round(base_cw * scale))), int(round(base_ch * scale))
|
||||||
|
card_sz = (card_w, card_h)
|
||||||
|
|
||||||
|
gap = max(8, int(card_w * 0.13))
|
||||||
|
start_x = t_cx - (5 * card_w + 4 * gap) // 2
|
||||||
|
board_cy = felt_top + card_h // 2 + max(4, (avail_h - card_h - 52) // 3)
|
||||||
|
card_top = board_cy - card_h // 2
|
||||||
|
|
||||||
|
for slot_i in range(5):
|
||||||
|
sx = start_x + slot_i * (card_w + gap)
|
||||||
|
if slot_i < len(view.engine.board):
|
||||||
|
photo = view.ctx.assets.get_card_photo(view.engine.board[slot_i].image_filename, size=card_sz)
|
||||||
|
if photo:
|
||||||
|
view._photo_refs.append(photo)
|
||||||
|
view.arena_canvas.create_image(sx, card_top, image=photo, anchor="nw", tags="fg")
|
||||||
|
continue
|
||||||
|
view.arena_canvas.create_rectangle(
|
||||||
|
sx, card_top, sx + card_w, card_top + card_h,
|
||||||
|
fill="#161220", outline=SUBTLE_BORDER, width=1, tags="fg",
|
||||||
|
)
|
||||||
|
|
||||||
|
pot_txt = t("pk_pot_banner", view.engine.total_pot).split("|")[0].strip()
|
||||||
|
pot_cy = min(felt_bot - 20, max(board_cy + card_h // 2 + 28, (board_cy + card_h // 2 + felt_bot) // 2))
|
||||||
|
pot_sz = max(15, FONT_SIZE_BODY)
|
||||||
|
pot_ph = view._make_goth_photo(pot_txt, pot_sz, FONT_COLOR_TITLE_MAIN)
|
||||||
|
if pot_ph is not None:
|
||||||
|
bw, bh = max(230, pot_ph.width() + 64), max(38, pot_ph.height() + 16)
|
||||||
|
view._draw_framed_panel(t_cx, pot_cy, bw, bh, frame_style="gold")
|
||||||
|
view.arena_canvas.create_image(t_cx, pot_cy, image=pot_ph, anchor="center", tags="fg")
|
||||||
|
else:
|
||||||
|
view._draw_framed_panel(t_cx, pot_cy, 240, 38, frame_style="gold")
|
||||||
|
view._place_goth_photo_or_fallback(t_cx, pot_cy, None, pot_txt, pot_sz, ACCENT_GOLD)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def draw_human_hand(cls, view, cw: int, pad_x: int, player_zone_top: int, player_zone_bot: int) -> None:
|
||||||
|
human = view.engine.human_seat
|
||||||
|
avail_h = max(140, player_zone_bot - player_zone_top)
|
||||||
|
zone_cy = (player_zone_top + player_zone_bot) // 2
|
||||||
|
|
||||||
|
base_w, base_h = PLAYING_CARD_SIZE
|
||||||
|
scale = max(88, min(base_h, avail_h - 52)) / max(1, base_h)
|
||||||
|
card_w, card_h = max(60, int(round(base_w * scale))), int(round(base_h * scale))
|
||||||
|
card_sz = (card_w, card_h)
|
||||||
|
|
||||||
|
p_photos = []
|
||||||
|
for card in human.hole_cards:
|
||||||
|
photo = view.ctx.assets.get_card_photo(card.image_filename, size=card_sz)
|
||||||
|
if photo:
|
||||||
|
view._photo_refs.append(photo)
|
||||||
|
p_photos.append(photo)
|
||||||
|
|
||||||
|
state_tag = t("pk_state_folded") if human.folded else (t("pk_state_allin") if human.all_in else "")
|
||||||
|
role_str = cls.role_badge(view.engine, 0) or t("pk_role_player")
|
||||||
|
lbl_txt = t("pk_player_bet_only", role_str, human.street_bet, human.total_committed, state_tag)
|
||||||
|
|
||||||
|
is_my_turn = (view.engine.street != "SHOWDOWN" and view.engine.turn_pos == 0 and human.can_act)
|
||||||
|
lbl_col = ERROR_FG if human.folded else FONT_COLOR_TITLE_MAIN
|
||||||
|
lbl_sz = max(14, FONT_SIZE_BODY - 1)
|
||||||
|
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, lbl_col)
|
||||||
|
|
||||||
|
cards_gap = 12
|
||||||
|
cards_span_w = len(p_photos) * card_w + max(0, len(p_photos) - 1) * cards_gap if p_photos else card_w * 2
|
||||||
|
txt_w = lbl_ph.width() if lbl_ph is not None else 250
|
||||||
|
|
||||||
|
box_w = max(300, min(540, max(cards_span_w + 96, txt_w + 72)))
|
||||||
|
box_h = min(avail_h, card_h + 52)
|
||||||
|
box_cx = cw // 2
|
||||||
|
|
||||||
|
status_bdr = ERROR_FG if human.folded else (ACCENT_GOTH if human.all_in else None)
|
||||||
|
view._draw_framed_panel(
|
||||||
|
box_cx, zone_cy, box_w, box_h,
|
||||||
|
frame_style="gold" if is_my_turn else "purple", status_border=status_bdr,
|
||||||
|
)
|
||||||
|
|
||||||
|
if p_photos:
|
||||||
|
c_start_x = box_cx - cards_span_w // 2
|
||||||
|
c_top_y = (zone_cy - 11) - card_h // 2
|
||||||
|
for idx, ph in enumerate(p_photos):
|
||||||
|
view.arena_canvas.create_image(
|
||||||
|
c_start_x + idx * (card_w + cards_gap), c_top_y, image=ph, anchor="nw", tags="fg"
|
||||||
|
)
|
||||||
|
|
||||||
|
view._place_goth_photo_or_fallback(box_cx, zone_cy + box_h // 2 - 20, lbl_ph, lbl_txt, lbl_sz, lbl_col)
|
||||||
|
|
||||||
|
ref_btn = view._card_ref_btn
|
||||||
|
if ref_btn is not None and ref_btn.winfo_exists():
|
||||||
|
if view._result_dialog is not None or view._fx_overlay is not None or view.engine.street == "SHOWDOWN":
|
||||||
|
ref_btn.place_forget()
|
||||||
|
else:
|
||||||
|
ref_bw, ref_bh = ref_btn.pixel_width, ref_btn.pixel_height
|
||||||
|
ref_x = box_cx + box_w // 2 + 16
|
||||||
|
if ref_x + ref_bw > cw - pad_x - 6:
|
||||||
|
ref_x = max(pad_x + 6, box_cx - box_w // 2 - ref_bw - 16)
|
||||||
|
ref_y = zone_cy + box_h // 2 - ref_bh - 6
|
||||||
|
ref_btn.place(x=ref_x, y=ref_y, width=ref_bw, height=ref_bh)
|
||||||
|
tk.Widget.tkraise(ref_btn)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def collect_all_seats_reveal(eng, winner_names: list[str]) -> list[dict]:
|
||||||
|
win_set = set(winner_names)
|
||||||
|
entries = []
|
||||||
|
for s in eng.seats:
|
||||||
|
if s.hole_cards:
|
||||||
|
cat_id, _ = PokerEvaluator.evaluate_best(s.hole_cards + eng.board)
|
||||||
|
entries.append({
|
||||||
|
"name": s.name,
|
||||||
|
"cards": [[c.suit, c.rank] for c in s.hole_cards],
|
||||||
|
"folded": s.folded,
|
||||||
|
"cat_id": cat_id,
|
||||||
|
"is_winner": (s.name in win_set) and (not s.folded),
|
||||||
|
})
|
||||||
|
return entries
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def build_localized_popup_data(view, payload: dict) -> dict:
|
||||||
|
hand_desc = (
|
||||||
|
t("pk_popup_fold_win")
|
||||||
|
if payload["by_fold"]
|
||||||
|
else t(f"pk_hand_{payload['winning_hand_cat'] or 0}")
|
||||||
|
)
|
||||||
|
human_in_win = payload.get("human_in_winners", bool(payload.get("player_won")))
|
||||||
|
if human_in_win:
|
||||||
|
headline = (
|
||||||
|
t("pk_popup_split_won", hand_desc)
|
||||||
|
if payload["is_split"]
|
||||||
|
else t("pk_popup_player_won", hand_desc)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
headline = t(
|
||||||
|
"pk_popup_bot_won", ", ".join(payload["winner_names"]), hand_desc
|
||||||
|
)
|
||||||
|
|
||||||
|
other_gains = [
|
||||||
|
t("pk_popup_bot_gain", b_n, b_g)
|
||||||
|
for b_n, b_g in payload["bot_gains"]
|
||||||
|
if b_g > 0
|
||||||
|
]
|
||||||
|
lvl_to = payload["leveled_to"]
|
||||||
|
lvl_str = (
|
||||||
|
t("bj_popup_level_up", lvl_to, Progression.get_prestige_title(lvl_to))
|
||||||
|
if lvl_to is not None
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
|
seat_showdown = []
|
||||||
|
for s_rev in payload.get("seats_reveal", []):
|
||||||
|
raw_c = t(f"pk_hand_{s_rev['cat_id']}").strip()
|
||||||
|
short_c = raw_c.split(" (")[0] if len(raw_c) > 20 else raw_c
|
||||||
|
seat_showdown.append({
|
||||||
|
"name": s_rev["name"],
|
||||||
|
"cards": s_rev["cards"],
|
||||||
|
"folded": s_rev["folded"],
|
||||||
|
"is_winner": s_rev["is_winner"],
|
||||||
|
"combo_text": (
|
||||||
|
f"{t('pk_bot_act_fold')} ({short_c})"
|
||||||
|
if s_rev["folded"]
|
||||||
|
else short_c
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|
||||||
|
cur_gold = Database.get_poker_account(view.pk_account["id"])["gold"]
|
||||||
|
return {
|
||||||
|
"headline": headline,
|
||||||
|
"player_won": payload["player_won"],
|
||||||
|
"player_net": payload["player_net"],
|
||||||
|
"other_gains": other_gains,
|
||||||
|
"xp_gained": payload["xp_gained"],
|
||||||
|
"new_level_title": lvl_str,
|
||||||
|
"board_cards": payload.get("board_cards", []),
|
||||||
|
"seat_showdown": seat_showdown,
|
||||||
|
"can_continue": cur_gold >= view.cfg["min_entry"],
|
||||||
|
"can_leave_menu": not view.devils_locked,
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,178 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/poker/views/poker_hands_overlay.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
from PIL import Image, ImageTk
|
||||||
|
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
ACCENT_GOLD,
|
||||||
|
BG_COLOR,
|
||||||
|
FG_COLOR,
|
||||||
|
FONT_COLOR_BODY_MUTED,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_HEADING,
|
||||||
|
RED_SUITS,
|
||||||
|
SUIT_SYMBOLS,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
|
||||||
|
HAND_REFERENCE_EXAMPLES = (
|
||||||
|
(1, 9, (("A", "S"), ("K", "S"), ("Q", "S"), ("J", "S"), ("10", "S"))),
|
||||||
|
(2, 8, (("J", "S"), ("10", "S"), ("9", "S"), ("8", "S"), ("7", "S"))),
|
||||||
|
(3, 7, (("K", "H"), ("K", "C"), ("K", "D"), ("K", "S"), None)),
|
||||||
|
(4, 6, (("A", "H"), ("A", "C"), ("A", "D"), ("9", "S"), ("9", "H"))),
|
||||||
|
(5, 5, (("K", "S"), ("J", "S"), ("8", "S"), ("7", "S"), ("5", "S"))),
|
||||||
|
(6, 4, (("J", "H"), ("10", "C"), ("9", "D"), ("8", "S"), ("7", "H"))),
|
||||||
|
(7, 3, (("K", "H"), ("K", "C"), ("K", "D"), None, None)),
|
||||||
|
(8, 2, (("A", "H"), ("A", "C"), ("9", "D"), ("9", "S"), None)),
|
||||||
|
(9, 1, (("K", "H"), ("K", "C"), None, None, None)),
|
||||||
|
(10, 0, (("A", "H"), None, None, None, None)),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class PokerHandsOverlay(tk.Canvas):
|
||||||
|
"""Neutrale Kartenreferenz-Übersicht der 10 Poker-Hände (ohne Spoiler der eigenen Hand)."""
|
||||||
|
|
||||||
|
OVL_W = 800
|
||||||
|
OVL_H = 468
|
||||||
|
|
||||||
|
def __init__(self, parent, ctx, on_close):
|
||||||
|
super().__init__(
|
||||||
|
parent,
|
||||||
|
width=self.OVL_W,
|
||||||
|
height=self.OVL_H,
|
||||||
|
bg=BG_COLOR,
|
||||||
|
bd=0,
|
||||||
|
highlightthickness=0,
|
||||||
|
)
|
||||||
|
self.ctx = ctx
|
||||||
|
self.assets = ctx.assets
|
||||||
|
self.on_close = on_close
|
||||||
|
self._photo_refs: list = []
|
||||||
|
|
||||||
|
self.place(relx=0.5, rely=0.5, anchor="center")
|
||||||
|
tk.Widget.tkraise(self)
|
||||||
|
self._build_content()
|
||||||
|
|
||||||
|
def _draw_mini_cards(self, x0: int, y0: int, cards_spec: tuple):
|
||||||
|
cw, ch, gap = 22, 26, 3
|
||||||
|
for i, spec in enumerate(cards_spec):
|
||||||
|
cx = x0 + i * (cw + gap)
|
||||||
|
if spec is None:
|
||||||
|
self.create_rectangle(
|
||||||
|
cx, y0, cx + cw, y0 + ch,
|
||||||
|
fill="#261321", outline="#4e2942", width=1,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
rank, suit = spec
|
||||||
|
fg_col = "#cf3848" if suit in RED_SUITS else "#181421"
|
||||||
|
sym = SUIT_SYMBOLS.get(suit, suit)
|
||||||
|
self.create_rectangle(
|
||||||
|
cx, y0, cx + cw, y0 + ch,
|
||||||
|
fill="#ede8f5", outline="#8e82a6", width=1,
|
||||||
|
)
|
||||||
|
self.create_text(
|
||||||
|
cx + cw // 2, y0 + 8,
|
||||||
|
text=rank, font=("Helvetica", 7, "bold"), fill=fg_col,
|
||||||
|
)
|
||||||
|
self.create_text(
|
||||||
|
cx + cw // 2, y0 + 18,
|
||||||
|
text=sym, font=("Helvetica", 8, "bold"), fill=fg_col,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _build_content(self):
|
||||||
|
w, h = self.OVL_W, self.OVL_H
|
||||||
|
bg_src = self.assets.raw_bg_horizontal or self.assets.raw_bg_vertical or self.assets.raw_bg
|
||||||
|
if bg_src is not None:
|
||||||
|
bg_ph = ImageTk.PhotoImage(bg_src.resize((w, h), Image.Resampling.BILINEAR))
|
||||||
|
self._photo_refs.append(bg_ph)
|
||||||
|
self.create_image(0, 0, image=bg_ph, anchor="nw")
|
||||||
|
|
||||||
|
outer = self.assets.get_box_photo("box_big", (w - 6, h - 6))
|
||||||
|
if outer:
|
||||||
|
self._photo_refs.append(outer)
|
||||||
|
self.create_image(w // 2, h // 2, image=outer, anchor="center")
|
||||||
|
|
||||||
|
hdr_ph = self.assets.get_goth_text_photo(
|
||||||
|
t("pk_help_header"),
|
||||||
|
size_px=FONT_SIZE_HEADING,
|
||||||
|
color=FONT_COLOR_TITLE_MAIN,
|
||||||
|
align="center",
|
||||||
|
)
|
||||||
|
self._photo_refs.append(hdr_ph)
|
||||||
|
self.create_image(w // 2, 32, image=hdr_ph, anchor="center")
|
||||||
|
|
||||||
|
self.create_text(
|
||||||
|
w // 2,
|
||||||
|
60,
|
||||||
|
text=t("pk_help_general_info"),
|
||||||
|
font=("Helvetica", 9),
|
||||||
|
fill=FONT_COLOR_BODY_MUTED,
|
||||||
|
width=w - 80,
|
||||||
|
justify="center",
|
||||||
|
anchor="center",
|
||||||
|
)
|
||||||
|
|
||||||
|
col_w = (w - 76) // 2
|
||||||
|
row_h = 62
|
||||||
|
start_y = 86
|
||||||
|
|
||||||
|
cell_box_purp = self.assets.get_box_photo("box_purple", (col_w, row_h - 4))
|
||||||
|
if cell_box_purp:
|
||||||
|
self._photo_refs.append(cell_box_purp)
|
||||||
|
|
||||||
|
for rank_no, cat_id, cards_spec in HAND_REFERENCE_EXAMPLES:
|
||||||
|
col_idx = 0 if rank_no <= 5 else 1
|
||||||
|
row_idx = (rank_no - 1) % 5
|
||||||
|
cx = 30 + col_idx * (col_w + 16) + col_w // 2
|
||||||
|
cy = start_y + row_idx * row_h + (row_h - 4) // 2
|
||||||
|
left_edge = cx - col_w // 2
|
||||||
|
|
||||||
|
if cell_box_purp:
|
||||||
|
self.create_image(cx, cy, image=cell_box_purp, anchor="center")
|
||||||
|
|
||||||
|
self._draw_mini_cards(left_edge + 14, cy - 13, cards_spec)
|
||||||
|
|
||||||
|
raw_name = t(f"pk_hand_{cat_id}").replace("★ ", "").replace(" ★", "")
|
||||||
|
short_name = raw_name.split(" (")[0]
|
||||||
|
name_col = ACCENT_GOLD if rank_no == 1 else FG_COLOR
|
||||||
|
|
||||||
|
tip_raw = t(f"pk_help_hand_{cat_id}")
|
||||||
|
tip_short = tip_raw.split(":", 1)[-1].strip() if ":" in tip_raw else tip_raw
|
||||||
|
|
||||||
|
txt_x = left_edge + 142
|
||||||
|
txt_max_w = col_w - 154
|
||||||
|
|
||||||
|
self.create_text(
|
||||||
|
txt_x,
|
||||||
|
cy - 12,
|
||||||
|
text=f"{rank_no}. {short_name}",
|
||||||
|
font=("Helvetica", 9, "bold"),
|
||||||
|
fill=name_col,
|
||||||
|
anchor="w",
|
||||||
|
)
|
||||||
|
self.create_text(
|
||||||
|
txt_x,
|
||||||
|
cy + 9,
|
||||||
|
text=tip_short,
|
||||||
|
font=("Helvetica", 8),
|
||||||
|
fill=FONT_COLOR_BODY_MUTED,
|
||||||
|
width=txt_max_w,
|
||||||
|
anchor="w",
|
||||||
|
)
|
||||||
|
|
||||||
|
btn_fire = self.assets.raw_btn_fire or self.assets.raw_btn_purple
|
||||||
|
close_btn = ImageButton(
|
||||||
|
self,
|
||||||
|
t("pk_btn_close_help"),
|
||||||
|
btn_fire,
|
||||||
|
btn_fire,
|
||||||
|
self.on_close,
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=156,
|
||||||
|
height=34,
|
||||||
|
style="fire",
|
||||||
|
)
|
||||||
|
self.create_window(w // 2, h - 30, window=close_btn, anchor="center")
|
||||||
|
|
@ -1,452 +1,82 @@
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
# games/poker/views/poker_menu_view.py
|
# games/poker/views/poker_menu_view.py
|
||||||
import sqlite3
|
from __future__ import annotations
|
||||||
import tkinter as tk
|
|
||||||
from tkinter import ttk
|
|
||||||
|
|
||||||
from games.poker.views.poker_stats_view import PokerStatsView
|
|
||||||
from games.poker.views.poker_table_view import PokerTableView
|
from games.poker.views.poker_table_view import PokerTableView
|
||||||
from models.database import Database
|
from models.database import Database
|
||||||
from models.progression import Progression
|
|
||||||
from resources.code_res.game_constants import (
|
from resources.code_res.game_constants import (
|
||||||
ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BORDER_COLOR, CELL_BG,
|
GOLD_MAX_ACCOUNTS,
|
||||||
DEVILS_DEAL_GOLD_REWARD, ERROR_FG, FG_COLOR, GOLD_MAX_ACCOUNTS,
|
PK_MAX_BOTS,
|
||||||
INPUT_BG, MUTED_FG, PANEL_BG, PK_MAX_BOTS, PK_STARTING_GOLD,
|
PK_STARTING_GOLD,
|
||||||
PK_VARIANTS, SUBTLE_BORDER, XP_TO_GOLD_AMOUNT
|
PK_VARIANTS,
|
||||||
|
XP_TO_GOLD_AMOUNT,
|
||||||
)
|
)
|
||||||
from resources.code_res.i18n import t
|
from resources.code_res.i18n import t
|
||||||
from view.widgets.bot_setup_widget import BotSetupWidget
|
from view.widgets.luck_pouch_menu_base import LuckPouchMenuBase
|
||||||
from view.widgets.image_button import ImageButton
|
|
||||||
|
|
||||||
GAME_FOLDER_ID = "poker"
|
GAME_FOLDER_ID = "poker"
|
||||||
|
|
||||||
|
|
||||||
class PokerMenuView:
|
class PokerMenuView(LuckPouchMenuBase):
|
||||||
def __init__(self, context):
|
GAME_FOLDER_ID = GAME_FOLDER_ID
|
||||||
self.ctx = context
|
LAST_ACC_SETTING_PREFIX = "last_pk_account"
|
||||||
self.bot_widget: BotSetupWidget | None = None
|
STARTING_GOLD = PK_STARTING_GOLD
|
||||||
|
MAX_BOTS = PK_MAX_BOTS
|
||||||
|
REQUIRES_MIN_ONE_BOT = True
|
||||||
|
DEVILS_DEFAULT_VARIANT = "poker_holdem"
|
||||||
|
|
||||||
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
|
KEY_TOPBAR = "pk_menu_topbar"
|
||||||
pid = self.ctx.profile["id"]
|
KEY_HEADER_GOLD = "pk_header_gold"
|
||||||
|
KEY_SEC1_TITLE = "pk_sec1_title"
|
||||||
|
KEY_BOTS_TITLE = "pk_bots_sec_title"
|
||||||
|
KEY_SEC3_TITLE = "pk_sec3_title"
|
||||||
|
KEY_GOLD_DISPLAY = "pk_gold_display_lbl"
|
||||||
|
KEY_DEFAULT_ACC_NAME = "pk_default_acc_name"
|
||||||
|
KEY_ERR_DUPLICATE = "pk_err_duplicate_name"
|
||||||
|
|
||||||
devils_acc = Database.get_active_devils_pk_account(pid)
|
def _default_bot_configs(self) -> dict[int, tuple[str, int]]:
|
||||||
if devils_acc is not None:
|
return {
|
||||||
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
|
0: (t("bot_default_name", 1), 1),
|
||||||
if saved is not None:
|
1: (t("bot_default_name", 2), 2),
|
||||||
PokerTableView(
|
}
|
||||||
self.ctx,
|
|
||||||
variant_key=saved["variant_key"],
|
|
||||||
pk_account_id=devils_acc["id"],
|
|
||||||
bot_configs=[],
|
|
||||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
|
|
||||||
resume_state_json=saved["state_json"],
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
self.ctx.sounds.play_menu_music()
|
def _get_active_devils_account(self, pid: int):
|
||||||
self.ctx.root.clear_window(apply_global_bg=True)
|
return Database.get_active_devils_pk_account(pid)
|
||||||
pk_prog = self.ctx.refresh_game_progress()
|
|
||||||
|
|
||||||
dyn_xp_cost = pk_prog["xp_exchange_cost"]
|
def _get_accounts(self, pid: int):
|
||||||
is_divine = pk_prog["is_divine_punishment"]
|
return Database.get_poker_accounts(pid)
|
||||||
at_floor = pk_prog["at_divine_floor"]
|
|
||||||
devils_deal_open = pk_prog["devils_deal_unlocked"]
|
|
||||||
|
|
||||||
setting_key = f"last_pk_account_{pid}"
|
def _get_account(self, acc_id: int):
|
||||||
accounts = Database.get_poker_accounts(pid)
|
return Database.get_poker_account(acc_id)
|
||||||
has_accounts = len(accounts) > 0
|
|
||||||
|
|
||||||
if preselect_id is None and has_accounts:
|
def _create_account(self, pid: int, name: str):
|
||||||
saved_id_str = Database.load_setting(setting_key, "")
|
return Database.create_poker_account(pid, name)
|
||||||
if saved_id_str.isdigit():
|
|
||||||
preselect_id = int(saved_id_str)
|
|
||||||
|
|
||||||
acc_by_name = {a["account_name"]: a for a in accounts}
|
def _delete_account(self, acc_id: int):
|
||||||
acc_names = list(acc_by_name.keys())
|
Database.delete_poker_account(acc_id)
|
||||||
|
|
||||||
active_acc = None
|
def _exchange_xp(self, pid: int, acc_id: int):
|
||||||
if has_accounts:
|
return Database.exchange_xp_for_pk_gold(pid, acc_id)
|
||||||
active_acc = accounts[0]
|
|
||||||
if preselect_id is not None:
|
|
||||||
for a in accounts:
|
|
||||||
if a["id"] == preselect_id:
|
|
||||||
active_acc = a
|
|
||||||
break
|
|
||||||
Database.save_setting(setting_key, str(active_acc["id"]))
|
|
||||||
|
|
||||||
selected_name_var = tk.StringVar(
|
def _variants_dict(self) -> dict[str, dict]:
|
||||||
value=active_acc["account_name"] if active_acc else t("bj_no_account_item")
|
return PK_VARIANTS
|
||||||
|
|
||||||
|
def _min_entry_for_variant(self, _v_key: str, cfg: dict) -> int:
|
||||||
|
return cfg["min_entry"]
|
||||||
|
|
||||||
|
def _format_variant_desc(self, _v_key: str, cfg: dict) -> str:
|
||||||
|
return t("pk_variant_desc", cfg["sb"], cfg["bb"], cfg["min_entry"])
|
||||||
|
|
||||||
|
def _format_limit_info(self, dyn_xp_cost: int) -> str:
|
||||||
|
classic = PK_VARIANTS["poker_holdem"]
|
||||||
|
return t("pk_acc_limit_info", GOLD_MAX_ACCOUNTS, classic["sb"], classic["bb"], dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
||||||
|
|
||||||
|
def _launch_table(self, variant_key: str, acc_id: int, bots: list, resume_json: str | None = None):
|
||||||
|
PokerTableView(
|
||||||
|
self.ctx,
|
||||||
|
variant_key=variant_key,
|
||||||
|
pk_account_id=acc_id,
|
||||||
|
bot_configs=bots,
|
||||||
|
on_back_to_menu=lambda aid, msg="": self.show(preselect_id=aid, status_msg=msg),
|
||||||
|
resume_state_json=resume_json,
|
||||||
)
|
)
|
||||||
feedback_var = tk.StringVar(value=status_msg)
|
|
||||||
|
|
||||||
def get_current_acc() -> dict | None:
|
|
||||||
return acc_by_name.get(selected_name_var.get())
|
|
||||||
|
|
||||||
def open_pk_stats():
|
|
||||||
cur = get_current_acc()
|
|
||||||
if cur is None:
|
|
||||||
return
|
|
||||||
if self.bot_widget is not None and has_accounts:
|
|
||||||
_, to_save = self.bot_widget.collect_configs()
|
|
||||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
|
||||||
PokerStatsView(
|
|
||||||
self.ctx,
|
|
||||||
on_back_to_pk_menu=lambda aid: self.show(preselect_id=aid)
|
|
||||||
).show(selected_acc_id=cur["id"])
|
|
||||||
|
|
||||||
def refresh_on_lang_switch():
|
|
||||||
cur = get_current_acc()
|
|
||||||
if self.bot_widget is not None and has_accounts:
|
|
||||||
_, to_save = self.bot_widget.collect_configs()
|
|
||||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
|
||||||
self.show(preselect_id=cur["id"] if cur else None)
|
|
||||||
|
|
||||||
topbar_gold_txt = (
|
|
||||||
t("pk_header_gold", active_acc["account_name"], active_acc["gold"])
|
|
||||||
if active_acc else ""
|
|
||||||
)
|
|
||||||
topbar = self.ctx.build_game_topbar(
|
|
||||||
self.ctx.root,
|
|
||||||
t("pk_menu_topbar"),
|
|
||||||
on_game_menu=None,
|
|
||||||
on_stats=open_pk_stats,
|
|
||||||
stats_enabled=has_accounts,
|
|
||||||
extra_right_text=topbar_gold_txt,
|
|
||||||
on_lang_refresh=refresh_on_lang_switch,
|
|
||||||
)
|
|
||||||
|
|
||||||
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=12)
|
|
||||||
container.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.93, relheight=0.85)
|
|
||||||
|
|
||||||
main_card = tk.Frame(
|
|
||||||
container, bg=PANEL_BG, padx=24, pady=16,
|
|
||||||
highlightthickness=1, highlightbackground=BORDER_COLOR
|
|
||||||
)
|
|
||||||
main_card.pack(fill="x")
|
|
||||||
|
|
||||||
upper_split = tk.Frame(main_card, bg=PANEL_BG)
|
|
||||||
upper_split.pack(fill="x", pady=(0, 10))
|
|
||||||
upper_split.columnconfigure(0, weight=1, uniform="cols")
|
|
||||||
upper_split.columnconfigure(1, weight=1, uniform="cols")
|
|
||||||
|
|
||||||
# =====================================================================
|
|
||||||
# SPALTE 1: Poker-Goldkonto
|
|
||||||
# =====================================================================
|
|
||||||
left_col = tk.Frame(upper_split, bg=PANEL_BG)
|
|
||||||
left_col.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
left_col,
|
|
||||||
text=t("pk_sec1_title", len(accounts), GOLD_MAX_ACCOUNTS, PK_STARTING_GOLD),
|
|
||||||
font=("Georgia", 12, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG
|
|
||||||
).pack(anchor="w", pady=(0, 6))
|
|
||||||
|
|
||||||
acc_box = tk.Frame(left_col, bg=CELL_BG, padx=14, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
|
|
||||||
acc_box.pack(fill="both", expand=True)
|
|
||||||
|
|
||||||
form_grid = tk.Frame(acc_box, bg=CELL_BG)
|
|
||||||
form_grid.pack(fill="x")
|
|
||||||
form_grid.columnconfigure(1, weight=1)
|
|
||||||
|
|
||||||
lbl_w = max(len(t("bj_active_acc_lbl")), len(t("bj_new_acc_lbl")))
|
|
||||||
tk.Label(
|
|
||||||
form_grid, text=t("bj_active_acc_lbl"), width=lbl_w, anchor="w",
|
|
||||||
font=("Helvetica", 10, "bold"), fg=FG_COLOR if has_accounts else MUTED_FG, bg=CELL_BG
|
|
||||||
).grid(row=0, column=0, sticky="w", padx=(0, 10), pady=4)
|
|
||||||
|
|
||||||
acc_cb = ttk.Combobox(
|
|
||||||
form_grid,
|
|
||||||
textvariable=selected_name_var,
|
|
||||||
values=acc_names if has_accounts else [t("bj_no_account_item")],
|
|
||||||
state="readonly" if has_accounts else "disabled",
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
style="Goth.TCombobox",
|
|
||||||
)
|
|
||||||
acc_cb.grid(row=0, column=1, sticky="ew", padx=(0, 10), pady=4, ipady=2)
|
|
||||||
|
|
||||||
def exchange_xp_action():
|
|
||||||
cur = get_current_acc()
|
|
||||||
if cur is None:
|
|
||||||
return
|
|
||||||
if self.bot_widget is not None:
|
|
||||||
_, to_save = self.bot_widget.collect_configs()
|
|
||||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
|
||||||
ok, msg = Database.exchange_xp_for_pk_gold(pid, cur["id"])
|
|
||||||
if ok and is_divine:
|
|
||||||
self.ctx.sounds.play("lose")
|
|
||||||
self.show(preselect_id=cur["id"], status_msg=msg, status_is_ok=ok)
|
|
||||||
|
|
||||||
can_afford_xp = is_divine or (pk_prog["total_points"] >= dyn_xp_cost)
|
|
||||||
can_exchange = has_accounts and (not at_floor) and can_afford_xp
|
|
||||||
|
|
||||||
ex_btn_txt = (
|
|
||||||
t("bj_exchange_divine_btn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
|
|
||||||
if is_divine else t("bj_exchange_btn", dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
|
||||||
)
|
|
||||||
ImageButton(
|
|
||||||
form_grid, ex_btn_txt,
|
|
||||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
|
||||||
exchange_xp_action, sound_mgr=self.ctx.sounds,
|
|
||||||
width=185, height=34, font=("Helvetica", 9, "bold"),
|
|
||||||
enabled=can_exchange,
|
|
||||||
).grid(row=0, column=2, sticky="e", pady=4)
|
|
||||||
|
|
||||||
# Prominente Gold-Anzeige
|
|
||||||
gold_banner = tk.Frame(
|
|
||||||
acc_box, bg=PANEL_BG, padx=12, pady=8,
|
|
||||||
highlightthickness=1, highlightbackground=BORDER_COLOR if has_accounts else SUBTLE_BORDER
|
|
||||||
)
|
|
||||||
gold_banner.pack(fill="x", pady=(8, 8))
|
|
||||||
|
|
||||||
gold_var = tk.StringVar(
|
|
||||||
value=t("bj_gold_display_lbl", active_acc["gold"]) if active_acc else t("bj_gold_display_none")
|
|
||||||
)
|
|
||||||
tk.Label(
|
|
||||||
gold_banner, textvariable=gold_var,
|
|
||||||
font=("Georgia", 13, "bold"),
|
|
||||||
fg=ACCENT_GOLD if active_acc else MUTED_FG,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(side="left")
|
|
||||||
|
|
||||||
def delete_selected_account():
|
|
||||||
cur = get_current_acc()
|
|
||||||
if cur is not None:
|
|
||||||
Database.delete_poker_account(cur["id"])
|
|
||||||
self.show()
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
gold_banner, t("bj_delete_acc_btn"),
|
|
||||||
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
|
|
||||||
delete_selected_account, sound_mgr=self.ctx.sounds,
|
|
||||||
width=120, height=30, font=("Helvetica", 9, "bold"),
|
|
||||||
enabled=has_accounts,
|
|
||||||
).pack(side="right")
|
|
||||||
|
|
||||||
# Neues Konto anlegen (exakt gleiche Spaltenbreite)
|
|
||||||
create_grid = tk.Frame(acc_box, bg=CELL_BG)
|
|
||||||
create_grid.pack(fill="x")
|
|
||||||
create_grid.columnconfigure(1, weight=1)
|
|
||||||
|
|
||||||
can_create_more = len(accounts) < GOLD_MAX_ACCOUNTS
|
|
||||||
tk.Label(
|
|
||||||
create_grid, text=t("bj_new_acc_lbl"), width=lbl_w, anchor="w",
|
|
||||||
font=("Helvetica", 10, "bold" if not has_accounts else "normal"),
|
|
||||||
fg=ACCENT_GOLD if not has_accounts else (FG_COLOR if can_create_more else MUTED_FG),
|
|
||||||
bg=CELL_BG,
|
|
||||||
).grid(row=0, column=0, sticky="w", padx=(0, 10), pady=4)
|
|
||||||
|
|
||||||
next_idx = len(accounts) + 1
|
|
||||||
new_acc_var = tk.StringVar(
|
|
||||||
value=t("pk_default_acc_name", next_idx) if can_create_more else t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS)
|
|
||||||
)
|
|
||||||
new_entry = tk.Entry(
|
|
||||||
create_grid, textvariable=new_acc_var, font=("Helvetica", 10),
|
|
||||||
bg=INPUT_BG, fg=FG_COLOR, disabledbackground="#16141c", disabledforeground="#666070",
|
|
||||||
bd=0, highlightthickness=1, highlightbackground=ACCENT_GOLD if not has_accounts else BORDER_COLOR,
|
|
||||||
insertbackground="white", state="normal" if can_create_more else "disabled"
|
|
||||||
)
|
|
||||||
new_entry.grid(row=0, column=1, sticky="ew", padx=(0, 10), pady=4, ipady=5)
|
|
||||||
|
|
||||||
def create_new_account():
|
|
||||||
if not can_create_more:
|
|
||||||
return
|
|
||||||
name = new_acc_var.get().strip()
|
|
||||||
if not name:
|
|
||||||
feedback_var.set(t("bj_err_empty_name"))
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
if self.bot_widget is not None and has_accounts:
|
|
||||||
_, to_save = self.bot_widget.collect_configs()
|
|
||||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
|
||||||
created = Database.create_poker_account(pid, name)
|
|
||||||
Database.save_setting(setting_key, str(created["id"]))
|
|
||||||
self.show(preselect_id=created["id"])
|
|
||||||
except (sqlite3.IntegrityError, RuntimeError) as exc:
|
|
||||||
feedback_var.set(t("pk_err_duplicate_name") if isinstance(exc, sqlite3.IntegrityError) else str(exc))
|
|
||||||
|
|
||||||
if can_create_more:
|
|
||||||
new_entry.bind("<Return>", lambda _e: create_new_account())
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
create_grid, t("bj_create_acc_btn", PK_STARTING_GOLD),
|
|
||||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
|
||||||
create_new_account, sound_mgr=self.ctx.sounds,
|
|
||||||
width=185, height=34, font=("Helvetica", 9, "bold"),
|
|
||||||
enabled=can_create_more,
|
|
||||||
).grid(row=0, column=2, sticky="e", pady=4)
|
|
||||||
|
|
||||||
# Info / Divine Punishment / The Devil's Deal (Poker-autark!)
|
|
||||||
min_sac_lvl = Progression.get_devils_deal_min_level()
|
|
||||||
classic_cfg = PK_VARIANTS["poker_holdem"]
|
|
||||||
if devils_deal_open and has_accounts:
|
|
||||||
tk.Label(
|
|
||||||
acc_box,
|
|
||||||
text=t("bj_devils_deal_warn", min_sac_lvl, DEVILS_DEAL_GOLD_REWARD),
|
|
||||||
font=("Helvetica", 8, "bold"), fg=ERROR_FG, bg=CELL_BG, wraplength=480, justify="left"
|
|
||||||
).pack(anchor="w", pady=(6, 4))
|
|
||||||
|
|
||||||
sac_candidates = Database.get_sacrificeable_profiles(pid, GAME_FOLDER_ID)
|
|
||||||
if sac_candidates:
|
|
||||||
devil_row = tk.Frame(acc_box, bg=CELL_BG)
|
|
||||||
devil_row.pack(fill="x", pady=(2, 0))
|
|
||||||
sac_map = {f"{c['name']} ({c['title']} • Lv. {c['level']})": c["id"] for c in sac_candidates}
|
|
||||||
sac_var = tk.StringVar(value=next(iter(sac_map.keys())))
|
|
||||||
ttk.Combobox(
|
|
||||||
devil_row, textvariable=sac_var, values=list(sac_map.keys()),
|
|
||||||
state="readonly", font=("Helvetica", 9), width=26, style="Goth.TCombobox"
|
|
||||||
).pack(side="left", fill="x", expand=True, padx=(0, 8))
|
|
||||||
|
|
||||||
def seal_devils_deal():
|
|
||||||
cur = get_current_acc()
|
|
||||||
victim_id = sac_map.get(sac_var.get())
|
|
||||||
if cur is None or victim_id is None:
|
|
||||||
return
|
|
||||||
active_bots, to_save = self.bot_widget.collect_configs() if self.bot_widget else ([], {})
|
|
||||||
if not active_bots:
|
|
||||||
feedback_var.set(t("pk_err_need_one_bot"))
|
|
||||||
return
|
|
||||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
|
||||||
ok, _msg = Database.execute_devils_deal(pid, GAME_FOLDER_ID, victim_id, cur["id"])
|
|
||||||
if ok:
|
|
||||||
self.ctx.sounds.play("end_battle")
|
|
||||||
PokerTableView(
|
|
||||||
self.ctx,
|
|
||||||
variant_key="poker_holdem",
|
|
||||||
pk_account_id=cur["id"],
|
|
||||||
bot_configs=active_bots,
|
|
||||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
|
|
||||||
)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
devil_row, t("bj_devils_deal_btn", DEVILS_DEAL_GOLD_REWARD),
|
|
||||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
|
||||||
seal_devils_deal, sound_mgr=None, width=185, height=32, font=("Helvetica", 9, "bold")
|
|
||||||
).pack(side="right")
|
|
||||||
else:
|
|
||||||
tk.Label(
|
|
||||||
acc_box, text=t("bj_devils_deal_none", min_sac_lvl),
|
|
||||||
font=("Helvetica", 8), fg=MUTED_FG, bg=CELL_BG
|
|
||||||
).pack(anchor="w")
|
|
||||||
else:
|
|
||||||
info_text = (
|
|
||||||
t("bj_divine_punishment_warn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
|
|
||||||
if is_divine
|
|
||||||
else t("pk_acc_limit_info", GOLD_MAX_ACCOUNTS, classic_cfg["sb"], classic_cfg["bb"], dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
|
||||||
)
|
|
||||||
tk.Label(
|
|
||||||
acc_box, text=info_text,
|
|
||||||
font=("Helvetica", 8, "bold" if is_divine else "normal"),
|
|
||||||
fg=ERROR_FG if is_divine else MUTED_FG,
|
|
||||||
bg=CELL_BG, wraplength=480, justify="left"
|
|
||||||
).pack(anchor="w", pady=(6, 0))
|
|
||||||
|
|
||||||
# =====================================================================
|
|
||||||
# SPALTE 2: 6-Max Gegner-Setup (1 bis 5 Bots)
|
|
||||||
# =====================================================================
|
|
||||||
right_col = tk.Frame(upper_split, bg=PANEL_BG)
|
|
||||||
right_col.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
right_col, text=t("pk_bots_sec_title"),
|
|
||||||
font=("Georgia", 12, "bold"), fg=ACCENT_GOTH if has_accounts else MUTED_FG, bg=PANEL_BG
|
|
||||||
).pack(anchor="w", pady=(0, 6))
|
|
||||||
|
|
||||||
saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID)
|
|
||||||
if not saved_bots:
|
|
||||||
# Komfort-Default beim allerersten Poker-Besuch: 2 solide Gegner voreingestellt
|
|
||||||
saved_bots = {
|
|
||||||
0: (t("bot_default_name", 1), 1),
|
|
||||||
1: (t("bot_default_name", 2), 2),
|
|
||||||
}
|
|
||||||
self.bot_widget = BotSetupWidget(right_col, saved_bots, max_bots=PK_MAX_BOTS, enabled=has_accounts)
|
|
||||||
self.bot_widget.pack(fill="both", expand=True)
|
|
||||||
|
|
||||||
fb_lbl = tk.Label(
|
|
||||||
main_card, textvariable=feedback_var,
|
|
||||||
font=("Helvetica", 9, "bold"),
|
|
||||||
fg="#7be08a" if status_is_ok else ERROR_FG,
|
|
||||||
bg=PANEL_BG
|
|
||||||
)
|
|
||||||
fb_lbl.pack(anchor="w", pady=(2, 4))
|
|
||||||
|
|
||||||
# =====================================================================
|
|
||||||
# SEKTION 3: Tischvariante wählen
|
|
||||||
# =====================================================================
|
|
||||||
tk.Label(
|
|
||||||
main_card, text=t("pk_sec3_title"),
|
|
||||||
font=("Georgia", 12, "bold"), fg=ACCENT_GOTH if has_accounts else MUTED_FG, bg=PANEL_BG
|
|
||||||
).pack(anchor="w", pady=(2, 8))
|
|
||||||
|
|
||||||
def enter_table(v_key: str):
|
|
||||||
fb_lbl.configure(fg=ERROR_FG)
|
|
||||||
cur = get_current_acc()
|
|
||||||
if not cur:
|
|
||||||
return
|
|
||||||
acc = Database.get_poker_account(cur["id"])
|
|
||||||
if not acc:
|
|
||||||
return
|
|
||||||
Database.save_setting(setting_key, str(acc["id"]))
|
|
||||||
active_bots, configs_to_save = self.bot_widget.collect_configs()
|
|
||||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, configs_to_save)
|
|
||||||
|
|
||||||
if not active_bots:
|
|
||||||
feedback_var.set(t("pk_err_need_one_bot"))
|
|
||||||
return
|
|
||||||
|
|
||||||
min_req = PK_VARIANTS[v_key]["min_entry"]
|
|
||||||
cur_pk_prog = self.ctx.refresh_game_progress()
|
|
||||||
if acc["gold"] < min_req:
|
|
||||||
feedback_var.set(t(
|
|
||||||
"bj_err_not_enough_gold_entry",
|
|
||||||
acc["account_name"], min_req, acc["gold"],
|
|
||||||
cur_pk_prog["xp_exchange_cost"], XP_TO_GOLD_AMOUNT
|
|
||||||
))
|
|
||||||
return
|
|
||||||
|
|
||||||
PokerTableView(
|
|
||||||
self.ctx, v_key, acc["id"], active_bots,
|
|
||||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg)
|
|
||||||
)
|
|
||||||
|
|
||||||
variants_row = tk.Frame(main_card, bg=PANEL_BG)
|
|
||||||
variants_row.pack(fill="x")
|
|
||||||
for idx in range(len(PK_VARIANTS)):
|
|
||||||
variants_row.columnconfigure(idx, weight=1)
|
|
||||||
|
|
||||||
table_buttons: list[tuple[str, ImageButton]] = []
|
|
||||||
for idx, (v_key, cfg) in enumerate(PK_VARIANTS.items()):
|
|
||||||
card = tk.Frame(variants_row, bg=CELL_BG, padx=16, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
|
|
||||||
card.grid(row=0, column=idx, padx=(0, 8) if idx == 0 else (8, 0), sticky="nsew")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
card, text=t(f"variant_{v_key}"),
|
|
||||||
font=("Georgia", 12, "bold"), fg=FG_COLOR if has_accounts else MUTED_FG, bg=CELL_BG
|
|
||||||
).pack(anchor="w")
|
|
||||||
tk.Label(
|
|
||||||
card, text=t("pk_variant_desc", cfg["sb"], cfg["bb"], cfg["min_entry"]),
|
|
||||||
font=("Helvetica", 9), fg=MUTED_FG, bg=CELL_BG
|
|
||||||
).pack(anchor="w", pady=(4, 10))
|
|
||||||
|
|
||||||
can_play_v = bool(active_acc and active_acc["gold"] >= cfg["min_entry"])
|
|
||||||
t_btn = ImageButton(
|
|
||||||
card, t("bj_enter_table_btn"),
|
|
||||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
|
||||||
lambda k=v_key: enter_table(k),
|
|
||||||
sound_mgr=self.ctx.sounds, width=160, height=36,
|
|
||||||
font=("Helvetica", 10, "bold"), enabled=can_play_v,
|
|
||||||
)
|
|
||||||
t_btn.pack(anchor="e")
|
|
||||||
table_buttons.append((v_key, t_btn))
|
|
||||||
|
|
||||||
def on_account_switched(*_):
|
|
||||||
cur = get_current_acc()
|
|
||||||
if cur is not None:
|
|
||||||
fresh = Database.get_poker_account(cur["id"])
|
|
||||||
Database.save_setting(setting_key, str(fresh["id"]))
|
|
||||||
gold_var.set(t("bj_gold_display_lbl", fresh["gold"]))
|
|
||||||
topbar.extra_label.configure(text=t("pk_header_gold", fresh["account_name"], fresh["gold"]))
|
|
||||||
for v_k, tb in table_buttons:
|
|
||||||
tb.set_enabled(fresh["gold"] >= PK_VARIANTS[v_k]["min_entry"])
|
|
||||||
feedback_var.set("")
|
|
||||||
|
|
||||||
acc_cb.bind("<<ComboboxSelected>>", on_account_switched)
|
|
||||||
|
|
@ -1,204 +1,129 @@
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
# games/poker/views/poker_result_dialog.py
|
# games/poker/views/poker_result_dialog.py
|
||||||
import tkinter as tk
|
from __future__ import annotations
|
||||||
|
|
||||||
from models.card import Card
|
from models.card import Card
|
||||||
from resources.code_res.game_constants import (
|
from resources.code_res.game_constants import (
|
||||||
ACCENT_GOLD, ACCENT_GOTH, CELL_BG, ERROR_FG,
|
FONT_COLOR_BODY_DEFAULT,
|
||||||
FG_COLOR, MODAL_BG, MUTED_FG, SUBTLE_BORDER
|
FONT_COLOR_BODY_MUTED,
|
||||||
|
FONT_COLOR_HEADING_SUB,
|
||||||
|
FONT_COLOR_STATUS_LOSS,
|
||||||
|
FONT_COLOR_STATUS_WIN,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_SMALL_MIN,
|
||||||
)
|
)
|
||||||
from resources.code_res.i18n import t
|
from resources.code_res.i18n import t
|
||||||
from view.widgets.image_button import ImageButton
|
from view.widgets.casino_result_dialog_base import CasinoResultDialogBase
|
||||||
|
|
||||||
POPUP_GIF_SIZE = (145, 80)
|
POPUP_HOLE_CARD_SIZE = (46, 68)
|
||||||
POPUP_HOLE_CARD_SIZE = (48, 70)
|
|
||||||
POPUP_BOARD_CARD_SIZE = (44, 64)
|
POPUP_BOARD_CARD_SIZE = (44, 64)
|
||||||
|
|
||||||
|
|
||||||
class PokerResultDialog(tk.Frame):
|
class PokerResultDialog(CasinoResultDialogBase):
|
||||||
"""Ergebnis-Overlay im einheitlichen BlackjackResultDialog-Stil inkl. Kartenbild-Showdown."""
|
"""Gothic-Showdown-Overlay für Texas Hold'em auf Basis von CasinoResultDialogBase."""
|
||||||
def __init__(
|
|
||||||
self,
|
def __init__(self, parent, assets, sounds, result_data: dict, on_next_round, on_back_to_menu):
|
||||||
parent,
|
seats = result_data.get("seat_showdown", [])
|
||||||
assets,
|
has_board = bool(result_data.get("board_cards"))
|
||||||
sounds,
|
cols = min(3, max(1, len(seats)))
|
||||||
result_data: dict,
|
rows = (len(seats) + 2) // 3 if seats else 0
|
||||||
on_next_round,
|
extra_lines = len(result_data.get("other_gains", []))
|
||||||
on_back_to_menu,
|
|
||||||
):
|
dlg_w = max(580, min(840, cols * 252 + 64))
|
||||||
super().__init__(
|
dlg_h = (
|
||||||
parent, bg=MODAL_BG, padx=26, pady=18,
|
62
|
||||||
highlightthickness=2, highlightbackground=ACCENT_GOTH
|
+ (86 if has_board else 8)
|
||||||
|
+ (rows * 134 + 14 if rows else 0)
|
||||||
|
+ 92 + min(2, extra_lines) * 20
|
||||||
|
+ (24 if result_data.get("new_level_title") else 0)
|
||||||
|
+ 62
|
||||||
)
|
)
|
||||||
self.assets = assets
|
super().__init__(parent, assets, sounds, result_data, dlg_w, dlg_h, on_next_round, on_back_to_menu)
|
||||||
self.sounds = sounds
|
|
||||||
self.data = result_data
|
|
||||||
self.on_next_round = on_next_round
|
|
||||||
self.on_back_to_menu = on_back_to_menu
|
|
||||||
self._gif_job = None
|
|
||||||
self._card_photos = []
|
|
||||||
|
|
||||||
self.place(relx=0.5, rely=0.5, anchor="center")
|
|
||||||
self.lift()
|
|
||||||
self._build()
|
|
||||||
|
|
||||||
def _build(self):
|
|
||||||
self.gif_lbl = tk.Label(self, bg=MODAL_BG, bd=0)
|
|
||||||
self.gif_lbl.pack(pady=(0, 4))
|
|
||||||
|
|
||||||
p_won = self.data.get("player_won")
|
|
||||||
if p_won is True:
|
|
||||||
self._start_gif("win_gif")
|
|
||||||
elif p_won is False:
|
|
||||||
self._start_gif("lose_gif")
|
|
||||||
|
|
||||||
headline_color = ACCENT_GOLD if p_won else (
|
|
||||||
MUTED_FG if p_won is None else ERROR_FG
|
|
||||||
)
|
|
||||||
tk.Label(
|
|
||||||
self, text=self.data["headline"],
|
|
||||||
font=("Georgia", 16, "bold"), fg=headline_color, bg=MODAL_BG,
|
|
||||||
wraplength=680, justify="center"
|
|
||||||
).pack(pady=(2, 10))
|
|
||||||
|
|
||||||
# --- Karten-Aufdeckung: Gemeinschaftskarten + alle Sitze mit Kartenbildern ---
|
|
||||||
reveal_box = tk.Frame(
|
|
||||||
self, bg=CELL_BG, padx=12, pady=8,
|
|
||||||
highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
|
||||||
)
|
|
||||||
reveal_box.pack(fill="x", pady=(0, 10))
|
|
||||||
|
|
||||||
|
def _draw_showdown_middle(self, w: int, cx: int, cur_y: int) -> int:
|
||||||
board_raw = self.data.get("board_cards", [])
|
board_raw = self.data.get("board_cards", [])
|
||||||
if board_raw:
|
if board_raw:
|
||||||
b_row = tk.Frame(reveal_box, bg=CELL_BG)
|
b_box_h = 76
|
||||||
b_row.pack(pady=(0, 6))
|
b_cy = cur_y + b_box_h // 2
|
||||||
tk.Label(
|
b_box = self.assets.get_box_photo("box_gold_double", (w - 56, b_box_h))
|
||||||
b_row, text=f"{t('pk_board_title')}:",
|
if b_box:
|
||||||
font=("Georgia", 9, "bold"), fg=MUTED_FG, bg=CELL_BG
|
self._photo_refs.append(b_box)
|
||||||
).pack(side="left", padx=(0, 8))
|
self.create_image(cx, b_cy, image=b_box, anchor="center")
|
||||||
|
|
||||||
for s_suit, s_rank in board_raw:
|
lbl_ph = self.assets.get_goth_text_photo(
|
||||||
c_obj = Card(s_suit, s_rank)
|
f"{t('pk_board_title')}:", FONT_SIZE_SMALL_MIN, FONT_COLOR_HEADING_SUB, align="left"
|
||||||
ph = self.assets.get_card_photo(c_obj.image_filename, size=POPUP_BOARD_CARD_SIZE)
|
|
||||||
if ph:
|
|
||||||
self._card_photos.append(ph)
|
|
||||||
tk.Label(b_row, image=ph, bg=CELL_BG, bd=0).pack(side="left", padx=2)
|
|
||||||
|
|
||||||
tk.Frame(reveal_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(2, 6))
|
|
||||||
|
|
||||||
seats_row = tk.Frame(reveal_box, bg=CELL_BG)
|
|
||||||
seats_row.pack()
|
|
||||||
|
|
||||||
for idx, entry in enumerate(self.data.get("seat_showdown", [])):
|
|
||||||
is_win = entry["is_winner"]
|
|
||||||
folded = entry["folded"]
|
|
||||||
|
|
||||||
border_c = ACCENT_GOLD if is_win else (SUBTLE_BORDER if not folded else "#3a252a")
|
|
||||||
s_card = tk.Frame(
|
|
||||||
seats_row, bg="#191521", padx=8, pady=5,
|
|
||||||
highlightthickness=2 if is_win else 1, highlightbackground=border_c
|
|
||||||
)
|
)
|
||||||
s_card.grid(row=idx // 6, column=idx % 6, padx=4, pady=2, sticky="nsew")
|
self._photo_refs.append(lbl_ph)
|
||||||
|
|
||||||
name_col = ACCENT_GOLD if is_win else (MUTED_FG if folded else ACCENT_GOTH)
|
b_photos = []
|
||||||
tk.Label(
|
for s_suit, s_rank in board_raw:
|
||||||
s_card, text=entry["name"],
|
ph = self.assets.get_card_photo(Card(s_suit, s_rank).image_filename, size=POPUP_BOARD_CARD_SIZE)
|
||||||
font=("Georgia", 9, "bold"), fg=name_col, bg="#191521"
|
|
||||||
).pack()
|
|
||||||
|
|
||||||
c_frame = tk.Frame(s_card, bg="#191521", height=POPUP_HOLE_CARD_SIZE[1] + 2)
|
|
||||||
c_frame.pack(pady=3)
|
|
||||||
for s_suit, s_rank in entry["cards"]:
|
|
||||||
c_obj = Card(s_suit, s_rank)
|
|
||||||
ph = self.assets.get_card_photo(c_obj.image_filename, size=POPUP_HOLE_CARD_SIZE)
|
|
||||||
if ph:
|
if ph:
|
||||||
self._card_photos.append(ph)
|
self._photo_refs.append(ph)
|
||||||
tk.Label(c_frame, image=ph, bg="#191521", bd=0).pack(side="left", padx=1)
|
b_photos.append(ph)
|
||||||
|
|
||||||
combo_col = "#7be08a" if is_win else (ERROR_FG if folded else FG_COLOR)
|
cw_b, ch_b = POPUP_BOARD_CARD_SIZE
|
||||||
tk.Label(
|
cards_w = len(b_photos) * cw_b + max(0, len(b_photos) - 1) * 6
|
||||||
s_card, text=entry["combo_text"],
|
total_w = lbl_ph.width() + 14 + cards_w
|
||||||
font=("Helvetica", 8, "bold"), fg=combo_col, bg="#191521",
|
start_x = cx - total_w // 2
|
||||||
wraplength=112, justify="center"
|
|
||||||
).pack()
|
|
||||||
|
|
||||||
# --- Gewinn / Verlust & XP Box (identisch zu BlackjackResultDialog) ---
|
self.create_image(start_x, b_cy, image=lbl_ph, anchor="w")
|
||||||
info_box = tk.Frame(
|
cx_card = start_x + lbl_ph.width() + 14
|
||||||
self, bg=CELL_BG, padx=20, pady=10,
|
for bph in b_photos:
|
||||||
highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
self.create_image(cx_card, b_cy - ch_b // 2, image=bph, anchor="nw")
|
||||||
)
|
cx_card += cw_b + 6
|
||||||
info_box.pack(fill="x", pady=(0, 12))
|
|
||||||
|
|
||||||
p_net = self.data["player_net"]
|
cur_y += b_box_h + 8
|
||||||
if p_net > 0:
|
|
||||||
own_txt, own_col = t("bj_popup_your_gain", p_net), "#7be08a"
|
|
||||||
elif p_net < 0:
|
|
||||||
own_txt, own_col = t("bj_popup_your_loss", abs(p_net)), ERROR_FG
|
|
||||||
else:
|
|
||||||
own_txt, own_col = t("bj_popup_your_even"), FG_COLOR
|
|
||||||
|
|
||||||
tk.Label(info_box, text=own_txt, font=("Helvetica", 11, "bold"), fg=own_col, bg=CELL_BG).pack(pady=2)
|
seats = self.data.get("seat_showdown", [])
|
||||||
|
if not seats:
|
||||||
|
return cur_y
|
||||||
|
|
||||||
for extra_line in self.data.get("other_gains", []):
|
max_cols = 3
|
||||||
tk.Label(info_box, text=extra_line, font=("Helvetica", 10), fg=MUTED_FG, bg=CELL_BG).pack(pady=1)
|
rows = (len(seats) + max_cols - 1) // max_cols
|
||||||
|
seat_w = min(244, (w - 64 - (max_cols - 1) * 10) // max(1, min(max_cols, len(seats))))
|
||||||
|
seat_h = 126 if rows > 1 else 132
|
||||||
|
|
||||||
tk.Frame(info_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=8)
|
win_box = self.assets.get_box_photo("box_gold_small", (seat_w, seat_h))
|
||||||
|
std_box = self.assets.get_box_photo("box_purple", (seat_w, seat_h))
|
||||||
|
if win_box:
|
||||||
|
self._photo_refs.append(win_box)
|
||||||
|
if std_box:
|
||||||
|
self._photo_refs.append(std_box)
|
||||||
|
|
||||||
tk.Label(
|
for idx, entry in enumerate(seats):
|
||||||
info_box, text=t("bj_popup_xp_earned", self.data["xp_gained"]),
|
r_i, c_i = divmod(idx, max_cols)
|
||||||
font=("Helvetica", 11, "bold"), fg=ACCENT_GOTH, bg=CELL_BG,
|
in_row = min(max_cols, len(seats) - r_i * max_cols)
|
||||||
).pack(pady=1)
|
row_total_w = in_row * seat_w + (in_row - 1) * 10
|
||||||
|
sx = (w - row_total_w) // 2 + c_i * (seat_w + 10) + seat_w // 2
|
||||||
|
sy = cur_y + r_i * (seat_h + 6) + seat_h // 2
|
||||||
|
|
||||||
if self.data.get("new_level_title"):
|
is_win, folded = entry["is_winner"], entry["folded"]
|
||||||
tk.Label(
|
frame_ph = win_box if is_win else std_box
|
||||||
info_box, text=self.data["new_level_title"],
|
if frame_ph:
|
||||||
font=("Georgia", 11, "bold"), fg=ACCENT_GOLD, bg=CELL_BG,
|
self.create_image(sx, sy, image=frame_ph, anchor="center")
|
||||||
).pack(pady=(3, 0))
|
|
||||||
|
|
||||||
# --- Buttons ---
|
n_col = FONT_COLOR_TITLE_MAIN if is_win else (FONT_COLOR_BODY_MUTED if folded else FONT_COLOR_HEADING_SUB)
|
||||||
btn_row = tk.Frame(self, bg=MODAL_BG)
|
n_ph = self.assets.get_goth_text_photo(entry["name"], FONT_SIZE_SMALL_MIN + 1, n_col, max_width=seat_w - 24)
|
||||||
btn_row.pack(fill="x", pady=(4, 0))
|
self._photo_refs.append(n_ph)
|
||||||
|
self.create_image(sx, sy - seat_h // 2 + 19, image=n_ph, anchor="center")
|
||||||
|
|
||||||
if self.data.get("can_continue", True):
|
cw_h, ch_h = POPUP_HOLE_CARD_SIZE
|
||||||
ImageButton(
|
h_photos = [
|
||||||
btn_row, t("bj_popup_next_round_btn"),
|
ph for s_suit, s_rank in entry["cards"]
|
||||||
self.assets.raw_btn, self.assets.raw_btn_active,
|
if (ph := self.assets.get_card_photo(Card(s_suit, s_rank).image_filename, size=POPUP_HOLE_CARD_SIZE))
|
||||||
self._handle_next, sound_mgr=self.sounds, width=200, height=40, font=("Helvetica", 10, "bold")
|
]
|
||||||
).pack(side="left", padx=(0, 10))
|
self._photo_refs.extend(h_photos)
|
||||||
|
if h_photos:
|
||||||
|
span_w = len(h_photos) * cw_h + max(0, len(h_photos) - 1) * 6
|
||||||
|
hx = sx - span_w // 2
|
||||||
|
for hph in h_photos:
|
||||||
|
self.create_image(hx, sy - ch_h // 2 + 1, image=hph, anchor="nw")
|
||||||
|
hx += cw_h + 6
|
||||||
|
|
||||||
if self.data.get("can_leave_menu", True):
|
cb_col = FONT_COLOR_STATUS_WIN if is_win else (FONT_COLOR_STATUS_LOSS if folded else FONT_COLOR_BODY_DEFAULT)
|
||||||
ImageButton(
|
cb_ph = self.assets.get_goth_text_photo(entry["combo_text"], FONT_SIZE_SMALL_MIN, cb_col, max_width=seat_w - 20)
|
||||||
btn_row, t("bj_popup_to_menu_btn"),
|
self._photo_refs.append(cb_ph)
|
||||||
self.assets.raw_sel, self.assets.raw_sel_active,
|
self.create_image(sx, sy + seat_h // 2 - 18, image=cb_ph, anchor="center")
|
||||||
self._handle_menu, sound_mgr=self.sounds, width=170, height=40, font=("Helvetica", 10, "bold")
|
|
||||||
).pack(side="right")
|
|
||||||
|
|
||||||
def _start_gif(self, key: str):
|
return cur_y + rows * (seat_h + 6) + 6
|
||||||
frames = self.assets.get_gif_frames(key, size=POPUP_GIF_SIZE)
|
|
||||||
if not frames:
|
|
||||||
return
|
|
||||||
|
|
||||||
def _step(idx=0):
|
|
||||||
if not self.gif_lbl.winfo_exists():
|
|
||||||
return
|
|
||||||
self.gif_lbl.configure(image=frames[idx])
|
|
||||||
self._gif_job = self.after(90, _step, (idx + 1) % len(frames))
|
|
||||||
|
|
||||||
_step(0)
|
|
||||||
|
|
||||||
def close_dialog(self):
|
|
||||||
if self._gif_job:
|
|
||||||
try:
|
|
||||||
self.after_cancel(self._gif_job)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
self._gif_job = None
|
|
||||||
if self.winfo_exists():
|
|
||||||
self.destroy()
|
|
||||||
|
|
||||||
def _handle_next(self):
|
|
||||||
self.close_dialog()
|
|
||||||
self.on_next_round()
|
|
||||||
|
|
||||||
def _handle_menu(self):
|
|
||||||
self.close_dialog()
|
|
||||||
self.on_back_to_menu()
|
|
||||||
|
|
@ -1,83 +0,0 @@
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
# games/poker/views/poker_stats_view.py
|
|
||||||
import tkinter as tk
|
|
||||||
from models.database import Database
|
|
||||||
from resources.code_res.game_constants import ACCENT_GOLD, BG_COLOR, BORDER_COLOR, PANEL_BG
|
|
||||||
from resources.code_res.i18n import t
|
|
||||||
from view.widgets.image_button import ImageButton
|
|
||||||
from view.widgets.stats_board_widget import StatsBoardWidget
|
|
||||||
|
|
||||||
GAME_FOLDER_ID = "poker"
|
|
||||||
|
|
||||||
|
|
||||||
class PokerStatsView:
|
|
||||||
"""Dedizierte Statistik-Ansicht für die einzelnen Poker-Goldbeutel."""
|
|
||||||
def __init__(self, context, on_back_to_pk_menu):
|
|
||||||
self.ctx = context
|
|
||||||
self.on_back_to_pk_menu = on_back_to_pk_menu
|
|
||||||
|
|
||||||
def show(self, selected_acc_id: int | None = None):
|
|
||||||
self.ctx.root.clear_window(apply_global_bg=True)
|
|
||||||
pid = self.ctx.profile["id"]
|
|
||||||
accounts = Database.get_poker_accounts(pid)
|
|
||||||
|
|
||||||
if not accounts:
|
|
||||||
self.on_back_to_pk_menu(None)
|
|
||||||
return
|
|
||||||
|
|
||||||
active_acc = accounts[0]
|
|
||||||
if selected_acc_id is not None:
|
|
||||||
for a in accounts:
|
|
||||||
if a["id"] == selected_acc_id:
|
|
||||||
active_acc = a
|
|
||||||
break
|
|
||||||
|
|
||||||
self.ctx.build_game_topbar(
|
|
||||||
self.ctx.root,
|
|
||||||
t("pk_stats_view_topbar"),
|
|
||||||
on_game_menu=lambda: self.on_back_to_pk_menu(active_acc["id"]),
|
|
||||||
extra_right_text=t("pk_header_gold", active_acc["account_name"], active_acc["gold"]),
|
|
||||||
on_lang_refresh=lambda: self.show(active_acc["id"]),
|
|
||||||
)
|
|
||||||
|
|
||||||
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=18)
|
|
||||||
container.place(relx=0.5, rely=0.54, anchor="center", relwidth=0.88, relheight=0.82)
|
|
||||||
|
|
||||||
selector_panel = tk.Frame(
|
|
||||||
container, bg=PANEL_BG, padx=18, pady=14,
|
|
||||||
highlightthickness=1, highlightbackground=BORDER_COLOR
|
|
||||||
)
|
|
||||||
selector_panel.pack(fill="x", pady=(0, 16))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
selector_panel, text=t("bj_stats_select_acc_lbl"),
|
|
||||||
font=("Georgia", 13, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG
|
|
||||||
).pack(anchor="w", pady=(0, 10))
|
|
||||||
|
|
||||||
tabs_row = tk.Frame(selector_panel, bg=PANEL_BG)
|
|
||||||
tabs_row.pack(fill="x")
|
|
||||||
|
|
||||||
for acc in accounts:
|
|
||||||
is_sel = (acc["id"] == active_acc["id"])
|
|
||||||
pil_norm = self.ctx.assets.raw_btn if is_sel else self.ctx.assets.raw_sel
|
|
||||||
pil_hov = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel_active
|
|
||||||
btn_lbl = f"{acc['account_name']} ({acc['gold']}g)"
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
tabs_row, btn_lbl, pil_norm, pil_hov,
|
|
||||||
lambda aid=acc["id"]: self.show(selected_acc_id=aid),
|
|
||||||
sound_mgr=self.ctx.sounds, width=185, height=38, font=("Helvetica", 9, "bold")
|
|
||||||
).pack(side="left", padx=(0, 8))
|
|
||||||
|
|
||||||
pk_variants = Database.get_variants_for_filter(folder_path=GAME_FOLDER_ID)
|
|
||||||
pk_filter_map = {t("pk_filter_all_tables"): None}
|
|
||||||
for v in pk_variants:
|
|
||||||
pk_filter_map[v["translated_name"]] = v["id"]
|
|
||||||
|
|
||||||
board = StatsBoardWidget(
|
|
||||||
container,
|
|
||||||
title=t("bj_stats_acc_title", active_acc["account_name"]),
|
|
||||||
filter_map=pk_filter_map,
|
|
||||||
fetch_callback=lambda vid: Database.get_pk_account_stats_overview(active_acc["id"], vid)
|
|
||||||
)
|
|
||||||
board.pack(fill="x")
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,270 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/poker/views/poker_turn_driver.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
from games.poker.models.poker_seat import PokerSeat
|
||||||
|
from games.poker.views.poker_arena_renderer import PokerArenaRenderer
|
||||||
|
from models.database import Database
|
||||||
|
from models.progression import Progression
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
PK_BOT_TURN_DELAY_MS,
|
||||||
|
PK_STREET_DELAY_MS,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
|
||||||
|
|
||||||
|
class PokerTurnDriver:
|
||||||
|
"""Steuert Setzrunden, Spieler-Aktionsleiste, KI-Züge und Showdown-Abrechnung beim Poker."""
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def process_current_turn(cls, view) -> None:
|
||||||
|
if not view._canvas_alive():
|
||||||
|
return
|
||||||
|
if view.engine.only_one_left():
|
||||||
|
cls.finalize_hand(view)
|
||||||
|
return
|
||||||
|
if view.engine.is_betting_round_complete():
|
||||||
|
cls.advance_street_or_showdown(view)
|
||||||
|
return
|
||||||
|
if (
|
||||||
|
view.engine.turn_pos < 0
|
||||||
|
or not view.engine.seats[view.engine.turn_pos].can_act
|
||||||
|
):
|
||||||
|
view.engine.advance_turn_pointer()
|
||||||
|
if view.engine.turn_pos < 0:
|
||||||
|
cls.advance_street_or_showdown(view)
|
||||||
|
return
|
||||||
|
|
||||||
|
if view.engine.turn_pos == 0:
|
||||||
|
view._render_table()
|
||||||
|
cls.show_human_controls(view)
|
||||||
|
else:
|
||||||
|
view._set_bottom_buttons([])
|
||||||
|
bot = view.engine.seats[view.engine.turn_pos]
|
||||||
|
view._render_table()
|
||||||
|
view._turn_job = view.ctx.root.after(
|
||||||
|
PK_BOT_TURN_DELAY_MS, lambda b=bot: cls.execute_bot_turn(view, b)
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def advance_street_or_showdown(cls, view) -> None:
|
||||||
|
view._set_bottom_buttons([])
|
||||||
|
if view.engine.street == "RIVER":
|
||||||
|
cls.finalize_hand(view)
|
||||||
|
return
|
||||||
|
view.ctx.sounds.play("click")
|
||||||
|
new_street = view.engine.advance_to_next_street()
|
||||||
|
view._persist_state()
|
||||||
|
view._render_table()
|
||||||
|
if new_street == "SHOWDOWN":
|
||||||
|
cls.finalize_hand(view)
|
||||||
|
elif view.engine.should_auto_runout_board():
|
||||||
|
view._turn_job = view.ctx.root.after(
|
||||||
|
PK_STREET_DELAY_MS, lambda: cls.advance_street_or_showdown(view)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
cls.process_current_turn(view)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def show_human_controls(view) -> None:
|
||||||
|
if not hasattr(view, "bottom_bar") or not view.bottom_bar.winfo_exists():
|
||||||
|
return
|
||||||
|
human = view.engine.human_seat
|
||||||
|
to_call = max(0, view.engine.current_bet - human.street_bet)
|
||||||
|
dyn_chips = view._get_current_level_chips()
|
||||||
|
btn_norm = view.ctx.assets.raw_btn_default
|
||||||
|
btn_purp = view.ctx.assets.raw_btn_purple
|
||||||
|
btn_fire = view.ctx.assets.raw_btn_fire or btn_purp
|
||||||
|
|
||||||
|
primary_btns: list[ImageButton] = []
|
||||||
|
overflow_btns: list[ImageButton] = []
|
||||||
|
|
||||||
|
if to_call == 0:
|
||||||
|
primary_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, t("pk_btn_check"), btn_fire, btn_fire,
|
||||||
|
lambda: view._on_human_action("CHECK", 0), sound_mgr=None,
|
||||||
|
width=138, height=30, style="fire",
|
||||||
|
hover_text=lambda: t("pk_tip_check"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
elif human.stack > to_call:
|
||||||
|
primary_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, t("pk_btn_call", to_call), btn_fire, btn_fire,
|
||||||
|
lambda: view._on_human_action("CALL", 0),
|
||||||
|
sound_mgr=view.ctx.sounds, width=138, height=30, style="fire",
|
||||||
|
hover_text=lambda: t("pk_tip_call"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
avail_after_call = human.stack - to_call
|
||||||
|
min_r = view.engine.min_raise_delta
|
||||||
|
offered = sorted(
|
||||||
|
{max(min_r, c) for c in dyn_chips if max(min_r, c) < avail_after_call}
|
||||||
|
)[:4]
|
||||||
|
for r_delta in offered:
|
||||||
|
primary_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, f"+{r_delta}g", btn_norm, btn_purp,
|
||||||
|
lambda d=r_delta: view._on_human_action("RAISE", d),
|
||||||
|
sound_mgr=view.ctx.sounds, width=74, height=30, style="amethyst",
|
||||||
|
hover_text=lambda: t("pk_tip_raise"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
if human.stack > 0:
|
||||||
|
allin_fire = to_call > 0 and human.stack <= to_call
|
||||||
|
overflow_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, t("pk_btn_allin", human.stack),
|
||||||
|
btn_fire if allin_fire else btn_norm,
|
||||||
|
btn_fire if allin_fire else btn_purp,
|
||||||
|
lambda: view._on_human_action("ALLIN", 0),
|
||||||
|
sound_mgr=view.ctx.sounds, width=132, height=30,
|
||||||
|
style="fire" if allin_fire else "amethyst",
|
||||||
|
hover_text=lambda: t("pk_tip_allin"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
overflow_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
view.bottom_bar, t("pk_btn_fold"), btn_norm, btn_purp,
|
||||||
|
lambda: view._on_human_action("FOLD", 0),
|
||||||
|
sound_mgr=view.ctx.sounds, width=122, height=30, style="amethyst",
|
||||||
|
hover_text=lambda: t("pk_tip_fold"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
view._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def execute_bot_turn(cls, view, bot: PokerSeat) -> None:
|
||||||
|
if not view._canvas_alive():
|
||||||
|
return
|
||||||
|
active_opps = sum(
|
||||||
|
1 for s in view.engine.seats if s.is_in_hand and s.seat_id != bot.seat_id
|
||||||
|
)
|
||||||
|
act, r_delta = view.bot_ai.decide_action(
|
||||||
|
bot=bot,
|
||||||
|
board=view.engine.board,
|
||||||
|
current_bet=view.engine.current_bet,
|
||||||
|
pot=view.engine.total_pot,
|
||||||
|
min_raise_delta=view.engine.min_raise_delta,
|
||||||
|
chips=view._get_current_level_chips(),
|
||||||
|
active_opponents=active_opps,
|
||||||
|
)
|
||||||
|
paid = view.engine.apply_action(bot.seat_id, act, r_delta)
|
||||||
|
if act == "FOLD":
|
||||||
|
bot.status_text = t("pk_bot_act_fold")
|
||||||
|
elif act == "CHECK":
|
||||||
|
bot.status_text = t("pk_bot_act_check")
|
||||||
|
elif act == "ALLIN":
|
||||||
|
view.ctx.sounds.play("click")
|
||||||
|
bot.status_text = t("pk_bot_act_allin", bot.total_committed)
|
||||||
|
elif act == "RAISE":
|
||||||
|
view.ctx.sounds.play("click")
|
||||||
|
bot.status_text = t("pk_bot_act_raise", paid)
|
||||||
|
else:
|
||||||
|
view.ctx.sounds.play("click")
|
||||||
|
bot.status_text = t("pk_bot_act_call", paid)
|
||||||
|
|
||||||
|
view.engine.advance_turn_pointer()
|
||||||
|
view._persist_state()
|
||||||
|
view._render_table()
|
||||||
|
cls.process_current_turn(view)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def finalize_hand(view) -> None:
|
||||||
|
ImageButton.close_active_hover_tip()
|
||||||
|
view._close_hands_overlay()
|
||||||
|
view._set_bottom_buttons([])
|
||||||
|
|
||||||
|
res = view.engine.resolve_hand()
|
||||||
|
if res["human_payout"] > 0:
|
||||||
|
view.pk_account = Database.update_poker_gold(
|
||||||
|
view.pk_account["id"], res["human_payout"]
|
||||||
|
)
|
||||||
|
|
||||||
|
duration = max(0.5, time.time() - view.round_start_time)
|
||||||
|
prog_before = view.ctx.refresh_game_progress()
|
||||||
|
opp_levels = [s.ai_level for s in view.engine.seats[1:]]
|
||||||
|
win_cat = res["winning_hand_cat"] or 0
|
||||||
|
|
||||||
|
if res["human_won"] and res["human_net"] > 0:
|
||||||
|
out_type = (
|
||||||
|
"WIN_777" if win_cat >= 8 else ("WIN_BJ" if win_cat >= 6 else "WIN")
|
||||||
|
)
|
||||||
|
won_stat: bool | None = True
|
||||||
|
elif res["human_net"] == 0 and res["human_payout"] > 0:
|
||||||
|
out_type, won_stat = "TIE", None
|
||||||
|
elif res["human_won"]:
|
||||||
|
out_type, won_stat = "WIN", True
|
||||||
|
else:
|
||||||
|
out_type, won_stat = "LOSE", False
|
||||||
|
|
||||||
|
xp_gained = Progression.calculate_match_xp(
|
||||||
|
prog_before["level"],
|
||||||
|
opp_levels,
|
||||||
|
out_type,
|
||||||
|
variant_mult=view.cfg["xp_mult"],
|
||||||
|
)
|
||||||
|
if won_stat is None:
|
||||||
|
Database.add_game_points(
|
||||||
|
view.ctx.profile["id"], view.GAME_FOLDER_ID, xp_gained
|
||||||
|
)
|
||||||
|
prog_after = view.ctx.refresh_game_progress()
|
||||||
|
view.ctx.sounds.play("end_battle")
|
||||||
|
leveled_to = (
|
||||||
|
prog_after["level"]
|
||||||
|
if prog_after["level"] > prog_before["level"]
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
old_lvl, new_lvl = view.ctx.record_result(
|
||||||
|
view.variant_key,
|
||||||
|
won=won_stat,
|
||||||
|
duration_sec=duration,
|
||||||
|
points_gained=xp_gained,
|
||||||
|
pk_account_id=view.pk_account["id"],
|
||||||
|
)
|
||||||
|
leveled_to = new_lvl if new_lvl > old_lvl else None
|
||||||
|
|
||||||
|
if view.devils_locked:
|
||||||
|
fresh_acc = Database.get_poker_account(view.pk_account["id"])
|
||||||
|
if not (out_type == "TIE" and fresh_acc["gold"] == 10):
|
||||||
|
Database.set_pk_devils_deal_active(view.pk_account["id"], False)
|
||||||
|
view.devils_locked = False
|
||||||
|
view._clear_persisted_state()
|
||||||
|
else:
|
||||||
|
view._clear_persisted_state()
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"by_fold": res["by_fold"],
|
||||||
|
"winner_names": res["winner_names"],
|
||||||
|
"winning_hand_cat": res["winning_hand_cat"],
|
||||||
|
"player_won": won_stat,
|
||||||
|
"human_in_winners": bool(res["human_won"]),
|
||||||
|
"is_split": res["is_split"],
|
||||||
|
"player_net": res["human_net"],
|
||||||
|
"bot_gains": res["bot_gains"],
|
||||||
|
"xp_gained": xp_gained,
|
||||||
|
"leveled_to": leveled_to,
|
||||||
|
"board_cards": [[c.suit, c.rank] for c in view.engine.board],
|
||||||
|
"seats_reveal": PokerArenaRenderer.collect_all_seats_reveal(
|
||||||
|
view.engine, res["winner_names"]
|
||||||
|
),
|
||||||
|
}
|
||||||
|
view._last_popup_payload = payload
|
||||||
|
if view.devils_locked:
|
||||||
|
view._persist_state()
|
||||||
|
elif view._canvas_alive():
|
||||||
|
view.topbar.set_locked_exit(False)
|
||||||
|
|
||||||
|
view._render_table()
|
||||||
|
view._open_result_popup(
|
||||||
|
PokerArenaRenderer.build_localized_popup_data(view, payload),
|
||||||
|
play_fx=True,
|
||||||
|
)
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -2,60 +2,104 @@
|
||||||
# games/solitaire/base/card_animator.py
|
# games/solitaire/base/card_animator.py
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import random
|
||||||
import time
|
import time
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from typing import Callable
|
from typing import Callable, Iterable
|
||||||
|
from PIL import Image, ImageTk
|
||||||
|
|
||||||
|
|
||||||
class CardFlightAnimator:
|
class CardFlightAnimator:
|
||||||
"""
|
"""
|
||||||
Schneller, nicht-blockierender Canvas-Animator für gleitende Kartenbewegungen.
|
Zentraler, nicht-blockierender Canvas-Animator für alle Solitaire-Tische:
|
||||||
Nutzt Canvas-Tag-Verschiebung (canvas.move) ohne teures Neu-Rendern des Hintergrunds.
|
1. Gleitende Kartenflüge zwischen Stapeln (start / flush)
|
||||||
|
2. Rotierend nach unten aus dem Fenster fallende Karten (spawn_falling_cards)
|
||||||
|
3. Kurzes horizontales Fehler-Wackeln bei ungültigen Kombis (start_shake)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
FRAME_MS = 14 # ~70 FPS Zielrate auf Tkinter
|
FRAME_MS = 14
|
||||||
|
FALL_STEP_MS = 16
|
||||||
|
SHAKE_OFFSETS_PX: tuple[int, ...] = (-7, 7, -5, 5, -3, 3, 0)
|
||||||
|
SHAKE_STEP_MS = 26
|
||||||
|
|
||||||
def __init__(self, root: tk.Misc, canvas: tk.Canvas):
|
def __init__(self, root: tk.Misc, canvas: tk.Canvas):
|
||||||
self.root = root
|
self.root = root
|
||||||
self.canvas = canvas
|
self.canvas = canvas
|
||||||
|
|
||||||
|
# 1. Lineare Kartenflüge
|
||||||
self._job: str | None = None
|
self._job: str | None = None
|
||||||
self._flights: list[dict] = []
|
self._flights: list[dict] = []
|
||||||
self._on_done: Callable[[], None] | None = None
|
self._on_done: Callable[[], None] | None = None
|
||||||
self._start_ts: float = 0.0
|
self._start_ts: float = 0.0
|
||||||
self._duration_sec: float = 0.12
|
self._duration_sec: float = 0.12
|
||||||
|
|
||||||
|
# 2. Rotierend herausfallende Karten
|
||||||
|
self._fall_job: str | None = None
|
||||||
|
self._falling_cards: list[dict] = []
|
||||||
|
self._fall_photo_refs: list[ImageTk.PhotoImage] = []
|
||||||
|
|
||||||
|
# 3. Horizontales Fehler-Wackeln
|
||||||
|
self._shake_job: str | None = None
|
||||||
|
self._shake_refs: set[tuple] = set()
|
||||||
|
self._shake_dx: int = 0
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def is_active(self) -> bool:
|
def is_active(self) -> bool:
|
||||||
return self._job is not None
|
return self._job is not None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def has_shake(self) -> bool:
|
||||||
|
return bool(self._shake_refs)
|
||||||
|
|
||||||
|
def _canvas_alive(self) -> bool:
|
||||||
|
try:
|
||||||
|
return bool(self.canvas.winfo_exists())
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
def cancel(self):
|
def cancel(self):
|
||||||
"""Bricht laufende Timer sofort ab (z. B. beim Schließen des Fensters)."""
|
"""Bricht alle laufenden Flug-, Fall- und Wackel-Timer sofort sauber ab."""
|
||||||
if self._job is not None:
|
if self._job is not None:
|
||||||
try:
|
try:
|
||||||
self.root.after_cancel(self._job)
|
self.root.after_cancel(self._job)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
self._job = None
|
self._job = None
|
||||||
try:
|
if self._canvas_alive_safe():
|
||||||
if self.canvas.winfo_exists():
|
self.canvas.delete("anim_flight")
|
||||||
self.canvas.delete("anim_flight")
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
self._flights.clear()
|
self._flights.clear()
|
||||||
self._on_done = None
|
self._on_done = None
|
||||||
|
|
||||||
|
self.cancel_falling()
|
||||||
|
self.cancel_shake()
|
||||||
|
|
||||||
|
def _canvas_alive_safe(self) -> bool:
|
||||||
|
try:
|
||||||
|
return bool(self.canvas.winfo_exists())
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
def flush(self):
|
def flush(self):
|
||||||
"""
|
"""Beendet eine laufende Flug-Animation sofort sauber im Zielzustand."""
|
||||||
Beendet eine laufende Animation sofort sauber im Zielzustand,
|
|
||||||
damit schnelle Klickfolgen des Spielers niemals ausgebremst werden.
|
|
||||||
"""
|
|
||||||
if not self.is_active:
|
if not self.is_active:
|
||||||
return
|
return
|
||||||
cb = self._on_done
|
cb = self._on_done
|
||||||
self.cancel()
|
if self._job is not None:
|
||||||
|
try:
|
||||||
|
self.root.after_cancel(self._job)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._job = None
|
||||||
|
if self._canvas_alive_safe():
|
||||||
|
self.canvas.delete("anim_flight")
|
||||||
|
self._flights.clear()
|
||||||
|
self._on_done = None
|
||||||
if callable(cb):
|
if callable(cb):
|
||||||
cb()
|
cb()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 1. Lineare Kartenflüge (Tableau / Foundation / Talon -> Waste)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
def start(
|
def start(
|
||||||
self,
|
self,
|
||||||
flights: list[dict],
|
flights: list[dict],
|
||||||
|
|
@ -63,29 +107,12 @@ class CardFlightAnimator:
|
||||||
duration_ms: int = 115,
|
duration_ms: int = 115,
|
||||||
on_done: Callable[[], None] | None = None,
|
on_done: Callable[[], None] | None = None,
|
||||||
):
|
):
|
||||||
"""
|
|
||||||
flights: Liste aus Dicts:
|
|
||||||
{
|
|
||||||
"card": SolitaireCard,
|
|
||||||
"start": (x0, y0),
|
|
||||||
"end": (x1, y1),
|
|
||||||
"highlight": Optional[str],
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
self.flush()
|
self.flush()
|
||||||
if not flights:
|
if not flights or not self._canvas_alive():
|
||||||
if callable(on_done):
|
if callable(on_done):
|
||||||
on_done()
|
on_done()
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
|
||||||
if not self.canvas.winfo_exists():
|
|
||||||
if callable(on_done):
|
|
||||||
on_done()
|
|
||||||
return
|
|
||||||
except Exception:
|
|
||||||
return
|
|
||||||
|
|
||||||
active_flights: list[dict] = []
|
active_flights: list[dict] = []
|
||||||
max_dist = 0.0
|
max_dist = 0.0
|
||||||
for idx, item in enumerate(flights):
|
for idx, item in enumerate(flights):
|
||||||
|
|
@ -112,15 +139,15 @@ class CardFlightAnimator:
|
||||||
"cur_y": float(sy),
|
"cur_y": float(sy),
|
||||||
})
|
})
|
||||||
|
|
||||||
# Bei minimaler Distanz (< 4 px) direkt fertigstellen
|
|
||||||
if max_dist < 4.0:
|
if max_dist < 4.0:
|
||||||
self.canvas.delete("anim_flight")
|
self.canvas.delete("anim_flight")
|
||||||
if callable(on_done):
|
if callable(on_done):
|
||||||
on_done()
|
on_done()
|
||||||
return
|
return
|
||||||
|
|
||||||
# Kurze Wege noch knackiger, weite Wege über den ganzen Tisch minimal länger
|
scaled_ms = max(
|
||||||
scaled_ms = max(65, min(165, int(duration_ms * (0.72 + min(1.0, max_dist / 520.0) * 0.45))))
|
65, min(165, int(duration_ms * (0.72 + min(1.0, max_dist / 520.0) * 0.45)))
|
||||||
|
)
|
||||||
self._flights = active_flights
|
self._flights = active_flights
|
||||||
self._on_done = on_done
|
self._on_done = on_done
|
||||||
self._duration_sec = scaled_ms / 1000.0
|
self._duration_sec = scaled_ms / 1000.0
|
||||||
|
|
@ -129,19 +156,13 @@ class CardFlightAnimator:
|
||||||
|
|
||||||
def _step(self):
|
def _step(self):
|
||||||
self._job = None
|
self._job = None
|
||||||
try:
|
if not self._canvas_alive():
|
||||||
if not self.canvas.winfo_exists():
|
|
||||||
self._flights.clear()
|
|
||||||
self._on_done = None
|
|
||||||
return
|
|
||||||
except Exception:
|
|
||||||
self._flights.clear()
|
self._flights.clear()
|
||||||
self._on_done = None
|
self._on_done = None
|
||||||
return
|
return
|
||||||
|
|
||||||
elapsed = time.perf_counter() - self._start_ts
|
elapsed = time.perf_counter() - self._start_ts
|
||||||
t_raw = min(1.0, max(0.0, elapsed / max(0.001, self._duration_sec)))
|
t_raw = min(1.0, max(0.0, elapsed / max(0.001, self._duration_sec)))
|
||||||
# Cubic Ease-Out: spritziger Start, weiches Einrasten am Zielstapel
|
|
||||||
ease = 1.0 - ((1.0 - t_raw) ** 3)
|
ease = 1.0 - ((1.0 - t_raw) ** 3)
|
||||||
|
|
||||||
for fl in self._flights:
|
for fl in self._flights:
|
||||||
|
|
@ -170,3 +191,162 @@ class CardFlightAnimator:
|
||||||
self._job = self.root.after(self.FRAME_MS, self._step)
|
self._job = self.root.after(self.FRAME_MS, self._step)
|
||||||
except Exception:
|
except Exception:
|
||||||
self._job = None
|
self._job = None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 2. Drehendes Herausfallen abgeräumter Karten (Pyramid / Effects)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def cancel_falling(self):
|
||||||
|
if self._fall_job is not None:
|
||||||
|
try:
|
||||||
|
self.root.after_cancel(self._fall_job)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._fall_job = None
|
||||||
|
self._falling_cards.clear()
|
||||||
|
self._fall_photo_refs.clear()
|
||||||
|
if self._canvas_alive():
|
||||||
|
self.canvas.delete("falling_fx")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _load_scaled_card_pil(assets, card, card_size: tuple[int, int]) -> Image.Image | None:
|
||||||
|
card_path = assets.res.get_card_path(card.filename)
|
||||||
|
raw_pil = None
|
||||||
|
if hasattr(assets, "_get_raw_card_pil"):
|
||||||
|
raw_pil = assets._get_raw_card_pil(card_path)
|
||||||
|
elif card_path.is_file():
|
||||||
|
try:
|
||||||
|
with Image.open(card_path) as im:
|
||||||
|
raw_pil = im.convert("RGBA")
|
||||||
|
except Exception:
|
||||||
|
raw_pil = None
|
||||||
|
if raw_pil is None:
|
||||||
|
return None
|
||||||
|
return raw_pil.convert("RGBA").resize(card_size, Image.Resampling.BILINEAR)
|
||||||
|
|
||||||
|
def spawn_falling_cards(
|
||||||
|
self,
|
||||||
|
assets,
|
||||||
|
card_size: tuple[int, int],
|
||||||
|
items: list[tuple[object, tuple[int, int]]],
|
||||||
|
):
|
||||||
|
"""Lässt abgeräumte Karten leicht hochhüpfen und sich drehend nach unten herausfallen."""
|
||||||
|
if not self._canvas_alive() or not items:
|
||||||
|
return
|
||||||
|
cw, ch = card_size
|
||||||
|
n = len(items)
|
||||||
|
for idx, (card, (sx, sy)) in enumerate(items):
|
||||||
|
base_pil = self._load_scaled_card_pil(assets, card, card_size)
|
||||||
|
if base_pil is None:
|
||||||
|
continue
|
||||||
|
dir_sign = (-1 if idx == 0 else 1) if n >= 2 else random.choice((-1, 1))
|
||||||
|
self._falling_cards.append({
|
||||||
|
"pil": base_pil,
|
||||||
|
"cx": float(sx + cw // 2),
|
||||||
|
"cy": float(sy + ch // 2),
|
||||||
|
"vx": dir_sign * random.uniform(1.8, 4.2),
|
||||||
|
"vy": random.uniform(-6.4, -3.8),
|
||||||
|
"angle": 0.0,
|
||||||
|
"ang_vel": dir_sign * random.uniform(7.5, 13.5),
|
||||||
|
})
|
||||||
|
|
||||||
|
if self._falling_cards and self._fall_job is None:
|
||||||
|
self._step_falling()
|
||||||
|
|
||||||
|
def redraw_falling_layer(self):
|
||||||
|
if not self._falling_cards or not self._canvas_alive():
|
||||||
|
return
|
||||||
|
self.canvas.delete("falling_fx")
|
||||||
|
self._fall_photo_refs.clear()
|
||||||
|
for p in self._falling_cards:
|
||||||
|
rot_pil = p["pil"].rotate(
|
||||||
|
p["angle"], resample=Image.Resampling.BILINEAR, expand=True
|
||||||
|
)
|
||||||
|
tk_ph = ImageTk.PhotoImage(rot_pil)
|
||||||
|
self._fall_photo_refs.append(tk_ph)
|
||||||
|
self.canvas.create_image(
|
||||||
|
int(round(p["cx"])),
|
||||||
|
int(round(p["cy"])),
|
||||||
|
image=tk_ph,
|
||||||
|
anchor="center",
|
||||||
|
tags=("falling_fx",),
|
||||||
|
)
|
||||||
|
if self.canvas.find_withtag("modal_dim_veil"):
|
||||||
|
self.canvas.tag_lower("falling_fx", "modal_dim_veil")
|
||||||
|
|
||||||
|
def _step_falling(self):
|
||||||
|
self._fall_job = None
|
||||||
|
if not self._canvas_alive():
|
||||||
|
self._falling_cards.clear()
|
||||||
|
self._fall_photo_refs.clear()
|
||||||
|
return
|
||||||
|
|
||||||
|
limit_y = max(600, self.canvas.winfo_height()) + 240
|
||||||
|
survivors: list[dict] = []
|
||||||
|
for p in self._falling_cards:
|
||||||
|
p["cx"] += p["vx"]
|
||||||
|
p["cy"] += p["vy"]
|
||||||
|
p["vy"] += 1.20
|
||||||
|
p["angle"] = (p["angle"] + p["ang_vel"]) % 360.0
|
||||||
|
if p["cy"] < limit_y:
|
||||||
|
survivors.append(p)
|
||||||
|
|
||||||
|
self._falling_cards = survivors
|
||||||
|
if not self._falling_cards:
|
||||||
|
self._fall_photo_refs.clear()
|
||||||
|
self.canvas.delete("falling_fx")
|
||||||
|
return
|
||||||
|
|
||||||
|
self.redraw_falling_layer()
|
||||||
|
try:
|
||||||
|
self._fall_job = self.root.after(self.FALL_STEP_MS, self._step_falling)
|
||||||
|
except Exception:
|
||||||
|
self._fall_job = None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 3. Horizontales Fehler-Wackeln (Pyramid & TriPeaks)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def cancel_shake(self, on_clear: Callable[[], None] | None = None):
|
||||||
|
was_shaking = bool(self._shake_refs) or (self._shake_job is not None)
|
||||||
|
if self._shake_job is not None:
|
||||||
|
try:
|
||||||
|
self.root.after_cancel(self._shake_job)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._shake_job = None
|
||||||
|
self._shake_refs.clear()
|
||||||
|
self._shake_dx = 0
|
||||||
|
if was_shaking and callable(on_clear) and self._canvas_alive():
|
||||||
|
on_clear()
|
||||||
|
|
||||||
|
def shake_state_for(self, ref: tuple) -> tuple[bool, int]:
|
||||||
|
if ref in self._shake_refs:
|
||||||
|
return True, self._shake_dx
|
||||||
|
return False, 0
|
||||||
|
|
||||||
|
def start_shake(self, refs: Iterable[tuple], redraw_cb: Callable[[], None]):
|
||||||
|
self.cancel_shake()
|
||||||
|
self._shake_refs = {r for r in refs if r is not None}
|
||||||
|
if not self._shake_refs or not self._canvas_alive():
|
||||||
|
return
|
||||||
|
|
||||||
|
def _step_shake(idx: int):
|
||||||
|
self._shake_job = None
|
||||||
|
if not self._canvas_alive():
|
||||||
|
self._shake_refs.clear()
|
||||||
|
self._shake_dx = 0
|
||||||
|
return
|
||||||
|
if idx >= len(self.SHAKE_OFFSETS_PX):
|
||||||
|
self._shake_refs.clear()
|
||||||
|
self._shake_dx = 0
|
||||||
|
redraw_cb()
|
||||||
|
return
|
||||||
|
self._shake_dx = self.SHAKE_OFFSETS_PX[idx]
|
||||||
|
redraw_cb()
|
||||||
|
try:
|
||||||
|
self._shake_job = self.root.after(
|
||||||
|
self.SHAKE_STEP_MS, lambda: _step_shake(idx + 1)
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
self._shake_job = None
|
||||||
|
|
||||||
|
_step_shake(0)
|
||||||
|
|
@ -0,0 +1,266 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/base/card_hover_zoom.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from games.solitaire.base.solitaire_card import SolitaireCard
|
||||||
|
from resources.code_res.game_constants import ACCENT_GOLD, BORDER_COLOR
|
||||||
|
|
||||||
|
|
||||||
|
class CardHoverZoom:
|
||||||
|
"""
|
||||||
|
Subtile Karten-Hervorhebung im Stil von Microsoft Solitaire:
|
||||||
|
Hebt die Karte unter dem Mauszeiger leicht vergrößert und nach oben versetzt hervor,
|
||||||
|
behält aber strikt die Stapel-Reihenfolge (Z-Order) bei, sodass alle Karten, die in
|
||||||
|
einer Kaskade auf ihr liegen, weiterhin vollständig sichtbar bleiben.
|
||||||
|
"""
|
||||||
|
|
||||||
|
ZOOM_FACTOR = 1.12 # Dezente Verbreitung/Vergrößerung unter den Folgekarten
|
||||||
|
PEEK_UP_PX = 8 # Leichtes Anheben nach oben, damit Wert & Symbol frei herausschauen
|
||||||
|
HOVER_DELAY_MS = 45
|
||||||
|
TAG = "sol_hover_zoom"
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
root: tk.Misc,
|
||||||
|
canvas: tk.Canvas,
|
||||||
|
assets,
|
||||||
|
probe_fn: Callable[[int, int], dict | tuple | None],
|
||||||
|
can_show_fn: Callable[[], bool] | None = None,
|
||||||
|
):
|
||||||
|
self._root = root
|
||||||
|
self._canvas = canvas
|
||||||
|
self._assets = assets
|
||||||
|
self._probe_fn = probe_fn
|
||||||
|
self._can_show_fn = can_show_fn
|
||||||
|
|
||||||
|
self._after_job: str | None = None
|
||||||
|
self._active_target_id: tuple | None = None
|
||||||
|
self._pending_info: dict | None = None
|
||||||
|
self._last_pointer_xy: tuple[int, int] | None = None
|
||||||
|
self._zoom_photo_ref = None
|
||||||
|
|
||||||
|
self._canvas.bind("<Motion>", self._on_motion, add="+")
|
||||||
|
self._canvas.bind("<Leave>", self._on_leave, add="+")
|
||||||
|
self._canvas.bind("<ButtonPress-1>", self._on_press_clear, add="+")
|
||||||
|
self._canvas.bind("<ButtonPress-3>", self._on_press_clear, add="+")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _normalize_probe(raw: dict | tuple | None) -> dict | None:
|
||||||
|
if raw is None:
|
||||||
|
return None
|
||||||
|
if isinstance(raw, dict):
|
||||||
|
return raw
|
||||||
|
if isinstance(raw, tuple) and len(raw) >= 4:
|
||||||
|
card, cx, cy, base_sz = raw[:4]
|
||||||
|
under_tag = raw[4] if len(raw) >= 5 else None
|
||||||
|
return {
|
||||||
|
"card": card,
|
||||||
|
"x": cx,
|
||||||
|
"y": cy,
|
||||||
|
"size": base_sz,
|
||||||
|
"under_tag": under_tag,
|
||||||
|
}
|
||||||
|
return None
|
||||||
|
|
||||||
|
def cancel(self):
|
||||||
|
"""Räumt Timer und aktive Hervorhebung restlos ab."""
|
||||||
|
self._cancel_timer()
|
||||||
|
self._clear_drawn()
|
||||||
|
self._active_target_id = None
|
||||||
|
self._pending_info = None
|
||||||
|
|
||||||
|
def refresh_after_redraw(self):
|
||||||
|
"""Stellt nach einem Hintergrund-Redraw (z. B. Uhr-Tick) die Hervorhebung sauber wieder her."""
|
||||||
|
if self._active_target_id is None or self._last_pointer_xy is None:
|
||||||
|
return
|
||||||
|
if self._can_show_fn is not None and not self._can_show_fn():
|
||||||
|
self.cancel()
|
||||||
|
return
|
||||||
|
px, py = self._last_pointer_xy
|
||||||
|
info = self._normalize_probe(self._probe_fn(px, py))
|
||||||
|
if info is None:
|
||||||
|
self.cancel()
|
||||||
|
return
|
||||||
|
card: SolitaireCard = info["card"]
|
||||||
|
target_id = (
|
||||||
|
card.suit,
|
||||||
|
card.rank,
|
||||||
|
card.deck_id,
|
||||||
|
info["x"],
|
||||||
|
info["y"],
|
||||||
|
info.get("under_tag"),
|
||||||
|
)
|
||||||
|
if target_id == self._active_target_id:
|
||||||
|
self._render_zoom(info)
|
||||||
|
else:
|
||||||
|
self.cancel()
|
||||||
|
|
||||||
|
def _cancel_timer(self):
|
||||||
|
if self._after_job is not None:
|
||||||
|
try:
|
||||||
|
self._root.after_cancel(self._after_job)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._after_job = None
|
||||||
|
|
||||||
|
def _clear_drawn(self):
|
||||||
|
try:
|
||||||
|
if self._canvas.winfo_exists():
|
||||||
|
self._canvas.delete(self.TAG)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._zoom_photo_ref = None
|
||||||
|
|
||||||
|
def _on_leave(self, _event=None):
|
||||||
|
self._last_pointer_xy = None
|
||||||
|
self.cancel()
|
||||||
|
|
||||||
|
def _on_press_clear(self, _event=None):
|
||||||
|
self.cancel()
|
||||||
|
|
||||||
|
def _on_motion(self, event):
|
||||||
|
# Während Drag & Drop niemals einblenden
|
||||||
|
if event.state & 0x0100:
|
||||||
|
self.cancel()
|
||||||
|
return
|
||||||
|
|
||||||
|
self._last_pointer_xy = (event.x, event.y)
|
||||||
|
|
||||||
|
if self._can_show_fn is not None and not self._can_show_fn():
|
||||||
|
self.cancel()
|
||||||
|
return
|
||||||
|
|
||||||
|
info = self._normalize_probe(self._probe_fn(event.x, event.y))
|
||||||
|
if info is None:
|
||||||
|
self.cancel()
|
||||||
|
return
|
||||||
|
|
||||||
|
card: SolitaireCard = info["card"]
|
||||||
|
if not card.face_up:
|
||||||
|
self.cancel()
|
||||||
|
return
|
||||||
|
|
||||||
|
target_id = (
|
||||||
|
card.suit,
|
||||||
|
card.rank,
|
||||||
|
card.deck_id,
|
||||||
|
info["x"],
|
||||||
|
info["y"],
|
||||||
|
info.get("under_tag"),
|
||||||
|
)
|
||||||
|
if target_id == self._active_target_id:
|
||||||
|
return
|
||||||
|
|
||||||
|
self._cancel_timer()
|
||||||
|
self._clear_drawn()
|
||||||
|
self._active_target_id = None
|
||||||
|
self._pending_info = info
|
||||||
|
try:
|
||||||
|
self._after_job = self._root.after(self.HOVER_DELAY_MS, self._show_pending)
|
||||||
|
except Exception:
|
||||||
|
self._after_job = None
|
||||||
|
|
||||||
|
def _show_pending(self):
|
||||||
|
self._after_job = None
|
||||||
|
if self._pending_info is None:
|
||||||
|
return
|
||||||
|
if self._can_show_fn is not None and not self._can_show_fn():
|
||||||
|
self._pending_info = None
|
||||||
|
return
|
||||||
|
if not self._canvas.winfo_exists():
|
||||||
|
return
|
||||||
|
|
||||||
|
info = self._pending_info
|
||||||
|
card: SolitaireCard = info["card"]
|
||||||
|
self._active_target_id = (
|
||||||
|
card.suit,
|
||||||
|
card.rank,
|
||||||
|
card.deck_id,
|
||||||
|
info["x"],
|
||||||
|
info["y"],
|
||||||
|
info.get("under_tag"),
|
||||||
|
)
|
||||||
|
self._render_zoom(info)
|
||||||
|
|
||||||
|
def _render_zoom(self, info: dict):
|
||||||
|
self._clear_drawn()
|
||||||
|
card: SolitaireCard = info["card"]
|
||||||
|
card_x: int = info["x"]
|
||||||
|
card_y: int = info["y"]
|
||||||
|
bw, bh = info["size"]
|
||||||
|
under_tag: str | None = info.get("under_tag")
|
||||||
|
|
||||||
|
if bw < 24 or bh < 32:
|
||||||
|
return
|
||||||
|
|
||||||
|
zw = max(bw + 8, int(round(bw * self.ZOOM_FACTOR)))
|
||||||
|
zh = max(bh + 12, int(round(bh * self.ZOOM_FACTOR)))
|
||||||
|
|
||||||
|
cw = max(1, self._canvas.winfo_width())
|
||||||
|
ch = max(1, self._canvas.winfo_height())
|
||||||
|
|
||||||
|
# Horizontal mittig auf der Spalte, vertikal leicht nach oben gelupft ("Peek"),
|
||||||
|
# damit Rang & Farbe über den aufliegenden Folgekarten klar hervortreten
|
||||||
|
zx = card_x - (zw - bw) // 2
|
||||||
|
if under_tag:
|
||||||
|
zy = card_y - self.PEEK_UP_PX - (zh - bh) // 3
|
||||||
|
else:
|
||||||
|
zy = card_y - (zh - bh) // 2
|
||||||
|
|
||||||
|
pad = 6
|
||||||
|
zx = max(pad, min(max(pad, cw - zw - pad), zx))
|
||||||
|
zy = max(pad, min(max(pad, ch - zh - pad), zy))
|
||||||
|
|
||||||
|
photo = self._assets.get_card_photo(card.filename, size=(zw, zh))
|
||||||
|
if photo is None:
|
||||||
|
return
|
||||||
|
self._zoom_photo_ref = photo
|
||||||
|
|
||||||
|
# 1. Dezenter dunkler Schlagschatten
|
||||||
|
self._canvas.create_rectangle(
|
||||||
|
zx + 4,
|
||||||
|
zy + 5,
|
||||||
|
zx + zw + 4,
|
||||||
|
zy + zh + 5,
|
||||||
|
fill="#07050c",
|
||||||
|
outline="",
|
||||||
|
tags=(self.TAG,),
|
||||||
|
)
|
||||||
|
# 2. Leicht vergrößerte Karte
|
||||||
|
self._canvas.create_image(
|
||||||
|
zx,
|
||||||
|
zy,
|
||||||
|
image=photo,
|
||||||
|
anchor="nw",
|
||||||
|
tags=(self.TAG,),
|
||||||
|
)
|
||||||
|
# 3. Goldener Hervorhebungs-Rahmen
|
||||||
|
self._canvas.create_rectangle(
|
||||||
|
zx - 2,
|
||||||
|
zy - 2,
|
||||||
|
zx + zw + 2,
|
||||||
|
zy + zh + 2,
|
||||||
|
outline=ACCENT_GOLD,
|
||||||
|
width=2,
|
||||||
|
tags=(self.TAG,),
|
||||||
|
)
|
||||||
|
self._canvas.create_rectangle(
|
||||||
|
zx - 3,
|
||||||
|
zy - 3,
|
||||||
|
zx + zw + 3,
|
||||||
|
zy + zh + 3,
|
||||||
|
outline=BORDER_COLOR,
|
||||||
|
width=1,
|
||||||
|
tags=(self.TAG,),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Entscheidend: Liegen in der Kaskade weitere Karten auf dieser Karte,
|
||||||
|
# sortieren wir die Hervorhebung direkt UNTER die nächste Karte ein!
|
||||||
|
if under_tag and self._canvas.find_withtag(under_tag):
|
||||||
|
try:
|
||||||
|
self._canvas.tag_lower(self.TAG, under_tag)
|
||||||
|
except tk.TclError:
|
||||||
|
pass
|
||||||
|
|
@ -0,0 +1,468 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/base/solitaire_bottom_bar.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
from PIL import Image, ImageTk
|
||||||
|
|
||||||
|
import resources.code_res.game_constants as gc
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
BG_COLOR,
|
||||||
|
FONT_COLOR_HEADING_SUB,
|
||||||
|
FONT_SIZE_SMALL_MIN,
|
||||||
|
UI_ACCENT_AMETHYST,
|
||||||
|
)
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
|
||||||
|
BG_SAFE_SIDE_RATIO = getattr(gc, "BG_SAFE_SIDE_RATIO", 0.088)
|
||||||
|
BG_SAFE_BOTTOM_RATIO = getattr(gc, "BG_SAFE_BOTTOM_RATIO", 0.095)
|
||||||
|
|
||||||
|
|
||||||
|
class SolitaireBottomBar(tk.Canvas):
|
||||||
|
"""
|
||||||
|
Gerahmte HUD- & Aktionsleiste innerhalb der unteren Safe-Area von background.jpg.
|
||||||
|
Unterstützt kompakte Pipe-Trenner ('|') sowie zwei optionale Overflow-Erweiterungsflächen
|
||||||
|
links (für Text-Segmente mit Präfix '~') und rechts (für sekundäre Aktions-Buttons),
|
||||||
|
die automatisch nur dann eingeblendet werden, wenn der Platz in der Hauptleiste eng wird.
|
||||||
|
"""
|
||||||
|
|
||||||
|
CONTENT_H = 48
|
||||||
|
SUB_TOP_GAP = 3
|
||||||
|
SUB_BAR_H = 38
|
||||||
|
MIN_BOTTOM_INSET = 56
|
||||||
|
|
||||||
|
# Fein-Offsets für den linken HUD-Textblock ("Punkte: 0 | Züge: 0 | ...")
|
||||||
|
HUD_TEXT_X_OFFSET = 0 # Positiv = weiter nach rechts zur Mitte, Negativ = näher an den linken Rahmen
|
||||||
|
HUD_TEXT_Y_OFFSET = 6 # Optische Vertikalzentrierung im Goldrahmen
|
||||||
|
|
||||||
|
def __init__(self, parent, ctx, hud_var: tk.StringVar, status_var: tk.StringVar):
|
||||||
|
root_h = max(720, ctx.root.winfo_height())
|
||||||
|
self._bottom_inset = max(self.MIN_BOTTOM_INSET, int(root_h * BG_SAFE_BOTTOM_RATIO))
|
||||||
|
init_h = self.CONTENT_H + self._bottom_inset
|
||||||
|
|
||||||
|
super().__init__(
|
||||||
|
parent,
|
||||||
|
height=init_h,
|
||||||
|
bg=BG_COLOR,
|
||||||
|
bd=0,
|
||||||
|
highlightthickness=0,
|
||||||
|
)
|
||||||
|
self.ctx = ctx
|
||||||
|
self.assets = ctx.assets
|
||||||
|
self.hud_var = hud_var
|
||||||
|
self.status_var = status_var
|
||||||
|
|
||||||
|
self._buttons: list[ImageButton] = []
|
||||||
|
self._bg_ph: ImageTk.PhotoImage | None = None
|
||||||
|
self._frame_ph: ImageTk.PhotoImage | None = None
|
||||||
|
self._sub_left_frame_ph: ImageTk.PhotoImage | None = None
|
||||||
|
self._sub_right_frame_ph: ImageTk.PhotoImage | None = None
|
||||||
|
self._txt_refs: list[ImageTk.PhotoImage] = []
|
||||||
|
self._last_btn_split: tuple[tuple[int, ...], tuple[int, ...]] | None = None
|
||||||
|
|
||||||
|
self.hud_var.trace_add("write", lambda *_: self.refresh_texts())
|
||||||
|
self.status_var.trace_add("write", lambda *_: self.refresh_texts())
|
||||||
|
self.bind("<Configure>", self._on_configure)
|
||||||
|
|
||||||
|
def set_buttons(
|
||||||
|
self,
|
||||||
|
buttons: list[ImageButton],
|
||||||
|
overflow_buttons: list[ImageButton] | None = None,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Setzt die aktiven Leisten-Buttons und räumt alte Button-Widgets sauber ab.
|
||||||
|
Buttons in `overflow_buttons` (oder mit Attribut `can_overflow=True`) bleiben
|
||||||
|
solange möglich oben in der Hauptleiste und weichen bei Platzmangel automatisch
|
||||||
|
rechtsbündig in die untere rechte Erweiterungsfläche aus.
|
||||||
|
"""
|
||||||
|
primary_list = list(buttons)
|
||||||
|
extra_list = list(overflow_buttons) if overflow_buttons else []
|
||||||
|
for b in extra_list:
|
||||||
|
setattr(b, "can_overflow", True)
|
||||||
|
|
||||||
|
combined = primary_list + extra_list
|
||||||
|
keep_ids = {id(b) for b in combined}
|
||||||
|
|
||||||
|
for old_b in self._buttons:
|
||||||
|
if id(old_b) not in keep_ids:
|
||||||
|
try:
|
||||||
|
if old_b.winfo_exists():
|
||||||
|
old_b.place_forget()
|
||||||
|
old_b.destroy()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
self._buttons = combined
|
||||||
|
self._last_btn_split = None
|
||||||
|
self.relayout()
|
||||||
|
self.after(20, self.relayout)
|
||||||
|
|
||||||
|
def relayout(self):
|
||||||
|
if not self.winfo_exists():
|
||||||
|
return
|
||||||
|
w = self.winfo_width()
|
||||||
|
h = self.winfo_height()
|
||||||
|
if w >= 120 and h >= 40:
|
||||||
|
self._slice_bg(w, h)
|
||||||
|
self._layout(w, h)
|
||||||
|
|
||||||
|
def _slice_bg(self, w: int, h: int):
|
||||||
|
root = self.ctx.root
|
||||||
|
rw = max(w, root.winfo_width())
|
||||||
|
rh = max(h, root.winfo_height())
|
||||||
|
ox = max(0, min(rw - w, self.winfo_rootx() - root.winfo_rootx()))
|
||||||
|
oy = max(0, min(rh - h, self.winfo_rooty() - root.winfo_rooty()))
|
||||||
|
|
||||||
|
if hasattr(self.assets, "get_bg_patch_photo"):
|
||||||
|
self._bg_ph = self.assets.get_bg_patch_photo(rw, rh, ox, oy, w, h)
|
||||||
|
else:
|
||||||
|
src = (
|
||||||
|
self.assets.raw_bg_vertical
|
||||||
|
if (rh > rw and self.assets.raw_bg_vertical is not None)
|
||||||
|
else (self.assets.raw_bg_horizontal or self.assets.raw_bg)
|
||||||
|
)
|
||||||
|
if src is None:
|
||||||
|
return
|
||||||
|
scaled = src.resize((rw, rh), Image.Resampling.BILINEAR)
|
||||||
|
self._bg_ph = ImageTk.PhotoImage(scaled.crop((ox, oy, ox + w, oy + h)))
|
||||||
|
|
||||||
|
if self._bg_ph is None:
|
||||||
|
return
|
||||||
|
self.delete("bb_bg")
|
||||||
|
self.create_image(0, 0, image=self._bg_ph, anchor="nw", tags="bb_bg")
|
||||||
|
self.tag_lower("bb_bg")
|
||||||
|
|
||||||
|
def _on_configure(self, event):
|
||||||
|
if event.widget is not self:
|
||||||
|
return
|
||||||
|
w, h = max(1, event.width), max(1, event.height)
|
||||||
|
if w < 120:
|
||||||
|
return
|
||||||
|
|
||||||
|
root_h = max(600, self.ctx.root.winfo_height())
|
||||||
|
new_bot = max(self.MIN_BOTTOM_INSET, int(root_h * BG_SAFE_BOTTOM_RATIO))
|
||||||
|
if new_bot != self._bottom_inset:
|
||||||
|
self._bottom_inset = new_bot
|
||||||
|
h = self.CONTENT_H + self._bottom_inset
|
||||||
|
self.configure(height=h)
|
||||||
|
|
||||||
|
self._slice_bg(w, h)
|
||||||
|
self._layout(w, h)
|
||||||
|
|
||||||
|
def _render_seg_photo(self, txt: str) -> ImageTk.PhotoImage:
|
||||||
|
# Dynamische Timer-Segmente (z. B. 00:12) nicht dauerhaft im Text-Cache ablegen
|
||||||
|
if ":" in txt and any(ch.isdigit() for ch in txt) and "'" not in txt:
|
||||||
|
try:
|
||||||
|
pil_seg = self.assets.render_goth_text_pil(
|
||||||
|
txt,
|
||||||
|
size_px=FONT_SIZE_SMALL_MIN + 1,
|
||||||
|
color=FONT_COLOR_HEADING_SUB,
|
||||||
|
align="left",
|
||||||
|
uncached=True,
|
||||||
|
)
|
||||||
|
except TypeError:
|
||||||
|
pil_seg = self.assets.render_goth_text_pil(
|
||||||
|
txt,
|
||||||
|
size_px=FONT_SIZE_SMALL_MIN + 1,
|
||||||
|
color=FONT_COLOR_HEADING_SUB,
|
||||||
|
align="left",
|
||||||
|
)
|
||||||
|
return ImageTk.PhotoImage(pil_seg)
|
||||||
|
|
||||||
|
return self.assets.get_goth_text_photo(
|
||||||
|
txt,
|
||||||
|
size_px=FONT_SIZE_SMALL_MIN + 1,
|
||||||
|
color=FONT_COLOR_HEADING_SUB,
|
||||||
|
align="left",
|
||||||
|
)
|
||||||
|
|
||||||
|
def _prepare_hud_segments(self) -> tuple[list[dict], ImageTk.PhotoImage, int]:
|
||||||
|
raw_hud = (self.hud_var.get() or "").replace("•", "|")
|
||||||
|
raw_parts = [p.strip() for p in raw_hud.split("|") if p.strip()]
|
||||||
|
|
||||||
|
pipe_ph = self.assets.get_goth_text_photo(
|
||||||
|
"|",
|
||||||
|
size_px=FONT_SIZE_SMALL_MIN + 1,
|
||||||
|
color=FONT_COLOR_HEADING_SUB,
|
||||||
|
align="center",
|
||||||
|
)
|
||||||
|
pipe_step = pipe_ph.width() + 12
|
||||||
|
|
||||||
|
items: list[dict] = []
|
||||||
|
for part in raw_parts:
|
||||||
|
can_ovf = part.startswith("~")
|
||||||
|
clean_txt = part[1:].strip() if can_ovf else part
|
||||||
|
if not clean_txt:
|
||||||
|
continue
|
||||||
|
ph = self._render_seg_photo(clean_txt)
|
||||||
|
items.append({
|
||||||
|
"text": clean_txt,
|
||||||
|
"photo": ph,
|
||||||
|
"w": ph.width(),
|
||||||
|
"can_overflow": can_ovf,
|
||||||
|
})
|
||||||
|
return items, pipe_ph, pipe_step
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _calc_segs_width(segs: list[dict], pipe_step: int) -> int:
|
||||||
|
if not segs:
|
||||||
|
return 0
|
||||||
|
return sum(s["w"] for s in segs) + max(0, len(segs) - 1) * pipe_step
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _calc_btns_width(btns: list[ImageButton]) -> int:
|
||||||
|
if not btns:
|
||||||
|
return 0
|
||||||
|
return sum(b.pixel_width for b in btns) + max(0, len(btns) - 1) * 6
|
||||||
|
|
||||||
|
def _compute_partition(
|
||||||
|
self, w: int
|
||||||
|
) -> tuple[list[dict], list[dict], list[ImageButton], list[ImageButton], ImageTk.PhotoImage, int]:
|
||||||
|
seg_items, pipe_ph, pipe_step = self._prepare_hud_segments()
|
||||||
|
|
||||||
|
side_inset = max(92, int(w * BG_SAFE_SIDE_RATIO))
|
||||||
|
avail_main_w = max(200, (w - 2 * side_inset) - 32)
|
||||||
|
min_mid_gap = 22
|
||||||
|
|
||||||
|
avail_left_wing = max(120, int(w * 0.415) - side_inset - 24)
|
||||||
|
avail_right_wing = max(120, (w - side_inset) - int(w * 0.585) - 24)
|
||||||
|
|
||||||
|
top_segs = list(seg_items)
|
||||||
|
sub_segs: list[dict] = []
|
||||||
|
|
||||||
|
alive_btns = [b for b in self._buttons if b.winfo_exists()]
|
||||||
|
top_btns = list(alive_btns)
|
||||||
|
sub_btns: list[ImageButton] = []
|
||||||
|
|
||||||
|
def fits_main() -> bool:
|
||||||
|
sw = self._calc_segs_width(top_segs, pipe_step)
|
||||||
|
bw = self._calc_btns_width(top_btns)
|
||||||
|
if sw > 0 and bw > 0:
|
||||||
|
return (sw + min_mid_gap + bw) <= avail_main_w
|
||||||
|
return (sw + bw) <= avail_main_w
|
||||||
|
|
||||||
|
guard = 0
|
||||||
|
while not fits_main() and guard < 24:
|
||||||
|
guard += 1
|
||||||
|
moved = False
|
||||||
|
|
||||||
|
for idx in range(len(top_btns) - 1, -1, -1):
|
||||||
|
cand = top_btns[idx]
|
||||||
|
if getattr(cand, "can_overflow", False):
|
||||||
|
test_sub = [cand] + sub_btns
|
||||||
|
if self._calc_btns_width(test_sub) <= avail_right_wing or not sub_btns:
|
||||||
|
sub_btns.insert(0, top_btns.pop(idx))
|
||||||
|
moved = True
|
||||||
|
break
|
||||||
|
if moved:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for idx in range(len(top_segs) - 1, 0, -1):
|
||||||
|
cand_s = top_segs[idx]
|
||||||
|
if cand_s["can_overflow"]:
|
||||||
|
test_sub_s = [cand_s] + sub_segs
|
||||||
|
if self._calc_segs_width(test_sub_s, pipe_step) <= avail_left_wing or not sub_segs:
|
||||||
|
sub_segs.insert(0, top_segs.pop(idx))
|
||||||
|
moved = True
|
||||||
|
break
|
||||||
|
if moved:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if len(top_btns) > 1:
|
||||||
|
cand = top_btns[-1]
|
||||||
|
if self._calc_btns_width([cand] + sub_btns) <= avail_right_wing or not sub_btns:
|
||||||
|
sub_btns.insert(0, top_btns.pop())
|
||||||
|
continue
|
||||||
|
if len(top_segs) > 1:
|
||||||
|
cand_s = top_segs[-1]
|
||||||
|
if self._calc_segs_width([cand_s] + sub_segs, pipe_step) <= avail_left_wing or not sub_segs:
|
||||||
|
sub_segs.insert(0, top_segs.pop())
|
||||||
|
continue
|
||||||
|
break
|
||||||
|
|
||||||
|
return top_segs, sub_segs, top_btns, sub_btns, pipe_ph, pipe_step
|
||||||
|
|
||||||
|
def _get_bar_box_photo(self, box_key: str, w: int, h: int, scale: float = 0.80):
|
||||||
|
try:
|
||||||
|
return self.assets.get_box_photo(box_key, (w, h), border_scale=scale)
|
||||||
|
except TypeError:
|
||||||
|
return self.assets.get_box_photo(box_key, (w, h))
|
||||||
|
|
||||||
|
def refresh_texts(self):
|
||||||
|
if not self.winfo_exists() or self.winfo_width() < 120:
|
||||||
|
return
|
||||||
|
w, h = self.winfo_width(), self.winfo_height()
|
||||||
|
_ts, _ss, top_b, sub_b, _pp, _ps = self._compute_partition(w)
|
||||||
|
cur_split = (tuple(id(b) for b in top_b), tuple(id(b) for b in sub_b))
|
||||||
|
if cur_split != self._last_btn_split:
|
||||||
|
self._layout(w, h)
|
||||||
|
else:
|
||||||
|
self._render_partition(w, place_buttons=False)
|
||||||
|
|
||||||
|
def _layout(self, w: int, _h: int):
|
||||||
|
self.delete("bb_frame")
|
||||||
|
side_inset = max(92, int(w * BG_SAFE_SIDE_RATIO))
|
||||||
|
frame_w = max(240, w - 2 * side_inset)
|
||||||
|
cy = self.CONTENT_H // 2
|
||||||
|
|
||||||
|
self._frame_ph = self._get_bar_box_photo(
|
||||||
|
"box_gold_double", frame_w, self.CONTENT_H - 2, scale=0.85
|
||||||
|
)
|
||||||
|
if self._frame_ph:
|
||||||
|
self.create_image(w // 2, cy, image=self._frame_ph, anchor="center", tags="bb_frame")
|
||||||
|
|
||||||
|
self._render_partition(w, place_buttons=True)
|
||||||
|
|
||||||
|
def _render_partition(self, w: int, place_buttons: bool = True):
|
||||||
|
self.delete("bb_txt")
|
||||||
|
self.delete("bb_sub_frame")
|
||||||
|
self._txt_refs.clear()
|
||||||
|
self._sub_left_frame_ph = None
|
||||||
|
self._sub_right_frame_ph = None
|
||||||
|
|
||||||
|
top_segs, sub_segs, top_btns, sub_btns, pipe_ph, pipe_step = self._compute_partition(w)
|
||||||
|
self._txt_refs.append(pipe_ph)
|
||||||
|
|
||||||
|
side_inset = max(92, int(w * BG_SAFE_SIDE_RATIO))
|
||||||
|
cy_main = self.CONTENT_H // 2
|
||||||
|
txt_cy_main = cy_main + self.HUD_TEXT_Y_OFFSET
|
||||||
|
sub_top = self.CONTENT_H + self.SUB_TOP_GAP
|
||||||
|
cy_sub = sub_top + self.SUB_BAR_H // 2
|
||||||
|
txt_cy_sub = cy_sub + self.HUD_TEXT_Y_OFFSET
|
||||||
|
|
||||||
|
# 1. Hauptleisten-Buttons (oben rechts)
|
||||||
|
rx_main = w - side_inset - 16
|
||||||
|
if place_buttons:
|
||||||
|
for btn in reversed(top_btns):
|
||||||
|
bw = btn.pixel_width
|
||||||
|
bh = btn.pixel_height
|
||||||
|
btn.place(x=rx_main - bw, y=cy_main - bh // 2, width=bw, height=bh)
|
||||||
|
tk.Widget.tkraise(btn)
|
||||||
|
rx_main -= (bw + 6)
|
||||||
|
else:
|
||||||
|
rx_main -= self._calc_btns_width(top_btns)
|
||||||
|
|
||||||
|
# 2. Rechte Erweiterungsfläche (nur sichtbar, wenn Buttons nach unten ausgelagert wurden)
|
||||||
|
if sub_btns:
|
||||||
|
sub_btns_w = self._calc_btns_width(sub_btns)
|
||||||
|
r_box_w = sub_btns_w + 26
|
||||||
|
r_box_right = w - side_inset
|
||||||
|
r_box_cx = r_box_right - r_box_w // 2
|
||||||
|
|
||||||
|
self.create_rectangle(
|
||||||
|
r_box_right - r_box_w + 4,
|
||||||
|
sub_top + 4,
|
||||||
|
r_box_right - 4,
|
||||||
|
sub_top + self.SUB_BAR_H - 4,
|
||||||
|
fill="#100d17",
|
||||||
|
outline="",
|
||||||
|
tags="bb_sub_frame",
|
||||||
|
)
|
||||||
|
self._sub_right_frame_ph = self._get_bar_box_photo(
|
||||||
|
"box_gold_double", r_box_w, self.SUB_BAR_H, scale=0.72
|
||||||
|
)
|
||||||
|
if self._sub_right_frame_ph:
|
||||||
|
self.create_image(
|
||||||
|
r_box_cx,
|
||||||
|
cy_sub,
|
||||||
|
image=self._sub_right_frame_ph,
|
||||||
|
anchor="center",
|
||||||
|
tags="bb_sub_frame",
|
||||||
|
)
|
||||||
|
|
||||||
|
if place_buttons:
|
||||||
|
rx_sub = r_box_right - 13
|
||||||
|
for btn in reversed(sub_btns):
|
||||||
|
bw = btn.pixel_width
|
||||||
|
bh = min(btn.pixel_height, self.SUB_BAR_H - 6)
|
||||||
|
btn.place(x=rx_sub - bw, y=cy_sub - bh // 2, width=bw, height=bh)
|
||||||
|
tk.Widget.tkraise(btn)
|
||||||
|
rx_sub -= (bw + 6)
|
||||||
|
|
||||||
|
if place_buttons:
|
||||||
|
self._last_btn_split = (
|
||||||
|
tuple(id(b) for b in top_btns),
|
||||||
|
tuple(id(b) for b in sub_btns),
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Hauptleisten-Text im freien linken Bereich auf der X-Achse zentrieren
|
||||||
|
min_lx = side_inset + 22
|
||||||
|
right_limit = rx_main - 14
|
||||||
|
st_str = (self.status_var.get() or "").replace("•", "|")
|
||||||
|
|
||||||
|
segs_w = self._calc_segs_width(top_segs, pipe_step)
|
||||||
|
st_ph = None
|
||||||
|
total_txt_w = segs_w
|
||||||
|
|
||||||
|
if st_str and (right_limit - (min_lx + segs_w)) >= 90:
|
||||||
|
avail_st_w = right_limit - (min_lx + segs_w + (pipe_step if top_segs else 0))
|
||||||
|
st_ph = self.assets.get_goth_text_photo(
|
||||||
|
st_str,
|
||||||
|
size_px=FONT_SIZE_SMALL_MIN,
|
||||||
|
color=UI_ACCENT_AMETHYST,
|
||||||
|
max_width=max(80, avail_st_w),
|
||||||
|
align="left",
|
||||||
|
)
|
||||||
|
total_txt_w += (pipe_step if top_segs else 0) + st_ph.width()
|
||||||
|
|
||||||
|
avail_txt_span = max(0, right_limit - min_lx)
|
||||||
|
if total_txt_w > 0 and avail_txt_span > total_txt_w:
|
||||||
|
# Sanfte Zentrierung im freien Raum links neben den Buttons
|
||||||
|
centered_lx = min_lx + (avail_txt_span - total_txt_w) // 2 + self.HUD_TEXT_X_OFFSET
|
||||||
|
lx = max(min_lx, min(right_limit - total_txt_w, centered_lx))
|
||||||
|
else:
|
||||||
|
lx = min_lx + self.HUD_TEXT_X_OFFSET
|
||||||
|
|
||||||
|
for i, seg in enumerate(top_segs):
|
||||||
|
if i > 0:
|
||||||
|
self.create_image(lx + 5, txt_cy_main, image=pipe_ph, anchor="w", tags="bb_txt")
|
||||||
|
lx += pipe_step
|
||||||
|
ph = seg["photo"]
|
||||||
|
self._txt_refs.append(ph)
|
||||||
|
self.create_image(lx, txt_cy_main, image=ph, anchor="w", tags="bb_txt")
|
||||||
|
lx += ph.width()
|
||||||
|
|
||||||
|
if st_ph is not None:
|
||||||
|
if top_segs:
|
||||||
|
self.create_image(lx + 6, txt_cy_main, image=pipe_ph, anchor="w", tags="bb_txt")
|
||||||
|
lx += pipe_step
|
||||||
|
self._txt_refs.append(st_ph)
|
||||||
|
self.create_image(lx, txt_cy_main, image=st_ph, anchor="w", tags="bb_txt")
|
||||||
|
|
||||||
|
# 4. Linke Erweiterungsfläche (nur sichtbar, wenn Text-Segmente nach unten ausgelagert wurden)
|
||||||
|
if sub_segs:
|
||||||
|
sub_txt_w = self._calc_segs_width(sub_segs, pipe_step)
|
||||||
|
l_box_w = sub_txt_w + 36
|
||||||
|
l_box_left = side_inset
|
||||||
|
l_box_cx = l_box_left + l_box_w // 2
|
||||||
|
|
||||||
|
self.create_rectangle(
|
||||||
|
l_box_left + 4,
|
||||||
|
sub_top + 4,
|
||||||
|
l_box_left + l_box_w - 4,
|
||||||
|
sub_top + self.SUB_BAR_H - 4,
|
||||||
|
fill="#100d17",
|
||||||
|
outline="",
|
||||||
|
tags="bb_sub_frame",
|
||||||
|
)
|
||||||
|
self._sub_left_frame_ph = self._get_bar_box_photo(
|
||||||
|
"box_gold_double", l_box_w, self.SUB_BAR_H, scale=0.72
|
||||||
|
)
|
||||||
|
if self._sub_left_frame_ph:
|
||||||
|
self.create_image(
|
||||||
|
l_box_cx,
|
||||||
|
cy_sub,
|
||||||
|
image=self._sub_left_frame_ph,
|
||||||
|
anchor="center",
|
||||||
|
tags="bb_sub_frame",
|
||||||
|
)
|
||||||
|
|
||||||
|
sub_lx = l_box_cx - sub_txt_w // 2
|
||||||
|
for i, seg in enumerate(sub_segs):
|
||||||
|
if i > 0:
|
||||||
|
self.create_image(sub_lx + 5, txt_cy_sub, image=pipe_ph, anchor="w", tags="bb_txt")
|
||||||
|
sub_lx += pipe_step
|
||||||
|
ph = seg["photo"]
|
||||||
|
self._txt_refs.append(ph)
|
||||||
|
self.create_image(sub_lx, txt_cy_sub, image=ph, anchor="w", tags="bb_txt")
|
||||||
|
sub_lx += ph.width()
|
||||||
|
|
@ -0,0 +1,374 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/base/solitaire_canvas_input.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
from games.solitaire.base.solitaire_core import SolitaireCard
|
||||||
|
from games.solitaire.base.solitaire_tap_prefs import (
|
||||||
|
SINGLE_TAP_MAX_HOLD_SEC,
|
||||||
|
is_single_tap_to_move_enabled,
|
||||||
|
)
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
ACCENT_GOLD,
|
||||||
|
BORDER_COLOR,
|
||||||
|
CELL_BG,
|
||||||
|
ERROR_FG,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_BODY,
|
||||||
|
MUTED_FG,
|
||||||
|
PLAYING_CARD_SIZE,
|
||||||
|
SUBTLE_BORDER,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
|
||||||
|
|
||||||
|
class SolitaireCanvasInput:
|
||||||
|
"""
|
||||||
|
Kapselt für alle Solitaire-Tische das Canvas-Frame-Rendering, Slot-/Karten-Zeichnen,
|
||||||
|
Kartenflug-Animationen sowie Maus-, Drag-&-Drop- und Tap-/Doppelklick-Steuerung.
|
||||||
|
"""
|
||||||
|
|
||||||
|
DRAG_STACK_DY_FACTOR: float = 0.195
|
||||||
|
DRAG_THRESHOLD_PX: int = 5
|
||||||
|
DOUBLE_CLICK_SEC: float = 0.30
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _card_key(card: SolitaireCard) -> tuple[str, str, int]:
|
||||||
|
return (card.suit, card.rank, card.deck_id)
|
||||||
|
|
||||||
|
def _get_card_aspect(self) -> float:
|
||||||
|
if self._card_aspect is None:
|
||||||
|
sample_pil = self.ctx.assets._load_pil(
|
||||||
|
self.ctx.assets.res.get_card_back_path(self.cfg["back_color"])
|
||||||
|
)
|
||||||
|
if sample_pil and sample_pil.size[0] > 0:
|
||||||
|
self._card_aspect = sample_pil.size[1] / sample_pil.size[0]
|
||||||
|
else:
|
||||||
|
self._card_aspect = PLAYING_CARD_SIZE[1] / PLAYING_CARD_SIZE[0]
|
||||||
|
return self._card_aspect
|
||||||
|
|
||||||
|
def _on_canvas_configure(self, _event=None):
|
||||||
|
if not self._canvas_alive() or self._fx_overlay is not None:
|
||||||
|
return
|
||||||
|
if self.hover_zoom is not None:
|
||||||
|
self.hover_zoom.cancel()
|
||||||
|
if self.animator:
|
||||||
|
self.animator.flush()
|
||||||
|
if self._resize_job is not None:
|
||||||
|
try:
|
||||||
|
self.ctx.root.after_cancel(self._resize_job)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
self._resize_job = self.ctx.root.after(35, self._recompute_and_draw)
|
||||||
|
except Exception:
|
||||||
|
self._resize_job = None
|
||||||
|
|
||||||
|
def _prepare_canvas_frame(
|
||||||
|
self, min_w: int = 640, min_h: int = 420
|
||||||
|
) -> tuple[int, int]:
|
||||||
|
keep_ids = set(self.canvas.find_withtag("table_bg_slice")) | set(
|
||||||
|
self.canvas.find_withtag("modal_dim_veil")
|
||||||
|
)
|
||||||
|
for item_id in self.canvas.find_all():
|
||||||
|
if item_id not in keep_ids:
|
||||||
|
self.canvas.delete(item_id)
|
||||||
|
self._canvas_ui_refs.clear()
|
||||||
|
cw = max(min_w, self.canvas.winfo_width())
|
||||||
|
ch = max(min_h, self.canvas.winfo_height())
|
||||||
|
self._bg_renderer.draw_on_canvas(self.canvas, cw, ch)
|
||||||
|
return cw, ch
|
||||||
|
|
||||||
|
def _finish_canvas_frame(
|
||||||
|
self, canvas_w: int, canvas_h: int, exclude_source, hidden: set
|
||||||
|
):
|
||||||
|
if (
|
||||||
|
self.engine.has_timer_started
|
||||||
|
and not self._window_active
|
||||||
|
and not self.engine.won
|
||||||
|
and not self._game_concluded
|
||||||
|
and self._modal_overlay is None
|
||||||
|
and self._fx_overlay is None
|
||||||
|
):
|
||||||
|
p_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("sol_canvas_paused_banner"), FONT_SIZE_BODY, FONT_COLOR_TITLE_MAIN
|
||||||
|
)
|
||||||
|
bw, bh = p_ph.width() + 56, max(44, p_ph.height() + 18)
|
||||||
|
box_ph = self.ctx.assets.get_box_photo("box_purple", (bw, bh))
|
||||||
|
self._canvas_ui_refs.extend([p_ph, box_ph] if box_ph else [p_ph])
|
||||||
|
pcx, pcy = canvas_w // 2, canvas_h - bh // 2 - 18
|
||||||
|
if box_ph:
|
||||||
|
self.canvas.create_image(pcx, pcy, image=box_ph, anchor="center")
|
||||||
|
self.canvas.create_image(pcx, pcy, image=p_ph, anchor="center")
|
||||||
|
|
||||||
|
if self.canvas.find_withtag("modal_dim_veil"):
|
||||||
|
self.canvas.tag_raise("modal_dim_veil")
|
||||||
|
if self.hover_zoom is not None and exclude_source is None and not hidden:
|
||||||
|
self.hover_zoom.refresh_after_redraw()
|
||||||
|
self._sync_buttons()
|
||||||
|
|
||||||
|
def _draw_slot(
|
||||||
|
self,
|
||||||
|
x: int,
|
||||||
|
y: int,
|
||||||
|
symbol: str = "",
|
||||||
|
symbol_color: str = MUTED_FG,
|
||||||
|
highlight_color: str | None = None,
|
||||||
|
draw_red_cross: bool = False,
|
||||||
|
):
|
||||||
|
cw, ch = self.card_size
|
||||||
|
outline = (
|
||||||
|
ERROR_FG
|
||||||
|
if draw_red_cross
|
||||||
|
else (highlight_color if highlight_color else BORDER_COLOR)
|
||||||
|
)
|
||||||
|
width = 2 if (highlight_color or draw_red_cross) else 1
|
||||||
|
self.canvas.create_rectangle(
|
||||||
|
x, y, x + cw, y + ch, fill=CELL_BG, outline=outline, width=width
|
||||||
|
)
|
||||||
|
if draw_red_cross:
|
||||||
|
px, py = max(14, int(cw * 0.22)), max(18, int(ch * 0.22))
|
||||||
|
self.canvas.create_line(
|
||||||
|
x + px, y + py, x + cw - px, y + ch - py,
|
||||||
|
fill="#ff4455", width=4, capstyle="round",
|
||||||
|
)
|
||||||
|
self.canvas.create_line(
|
||||||
|
x + cw - px, y + py, x + px, y + ch - py,
|
||||||
|
fill="#ff4455", width=4, capstyle="round",
|
||||||
|
)
|
||||||
|
elif symbol:
|
||||||
|
self.canvas.create_text(
|
||||||
|
x + cw // 2,
|
||||||
|
y + ch // 2,
|
||||||
|
text=symbol,
|
||||||
|
font=("Georgia", max(13, cw // 4), "bold"),
|
||||||
|
fill=symbol_color,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _draw_card_at(
|
||||||
|
self,
|
||||||
|
card: SolitaireCard,
|
||||||
|
x: int,
|
||||||
|
y: int,
|
||||||
|
tags: tuple[str, ...] = (),
|
||||||
|
highlight_color: str | None = None,
|
||||||
|
dim_non_movable: bool = False,
|
||||||
|
):
|
||||||
|
cw, ch = self.card_size
|
||||||
|
photo = (
|
||||||
|
self.ctx.assets.get_card_photo(card.filename, size=self.card_size)
|
||||||
|
if card.face_up
|
||||||
|
else self.ctx.assets.get_card_back_photo(
|
||||||
|
self.cfg["back_color"], size=self.card_size
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if photo is not None:
|
||||||
|
self.canvas.create_image(x, y, image=photo, anchor="nw", tags=tags)
|
||||||
|
else:
|
||||||
|
fill_c = "#f5f2f8" if card.face_up else "#201a2b"
|
||||||
|
self.canvas.create_rectangle(
|
||||||
|
x, y, x + cw, y + ch, fill=fill_c, outline=BORDER_COLOR, tags=tags
|
||||||
|
)
|
||||||
|
if card.face_up:
|
||||||
|
txt_c = "#c93b4b" if card.is_red else "#16131d"
|
||||||
|
self.canvas.create_text(
|
||||||
|
x + 9, y + 11, text=card.label, anchor="nw",
|
||||||
|
font=("Georgia", 10, "bold"), fill=txt_c, tags=tags,
|
||||||
|
)
|
||||||
|
|
||||||
|
if dim_non_movable and card.face_up and not highlight_color:
|
||||||
|
self.canvas.create_rectangle(
|
||||||
|
x, y, x + cw, y + ch, outline=SUBTLE_BORDER, width=1, tags=tags
|
||||||
|
)
|
||||||
|
if highlight_color:
|
||||||
|
self.canvas.create_rectangle(
|
||||||
|
x - 2, y - 2, x + cw + 2, y + ch + 2,
|
||||||
|
outline=highlight_color, width=2, tags=tags,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _run_animated_action(
|
||||||
|
self, action_fn, override_starts=None, duration_ms: int = 115, after_cb=None
|
||||||
|
) -> bool:
|
||||||
|
if self.hover_zoom is not None:
|
||||||
|
self.hover_zoom.cancel()
|
||||||
|
if self.animator:
|
||||||
|
self.animator.flush()
|
||||||
|
before_pos = self._snapshot_card_positions()
|
||||||
|
if override_starts:
|
||||||
|
before_pos.update(override_starts)
|
||||||
|
|
||||||
|
if not action_fn():
|
||||||
|
return False
|
||||||
|
|
||||||
|
after_pos = self._snapshot_card_positions()
|
||||||
|
moved_keys = {
|
||||||
|
k
|
||||||
|
for k, end_xy in after_pos.items()
|
||||||
|
if k in before_pos
|
||||||
|
and (
|
||||||
|
abs(end_xy[0] - before_pos[k][0]) > 3
|
||||||
|
or abs(end_xy[1] - before_pos[k][1]) > 3
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if not moved_keys or self.animator is None:
|
||||||
|
(after_cb if callable(after_cb) else self.redraw)()
|
||||||
|
return True
|
||||||
|
|
||||||
|
flights = [
|
||||||
|
{
|
||||||
|
"card": c,
|
||||||
|
"start": before_pos[self._card_key(c)],
|
||||||
|
"end": after_pos[self._card_key(c)],
|
||||||
|
}
|
||||||
|
for c in self._ordered_moved_cards(moved_keys)
|
||||||
|
]
|
||||||
|
self.redraw(hidden_card_keys=moved_keys)
|
||||||
|
|
||||||
|
def finish():
|
||||||
|
if self._canvas_alive():
|
||||||
|
(after_cb if callable(after_cb) else self.redraw)()
|
||||||
|
|
||||||
|
self.animator.start(
|
||||||
|
flights, self._draw_card_at, duration_ms=duration_ms, on_done=finish
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _on_mouse_down(self, event):
|
||||||
|
if self.hover_zoom is not None:
|
||||||
|
self.hover_zoom.cancel()
|
||||||
|
if self._is_ui_locked():
|
||||||
|
return
|
||||||
|
if self.animator and self.animator.is_active:
|
||||||
|
self.animator.flush()
|
||||||
|
self._window_active = True
|
||||||
|
self._clear_hint()
|
||||||
|
hit = self._hit_test(event.x, event.y)
|
||||||
|
self._press_info = None
|
||||||
|
self._dragging = False
|
||||||
|
if not hit:
|
||||||
|
return
|
||||||
|
self.engine.start_timer_if_needed()
|
||||||
|
self._update_hud_text()
|
||||||
|
hit["start_xy"] = (event.x, event.y)
|
||||||
|
hit["press_ts"] = time.monotonic()
|
||||||
|
self._press_info = hit
|
||||||
|
|
||||||
|
def _on_mouse_move(self, event):
|
||||||
|
if (
|
||||||
|
not self._press_info
|
||||||
|
or not self._press_info.get("cards")
|
||||||
|
or self._fx_overlay is not None
|
||||||
|
):
|
||||||
|
return
|
||||||
|
sx, sy = self._press_info["start_xy"]
|
||||||
|
if not self._dragging:
|
||||||
|
if (
|
||||||
|
abs(event.x - sx) < self.DRAG_THRESHOLD_PX
|
||||||
|
and abs(event.y - sy) < self.DRAG_THRESHOLD_PX
|
||||||
|
):
|
||||||
|
return
|
||||||
|
if self.hover_zoom is not None:
|
||||||
|
self.hover_zoom.cancel()
|
||||||
|
self._dragging = True
|
||||||
|
self._drag_last_xy = (sx, sy)
|
||||||
|
self.redraw(exclude_source=self._press_info)
|
||||||
|
ox, oy = self._press_info["origin"]
|
||||||
|
drag_dy = max(15, int(self.card_size[1] * self.DRAG_STACK_DY_FACTOR))
|
||||||
|
for i, card in enumerate(self._press_info["cards"]):
|
||||||
|
self._draw_card_at(
|
||||||
|
card,
|
||||||
|
ox,
|
||||||
|
oy + i * drag_dy,
|
||||||
|
tags=("drag_ghost",),
|
||||||
|
highlight_color=ACCENT_GOLD if i == 0 else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
dx = event.x - self._drag_last_xy[0]
|
||||||
|
dy = event.y - self._drag_last_xy[1]
|
||||||
|
self._drag_last_xy = (event.x, event.y)
|
||||||
|
self.canvas.move("drag_ghost", dx, dy)
|
||||||
|
|
||||||
|
def _on_drop_succeeded_sound(self):
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
|
||||||
|
def _on_mouse_up(self, event):
|
||||||
|
info, was_dragging = self._press_info, self._dragging
|
||||||
|
self._press_info, self._dragging = None, False
|
||||||
|
if not info:
|
||||||
|
return
|
||||||
|
if not was_dragging:
|
||||||
|
self._handle_click(info)
|
||||||
|
return
|
||||||
|
|
||||||
|
ox, oy = info["origin"]
|
||||||
|
sx, sy = info["start_xy"]
|
||||||
|
drop_x, drop_y = ox + (event.x - sx), oy + (event.y - sy)
|
||||||
|
drag_dy = max(15, int(self.card_size[1] * self.DRAG_STACK_DY_FACTOR))
|
||||||
|
override = {
|
||||||
|
self._card_key(c): (drop_x, drop_y + i * drag_dy)
|
||||||
|
for i, c in enumerate(info["cards"])
|
||||||
|
}
|
||||||
|
|
||||||
|
if self._run_animated_action(
|
||||||
|
lambda: self._try_drop(info, drop_x, drop_y),
|
||||||
|
override_starts=override,
|
||||||
|
duration_ms=78,
|
||||||
|
after_cb=self._after_player_move,
|
||||||
|
):
|
||||||
|
self._on_drop_succeeded_sound()
|
||||||
|
else:
|
||||||
|
target_pos = self._snapshot_card_positions()
|
||||||
|
cards: list[SolitaireCard] = info["cards"]
|
||||||
|
hidden_keys = {self._card_key(c) for c in cards}
|
||||||
|
flights = [
|
||||||
|
{
|
||||||
|
"card": c,
|
||||||
|
"start": override[self._card_key(c)],
|
||||||
|
"end": target_pos.get(self._card_key(c), (ox, oy + i * drag_dy)),
|
||||||
|
}
|
||||||
|
for i, c in enumerate(cards)
|
||||||
|
]
|
||||||
|
self.redraw(hidden_card_keys=hidden_keys)
|
||||||
|
if self.animator:
|
||||||
|
self.animator.start(
|
||||||
|
flights, self._draw_card_at, duration_ms=85, on_done=self.redraw
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.redraw()
|
||||||
|
|
||||||
|
def _dispatch_tap_or_double_click(self, info: dict):
|
||||||
|
now = time.monotonic()
|
||||||
|
if is_single_tap_to_move_enabled():
|
||||||
|
self._last_click_target = None
|
||||||
|
if (now - info.get("press_ts", now)) <= SINGLE_TAP_MAX_HOLD_SEC:
|
||||||
|
self._smart_auto_move(info)
|
||||||
|
return
|
||||||
|
target_id = (info["zone"], info.get("col", -1), info.get("idx", -1))
|
||||||
|
if (
|
||||||
|
self._last_click_target == target_id
|
||||||
|
and (now - self._last_click_ts) <= self.DOUBLE_CLICK_SEC
|
||||||
|
):
|
||||||
|
self._last_click_target = None
|
||||||
|
self._smart_auto_move(info)
|
||||||
|
else:
|
||||||
|
self._last_click_ts = now
|
||||||
|
self._last_click_target = target_id
|
||||||
|
|
||||||
|
def _on_right_click(self, event):
|
||||||
|
if self.hover_zoom is not None:
|
||||||
|
self.hover_zoom.cancel()
|
||||||
|
if self._is_ui_locked():
|
||||||
|
return
|
||||||
|
if self.animator and self.animator.is_active:
|
||||||
|
self.animator.flush()
|
||||||
|
self._window_active = True
|
||||||
|
self._clear_hint()
|
||||||
|
hit = self._hit_test(event.x, event.y)
|
||||||
|
if hit:
|
||||||
|
self.engine.start_timer_if_needed()
|
||||||
|
self._update_hud_text()
|
||||||
|
if hit.get("zone") == "stock":
|
||||||
|
self._handle_click(hit)
|
||||||
|
else:
|
||||||
|
self._smart_auto_move(hit)
|
||||||
|
|
@ -0,0 +1,57 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/base/solitaire_card.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
CARD_FILE_PATTERN,
|
||||||
|
RED_SUITS,
|
||||||
|
SUIT_SYMBOLS,
|
||||||
|
)
|
||||||
|
|
||||||
|
SOLITAIRE_RANKS: tuple[str, ...] = (
|
||||||
|
"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"
|
||||||
|
)
|
||||||
|
RANK_VALUES: dict[str, int] = {rank: idx + 1 for idx, rank in enumerate(SOLITAIRE_RANKS)}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SolitaireCard:
|
||||||
|
suit: str
|
||||||
|
rank: str
|
||||||
|
face_up: bool = False
|
||||||
|
deck_id: int = 0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def value(self) -> int:
|
||||||
|
return RANK_VALUES[self.rank]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_red(self) -> bool:
|
||||||
|
return self.suit in RED_SUITS
|
||||||
|
|
||||||
|
@property
|
||||||
|
def filename(self) -> str:
|
||||||
|
return CARD_FILE_PATTERN.format(suit=self.suit, rank=self.rank)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def label(self) -> str:
|
||||||
|
return f"{self.rank}{SUIT_SYMBOLS.get(self.suit, self.suit)}"
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"s": self.suit,
|
||||||
|
"r": self.rank,
|
||||||
|
"u": 1 if self.face_up else 0,
|
||||||
|
"d": self.deck_id,
|
||||||
|
}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_dict(cls, data: dict) -> SolitaireCard:
|
||||||
|
return cls(
|
||||||
|
suit=data["s"],
|
||||||
|
rank=data["r"],
|
||||||
|
face_up=bool(data.get("u", 0)),
|
||||||
|
deck_id=int(data.get("d", 0)),
|
||||||
|
)
|
||||||
|
|
@ -5,60 +5,23 @@ from __future__ import annotations
|
||||||
import json
|
import json
|
||||||
import random
|
import random
|
||||||
import time
|
import time
|
||||||
from dataclasses import dataclass
|
|
||||||
|
|
||||||
from resources.code_res.game_constants import (
|
from games.solitaire.base.solitaire_card import (
|
||||||
CARD_FILE_PATTERN,
|
RANK_VALUES,
|
||||||
RED_SUITS,
|
SOLITAIRE_RANKS,
|
||||||
SUIT_SYMBOLS,
|
SolitaireCard,
|
||||||
SUITS,
|
|
||||||
)
|
)
|
||||||
|
from resources.code_res.game_constants import SUITS
|
||||||
|
|
||||||
SOLITAIRE_RANKS: tuple[str, ...] = (
|
__all__ = [
|
||||||
"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"
|
"SOLITAIRE_RANKS",
|
||||||
)
|
"RANK_VALUES",
|
||||||
RANK_VALUES: dict[str, int] = {rank: idx + 1 for idx, rank in enumerate(SOLITAIRE_RANKS)}
|
"SolitaireCard",
|
||||||
|
"SolitaireBaseEngine",
|
||||||
|
"create_solitaire_deck",
|
||||||
@dataclass
|
"is_alternating_descending",
|
||||||
class SolitaireCard:
|
"is_same_suit_descending",
|
||||||
suit: str
|
]
|
||||||
rank: str
|
|
||||||
face_up: bool = False
|
|
||||||
deck_id: int = 0
|
|
||||||
|
|
||||||
@property
|
|
||||||
def value(self) -> int:
|
|
||||||
return RANK_VALUES[self.rank]
|
|
||||||
|
|
||||||
@property
|
|
||||||
def is_red(self) -> bool:
|
|
||||||
return self.suit in RED_SUITS
|
|
||||||
|
|
||||||
@property
|
|
||||||
def filename(self) -> str:
|
|
||||||
return CARD_FILE_PATTERN.format(suit=self.suit, rank=self.rank)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def label(self) -> str:
|
|
||||||
return f"{self.rank}{SUIT_SYMBOLS.get(self.suit, self.suit)}"
|
|
||||||
|
|
||||||
def to_dict(self) -> dict:
|
|
||||||
return {
|
|
||||||
"s": self.suit,
|
|
||||||
"r": self.rank,
|
|
||||||
"u": 1 if self.face_up else 0,
|
|
||||||
"d": self.deck_id,
|
|
||||||
}
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def from_dict(cls, data: dict) -> SolitaireCard:
|
|
||||||
return cls(
|
|
||||||
suit=data["s"],
|
|
||||||
rank=data["r"],
|
|
||||||
face_up=bool(data.get("u", 0)),
|
|
||||||
deck_id=int(data.get("d", 0)),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def create_solitaire_deck(
|
def create_solitaire_deck(
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,417 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/base/solitaire_menu_base.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog
|
||||||
|
from models.database import Database
|
||||||
|
from models.progression import Progression
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
FONT_COLOR_BODY_DEFAULT,
|
||||||
|
FONT_COLOR_BODY_MUTED,
|
||||||
|
FONT_COLOR_HEADING_SUB,
|
||||||
|
FONT_COLOR_STATUS_LOSS,
|
||||||
|
FONT_COLOR_STATUS_WIN,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_BODY,
|
||||||
|
FONT_SIZE_HEADING,
|
||||||
|
FONT_SIZE_SMALL_MIN,
|
||||||
|
FONT_SIZE_TITLE_LG,
|
||||||
|
SOLITAIRE_DIFFICULTIES,
|
||||||
|
SOLO_FORFEIT_XP_RATIO,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from view.widgets.goth_dropdown import GothDropdown
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
from view.widgets.menu_body_canvas import MenuBodyCanvas
|
||||||
|
|
||||||
|
|
||||||
|
class SolitaireMenuBase:
|
||||||
|
"""
|
||||||
|
Gemeinsame Vorauswahl-Menü-Basisklasse für alle Solitaire-Spiele
|
||||||
|
(Klondike, FreeCell, Spider, Pyramid, TriPeaks):
|
||||||
|
Kapselt Fortsetzen-Banner, Aufgabe-Bestätigung, Varianten-Toggles & Schwierigkeits-Auswahl.
|
||||||
|
"""
|
||||||
|
|
||||||
|
GAME_FOLDER_ID: str = ""
|
||||||
|
GAME_TITLE_KEY: str = ""
|
||||||
|
TOPBAR_KEY: str = ""
|
||||||
|
SUBTITLE_KEY: str = "sol_menu_subtitle"
|
||||||
|
CONTROLS_HINT_KEY: str = ""
|
||||||
|
|
||||||
|
DIFF_SETTING_PREFIX: str = ""
|
||||||
|
VARIANT_SETTING_PREFIX: str = ""
|
||||||
|
DEFAULT_VARIANT_KEY: str = ""
|
||||||
|
DEFAULT_SCORE: int = 0
|
||||||
|
REQUIRED_BOARD_KEYS: tuple[str, ...] = ("tableau",)
|
||||||
|
|
||||||
|
MODE_LABEL_KEY: str = ""
|
||||||
|
VARIANT_TOGGLES: tuple[tuple[str, str], ...] = ()
|
||||||
|
TOGGLE_BTN_WIDTH: int = 160
|
||||||
|
DESC_KEY_PREFIX: str = ""
|
||||||
|
|
||||||
|
def __init__(self, context):
|
||||||
|
self.ctx = context
|
||||||
|
self._modal_overlay: tk.Widget | None = None
|
||||||
|
self._return_bind_id: str | None = None
|
||||||
|
self._photo_refs: list = []
|
||||||
|
|
||||||
|
def _variants_dict(self) -> dict[str, dict]:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _launch_table_view(
|
||||||
|
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
|
||||||
|
) -> None:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _clear_modal(self):
|
||||||
|
if self._return_bind_id is not None:
|
||||||
|
try:
|
||||||
|
self.ctx.root.unbind("<Return>", self._return_bind_id)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._return_bind_id = None
|
||||||
|
if self._modal_overlay is not None:
|
||||||
|
try:
|
||||||
|
self._modal_overlay.destroy()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._modal_overlay = None
|
||||||
|
|
||||||
|
def show(
|
||||||
|
self,
|
||||||
|
status_msg: str = "",
|
||||||
|
status_is_ok: bool = False,
|
||||||
|
ask_resume_popup: bool = False,
|
||||||
|
):
|
||||||
|
self._clear_modal()
|
||||||
|
pid = self.ctx.profile["id"]
|
||||||
|
self.ctx.sounds.play_menu_music()
|
||||||
|
self.ctx.root.clear_window(apply_global_bg=True)
|
||||||
|
self._photo_refs.clear()
|
||||||
|
self.ctx.refresh_game_progress()
|
||||||
|
|
||||||
|
diff_setting_key = f"{self.DIFF_SETTING_PREFIX}_{pid}"
|
||||||
|
saved_diff_str = Database.load_setting(diff_setting_key, "1")
|
||||||
|
selected_diff = (
|
||||||
|
int(saved_diff_str)
|
||||||
|
if saved_diff_str.isdigit() and int(saved_diff_str) in SOLITAIRE_DIFFICULTIES
|
||||||
|
else 1
|
||||||
|
)
|
||||||
|
|
||||||
|
variants_map = self._variants_dict()
|
||||||
|
if self.VARIANT_SETTING_PREFIX and len(variants_map) > 1:
|
||||||
|
var_setting_key = f"{self.VARIANT_SETTING_PREFIX}_{pid}"
|
||||||
|
selected_variant = Database.load_setting(var_setting_key, self.DEFAULT_VARIANT_KEY)
|
||||||
|
if selected_variant not in variants_map:
|
||||||
|
selected_variant = self.DEFAULT_VARIANT_KEY
|
||||||
|
else:
|
||||||
|
var_setting_key = ""
|
||||||
|
selected_variant = self.DEFAULT_VARIANT_KEY
|
||||||
|
|
||||||
|
self.ctx.build_game_topbar(
|
||||||
|
self.ctx.root,
|
||||||
|
t(self.TOPBAR_KEY),
|
||||||
|
stats_endpoint=self.GAME_FOLDER_ID,
|
||||||
|
on_game_menu=None,
|
||||||
|
on_stats_back=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
|
||||||
|
stats_enabled=True,
|
||||||
|
extra_right_text="",
|
||||||
|
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
|
||||||
|
)
|
||||||
|
|
||||||
|
cv = MenuBodyCanvas(self.ctx)
|
||||||
|
btn_norm = self.ctx.assets.raw_btn_default
|
||||||
|
btn_purp = self.ctx.assets.raw_btn_purple
|
||||||
|
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
|
||||||
|
|
||||||
|
saved = Database.load_game_state(pid, self.GAME_FOLDER_ID)
|
||||||
|
saved_meta = self._parse_saved_meta(saved)
|
||||||
|
|
||||||
|
resume_btn = None
|
||||||
|
if saved and saved_meta is not None:
|
||||||
|
resume_btn = ImageButton(
|
||||||
|
cv, t("sol_resume_btn"), btn_fire, btn_fire,
|
||||||
|
lambda: self._resume_saved(saved, saved_meta["difficulty"]),
|
||||||
|
sound_mgr=self.ctx.sounds, width=180, height=38, style="fire",
|
||||||
|
)
|
||||||
|
|
||||||
|
def switch_variant(v_key: str):
|
||||||
|
if v_key == selected_variant or self._modal_overlay is not None:
|
||||||
|
return
|
||||||
|
if var_setting_key:
|
||||||
|
Database.save_setting(var_setting_key, v_key)
|
||||||
|
self.show(status_msg=status_msg, status_is_ok=status_is_ok)
|
||||||
|
|
||||||
|
toggle_btns: list[ImageButton] = []
|
||||||
|
for v_key, lbl_key in self.VARIANT_TOGGLES:
|
||||||
|
is_sel = (selected_variant == v_key)
|
||||||
|
toggle_btns.append(
|
||||||
|
ImageButton(
|
||||||
|
cv, t(lbl_key),
|
||||||
|
btn_fire if is_sel else btn_norm,
|
||||||
|
btn_fire if is_sel else btn_purp,
|
||||||
|
lambda k=v_key: switch_variant(k),
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=self.TOGGLE_BTN_WIDTH, height=36,
|
||||||
|
style="fire" if is_sel else "amethyst",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
diff_levels = sorted(SOLITAIRE_DIFFICULTIES.keys())
|
||||||
|
diff_labels = [t(f"sol_diff_{lvl}") for lvl in diff_levels]
|
||||||
|
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in diff_levels}
|
||||||
|
diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}"))
|
||||||
|
|
||||||
|
diff_dd = GothDropdown(
|
||||||
|
cv, self.ctx.assets, values=diff_labels, textvariable=diff_var,
|
||||||
|
on_change=lambda val: Database.save_setting(diff_setting_key, str(diff_map.get(val, 1))),
|
||||||
|
sound_mgr=self.ctx.sounds, width=420, height=40,
|
||||||
|
)
|
||||||
|
|
||||||
|
start_btn = ImageButton(
|
||||||
|
cv, t("sol_start_btn"), btn_fire, btn_fire,
|
||||||
|
lambda: self._on_start_clicked(selected_variant, diff_map.get(diff_var.get(), 1), saved, saved_meta),
|
||||||
|
sound_mgr=self.ctx.sounds, width=205, height=40, style="fire",
|
||||||
|
)
|
||||||
|
|
||||||
|
has_toggles = len(toggle_btns) > 0
|
||||||
|
|
||||||
|
def draw_layout(w: int, h: int):
|
||||||
|
cv.sync_bg(w, h)
|
||||||
|
cv.delete("fg")
|
||||||
|
self._photo_refs.clear()
|
||||||
|
|
||||||
|
box_w = min(940, w - 120)
|
||||||
|
cx = w // 2
|
||||||
|
x_left = cx - box_w // 2
|
||||||
|
cur_y = max(24, int(h * 0.055))
|
||||||
|
|
||||||
|
title_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t(self.GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left"
|
||||||
|
)
|
||||||
|
sub_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t(self.SUBTITLE_KEY), FONT_SIZE_BODY, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.extend([title_ph, sub_ph])
|
||||||
|
cv.create_image(x_left, cur_y, image=title_ph, anchor="nw", tags="fg")
|
||||||
|
cur_y += title_ph.height() + 4
|
||||||
|
cv.create_image(x_left, cur_y, image=sub_ph, anchor="nw", tags="fg")
|
||||||
|
cur_y += sub_ph.height() + 14
|
||||||
|
|
||||||
|
if status_msg:
|
||||||
|
st_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
status_msg, FONT_SIZE_BODY,
|
||||||
|
FONT_COLOR_STATUS_WIN if status_is_ok else FONT_COLOR_STATUS_LOSS,
|
||||||
|
max_width=box_w, align="left",
|
||||||
|
)
|
||||||
|
self._photo_refs.append(st_ph)
|
||||||
|
cv.create_image(x_left, cur_y, image=st_ph, anchor="nw", tags="fg")
|
||||||
|
cur_y += st_ph.height() + 12
|
||||||
|
|
||||||
|
if saved and saved_meta is not None and resume_btn is not None:
|
||||||
|
res_h = 84
|
||||||
|
res_cy = cur_y + res_h // 2
|
||||||
|
r_box = self.ctx.assets.get_box_photo("box_gold_double", (box_w, res_h))
|
||||||
|
if r_box:
|
||||||
|
self._photo_refs.append(r_box)
|
||||||
|
cv.create_image(cx, res_cy, image=r_box, anchor="center", tags="fg")
|
||||||
|
|
||||||
|
rt_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("sol_resume_box_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
|
||||||
|
)
|
||||||
|
ri_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
self._format_resume_info(saved, saved_meta),
|
||||||
|
FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT,
|
||||||
|
max_width=box_w - resume_btn.pixel_width - 70, align="left",
|
||||||
|
)
|
||||||
|
self._photo_refs.extend([rt_ph, ri_ph])
|
||||||
|
cv.create_image(x_left + 26, res_cy - 17, image=rt_ph, anchor="w", tags="fg")
|
||||||
|
cv.create_image(x_left + 26, res_cy + 15, image=ri_ph, anchor="w", tags="fg")
|
||||||
|
cv.create_window(x_left + box_w - 26, res_cy, window=resume_btn, anchor="e", tags="fg")
|
||||||
|
cur_y += res_h + 18
|
||||||
|
|
||||||
|
sec_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("sol_setup_sec_title"), FONT_SIZE_HEADING - 2, FONT_COLOR_HEADING_SUB, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.append(sec_ph)
|
||||||
|
cv.create_image(x_left + 6, cur_y, image=sec_ph, anchor="nw", tags="fg")
|
||||||
|
cur_y += sec_ph.height() + 8
|
||||||
|
|
||||||
|
setup_h = 238 if has_toggles else 208
|
||||||
|
setup_cy = cur_y + setup_h // 2
|
||||||
|
s_box = self.ctx.assets.get_box_photo("box_big", (box_w, setup_h))
|
||||||
|
if s_box:
|
||||||
|
self._photo_refs.append(s_box)
|
||||||
|
cv.create_image(cx, setup_cy, image=s_box, anchor="center", tags="fg")
|
||||||
|
|
||||||
|
lbl_col, val_col = x_left + 32, x_left + 220
|
||||||
|
r1_y = cur_y + 44
|
||||||
|
m_lbl = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t(self.MODE_LABEL_KEY), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.append(m_lbl)
|
||||||
|
cv.create_image(lbl_col, r1_y, image=m_lbl, anchor="w", tags="fg")
|
||||||
|
|
||||||
|
dsc_txt = t(f"{self.DESC_KEY_PREFIX}{selected_variant}")
|
||||||
|
if has_toggles:
|
||||||
|
bx_cur = val_col
|
||||||
|
for tb in toggle_btns:
|
||||||
|
cv.create_window(bx_cur, r1_y, window=tb, anchor="w", tags="fg")
|
||||||
|
bx_cur += tb.pixel_width + 10
|
||||||
|
dsc_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
dsc_txt, FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=box_w - 260, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.append(dsc_ph)
|
||||||
|
cv.create_image(val_col, r1_y + 34, image=dsc_ph, anchor="w", tags="fg")
|
||||||
|
r2_y = cur_y + 128
|
||||||
|
else:
|
||||||
|
m_val = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t(f"variant_{selected_variant}"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
|
||||||
|
)
|
||||||
|
dsc_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
dsc_txt, FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED,
|
||||||
|
max_width=max(180, box_w - 275 - m_val.width()), align="left",
|
||||||
|
)
|
||||||
|
self._photo_refs.extend([m_val, dsc_ph])
|
||||||
|
cv.create_image(val_col, r1_y, image=m_val, anchor="w", tags="fg")
|
||||||
|
cv.create_image(val_col + m_val.width() + 18, r1_y, image=dsc_ph, anchor="w", tags="fg")
|
||||||
|
r2_y = cur_y + 104
|
||||||
|
|
||||||
|
d_lbl = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t("sol_diff_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.append(d_lbl)
|
||||||
|
cv.create_image(lbl_col, r2_y, image=d_lbl, anchor="w", tags="fg")
|
||||||
|
|
||||||
|
dd_w = max(240, box_w - 260)
|
||||||
|
if diff_dd._width != dd_w:
|
||||||
|
diff_dd._width = dd_w
|
||||||
|
diff_dd.configure(width=dd_w)
|
||||||
|
diff_dd._render_closed()
|
||||||
|
cv.create_window(val_col, r2_y, window=diff_dd, anchor="w", tags="fg")
|
||||||
|
|
||||||
|
cv.create_window(x_left + box_w - 32, cur_y + setup_h - 38, window=start_btn, anchor="e", tags="fg")
|
||||||
|
|
||||||
|
hint_ph = self.ctx.assets.get_goth_text_photo(
|
||||||
|
t(self.CONTROLS_HINT_KEY), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left"
|
||||||
|
)
|
||||||
|
self._photo_refs.append(hint_ph)
|
||||||
|
cv.create_image(x_left + 6, cur_y + setup_h + 14, image=hint_ph, anchor="nw", tags="fg")
|
||||||
|
|
||||||
|
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
|
||||||
|
self.ctx.root.update_idletasks()
|
||||||
|
draw_layout(max(900, cv.winfo_width()), max(620, cv.winfo_height()))
|
||||||
|
|
||||||
|
if ask_resume_popup and saved and saved_meta is not None:
|
||||||
|
self._show_resume_prompt_modal(saved, saved_meta)
|
||||||
|
|
||||||
|
def _parse_saved_meta(self, saved: dict | None) -> dict | None:
|
||||||
|
if not saved:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
data = json.loads(saved["state_json"])
|
||||||
|
if data.get("won"):
|
||||||
|
return None
|
||||||
|
board = data.get("board", {})
|
||||||
|
if not board or any(req_k not in board for req_k in self.REQUIRED_BOARD_KEYS):
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"moves": max(0, int(data.get("moves", 0))),
|
||||||
|
"score": int(data.get("score", self.DEFAULT_SCORE)),
|
||||||
|
"elapsed_sec": float(data.get("elapsed_sec", 0.0)),
|
||||||
|
"difficulty": max(0, min(3, int(board.get("difficulty", 1)))),
|
||||||
|
}
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _format_resume_info(saved: dict, saved_meta: dict) -> str:
|
||||||
|
return t(
|
||||||
|
"sol_resume_info",
|
||||||
|
t(f"variant_{saved['variant_key']}"),
|
||||||
|
t(f"sol_diff_short_{saved_meta['difficulty']}"),
|
||||||
|
saved_meta["moves"],
|
||||||
|
saved_meta["score"],
|
||||||
|
Database.format_seconds(saved_meta["elapsed_sec"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
|
||||||
|
self._clear_modal()
|
||||||
|
|
||||||
|
def resume_now(_event=None):
|
||||||
|
self._clear_modal()
|
||||||
|
self._resume_saved(saved, saved_meta["difficulty"])
|
||||||
|
|
||||||
|
try:
|
||||||
|
self._return_bind_id = self.ctx.root.bind("<Return>", resume_now, add="+")
|
||||||
|
except tk.TclError:
|
||||||
|
self._return_bind_id = None
|
||||||
|
|
||||||
|
self._modal_overlay = SolitaireModalDialog(
|
||||||
|
self.ctx,
|
||||||
|
title_txt=t("sol_resume_box_title"),
|
||||||
|
body_txt=self._format_resume_info(saved, saved_meta),
|
||||||
|
buttons=[
|
||||||
|
(t("sol_resume_btn"), "fire", resume_now),
|
||||||
|
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def _resume_saved(self, saved: dict, difficulty: int):
|
||||||
|
self._clear_modal()
|
||||||
|
self._launch_table_view(saved["variant_key"], difficulty, resume_state_json=saved["state_json"])
|
||||||
|
|
||||||
|
def _on_start_clicked(
|
||||||
|
self, variant_key: str, difficulty: int, saved: dict | None, saved_meta: dict | None
|
||||||
|
):
|
||||||
|
if self._modal_overlay is not None:
|
||||||
|
return
|
||||||
|
if saved and saved_meta and saved_meta["moves"] > 0:
|
||||||
|
self._show_overwrite_confirm_modal(variant_key, difficulty, saved, saved_meta)
|
||||||
|
return
|
||||||
|
self._launch_fresh_game(variant_key, difficulty)
|
||||||
|
|
||||||
|
def _show_overwrite_confirm_modal(
|
||||||
|
self, new_variant_key: str, new_difficulty: int, saved: dict, saved_meta: dict
|
||||||
|
):
|
||||||
|
pid = self.ctx.profile["id"]
|
||||||
|
old_v, old_diff = saved["variant_key"], saved_meta["difficulty"]
|
||||||
|
prog = Database.get_game_progress(pid, self.GAME_FOLDER_ID)
|
||||||
|
variants_map = self._variants_dict()
|
||||||
|
v_mult = variants_map.get(old_v, {"xp_mult": 1.0})["xp_mult"]
|
||||||
|
d_mult = SOLITAIRE_DIFFICULTIES.get(old_diff, SOLITAIRE_DIFFICULTIES[1])["xp_mult"]
|
||||||
|
win_xp = Progression.calculate_match_xp(prog["level"], [], "WIN", variant_mult=v_mult * d_mult)
|
||||||
|
penalty = max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO)))
|
||||||
|
|
||||||
|
def forfeit_and_start():
|
||||||
|
floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0
|
||||||
|
Database.record_game_result(
|
||||||
|
pid, variant_key=old_v, won=False, duration_sec=saved_meta["elapsed_sec"], points_gained=0
|
||||||
|
)
|
||||||
|
Database.adjust_game_points(pid, self.GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp)
|
||||||
|
self.ctx.refresh_game_progress()
|
||||||
|
self._clear_modal()
|
||||||
|
self._launch_fresh_game(new_variant_key, new_difficulty)
|
||||||
|
|
||||||
|
self._modal_overlay = SolitaireModalDialog(
|
||||||
|
self.ctx,
|
||||||
|
title_txt=t("sol_forfeit_title"),
|
||||||
|
body_txt=t("sol_forfeit_desc", penalty),
|
||||||
|
is_danger=True,
|
||||||
|
buttons=[
|
||||||
|
(t("sol_resume_btn"), "fire", lambda: self._resume_saved(saved, old_diff)),
|
||||||
|
(t("sol_forfeit_confirm_new"), "amethyst", forfeit_and_start),
|
||||||
|
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def _launch_fresh_game(self, variant_key: str, difficulty: int):
|
||||||
|
pid = self.ctx.profile["id"]
|
||||||
|
Database.save_setting(f"{self.DIFF_SETTING_PREFIX}_{pid}", str(difficulty))
|
||||||
|
if self.VARIANT_SETTING_PREFIX:
|
||||||
|
Database.save_setting(f"{self.VARIANT_SETTING_PREFIX}_{pid}", variant_key)
|
||||||
|
Database.delete_game_state(pid, self.GAME_FOLDER_ID)
|
||||||
|
self._launch_table_view(variant_key, difficulty, resume_state_json=None)
|
||||||
|
|
@ -0,0 +1,118 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/base/solitaire_modal_dialog.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
from PIL import Image, ImageTk
|
||||||
|
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
BG_COLOR,
|
||||||
|
FONT_COLOR_BODY_DEFAULT,
|
||||||
|
FONT_COLOR_STATUS_LOSS,
|
||||||
|
FONT_COLOR_TITLE_MAIN,
|
||||||
|
FONT_SIZE_BODY,
|
||||||
|
FONT_SIZE_TITLE_LG,
|
||||||
|
)
|
||||||
|
from view.widgets.goth_dropdown import GothDropdown
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
from view.widgets.modal_veil import ModalVeil
|
||||||
|
|
||||||
|
|
||||||
|
class SolitaireModalDialog(tk.Canvas):
|
||||||
|
"""
|
||||||
|
Rahmenloses Gothic-Modal (ohne eingebettetes GIF), das über allen UI-Elementen
|
||||||
|
schwebt, das Spielfeld dahinter abdunkelt und alle übrigen Buttons sperrt.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
ctx,
|
||||||
|
title_txt: str,
|
||||||
|
body_txt: str,
|
||||||
|
buttons: list[tuple[str, str, object, bool] | tuple[str, str, object]],
|
||||||
|
is_danger: bool = False,
|
||||||
|
gif_key: str = "", # abwärtskompatibel ignoriert (Animation läuft vorab)
|
||||||
|
):
|
||||||
|
GothDropdown.close_any_open_popup()
|
||||||
|
_ = gif_key
|
||||||
|
dlg_w = 590 if len(buttons) >= 3 else 500
|
||||||
|
dlg_h = 268
|
||||||
|
|
||||||
|
super().__init__(
|
||||||
|
ctx.root,
|
||||||
|
width=dlg_w,
|
||||||
|
height=dlg_h,
|
||||||
|
bg=BG_COLOR,
|
||||||
|
bd=0,
|
||||||
|
highlightthickness=0,
|
||||||
|
)
|
||||||
|
self.ctx = ctx
|
||||||
|
self._dlg_w = dlg_w
|
||||||
|
self._dlg_h = dlg_h
|
||||||
|
self._photo_refs: list[ImageTk.PhotoImage] = []
|
||||||
|
|
||||||
|
self.place(relx=0.5, rely=0.5, anchor="center")
|
||||||
|
self._build_scene(title_txt, body_txt, buttons, is_danger)
|
||||||
|
self._veil = ModalVeil(ctx.root, ctx.assets, modal_widget=self)
|
||||||
|
|
||||||
|
def _build_scene(
|
||||||
|
self,
|
||||||
|
title_txt: str,
|
||||||
|
body_txt: str,
|
||||||
|
buttons: list,
|
||||||
|
is_danger: bool,
|
||||||
|
):
|
||||||
|
w, h = self._dlg_w, self._dlg_h
|
||||||
|
assets = self.ctx.assets
|
||||||
|
|
||||||
|
bg_src = assets.raw_bg_vertical or assets.raw_bg_horizontal or assets.raw_bg
|
||||||
|
if bg_src is not None:
|
||||||
|
bg_ph = ImageTk.PhotoImage(bg_src.resize((w, h), Image.Resampling.LANCZOS))
|
||||||
|
self._photo_refs.append(bg_ph)
|
||||||
|
self.create_image(0, 0, image=bg_ph, anchor="nw")
|
||||||
|
|
||||||
|
box_ph = assets.get_box_photo("box_big", (w - 6, h - 6))
|
||||||
|
if box_ph:
|
||||||
|
self._photo_refs.append(box_ph)
|
||||||
|
self.create_image(w // 2, h // 2, image=box_ph, anchor="center")
|
||||||
|
|
||||||
|
cur_y = 38
|
||||||
|
t_col = FONT_COLOR_STATUS_LOSS if is_danger else FONT_COLOR_TITLE_MAIN
|
||||||
|
clean_body = str(body_txt or "").replace("•", "-")
|
||||||
|
t_ph = assets.get_goth_text_photo(title_txt, FONT_SIZE_TITLE_LG - 4, t_col, max_width=w - 64)
|
||||||
|
b_ph = assets.get_goth_text_photo(
|
||||||
|
clean_body, FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=w - 76, align="center"
|
||||||
|
)
|
||||||
|
self._photo_refs.extend([t_ph, b_ph])
|
||||||
|
self.create_image(w // 2, cur_y + t_ph.height() // 2, image=t_ph, anchor="center")
|
||||||
|
cur_y += t_ph.height() + 14
|
||||||
|
self.create_image(w // 2, cur_y + b_ph.height() // 2, image=b_ph, anchor="center")
|
||||||
|
|
||||||
|
btn_norm = assets.raw_btn_default
|
||||||
|
btn_purp = assets.raw_btn_purple
|
||||||
|
btn_fire = assets.raw_btn_fire or btn_purp
|
||||||
|
|
||||||
|
req_w = 152 if len(buttons) >= 3 else 176
|
||||||
|
gap = 10
|
||||||
|
created_btns: list[ImageButton] = []
|
||||||
|
for entry in buttons:
|
||||||
|
if len(entry) == 4:
|
||||||
|
lbl, style, cmd, enabled = entry
|
||||||
|
else:
|
||||||
|
lbl, style, cmd = entry
|
||||||
|
enabled = True
|
||||||
|
p_n = btn_fire if style == "fire" else btn_norm
|
||||||
|
p_h = btn_fire if style == "fire" else btn_purp
|
||||||
|
btn = ImageButton(
|
||||||
|
self, lbl, p_n, p_h, cmd,
|
||||||
|
sound_mgr=self.ctx.sounds, width=req_w, height=36,
|
||||||
|
enabled=bool(enabled), style=style,
|
||||||
|
)
|
||||||
|
created_btns.append(btn)
|
||||||
|
|
||||||
|
total_w = sum(b.pixel_width for b in created_btns) + max(0, len(created_btns) - 1) * gap
|
||||||
|
cur_x = (w - total_w) // 2
|
||||||
|
for btn in created_btns:
|
||||||
|
bw = btn.pixel_width
|
||||||
|
self.create_window(cur_x + bw // 2, h - 44, window=btn, anchor="center")
|
||||||
|
cur_x += bw + gap
|
||||||
|
|
@ -0,0 +1,253 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/base/solitaire_outcome_flow.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog
|
||||||
|
from models.database import Database
|
||||||
|
from models.progression import Progression
|
||||||
|
from resources.code_res.game_constants import SOLO_FORFEIT_XP_RATIO
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from view.widgets.endgame_fx_overlay import EndgameFxOverlay
|
||||||
|
|
||||||
|
|
||||||
|
class SolitaireOutcomeFlow:
|
||||||
|
"""Kapselt Sieg-, Niederlage-, Aufgabe- und Deadlock-Abläufe für alle Solitaire-Tische."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _leave_to_menu(view, status_msg: str = "", ok: bool = False) -> None:
|
||||||
|
view._close_active_modal()
|
||||||
|
view._cleanup_timers()
|
||||||
|
if callable(view.on_back_to_menu):
|
||||||
|
if status_msg:
|
||||||
|
view.on_back_to_menu(status_msg, ok)
|
||||||
|
else:
|
||||||
|
view.on_back_to_menu()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _restart_from_modal(view) -> None:
|
||||||
|
view._close_active_modal()
|
||||||
|
view._start_fresh_deal()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def compute_forfeit_penalty(view) -> int:
|
||||||
|
pid = view.ctx.profile["id"]
|
||||||
|
prog = Database.get_game_progress(pid, view.GAME_FOLDER_ID)
|
||||||
|
win_xp = Progression.calculate_match_xp(
|
||||||
|
prog["level"], [], "WIN", variant_mult=view._combined_xp_mult
|
||||||
|
)
|
||||||
|
return max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO)))
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def show_deadlock_modal(cls, view) -> None:
|
||||||
|
if view.hover_zoom is not None:
|
||||||
|
view.hover_zoom.cancel()
|
||||||
|
view.engine.pause_timer()
|
||||||
|
view._save_progress()
|
||||||
|
penalty = cls.compute_forfeit_penalty(view)
|
||||||
|
|
||||||
|
def undo_step():
|
||||||
|
view._close_active_modal()
|
||||||
|
view._on_undo()
|
||||||
|
|
||||||
|
def undo_everything():
|
||||||
|
view._close_active_modal()
|
||||||
|
view._on_undo_all()
|
||||||
|
|
||||||
|
view._modal_overlay = SolitaireModalDialog(
|
||||||
|
view.ctx,
|
||||||
|
title_txt=t("sol_deadlock_title"),
|
||||||
|
body_txt=t("sol_deadlock_desc", penalty),
|
||||||
|
is_danger=True,
|
||||||
|
buttons=[
|
||||||
|
(t("sol_deadlock_btn_undo"), "fire", undo_step, view.engine.can_undo),
|
||||||
|
(t("sol_deadlock_btn_undo_all"), "fire", undo_everything, view.engine.can_undo_all),
|
||||||
|
(
|
||||||
|
t("sol_deadlock_btn_end", penalty),
|
||||||
|
"amethyst",
|
||||||
|
lambda: cls.execute_forfeit(view, penalty, go_menu=True),
|
||||||
|
True,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
view._sync_buttons()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def show_forfeit_modal(cls, view) -> None:
|
||||||
|
if view.hover_zoom is not None:
|
||||||
|
view.hover_zoom.cancel()
|
||||||
|
view.engine.pause_timer()
|
||||||
|
view._save_progress()
|
||||||
|
penalty = cls.compute_forfeit_penalty(view)
|
||||||
|
|
||||||
|
view._modal_overlay = SolitaireModalDialog(
|
||||||
|
view.ctx,
|
||||||
|
title_txt=t("sol_forfeit_title"),
|
||||||
|
body_txt=t("sol_forfeit_desc", penalty),
|
||||||
|
is_danger=True,
|
||||||
|
buttons=[
|
||||||
|
(t("sol_btn_cancel"), "amethyst", view._close_active_modal),
|
||||||
|
(
|
||||||
|
t("sol_forfeit_confirm_new"),
|
||||||
|
"fire",
|
||||||
|
lambda: cls.execute_forfeit(view, penalty, go_menu=False),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
t("sol_forfeit_confirm_menu"),
|
||||||
|
"amethyst",
|
||||||
|
lambda: cls.execute_forfeit(view, penalty, go_menu=True),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
view._sync_buttons()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def execute_forfeit(cls, view, penalty: int, go_menu: bool) -> None:
|
||||||
|
if view.hover_zoom is not None:
|
||||||
|
view.hover_zoom.cancel()
|
||||||
|
pid = view.ctx.profile["id"]
|
||||||
|
prog = Database.get_game_progress(pid, view.GAME_FOLDER_ID)
|
||||||
|
floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0
|
||||||
|
|
||||||
|
view._game_concluded = True
|
||||||
|
view.engine.pause_timer()
|
||||||
|
dur = view.engine.get_elapsed_seconds()
|
||||||
|
Database.delete_game_state(pid, view.GAME_FOLDER_ID)
|
||||||
|
Database.record_game_result(
|
||||||
|
pid, variant_key=view.variant_key, won=False, duration_sec=dur, points_gained=0
|
||||||
|
)
|
||||||
|
updated = Database.adjust_game_points(
|
||||||
|
pid, view.GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp
|
||||||
|
)
|
||||||
|
deducted = max(0, prog["total_points"] - updated["total_points"])
|
||||||
|
view.topbar.update_level_xp_text()
|
||||||
|
view.ctx.sounds.play("lose")
|
||||||
|
|
||||||
|
if view._modal_overlay is not None:
|
||||||
|
try:
|
||||||
|
view._modal_overlay.destroy()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
view._modal_overlay = None
|
||||||
|
|
||||||
|
view._sync_buttons()
|
||||||
|
|
||||||
|
def _after_lose_fx():
|
||||||
|
view._fx_overlay = None
|
||||||
|
if not view._canvas_alive():
|
||||||
|
return
|
||||||
|
cls._show_defeat_result_modal(view, deducted, dur, prefer_menu=go_menu)
|
||||||
|
|
||||||
|
view._fx_overlay = EndgameFxOverlay.play(
|
||||||
|
view.ctx.root,
|
||||||
|
view.ctx.assets,
|
||||||
|
outcome="lose",
|
||||||
|
on_continue=_after_lose_fx,
|
||||||
|
target_canvas=view.canvas,
|
||||||
|
)
|
||||||
|
view._sync_buttons()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _show_defeat_result_modal(cls, view, deducted: int, dur: float, prefer_menu: bool) -> None:
|
||||||
|
lines = [
|
||||||
|
t(
|
||||||
|
"sol_win_summary",
|
||||||
|
view.engine.score,
|
||||||
|
view.engine.moves,
|
||||||
|
Database.format_seconds(dur),
|
||||||
|
t(f"sol_diff_short_{view.difficulty}"),
|
||||||
|
),
|
||||||
|
t("sol_loss_xp", deducted),
|
||||||
|
]
|
||||||
|
|
||||||
|
view._modal_overlay = SolitaireModalDialog(
|
||||||
|
view.ctx,
|
||||||
|
title_txt=t("sol_forfeit_title"),
|
||||||
|
body_txt="\n".join(lines),
|
||||||
|
is_danger=True,
|
||||||
|
buttons=[
|
||||||
|
(
|
||||||
|
t("sol_play_again_btn"),
|
||||||
|
"amethyst" if prefer_menu else "fire",
|
||||||
|
lambda: cls._restart_from_modal(view),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
t("bj_popup_to_menu_btn"),
|
||||||
|
"fire" if prefer_menu else "amethyst",
|
||||||
|
lambda: cls._leave_to_menu(view, t("sol_loss_xp", deducted), False),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
view._sync_buttons()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def handle_victory(cls, view) -> None:
|
||||||
|
if view.hover_zoom is not None:
|
||||||
|
view.hover_zoom.cancel()
|
||||||
|
view._game_concluded = True
|
||||||
|
view.engine.pause_timer()
|
||||||
|
pid = view.ctx.profile["id"]
|
||||||
|
Database.delete_game_state(pid, view.GAME_FOLDER_ID)
|
||||||
|
dur = view.engine.get_elapsed_seconds()
|
||||||
|
|
||||||
|
fast_t, mid_t = view.SPEED_THRESHOLDS_SEC
|
||||||
|
speed_bonus = 1.25 if dur <= fast_t else (1.12 if dur <= mid_t else 1.0)
|
||||||
|
prog = Database.get_game_progress(pid, view.GAME_FOLDER_ID)
|
||||||
|
xp_earned = Progression.calculate_match_xp(
|
||||||
|
prog["level"], [], "WIN", variant_mult=view._combined_xp_mult * speed_bonus
|
||||||
|
)
|
||||||
|
|
||||||
|
old_lvl, new_lvl = Database.record_game_result(
|
||||||
|
pid, variant_key=view.variant_key, won=True, duration_sec=dur, points_gained=xp_earned
|
||||||
|
)
|
||||||
|
view.topbar.update_level_xp_text()
|
||||||
|
view.ctx.sounds.play("win")
|
||||||
|
view._sync_buttons()
|
||||||
|
|
||||||
|
def _after_win_fx():
|
||||||
|
view._fx_overlay = None
|
||||||
|
if not view._canvas_alive():
|
||||||
|
return
|
||||||
|
cls._show_victory_modal(view, xp_earned, old_lvl, new_lvl, dur)
|
||||||
|
|
||||||
|
view._fx_overlay = EndgameFxOverlay.play(
|
||||||
|
view.ctx.root,
|
||||||
|
view.ctx.assets,
|
||||||
|
outcome="win",
|
||||||
|
on_continue=_after_win_fx,
|
||||||
|
target_canvas=view.canvas,
|
||||||
|
)
|
||||||
|
view._sync_buttons()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _show_victory_modal(cls, view, xp_earned: int, old_lvl: int, new_lvl: int, dur: float) -> None:
|
||||||
|
lines = [
|
||||||
|
t(
|
||||||
|
"sol_win_summary",
|
||||||
|
view.engine.score,
|
||||||
|
view.engine.moves,
|
||||||
|
Database.format_seconds(dur),
|
||||||
|
t(f"sol_diff_short_{view.difficulty}"),
|
||||||
|
),
|
||||||
|
t("bj_popup_xp_earned", xp_earned),
|
||||||
|
]
|
||||||
|
if new_lvl > old_lvl:
|
||||||
|
lines.append(t("bj_popup_level_up", new_lvl, Progression.get_prestige_title(new_lvl)))
|
||||||
|
|
||||||
|
view._modal_overlay = SolitaireModalDialog(
|
||||||
|
view.ctx,
|
||||||
|
title_txt=t("sol_win_title"),
|
||||||
|
body_txt="\n".join(lines),
|
||||||
|
buttons=[
|
||||||
|
(
|
||||||
|
t("sol_play_again_btn"),
|
||||||
|
"fire",
|
||||||
|
lambda: cls._restart_from_modal(view),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
t("bj_popup_to_menu_btn"),
|
||||||
|
"amethyst",
|
||||||
|
lambda: cls._leave_to_menu(view),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
view._sync_buttons()
|
||||||
|
|
@ -0,0 +1,243 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/base/solitaire_session_guard.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
from games.solitaire.base.solitaire_canvas_input import SolitaireCanvasInput
|
||||||
|
from models.database import Database
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
|
||||||
|
|
||||||
|
class SolitaireSessionGuard(SolitaireCanvasInput):
|
||||||
|
"""
|
||||||
|
Verwaltet für alle Solitaire-Tische Fokus-Pause, 500ms-Uhr-Tick,
|
||||||
|
Savegame-Checkpoints, Root-Keybindings, Sprachwechsel und sauberes Timer-Cleanup.
|
||||||
|
"""
|
||||||
|
|
||||||
|
CHECKPOINT_TICKS: int = 30
|
||||||
|
|
||||||
|
def _is_ui_locked(self) -> bool:
|
||||||
|
return (
|
||||||
|
self.engine.won
|
||||||
|
or self._game_concluded
|
||||||
|
or self._auto_running
|
||||||
|
or (self._modal_overlay is not None)
|
||||||
|
or (self._fx_overlay is not None)
|
||||||
|
)
|
||||||
|
|
||||||
|
def _canvas_alive(self) -> bool:
|
||||||
|
if not self._alive:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
return bool(self.canvas.winfo_exists())
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _can_show_hover_zoom(self) -> bool:
|
||||||
|
return (
|
||||||
|
self._canvas_alive()
|
||||||
|
and not self._is_ui_locked()
|
||||||
|
and not self._dragging
|
||||||
|
and self._press_info is None
|
||||||
|
and self._window_active
|
||||||
|
and (self.animator is None or not self.animator.is_active)
|
||||||
|
)
|
||||||
|
|
||||||
|
def _play_table_music(self):
|
||||||
|
for method_name in ("play_ingame_music", "play_table_music"):
|
||||||
|
fn = getattr(self.ctx.sounds, method_name, None)
|
||||||
|
if callable(fn):
|
||||||
|
fn()
|
||||||
|
return
|
||||||
|
|
||||||
|
def _bind_root(self, seq: str, callback):
|
||||||
|
if seq and seq.startswith("<") and seq.endswith(">"):
|
||||||
|
try:
|
||||||
|
func_id = self.ctx.root.bind(seq, callback, add="+")
|
||||||
|
if func_id:
|
||||||
|
self._bind_ids.append((seq, func_id))
|
||||||
|
except tk.TclError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _on_canvas_destroy(self, event=None):
|
||||||
|
if event is not None and event.widget is not self.canvas:
|
||||||
|
return
|
||||||
|
if not self._alive:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
self.engine.pause_timer()
|
||||||
|
if not self._game_concluded:
|
||||||
|
self._save_progress()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._cleanup_timers()
|
||||||
|
|
||||||
|
def _cleanup_timers(self):
|
||||||
|
self._alive = False
|
||||||
|
self.engine.pause_timer()
|
||||||
|
if self._fx_overlay is not None:
|
||||||
|
self._fx_overlay.cancel()
|
||||||
|
self._fx_overlay = None
|
||||||
|
if self.hover_zoom is not None:
|
||||||
|
self.hover_zoom.cancel()
|
||||||
|
if self.animator is not None:
|
||||||
|
self.animator.cancel()
|
||||||
|
for job in (
|
||||||
|
self._tick_job,
|
||||||
|
self._focus_job,
|
||||||
|
self._hint_job,
|
||||||
|
self._auto_job,
|
||||||
|
self._resize_job,
|
||||||
|
):
|
||||||
|
if job is not None:
|
||||||
|
try:
|
||||||
|
self.ctx.root.after_cancel(job)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._tick_job = self._focus_job = self._hint_job = None
|
||||||
|
self._auto_job = self._resize_job = None
|
||||||
|
|
||||||
|
for seq, func_id in self._bind_ids:
|
||||||
|
try:
|
||||||
|
self.ctx.root.unbind(seq, func_id)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._bind_ids.clear()
|
||||||
|
|
||||||
|
def _schedule_focus_check(self, _event=None):
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
if self._focus_job is not None:
|
||||||
|
try:
|
||||||
|
self.ctx.root.after_cancel(self._focus_job)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
self._focus_job = self.ctx.root.after(60, self._check_window_focus)
|
||||||
|
except Exception:
|
||||||
|
self._focus_job = None
|
||||||
|
|
||||||
|
def _check_window_focus(self):
|
||||||
|
self._focus_job = None
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
is_iconic = self.ctx.root.state() == "iconic"
|
||||||
|
has_focus = self.ctx.root.focus_displayof() is not None and not is_iconic
|
||||||
|
except Exception:
|
||||||
|
return
|
||||||
|
|
||||||
|
should_run = (
|
||||||
|
has_focus
|
||||||
|
and (self._modal_overlay is None)
|
||||||
|
and (self._fx_overlay is None)
|
||||||
|
and (not self._game_concluded)
|
||||||
|
and (not self.engine.won)
|
||||||
|
)
|
||||||
|
prev_paused = self.engine.is_timer_paused
|
||||||
|
self._window_active = has_focus
|
||||||
|
|
||||||
|
if should_run:
|
||||||
|
self.engine.resume_timer()
|
||||||
|
elif not prev_paused:
|
||||||
|
self.engine.pause_timer()
|
||||||
|
self._save_progress()
|
||||||
|
|
||||||
|
if prev_paused != self.engine.is_timer_paused:
|
||||||
|
self._update_hud_text()
|
||||||
|
if (
|
||||||
|
self.animator is None or not self.animator.is_active
|
||||||
|
) and self._fx_overlay is None:
|
||||||
|
self.redraw()
|
||||||
|
|
||||||
|
def _close_active_modal(self):
|
||||||
|
if self._modal_overlay is not None:
|
||||||
|
try:
|
||||||
|
self._modal_overlay.destroy()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._modal_overlay = None
|
||||||
|
self._check_window_focus()
|
||||||
|
self._sync_buttons()
|
||||||
|
|
||||||
|
def _refresh_lang(self):
|
||||||
|
if self.animator:
|
||||||
|
self.animator.flush()
|
||||||
|
self.engine.pause_timer()
|
||||||
|
self._save_progress()
|
||||||
|
state_json = self.engine.to_json()
|
||||||
|
self._cleanup_timers()
|
||||||
|
type(self)(
|
||||||
|
self.ctx,
|
||||||
|
variant_key=self.variant_key,
|
||||||
|
difficulty=self.difficulty,
|
||||||
|
on_back_to_menu=self.on_back_to_menu,
|
||||||
|
resume_state_json=state_json,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _save_progress(self):
|
||||||
|
if self._game_concluded:
|
||||||
|
return
|
||||||
|
pid = self.ctx.profile["id"]
|
||||||
|
if self.engine.won:
|
||||||
|
Database.delete_game_state(pid, self.GAME_FOLDER_ID)
|
||||||
|
return
|
||||||
|
Database.save_game_state(
|
||||||
|
pid, self.GAME_FOLDER_ID, self.variant_key, self.engine.to_json()
|
||||||
|
)
|
||||||
|
|
||||||
|
def _start_clock(self):
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
self._check_window_focus()
|
||||||
|
self._update_hud_text()
|
||||||
|
|
||||||
|
if (
|
||||||
|
self.engine.has_timer_started
|
||||||
|
and not self.engine.is_timer_paused
|
||||||
|
and not self.engine.won
|
||||||
|
and not self._game_concluded
|
||||||
|
):
|
||||||
|
self._checkpoint_ticks += 1
|
||||||
|
if self._checkpoint_ticks >= self.CHECKPOINT_TICKS:
|
||||||
|
self._checkpoint_ticks = 0
|
||||||
|
self._save_progress()
|
||||||
|
try:
|
||||||
|
self._tick_job = self.ctx.root.after(500, self._start_clock)
|
||||||
|
except Exception:
|
||||||
|
self._tick_job = None
|
||||||
|
|
||||||
|
def _extra_hud_suffix(self) -> str:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def _update_hud_text(self):
|
||||||
|
if not self._alive:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
elapsed_str = Database.format_seconds(self.engine.get_elapsed_seconds())
|
||||||
|
paused_tag = (
|
||||||
|
t("sol_hud_paused_tag")
|
||||||
|
if (
|
||||||
|
self.engine.is_timer_paused
|
||||||
|
and not self.engine.won
|
||||||
|
and not self._game_concluded
|
||||||
|
)
|
||||||
|
else ""
|
||||||
|
)
|
||||||
|
diff_label = t(f"sol_diff_short_{self.difficulty}")
|
||||||
|
new_hud = (
|
||||||
|
t(
|
||||||
|
"sol_hud_stats",
|
||||||
|
self.engine.score,
|
||||||
|
self.engine.moves,
|
||||||
|
elapsed_str,
|
||||||
|
paused_tag,
|
||||||
|
diff_label,
|
||||||
|
)
|
||||||
|
+ self._extra_hud_suffix()
|
||||||
|
)
|
||||||
|
if self.hud_var.get() != new_hud:
|
||||||
|
self.hud_var.set(new_hud)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
@ -1,182 +0,0 @@
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
# games/solitaire/base/solitaire_stats_view.py
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import tkinter as tk
|
|
||||||
|
|
||||||
from models.database import Database
|
|
||||||
from resources.code_res.game_constants import (
|
|
||||||
ACCENT_GOLD,
|
|
||||||
ACCENT_GOTH,
|
|
||||||
BG_COLOR,
|
|
||||||
BORDER_COLOR,
|
|
||||||
CELL_BG,
|
|
||||||
FG_COLOR,
|
|
||||||
MUTED_FG,
|
|
||||||
PANEL_BG,
|
|
||||||
STAT_FIELD_KEYS,
|
|
||||||
SUBTLE_BORDER,
|
|
||||||
)
|
|
||||||
from resources.code_res.i18n import t
|
|
||||||
from view.widgets.image_button import ImageButton
|
|
||||||
|
|
||||||
# Kurze, prägnante Button-Labels für Varianten mit mehreren Modi
|
|
||||||
SHORT_VARIANT_TAB_KEYS: dict[str, str] = {
|
|
||||||
"klondike_1": "kl_draw_toggle_1",
|
|
||||||
"klondike_3": "kl_draw_toggle_3",
|
|
||||||
"spider_1suit": "sp_suit_toggle_1",
|
|
||||||
"spider_2suit": "sp_suit_toggle_2",
|
|
||||||
"spider_4suit": "sp_suit_toggle_4",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class SolitaireStatsView:
|
|
||||||
"""Kompakte Statistik-Ansicht mit direktem Varianten-Umschalter im selben Block."""
|
|
||||||
|
|
||||||
def __init__(self, context, game_folder: str, game_title_key: str, on_back):
|
|
||||||
self.ctx = context
|
|
||||||
self.game_folder = game_folder
|
|
||||||
self.game_title_key = game_title_key
|
|
||||||
self.on_back = on_back
|
|
||||||
self._active_variant_id: int | None = None
|
|
||||||
|
|
||||||
def show(self, preselect_variant_id: int | None = None):
|
|
||||||
pid = self.ctx.profile["id"]
|
|
||||||
self._active_variant_id = preselect_variant_id
|
|
||||||
|
|
||||||
self.ctx.root.clear_window(apply_global_bg=True)
|
|
||||||
prog = Database.get_game_progress(pid, self.game_folder)
|
|
||||||
game_name = t(self.game_title_key)
|
|
||||||
|
|
||||||
self.ctx.build_game_topbar(
|
|
||||||
self.ctx.root,
|
|
||||||
t("stats_view_topbar", game_name),
|
|
||||||
on_game_menu=self.on_back,
|
|
||||||
on_stats=None,
|
|
||||||
stats_enabled=False,
|
|
||||||
on_lang_refresh=lambda: self.show(preselect_variant_id=self._active_variant_id),
|
|
||||||
)
|
|
||||||
|
|
||||||
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=16)
|
|
||||||
container.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.86, relheight=0.80)
|
|
||||||
|
|
||||||
card = tk.Frame(
|
|
||||||
container,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
padx=24,
|
|
||||||
pady=20,
|
|
||||||
highlightthickness=1,
|
|
||||||
highlightbackground=BORDER_COLOR,
|
|
||||||
)
|
|
||||||
card.pack(fill="both", expand=True)
|
|
||||||
|
|
||||||
# Kopfzeile: Links Rang/XP, rechts kompakter Umschalter (z. B. Gesamt | 1 Karte | 3 Karten)
|
|
||||||
header_row = tk.Frame(card, bg=PANEL_BG)
|
|
||||||
header_row.pack(fill="x", pady=(0, 14))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
header_row,
|
|
||||||
text=t(
|
|
||||||
"stats_game_rank_info",
|
|
||||||
game_name,
|
|
||||||
prog["title"],
|
|
||||||
prog["level"],
|
|
||||||
prog["current_xp"],
|
|
||||||
prog["needed_xp"],
|
|
||||||
),
|
|
||||||
font=("Georgia", 11, "bold"),
|
|
||||||
fg=ACCENT_GOLD,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(side="left", anchor="w")
|
|
||||||
|
|
||||||
variants = Database.get_variants_for_filter(self.game_folder)
|
|
||||||
if len(variants) > 1:
|
|
||||||
toggle_bar = tk.Frame(header_row, bg=PANEL_BG)
|
|
||||||
toggle_bar.pack(side="right")
|
|
||||||
|
|
||||||
tabs: list[tuple[int | None, str]] = [(None, t("sol_stats_tab_all"))]
|
|
||||||
for v in variants:
|
|
||||||
v_key = v["variant_key"]
|
|
||||||
short_lbl = (
|
|
||||||
t(SHORT_VARIANT_TAB_KEYS[v_key])
|
|
||||||
if v_key in SHORT_VARIANT_TAB_KEYS
|
|
||||||
else v["translated_name"]
|
|
||||||
)
|
|
||||||
tabs.append((v["id"], short_lbl))
|
|
||||||
|
|
||||||
for vid, tab_text in tabs:
|
|
||||||
is_selected = self._active_variant_id == vid
|
|
||||||
raw_norm = self.ctx.assets.raw_btn_active if is_selected else self.ctx.assets.raw_sel
|
|
||||||
raw_act = self.ctx.assets.raw_btn_active if is_selected else self.ctx.assets.raw_sel_active
|
|
||||||
btn_w = 110 if vid is None else 150
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
toggle_bar,
|
|
||||||
tab_text,
|
|
||||||
raw_norm,
|
|
||||||
raw_act,
|
|
||||||
lambda target_vid=vid: self._switch_tab(target_vid),
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=btn_w,
|
|
||||||
height=32,
|
|
||||||
font=("Helvetica", 9, "bold"),
|
|
||||||
).pack(side="left", padx=(6, 0))
|
|
||||||
|
|
||||||
# Aktive Unterüberschrift des Blocks
|
|
||||||
active_title = t("stats_all_variants_of_game", game_name)
|
|
||||||
for v in variants:
|
|
||||||
if v["id"] == self._active_variant_id:
|
|
||||||
active_title = v["translated_name"]
|
|
||||||
break
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
card,
|
|
||||||
text=t("stats_game_board_title", active_title),
|
|
||||||
font=("Georgia", 12, "bold"),
|
|
||||||
fg=ACCENT_GOTH,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w", pady=(0, 10))
|
|
||||||
|
|
||||||
grid_frame = tk.Frame(card, bg=PANEL_BG)
|
|
||||||
grid_frame.pack(fill="x", pady=(4, 0))
|
|
||||||
grid_frame.columnconfigure(0, weight=1, uniform="statcol")
|
|
||||||
grid_frame.columnconfigure(1, weight=1, uniform="statcol")
|
|
||||||
|
|
||||||
stats = Database.get_stats_overview(
|
|
||||||
pid,
|
|
||||||
variant_id=self._active_variant_id,
|
|
||||||
folder_path=self.game_folder if self._active_variant_id is None else None,
|
|
||||||
)
|
|
||||||
|
|
||||||
for idx, (field_key, label_i18n_key) in enumerate(STAT_FIELD_KEYS):
|
|
||||||
r, c = divmod(idx, 2)
|
|
||||||
cell = tk.Frame(
|
|
||||||
grid_frame,
|
|
||||||
bg=CELL_BG,
|
|
||||||
padx=16,
|
|
||||||
pady=12,
|
|
||||||
highlightthickness=1,
|
|
||||||
highlightbackground=SUBTLE_BORDER,
|
|
||||||
)
|
|
||||||
cell.grid(row=r, column=c, sticky="ew", padx=(0, 8) if c == 0 else (8, 0), pady=6)
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
cell,
|
|
||||||
text=t(label_i18n_key),
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
fg=MUTED_FG,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(side="left")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
cell,
|
|
||||||
text=str(stats.get(field_key, "--")),
|
|
||||||
font=("Georgia", 12, "bold"),
|
|
||||||
fg=ACCENT_GOTH if "streak" in field_key else FG_COLOR,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(side="right")
|
|
||||||
|
|
||||||
def _switch_tab(self, variant_id: int | None):
|
|
||||||
if variant_id == self._active_variant_id:
|
|
||||||
return
|
|
||||||
self.show(preselect_variant_id=variant_id)
|
|
||||||
|
|
@ -0,0 +1,387 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/base/solitaire_table_controller.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
from games.solitaire.base.card_animator import CardFlightAnimator
|
||||||
|
from games.solitaire.base.card_hover_zoom import CardHoverZoom
|
||||||
|
from games.solitaire.base.solitaire_bottom_bar import SolitaireBottomBar
|
||||||
|
from games.solitaire.base.solitaire_core import SolitaireCard
|
||||||
|
from games.solitaire.base.solitaire_outcome_flow import SolitaireOutcomeFlow
|
||||||
|
from games.solitaire.base.solitaire_session_guard import SolitaireSessionGuard
|
||||||
|
from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
PLAYING_CARD_SIZE,
|
||||||
|
SOLITAIRE_DIFFICULTIES,
|
||||||
|
TABLE_BG,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from view.widgets.endgame_fx_overlay import EndgameFxOverlay
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
|
||||||
|
|
||||||
|
class SolitaireTableController(SolitaireSessionGuard):
|
||||||
|
"""
|
||||||
|
Gemeinsame Tisch-Basisklasse für alle Solitaire-Spiele:
|
||||||
|
Baut Topbar/BottomBar/Canvas auf und steuert Undo, Hint, Auto-Complete & Neu-Geben.
|
||||||
|
"""
|
||||||
|
|
||||||
|
GAME_FOLDER_ID: str = ""
|
||||||
|
HAS_AUTOCOMPLETE_BTN: bool = True
|
||||||
|
AUTO_STEP_DELAY_MS: int = 12
|
||||||
|
AUTO_FLIGHT_MS: int = 75
|
||||||
|
SPEED_THRESHOLDS_SEC: tuple[int, int] = (180, 330)
|
||||||
|
|
||||||
|
def _init_controller_state(
|
||||||
|
self, context, variant_key: str, cfg: dict, difficulty: int, on_back_to_menu
|
||||||
|
):
|
||||||
|
self.ctx = context
|
||||||
|
self.variant_key = variant_key
|
||||||
|
self.cfg = cfg
|
||||||
|
self.difficulty = max(0, min(3, int(difficulty)))
|
||||||
|
self.on_back_to_menu = on_back_to_menu
|
||||||
|
|
||||||
|
self._alive = True
|
||||||
|
self._game_concluded = False
|
||||||
|
self._window_active = True
|
||||||
|
self._checkpoint_ticks = 0
|
||||||
|
self._tick_job: str | None = None
|
||||||
|
self._focus_job: str | None = None
|
||||||
|
self._hint_job: str | None = None
|
||||||
|
self._auto_job: str | None = None
|
||||||
|
self._resize_job: str | None = None
|
||||||
|
self._bind_ids: list[tuple[str, str]] = []
|
||||||
|
self._auto_running = False
|
||||||
|
|
||||||
|
self.animator: CardFlightAnimator | None = None
|
||||||
|
self.hover_zoom: CardHoverZoom | None = None
|
||||||
|
self._fx_overlay: EndgameFxOverlay | None = None
|
||||||
|
self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res)
|
||||||
|
self._frame_bot_pad: int = 18
|
||||||
|
self._canvas_ui_refs: list = []
|
||||||
|
|
||||||
|
self._card_aspect: float | None = None
|
||||||
|
self.card_size: tuple[int, int] = PLAYING_CARD_SIZE
|
||||||
|
|
||||||
|
self._press_info: dict | None = None
|
||||||
|
self._dragging: bool = False
|
||||||
|
self._drag_last_xy: tuple[int, int] = (0, 0)
|
||||||
|
self._last_click_ts: float = 0.0
|
||||||
|
self._last_click_target: tuple | None = None
|
||||||
|
self._active_hint: dict | None = None
|
||||||
|
self._modal_overlay: tk.Widget | None = None
|
||||||
|
self.auto_btn: ImageButton | None = None
|
||||||
|
|
||||||
|
def _finish_startup(self, is_resumed: bool):
|
||||||
|
self._build_ui()
|
||||||
|
if not is_resumed:
|
||||||
|
self.ctx.sounds.play("deal")
|
||||||
|
self._check_window_focus()
|
||||||
|
self._save_progress()
|
||||||
|
self._start_clock()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def _combined_xp_mult(self) -> float:
|
||||||
|
d_mult = SOLITAIRE_DIFFICULTIES.get(
|
||||||
|
self.difficulty, SOLITAIRE_DIFFICULTIES[1]
|
||||||
|
)["xp_mult"]
|
||||||
|
return self.cfg["xp_mult"] * d_mult
|
||||||
|
|
||||||
|
def _build_ui(self):
|
||||||
|
self._play_table_music()
|
||||||
|
self.ctx.root.clear_window(apply_global_bg=True)
|
||||||
|
self.ctx.refresh_game_progress()
|
||||||
|
|
||||||
|
self.topbar = self.ctx.build_game_topbar(
|
||||||
|
self.ctx.root,
|
||||||
|
stats_endpoint=self.GAME_FOLDER_ID,
|
||||||
|
stats_enabled=True,
|
||||||
|
on_lang_refresh=self._refresh_lang,
|
||||||
|
on_stats_back=self._schedule_focus_check,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.hud_var = tk.StringVar(value="")
|
||||||
|
self.status_var = tk.StringVar(value="")
|
||||||
|
|
||||||
|
self.bottom_bar = SolitaireBottomBar(
|
||||||
|
self.ctx.root, self.ctx, self.hud_var, self.status_var
|
||||||
|
)
|
||||||
|
self.bottom_bar.pack(fill="x", side="bottom", padx=14, pady=(4, 10))
|
||||||
|
|
||||||
|
btn_norm = self.ctx.assets.raw_btn_default
|
||||||
|
btn_purp = self.ctx.assets.raw_btn_purple
|
||||||
|
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
|
||||||
|
|
||||||
|
self.undo_btn = ImageButton(
|
||||||
|
self.bottom_bar, t("sol_btn_undo"), btn_norm, btn_purp,
|
||||||
|
self._on_undo, sound_mgr=self.ctx.sounds, width=136, height=32,
|
||||||
|
enabled=self.engine.can_undo, style="amethyst",
|
||||||
|
)
|
||||||
|
self.undo_all_btn = ImageButton(
|
||||||
|
self.bottom_bar, t("sol_btn_undo_all"), btn_norm, btn_purp,
|
||||||
|
self._on_undo_all, sound_mgr=self.ctx.sounds, width=92, height=32,
|
||||||
|
enabled=self.engine.can_undo_all, style="amethyst",
|
||||||
|
)
|
||||||
|
self.hint_btn = ImageButton(
|
||||||
|
self.bottom_bar, t("sol_btn_hint"), btn_norm, btn_purp,
|
||||||
|
self._on_hint, sound_mgr=self.ctx.sounds, width=92, height=32,
|
||||||
|
enabled=not self.engine.won, style="amethyst",
|
||||||
|
)
|
||||||
|
main_btns = [self.undo_btn, self.undo_all_btn, self.hint_btn]
|
||||||
|
if self.HAS_AUTOCOMPLETE_BTN:
|
||||||
|
self.auto_btn = ImageButton(
|
||||||
|
self.bottom_bar, t("sol_btn_autocomplete"), btn_fire, btn_fire,
|
||||||
|
self._start_auto_complete, sound_mgr=self.ctx.sounds,
|
||||||
|
width=112, height=32, enabled=self.engine.can_auto_complete(),
|
||||||
|
style="fire",
|
||||||
|
)
|
||||||
|
main_btns.append(self.auto_btn)
|
||||||
|
|
||||||
|
self.new_btn = ImageButton(
|
||||||
|
self.bottom_bar,
|
||||||
|
t("sol_btn_forfeit") if self.engine.moves > 0 else t("sol_btn_new_deal"),
|
||||||
|
btn_norm, btn_purp, self._on_new_or_forfeit_clicked,
|
||||||
|
sound_mgr=self.ctx.sounds, width=104, height=32, style="amethyst",
|
||||||
|
)
|
||||||
|
self.bottom_bar.set_buttons(main_btns, overflow_buttons=[self.new_btn])
|
||||||
|
|
||||||
|
self.canvas = tk.Canvas(
|
||||||
|
self.ctx.root, bg=TABLE_BG, bd=0, highlightthickness=0
|
||||||
|
)
|
||||||
|
self.canvas.pack(fill="both", expand=True, padx=14, pady=(4, 2))
|
||||||
|
self.animator = CardFlightAnimator(self.ctx.root, self.canvas)
|
||||||
|
self.hover_zoom = CardHoverZoom(
|
||||||
|
self.ctx.root,
|
||||||
|
self.canvas,
|
||||||
|
self.ctx.assets,
|
||||||
|
probe_fn=self._hover_card_probe,
|
||||||
|
can_show_fn=self._can_show_hover_zoom,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.canvas.bind("<Configure>", self._on_canvas_configure)
|
||||||
|
self.canvas.bind("<Destroy>", self._on_canvas_destroy)
|
||||||
|
self.canvas.bind("<ButtonPress-1>", self._on_mouse_down)
|
||||||
|
self.canvas.bind("<B1-Motion>", self._on_mouse_move)
|
||||||
|
self.canvas.bind("<ButtonRelease-1>", self._on_mouse_up)
|
||||||
|
self.canvas.bind("<ButtonPress-3>", self._on_right_click)
|
||||||
|
|
||||||
|
self._bind_root("<Control-z>", lambda _e: self._run_undo_shortcut(False))
|
||||||
|
self._bind_root("<Control-Shift-Z>", lambda _e: self._run_undo_shortcut(True))
|
||||||
|
self._bind_root("<Control-Shift-z>", lambda _e: self._run_undo_shortcut(True))
|
||||||
|
self._bind_root("<KeyPress-h>", lambda _e: self._on_hint())
|
||||||
|
self._bind_root("<KeyPress-H>", lambda _e: self._on_hint())
|
||||||
|
self._bind_root("<FocusIn>", self._schedule_focus_check)
|
||||||
|
self._bind_root("<FocusOut>", self._schedule_focus_check)
|
||||||
|
|
||||||
|
self._update_hud_text()
|
||||||
|
|
||||||
|
def _run_undo_shortcut(self, all_moves: bool) -> str:
|
||||||
|
if self._fx_overlay is not None or self._game_concluded or self._auto_running:
|
||||||
|
return "break"
|
||||||
|
can_act = self.engine.can_undo_all if all_moves else self.engine.can_undo
|
||||||
|
if can_act:
|
||||||
|
if self._modal_overlay is not None:
|
||||||
|
self._close_active_modal()
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
(self._on_undo_all if all_moves else self._on_undo)()
|
||||||
|
return "break"
|
||||||
|
|
||||||
|
def _sync_buttons(self):
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
locked = self._is_ui_locked()
|
||||||
|
self.undo_btn.set_enabled((not locked) and self.engine.can_undo)
|
||||||
|
self.undo_all_btn.set_enabled((not locked) and self.engine.can_undo_all)
|
||||||
|
self.hint_btn.set_enabled(not locked)
|
||||||
|
if self.auto_btn is not None:
|
||||||
|
self.auto_btn.set_enabled((not locked) and self.engine.can_auto_complete())
|
||||||
|
self.new_btn.set_enabled(
|
||||||
|
(not self._auto_running)
|
||||||
|
and (self._fx_overlay is None)
|
||||||
|
and (self._modal_overlay is None)
|
||||||
|
)
|
||||||
|
new_lbl = (
|
||||||
|
t("sol_btn_forfeit")
|
||||||
|
if (self.engine.moves > 0 and not self.engine.won and not self._game_concluded)
|
||||||
|
else t("sol_btn_new_deal")
|
||||||
|
)
|
||||||
|
prev_w = self.new_btn.pixel_width
|
||||||
|
self.new_btn.set_text(new_lbl)
|
||||||
|
if self.new_btn.pixel_width != prev_w:
|
||||||
|
self.bottom_bar.relayout()
|
||||||
|
self._update_hud_text()
|
||||||
|
|
||||||
|
def _status_after_move(self) -> str:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def _after_player_move(self):
|
||||||
|
self.status_var.set(self._status_after_move())
|
||||||
|
self._checkpoint_ticks = 0
|
||||||
|
self.redraw()
|
||||||
|
if self.engine.won:
|
||||||
|
SolitaireOutcomeFlow.handle_victory(self)
|
||||||
|
return
|
||||||
|
self._save_progress()
|
||||||
|
self._check_deadlock_and_prompt()
|
||||||
|
|
||||||
|
def _check_deadlock_and_prompt(self):
|
||||||
|
if not self._is_ui_locked() and not self.engine.has_any_meaningful_move():
|
||||||
|
SolitaireOutcomeFlow.show_deadlock_modal(self)
|
||||||
|
|
||||||
|
def _on_undo(self):
|
||||||
|
if self._is_ui_locked():
|
||||||
|
return
|
||||||
|
self._clear_hint()
|
||||||
|
|
||||||
|
def _done():
|
||||||
|
self.status_var.set("")
|
||||||
|
self._checkpoint_ticks = 0
|
||||||
|
self._save_progress()
|
||||||
|
self.redraw()
|
||||||
|
|
||||||
|
self._run_animated_action(self.engine.undo, duration_ms=105, after_cb=_done)
|
||||||
|
|
||||||
|
def _on_undo_all(self):
|
||||||
|
if self._is_ui_locked():
|
||||||
|
return
|
||||||
|
if self.animator:
|
||||||
|
self.animator.flush()
|
||||||
|
self._clear_hint()
|
||||||
|
if self.engine.undo_all():
|
||||||
|
self.status_var.set("")
|
||||||
|
self._checkpoint_ticks = 0
|
||||||
|
self._save_progress()
|
||||||
|
self.redraw()
|
||||||
|
|
||||||
|
def _clear_hint(self):
|
||||||
|
if self._hint_job is not None:
|
||||||
|
try:
|
||||||
|
self.ctx.root.after_cancel(self._hint_job)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._hint_job = None
|
||||||
|
self._active_hint = None
|
||||||
|
|
||||||
|
def _on_hint(self):
|
||||||
|
if self._is_ui_locked():
|
||||||
|
return
|
||||||
|
if self.animator:
|
||||||
|
self.animator.flush()
|
||||||
|
self._clear_hint()
|
||||||
|
self.engine.start_timer_if_needed()
|
||||||
|
self._update_hud_text()
|
||||||
|
hint = self.engine.get_hint()
|
||||||
|
if not hint:
|
||||||
|
self.status_var.set(t("sol_no_hint_msg"))
|
||||||
|
self._check_deadlock_and_prompt()
|
||||||
|
return
|
||||||
|
self.status_var.set("")
|
||||||
|
self._active_hint = hint
|
||||||
|
self.redraw()
|
||||||
|
self._hint_job = self.ctx.root.after(1600, self._expire_hint)
|
||||||
|
|
||||||
|
def _expire_hint(self):
|
||||||
|
self._hint_job = None
|
||||||
|
self._active_hint = None
|
||||||
|
if self._canvas_alive() and self._fx_overlay is None:
|
||||||
|
self.redraw()
|
||||||
|
|
||||||
|
def _start_auto_complete(self):
|
||||||
|
if (
|
||||||
|
not self.HAS_AUTOCOMPLETE_BTN
|
||||||
|
or not self.engine.can_auto_complete()
|
||||||
|
or self._is_ui_locked()
|
||||||
|
):
|
||||||
|
return
|
||||||
|
if self.animator:
|
||||||
|
self.animator.flush()
|
||||||
|
self._clear_hint()
|
||||||
|
self.engine.push_undo()
|
||||||
|
self._save_progress()
|
||||||
|
self._auto_running = True
|
||||||
|
self._sync_buttons()
|
||||||
|
self._step_auto_complete()
|
||||||
|
|
||||||
|
def _step_auto_complete(self):
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
|
||||||
|
def after_step():
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
self.redraw()
|
||||||
|
if not self.engine.won:
|
||||||
|
self._auto_job = self.ctx.root.after(
|
||||||
|
self.AUTO_STEP_DELAY_MS, self._step_auto_complete
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._auto_running, self._auto_job = False, None
|
||||||
|
SolitaireOutcomeFlow.handle_victory(self)
|
||||||
|
|
||||||
|
if self._run_animated_action(
|
||||||
|
lambda: bool(self.engine.auto_complete_step(record_undo=False)),
|
||||||
|
duration_ms=self.AUTO_FLIGHT_MS,
|
||||||
|
after_cb=after_step,
|
||||||
|
):
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
else:
|
||||||
|
self._auto_running, self._auto_job = False, None
|
||||||
|
self.redraw()
|
||||||
|
if self.engine.won:
|
||||||
|
SolitaireOutcomeFlow.handle_victory(self)
|
||||||
|
else:
|
||||||
|
self._save_progress()
|
||||||
|
|
||||||
|
def _start_fresh_deal(self):
|
||||||
|
self._game_concluded = False
|
||||||
|
self._reset_engine_for_new_deal()
|
||||||
|
self._check_window_focus()
|
||||||
|
self._save_progress()
|
||||||
|
self.status_var.set("")
|
||||||
|
self.ctx.sounds.play("deal")
|
||||||
|
self.redraw()
|
||||||
|
|
||||||
|
def _on_new_or_forfeit_clicked(self):
|
||||||
|
if (
|
||||||
|
self._auto_running
|
||||||
|
or self._modal_overlay is not None
|
||||||
|
or self._fx_overlay is not None
|
||||||
|
):
|
||||||
|
return
|
||||||
|
if self.animator:
|
||||||
|
self.animator.flush()
|
||||||
|
if self.engine.won or self._game_concluded or self.engine.moves == 0:
|
||||||
|
self._start_fresh_deal()
|
||||||
|
return
|
||||||
|
SolitaireOutcomeFlow.show_forfeit_modal(self)
|
||||||
|
|
||||||
|
def _reset_engine_for_new_deal(self):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _recompute_and_draw(self):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def redraw(self, exclude_source=None, hidden_card_keys=None):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _snapshot_card_positions(self) -> dict:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _ordered_moved_cards(self, moved_keys: set) -> list[SolitaireCard]:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _hover_card_probe(self, x: int, y: int) -> dict | None:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _hit_test(self, x: int, y: int) -> dict | None:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _handle_click(self, info: dict):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _smart_auto_move(self, info: dict):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _try_drop(self, info: dict, drop_x: int, drop_y: int) -> bool:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
@ -0,0 +1,38 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/base/solitaire_tap_prefs.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from models.database import Database
|
||||||
|
|
||||||
|
TAP_TO_MOVE_SETTING_KEY = "sol_single_tap_to_move"
|
||||||
|
SINGLE_TAP_MAX_HOLD_SEC = 0.28
|
||||||
|
|
||||||
|
_single_tap_cache: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def invalidate_tap_prefs_cache() -> None:
|
||||||
|
"""Leert den Cache beim Wechsel auf eine andere user_data.db."""
|
||||||
|
global _single_tap_cache
|
||||||
|
_single_tap_cache = None
|
||||||
|
|
||||||
|
|
||||||
|
def is_single_tap_to_move_enabled() -> bool:
|
||||||
|
global _single_tap_cache
|
||||||
|
if _single_tap_cache is None:
|
||||||
|
try:
|
||||||
|
raw = Database.load_setting(TAP_TO_MOVE_SETTING_KEY, "0")
|
||||||
|
_single_tap_cache = str(raw).strip().lower() in ("1", "true", "yes", "on")
|
||||||
|
except Exception:
|
||||||
|
_single_tap_cache = False
|
||||||
|
return _single_tap_cache
|
||||||
|
|
||||||
|
|
||||||
|
def set_single_tap_to_move_enabled(enabled: bool, persist: bool = True) -> None:
|
||||||
|
global _single_tap_cache
|
||||||
|
state = bool(enabled)
|
||||||
|
_single_tap_cache = state
|
||||||
|
if persist:
|
||||||
|
try:
|
||||||
|
Database.save_setting(TAP_TO_MOVE_SETTING_KEY, "1" if state else "0")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
@ -2,110 +2,90 @@
|
||||||
# games/solitaire/base/solitaire_theme.py
|
# games/solitaire/base/solitaire_theme.py
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import warnings
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
import tkinter as tk
|
||||||
|
import warnings
|
||||||
from PIL import Image, ImageChops, ImageDraw, ImageTk
|
from PIL import Image, ImageChops, ImageDraw, ImageTk
|
||||||
|
|
||||||
_ICON_PIL_CACHE: dict[Path, Image.Image] = {}
|
_ICON_PIL_CACHE: dict[Path, Image.Image] = {}
|
||||||
_ICON_TK_CACHE: dict[tuple[Path, int], ImageTk.PhotoImage] = {}
|
_ICON_TK_CACHE: dict[tuple[Path, int], ImageTk.PhotoImage] = {}
|
||||||
|
|
||||||
|
|
||||||
def _extract_best_ico_pil(icon_path: Path) -> Image.Image | None:
|
def _pick_largest_rgba_frame(candidates, loader_fn) -> Image.Image | None:
|
||||||
|
best_img: Image.Image | None = None
|
||||||
|
best_area = -1
|
||||||
|
for item in candidates:
|
||||||
|
try:
|
||||||
|
frame = loader_fn(item).convert("RGBA")
|
||||||
|
area = frame.width * frame.height
|
||||||
|
if area > best_area:
|
||||||
|
best_area = area
|
||||||
|
best_img = frame
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
return best_img
|
||||||
|
|
||||||
|
|
||||||
|
def extract_best_ico_pil(icon_path: Path) -> Image.Image | None:
|
||||||
|
"""Liest den höchstauflösenden RGBA-Frame aus einer .ico-Datei."""
|
||||||
try:
|
try:
|
||||||
with warnings.catch_warnings():
|
with warnings.catch_warnings():
|
||||||
warnings.simplefilter("ignore", UserWarning)
|
warnings.simplefilter("ignore", UserWarning)
|
||||||
with Image.open(icon_path) as ico:
|
with Image.open(icon_path) as ico:
|
||||||
best_img = None
|
|
||||||
best_area = -1
|
|
||||||
ico_helper = getattr(ico, "ico", None)
|
ico_helper = getattr(ico, "ico", None)
|
||||||
|
best_img = None
|
||||||
if ico_helper is not None and hasattr(ico_helper, "sizes"):
|
if ico_helper is not None and hasattr(ico_helper, "sizes"):
|
||||||
for sz in ico_helper.sizes():
|
best_img = _pick_largest_rgba_frame(ico_helper.sizes(), ico_helper.getimage)
|
||||||
try:
|
|
||||||
frame = ico_helper.getimage(sz).convert("RGBA")
|
|
||||||
area = frame.width * frame.height
|
|
||||||
if area > best_area:
|
|
||||||
best_area = area
|
|
||||||
best_img = frame
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
if best_img is None:
|
if best_img is None:
|
||||||
for idx in range(getattr(ico, "n_frames", 1)):
|
best_img = _pick_largest_rgba_frame(
|
||||||
try:
|
range(getattr(ico, "n_frames", 1)),
|
||||||
ico.seek(idx)
|
lambda idx: (ico.seek(idx), ico.copy())[1],
|
||||||
frame = ico.copy().convert("RGBA")
|
)
|
||||||
area = frame.width * frame.height
|
|
||||||
if area > best_area:
|
|
||||||
best_area = area
|
|
||||||
best_img = frame
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
return best_img if best_img is not None else ico.convert("RGBA")
|
return best_img if best_img is not None else ico.convert("RGBA")
|
||||||
except Exception:
|
except Exception:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _scan_badge_axis(primary_len: int, secondary_len: int, probe_pixel_fn) -> list[int]:
|
||||||
|
min_span = int(secondary_len * 0.38)
|
||||||
|
valid: list[int] = []
|
||||||
|
for p in range(primary_len):
|
||||||
|
cnt = sum(2 for s in range(0, secondary_len, 2) if probe_pixel_fn(p, s))
|
||||||
|
if cnt >= min_span:
|
||||||
|
valid.append(p)
|
||||||
|
return valid
|
||||||
|
|
||||||
|
|
||||||
def _auto_crop_and_round_badge(img: Image.Image) -> Image.Image:
|
def _auto_crop_and_round_badge(img: Image.Image) -> Image.Image:
|
||||||
"""
|
|
||||||
Schneidet weiße/transparente Außenränder (und eventuelle Text-Artefakte ganz oben)
|
|
||||||
ab und stanzt das quadratische App-Badge sauber mit abgerundeten Ecken aus.
|
|
||||||
"""
|
|
||||||
w, h = img.size
|
w, h = img.size
|
||||||
px = img.load()
|
px = img.load()
|
||||||
|
|
||||||
def is_badge_pixel(r: int, g: int, b: int, a: int) -> bool:
|
def is_badge_pixel(r: int, g: int, b: int, a: int) -> bool:
|
||||||
if a < 40:
|
return a >= 40 and not (r > 228 and g > 228 and b > 228)
|
||||||
return False
|
|
||||||
# Helle/weiße Schachbrett- oder Hintergrundpixel ignorieren
|
|
||||||
if r > 228 and g > 228 and b > 228:
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
# Suche horizontale & vertikale Ausdehnung des eigentlichen breiten Icon-Blocks
|
valid_rows = _scan_badge_axis(h, w, lambda y, x: is_badge_pixel(*px[x, y]))
|
||||||
# (Zeilen mit nur wenigen schmalen Buchstaben-Pixeln < 35% Breite werden oben übersprungen!)
|
valid_cols = _scan_badge_axis(w, h, lambda x, y: is_badge_pixel(*px[x, y]))
|
||||||
min_row_span = int(w * 0.38)
|
|
||||||
valid_rows: list[int] = []
|
|
||||||
for y in range(h):
|
|
||||||
cnt = 0
|
|
||||||
for x in range(0, w, 2):
|
|
||||||
if is_badge_pixel(*px[x, y]):
|
|
||||||
cnt += 2
|
|
||||||
if cnt >= min_row_span:
|
|
||||||
valid_rows.append(y)
|
|
||||||
|
|
||||||
min_col_span = int(h * 0.38)
|
cropped = (
|
||||||
valid_cols: list[int] = []
|
img.crop((valid_cols[0], valid_rows[0], valid_cols[-1] + 1, valid_rows[-1] + 1))
|
||||||
for x in range(w):
|
if (valid_rows and valid_cols)
|
||||||
cnt = 0
|
else img
|
||||||
for y in range(0, h, 2):
|
)
|
||||||
if is_badge_pixel(*px[x, y]):
|
|
||||||
cnt += 2
|
|
||||||
if cnt >= min_col_span:
|
|
||||||
valid_cols.append(x)
|
|
||||||
|
|
||||||
if valid_rows and valid_cols:
|
|
||||||
top, bottom = valid_rows[0], valid_rows[-1] + 1
|
|
||||||
left, right = valid_cols[0], valid_cols[-1] + 1
|
|
||||||
cropped = img.crop((left, top, right, bottom))
|
|
||||||
else:
|
|
||||||
cropped = img
|
|
||||||
|
|
||||||
# Auf sauberes Quadrat bringen & mit 2x Supersampling rund maskieren
|
|
||||||
side = max(cropped.width, cropped.height)
|
side = max(cropped.width, cropped.height)
|
||||||
square = cropped.resize((side, side), Image.Resampling.LANCZOS)
|
square = cropped.resize((side, side), Image.Resampling.LANCZOS)
|
||||||
|
|
||||||
mask_big = Image.new("L", (side * 2, side * 2), 0)
|
mask_big = Image.new("L", (side * 2, side * 2), 0)
|
||||||
draw = ImageDraw.Draw(mask_big)
|
draw = ImageDraw.Draw(mask_big)
|
||||||
radius = int(side * 2 * 0.195)
|
|
||||||
pad = int(side * 2 * 0.008)
|
pad = int(side * 2 * 0.008)
|
||||||
draw.rounded_rectangle(
|
draw.rounded_rectangle(
|
||||||
(pad, pad, side * 2 - 1 - pad, side * 2 - 1 - pad),
|
(pad, pad, side * 2 - 1 - pad, side * 2 - 1 - pad),
|
||||||
radius=radius,
|
radius=int(side * 2 * 0.195),
|
||||||
fill=255,
|
fill=255,
|
||||||
)
|
)
|
||||||
mask = mask_big.resize((side, side), Image.Resampling.LANCZOS)
|
mask = mask_big.resize((side, side), Image.Resampling.LANCZOS)
|
||||||
|
|
||||||
r_ch, g_ch, b_ch, a_ch = square.split()
|
square.putalpha(ImageChops.multiply(square.getchannel("A"), mask))
|
||||||
square.putalpha(ImageChops.multiply(a_ch, mask))
|
|
||||||
return square
|
return square
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -119,24 +99,19 @@ def get_game_icon_photo(res_mgr, game_folder: str, size_px: int = 92) -> ImageTk
|
||||||
return _ICON_TK_CACHE[cache_key]
|
return _ICON_TK_CACHE[cache_key]
|
||||||
|
|
||||||
if icon_path not in _ICON_PIL_CACHE:
|
if icon_path not in _ICON_PIL_CACHE:
|
||||||
raw = _extract_best_ico_pil(icon_path)
|
raw = extract_best_ico_pil(icon_path)
|
||||||
if raw is None:
|
if raw is None:
|
||||||
return None
|
return None
|
||||||
_ICON_PIL_CACHE[icon_path] = _auto_crop_and_round_badge(raw)
|
_ICON_PIL_CACHE[icon_path] = _auto_crop_and_round_badge(raw)
|
||||||
|
|
||||||
resized = _ICON_PIL_CACHE[icon_path].resize((size_px, size_px), Image.Resampling.LANCZOS)
|
photo = ImageTk.PhotoImage(_ICON_PIL_CACHE[icon_path].resize((size_px, size_px), Image.Resampling.LANCZOS))
|
||||||
photo = ImageTk.PhotoImage(resized)
|
|
||||||
_ICON_TK_CACHE[cache_key] = photo
|
_ICON_TK_CACHE[cache_key] = photo
|
||||||
return photo
|
return photo
|
||||||
|
|
||||||
|
|
||||||
class SolitaireTableBgRenderer:
|
class SolitaireTableBgRenderer:
|
||||||
"""
|
"""Zeichnet den nahtlosen Fenster-Hintergrundausschnitt auf das Tisch-Canvas."""
|
||||||
Zeichnet und cached resources/images/general_table.jpg passgenau auf das Solitaire-Canvas
|
|
||||||
und liefert die Rahmen-Abstände, damit alle Stapel sauber innerhalb des Holzrahmens sitzen.
|
|
||||||
"""
|
|
||||||
|
|
||||||
# Prozentuale Rahmenstärke von general_table.jpg (Steinmauer + Kerzen + Holzrahmen)
|
|
||||||
FRAME_X_RATIO = 0.075
|
FRAME_X_RATIO = 0.075
|
||||||
FRAME_TOP_RATIO = 0.095
|
FRAME_TOP_RATIO = 0.095
|
||||||
FRAME_BOT_RATIO = 0.090
|
FRAME_BOT_RATIO = 0.090
|
||||||
|
|
@ -145,8 +120,7 @@ class SolitaireTableBgRenderer:
|
||||||
self.res_mgr = res_mgr
|
self.res_mgr = res_mgr
|
||||||
self._raw_pil: Image.Image | None = None
|
self._raw_pil: Image.Image | None = None
|
||||||
self._loaded = False
|
self._loaded = False
|
||||||
self._cached_size: tuple[int, int] = (0, 0)
|
self._slice_photo: ImageTk.PhotoImage | None = None
|
||||||
self._cached_photo: ImageTk.PhotoImage | None = None
|
|
||||||
|
|
||||||
def _ensure_pil(self) -> Image.Image | None:
|
def _ensure_pil(self) -> Image.Image | None:
|
||||||
if not self._loaded:
|
if not self._loaded:
|
||||||
|
|
@ -161,21 +135,35 @@ class SolitaireTableBgRenderer:
|
||||||
return self._raw_pil
|
return self._raw_pil
|
||||||
|
|
||||||
def get_frame_insets(self, canvas_w: int, canvas_h: int) -> tuple[int, int, int]:
|
def get_frame_insets(self, canvas_w: int, canvas_h: int) -> tuple[int, int, int]:
|
||||||
"""Gibt (inset_x, inset_top, inset_bottom) passend zum Zierrahmen zurück."""
|
|
||||||
if self._ensure_pil() is None:
|
if self._ensure_pil() is None:
|
||||||
return max(20, int(canvas_w * 0.04)), max(14, int(canvas_h * 0.022)), 16
|
return max(20, int(canvas_w * 0.04)), max(14, int(canvas_h * 0.022)), 16
|
||||||
ix = max(36, int(canvas_w * self.FRAME_X_RATIO))
|
return (
|
||||||
itop = max(28, int(canvas_h * self.FRAME_TOP_RATIO))
|
max(36, int(canvas_w * self.FRAME_X_RATIO)),
|
||||||
ibot = max(26, int(canvas_h * self.FRAME_BOT_RATIO))
|
max(28, int(canvas_h * self.FRAME_TOP_RATIO)),
|
||||||
return ix, itop, ibot
|
max(26, int(canvas_h * self.FRAME_BOT_RATIO)),
|
||||||
|
)
|
||||||
|
|
||||||
def draw_on_canvas(self, canvas, canvas_w: int, canvas_h: int):
|
def draw_on_canvas(self, canvas: tk.Canvas, canvas_w: int, canvas_h: int):
|
||||||
pil_img = self._ensure_pil()
|
if canvas_w < 80 or canvas_h < 80:
|
||||||
if pil_img is None or canvas_w < 50 or canvas_h < 50:
|
|
||||||
return
|
return
|
||||||
target_sz = (canvas_w, canvas_h)
|
root = canvas.winfo_toplevel()
|
||||||
if self._cached_photo is None or self._cached_size != target_sz:
|
assets = getattr(root, "assets", None)
|
||||||
scaled = pil_img.resize(target_sz, Image.Resampling.BILINEAR)
|
if assets is None:
|
||||||
self._cached_photo = ImageTk.PhotoImage(scaled)
|
return
|
||||||
self._cached_size = target_sz
|
|
||||||
canvas.create_image(0, 0, image=self._cached_photo, anchor="nw", tags=("table_bg",))
|
rw, rh = max(canvas_w, root.winfo_width()), max(canvas_h, root.winfo_height())
|
||||||
|
ox = max(0, min(rw - canvas_w, canvas.winfo_rootx() - root.winfo_rootx()))
|
||||||
|
oy = max(0, min(rh - canvas_h, canvas.winfo_rooty() - root.winfo_rooty()))
|
||||||
|
new_photo = assets.get_bg_patch_photo(rw, rh, ox, oy, canvas_w, canvas_h)
|
||||||
|
if new_photo is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
existing = canvas.find_withtag("table_bg_slice")
|
||||||
|
if existing:
|
||||||
|
if new_photo is not self._slice_photo:
|
||||||
|
self._slice_photo = new_photo
|
||||||
|
canvas.itemconfigure(existing[0], image=self._slice_photo)
|
||||||
|
else:
|
||||||
|
self._slice_photo = new_photo
|
||||||
|
canvas.create_image(0, 0, image=self._slice_photo, anchor="nw", tags=("table_bg_slice",))
|
||||||
|
canvas.tag_lower("table_bg_slice")
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -2,521 +2,38 @@
|
||||||
# games/solitaire/freecell/views/freecell_menu_view.py
|
# games/solitaire/freecell/views/freecell_menu_view.py
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
|
||||||
import tkinter as tk
|
|
||||||
from tkinter import ttk
|
|
||||||
|
|
||||||
from games.solitaire.base.solitaire_stats_view import SolitaireStatsView
|
|
||||||
from games.solitaire.freecell.views.freecell_table_view import FreeCellTableView
|
from games.solitaire.freecell.views.freecell_table_view import FreeCellTableView
|
||||||
from models.database import Database
|
from resources.code_res.game_constants import FREECELL_VARIANTS
|
||||||
from models.progression import Progression
|
|
||||||
from resources.code_res.game_constants import (
|
|
||||||
ACCENT_GOLD,
|
|
||||||
ACCENT_GOTH,
|
|
||||||
BG_COLOR,
|
|
||||||
BORDER_COLOR,
|
|
||||||
CELL_BG,
|
|
||||||
ERROR_FG,
|
|
||||||
FG_COLOR,
|
|
||||||
FREECELL_VARIANTS,
|
|
||||||
MODAL_BG,
|
|
||||||
MUTED_FG,
|
|
||||||
PANEL_BG,
|
|
||||||
SOLITAIRE_DIFFICULTIES,
|
|
||||||
SOLO_FORFEIT_XP_RATIO,
|
|
||||||
SUBTLE_BORDER,
|
|
||||||
)
|
|
||||||
from resources.code_res.i18n import t
|
|
||||||
from view.widgets.image_button import ImageButton
|
|
||||||
|
|
||||||
GAME_FOLDER_ID = "solitaire/freecell"
|
GAME_FOLDER_ID = "solitaire/freecell"
|
||||||
GAME_TITLE_KEY = "game_title_freecell"
|
GAME_TITLE_KEY = "game_title_freecell"
|
||||||
DEFAULT_VARIANT_KEY = "freecell_std"
|
|
||||||
|
|
||||||
|
|
||||||
class FreeCellMenuView:
|
class FreeCellMenuView(SolitaireMenuBase):
|
||||||
def __init__(self, context):
|
GAME_FOLDER_ID = GAME_FOLDER_ID
|
||||||
self.ctx = context
|
GAME_TITLE_KEY = GAME_TITLE_KEY
|
||||||
self._modal_overlay: tk.Frame | None = None
|
TOPBAR_KEY = "fc_menu_topbar"
|
||||||
self._return_bind_id: str | None = None
|
SUBTITLE_KEY = "fc_menu_subtitle"
|
||||||
|
CONTROLS_HINT_KEY = "fc_controls_hint"
|
||||||
|
|
||||||
def _clear_modal(self):
|
DIFF_SETTING_PREFIX = "freecell_diff"
|
||||||
if self._return_bind_id is not None:
|
DEFAULT_VARIANT_KEY = "freecell_std"
|
||||||
try:
|
REQUIRED_BOARD_KEYS = ("tableau", "freecells")
|
||||||
self.ctx.root.unbind("<Return>", self._return_bind_id)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
self._return_bind_id = None
|
|
||||||
if self._modal_overlay is not None:
|
|
||||||
try:
|
|
||||||
self._modal_overlay.destroy()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
self._modal_overlay = None
|
|
||||||
|
|
||||||
def show(
|
MODE_LABEL_KEY = "fc_variant_info_lbl"
|
||||||
self,
|
DESC_KEY_PREFIX = "fc_desc_"
|
||||||
status_msg: str = "",
|
|
||||||
status_is_ok: bool = False,
|
|
||||||
ask_resume_popup: bool = False,
|
|
||||||
):
|
|
||||||
self._clear_modal()
|
|
||||||
pid = self.ctx.profile["id"]
|
|
||||||
self.ctx.sounds.play_menu_music()
|
|
||||||
self.ctx.root.clear_window(apply_global_bg=True)
|
|
||||||
prog = self.ctx.refresh_game_progress()
|
|
||||||
|
|
||||||
diff_setting_key = f"freecell_diff_{pid}"
|
def _variants_dict(self) -> dict[str, dict]:
|
||||||
saved_diff_str = Database.load_setting(diff_setting_key, "1")
|
return FREECELL_VARIANTS
|
||||||
selected_diff = (
|
|
||||||
int(saved_diff_str)
|
|
||||||
if saved_diff_str.isdigit() and int(saved_diff_str) in SOLITAIRE_DIFFICULTIES
|
|
||||||
else 1
|
|
||||||
)
|
|
||||||
|
|
||||||
def open_stats():
|
def _launch_table_view(
|
||||||
self._clear_modal()
|
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
|
||||||
SolitaireStatsView(
|
) -> None:
|
||||||
self.ctx,
|
|
||||||
game_folder=GAME_FOLDER_ID,
|
|
||||||
game_title_key=GAME_TITLE_KEY,
|
|
||||||
on_back=lambda: self.show(),
|
|
||||||
).show()
|
|
||||||
|
|
||||||
rank_badge = f"{prog['title']} (Lv. {prog['level']} • {prog['current_xp']}/{prog['needed_xp']} XP)"
|
|
||||||
self.ctx.build_game_topbar(
|
|
||||||
self.ctx.root,
|
|
||||||
t("fc_menu_topbar"),
|
|
||||||
on_game_menu=None,
|
|
||||||
on_stats=open_stats,
|
|
||||||
stats_enabled=True,
|
|
||||||
extra_right_text=rank_badge,
|
|
||||||
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
|
|
||||||
)
|
|
||||||
|
|
||||||
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=14)
|
|
||||||
container.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.88, relheight=0.84)
|
|
||||||
|
|
||||||
main_card = tk.Frame(
|
|
||||||
container,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
padx=26,
|
|
||||||
pady=20,
|
|
||||||
highlightthickness=1,
|
|
||||||
highlightbackground=BORDER_COLOR,
|
|
||||||
)
|
|
||||||
main_card.pack(fill="x")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=t(GAME_TITLE_KEY),
|
|
||||||
font=("Georgia", 18, "bold"),
|
|
||||||
fg=ACCENT_GOLD,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=t("fc_menu_subtitle"),
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
fg=MUTED_FG,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w", pady=(4, 14))
|
|
||||||
|
|
||||||
if status_msg:
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=status_msg,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
fg="#7be08a" if status_is_ok else ERROR_FG,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w", pady=(0, 12))
|
|
||||||
|
|
||||||
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
|
|
||||||
saved_meta = self._parse_saved_meta(saved)
|
|
||||||
|
|
||||||
if saved and saved_meta is not None:
|
|
||||||
resume_box = tk.Frame(
|
|
||||||
main_card,
|
|
||||||
bg=CELL_BG,
|
|
||||||
padx=18,
|
|
||||||
pady=12,
|
|
||||||
highlightthickness=1,
|
|
||||||
highlightbackground=ACCENT_GOTH,
|
|
||||||
)
|
|
||||||
resume_box.pack(fill="x", pady=(0, 16))
|
|
||||||
|
|
||||||
left_info = tk.Frame(resume_box, bg=CELL_BG)
|
|
||||||
left_info.pack(side="left", fill="x", expand=True)
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
left_info,
|
|
||||||
text=t("sol_resume_box_title"),
|
|
||||||
font=("Georgia", 12, "bold"),
|
|
||||||
fg=ACCENT_GOTH,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(anchor="w")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
left_info,
|
|
||||||
text=t(
|
|
||||||
"sol_resume_info",
|
|
||||||
t(f"variant_{saved['variant_key']}"),
|
|
||||||
t(f"sol_diff_short_{saved_meta['difficulty']}"),
|
|
||||||
saved_meta["moves"],
|
|
||||||
saved_meta["score"],
|
|
||||||
Database.format_seconds(saved_meta["elapsed_sec"]),
|
|
||||||
),
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(anchor="w", pady=(4, 0))
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
resume_box,
|
|
||||||
t("sol_resume_btn"),
|
|
||||||
self.ctx.assets.raw_btn,
|
|
||||||
self.ctx.assets.raw_btn_active,
|
|
||||||
lambda: self._resume_saved(saved, saved_meta["difficulty"]),
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=185,
|
|
||||||
height=36,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="right", padx=(12, 0))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=t("sol_setup_sec_title"),
|
|
||||||
font=("Georgia", 12, "bold"),
|
|
||||||
fg=ACCENT_GOTH,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w", pady=(2, 8))
|
|
||||||
|
|
||||||
setup_box = tk.Frame(
|
|
||||||
main_card,
|
|
||||||
bg=CELL_BG,
|
|
||||||
padx=20,
|
|
||||||
pady=18,
|
|
||||||
highlightthickness=1,
|
|
||||||
highlightbackground=SUBTLE_BORDER,
|
|
||||||
)
|
|
||||||
setup_box.pack(fill="x")
|
|
||||||
|
|
||||||
# Zeile 1: Modus-Info
|
|
||||||
mode_row = tk.Frame(setup_box, bg=CELL_BG)
|
|
||||||
mode_row.pack(fill="x", pady=(0, 12))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
mode_row,
|
|
||||||
text=t("fc_variant_info_lbl"),
|
|
||||||
width=16,
|
|
||||||
anchor="w",
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(side="left")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
mode_row,
|
|
||||||
text=t("variant_freecell_std"),
|
|
||||||
font=("Georgia", 11, "bold"),
|
|
||||||
fg=ACCENT_GOLD,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(side="left", padx=(0, 14))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
mode_row,
|
|
||||||
text=t("fc_desc_freecell_std"),
|
|
||||||
font=("Helvetica", 9),
|
|
||||||
fg=MUTED_FG,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(side="left")
|
|
||||||
|
|
||||||
# Zeile 2: Schwierigkeitsgrad
|
|
||||||
diff_row = tk.Frame(setup_box, bg=CELL_BG)
|
|
||||||
diff_row.pack(fill="x", pady=(0, 16))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
diff_row,
|
|
||||||
text=t("sol_diff_lbl"),
|
|
||||||
width=16,
|
|
||||||
anchor="w",
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(side="left")
|
|
||||||
|
|
||||||
diff_labels = [t(f"sol_diff_{lvl}") for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())]
|
|
||||||
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())}
|
|
||||||
diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}"))
|
|
||||||
|
|
||||||
diff_cb = ttk.Combobox(
|
|
||||||
diff_row,
|
|
||||||
textvariable=diff_var,
|
|
||||||
values=diff_labels,
|
|
||||||
state="readonly",
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
style="Goth.TCombobox",
|
|
||||||
)
|
|
||||||
diff_cb.pack(side="left", fill="x", expand=True, ipady=3)
|
|
||||||
|
|
||||||
def on_diff_changed(*_):
|
|
||||||
chosen = diff_map.get(diff_var.get(), 1)
|
|
||||||
Database.save_setting(diff_setting_key, str(chosen))
|
|
||||||
|
|
||||||
diff_cb.bind("<<ComboboxSelected>>", on_diff_changed)
|
|
||||||
|
|
||||||
# Zeile 3: Start
|
|
||||||
action_row = tk.Frame(setup_box, bg=CELL_BG)
|
|
||||||
action_row.pack(fill="x")
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
action_row,
|
|
||||||
t("sol_start_btn"),
|
|
||||||
self.ctx.assets.raw_btn,
|
|
||||||
self.ctx.assets.raw_btn_active,
|
|
||||||
lambda: self._on_start_clicked(
|
|
||||||
DEFAULT_VARIANT_KEY, diff_map.get(diff_var.get(), 1), saved, saved_meta
|
|
||||||
),
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=210,
|
|
||||||
height=38,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="right")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=t("fc_controls_hint"),
|
|
||||||
font=("Helvetica", 9),
|
|
||||||
fg=MUTED_FG,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w", pady=(14, 0))
|
|
||||||
|
|
||||||
if ask_resume_popup and saved and saved_meta is not None:
|
|
||||||
self._show_resume_prompt_modal(saved, saved_meta)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _parse_saved_meta(saved: dict | None) -> dict | None:
|
|
||||||
if not saved:
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
data = json.loads(saved["state_json"])
|
|
||||||
if data.get("won"):
|
|
||||||
return None
|
|
||||||
board = data.get("board", {})
|
|
||||||
if not board or "tableau" not in board or "freecells" not in board:
|
|
||||||
return None
|
|
||||||
return {
|
|
||||||
"moves": max(0, int(data.get("moves", 0))),
|
|
||||||
"score": int(data.get("score", 0)),
|
|
||||||
"elapsed_sec": float(data.get("elapsed_sec", 0.0)),
|
|
||||||
"difficulty": max(0, min(3, int(board.get("difficulty", 1)))),
|
|
||||||
}
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
|
|
||||||
self._clear_modal()
|
|
||||||
overlay = tk.Frame(
|
|
||||||
self.ctx.root,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
padx=30,
|
|
||||||
pady=24,
|
|
||||||
highlightthickness=2,
|
|
||||||
highlightbackground=ACCENT_GOTH,
|
|
||||||
)
|
|
||||||
overlay.place(relx=0.5, rely=0.52, anchor="center")
|
|
||||||
self._modal_overlay = overlay
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
overlay,
|
|
||||||
text=t("sol_resume_box_title"),
|
|
||||||
font=("Georgia", 16, "bold"),
|
|
||||||
fg=ACCENT_GOLD,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
).pack(pady=(0, 10))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
overlay,
|
|
||||||
text=t(
|
|
||||||
"sol_resume_info",
|
|
||||||
t(f"variant_{saved['variant_key']}"),
|
|
||||||
t(f"sol_diff_short_{saved_meta['difficulty']}"),
|
|
||||||
saved_meta["moves"],
|
|
||||||
saved_meta["score"],
|
|
||||||
Database.format_seconds(saved_meta["elapsed_sec"]),
|
|
||||||
),
|
|
||||||
font=("Helvetica", 11),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
justify="center",
|
|
||||||
).pack(pady=(0, 20))
|
|
||||||
|
|
||||||
btn_row = tk.Frame(overlay, bg=MODAL_BG)
|
|
||||||
btn_row.pack()
|
|
||||||
|
|
||||||
def resume_now(_event=None):
|
|
||||||
self._clear_modal()
|
|
||||||
self._resume_saved(saved, saved_meta["difficulty"])
|
|
||||||
|
|
||||||
try:
|
|
||||||
self._return_bind_id = self.ctx.root.bind("<Return>", resume_now, add="+")
|
|
||||||
except tk.TclError:
|
|
||||||
self._return_bind_id = None
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
btn_row,
|
|
||||||
t("sol_resume_btn"),
|
|
||||||
self.ctx.assets.raw_btn,
|
|
||||||
self.ctx.assets.raw_btn_active,
|
|
||||||
resume_now,
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=190,
|
|
||||||
height=38,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="left", padx=6)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
btn_row,
|
|
||||||
t("bj_popup_to_menu_btn"),
|
|
||||||
self.ctx.assets.raw_sel,
|
|
||||||
self.ctx.assets.raw_sel_active,
|
|
||||||
self._clear_modal,
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=175,
|
|
||||||
height=38,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="left", padx=6)
|
|
||||||
|
|
||||||
def _resume_saved(self, saved: dict, difficulty: int):
|
|
||||||
self._clear_modal()
|
|
||||||
FreeCellTableView(
|
|
||||||
self.ctx,
|
|
||||||
variant_key=saved["variant_key"],
|
|
||||||
difficulty=difficulty,
|
|
||||||
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
|
|
||||||
resume_state_json=saved["state_json"],
|
|
||||||
)
|
|
||||||
|
|
||||||
def _on_start_clicked(
|
|
||||||
self,
|
|
||||||
variant_key: str,
|
|
||||||
difficulty: int,
|
|
||||||
saved: dict | None,
|
|
||||||
saved_meta: dict | None,
|
|
||||||
):
|
|
||||||
if self._modal_overlay is not None:
|
|
||||||
return
|
|
||||||
if saved and saved_meta and saved_meta["moves"] > 0:
|
|
||||||
self._show_overwrite_confirm_modal(variant_key, difficulty, saved, saved_meta)
|
|
||||||
return
|
|
||||||
self._launch_fresh_game(variant_key, difficulty)
|
|
||||||
|
|
||||||
def _show_overwrite_confirm_modal(
|
|
||||||
self,
|
|
||||||
new_variant_key: str,
|
|
||||||
new_difficulty: int,
|
|
||||||
saved: dict,
|
|
||||||
saved_meta: dict,
|
|
||||||
):
|
|
||||||
pid = self.ctx.profile["id"]
|
|
||||||
old_v = saved["variant_key"]
|
|
||||||
old_diff = saved_meta["difficulty"]
|
|
||||||
prog = Database.get_game_progress(pid, GAME_FOLDER_ID)
|
|
||||||
v_mult = FREECELL_VARIANTS.get(old_v, {"xp_mult": 1.15})["xp_mult"]
|
|
||||||
d_mult = SOLITAIRE_DIFFICULTIES.get(old_diff, SOLITAIRE_DIFFICULTIES[1])["xp_mult"]
|
|
||||||
win_xp = Progression.calculate_match_xp(prog["level"], [], "WIN", variant_mult=v_mult * d_mult)
|
|
||||||
penalty = max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO)))
|
|
||||||
|
|
||||||
overlay = tk.Frame(
|
|
||||||
self.ctx.root,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
padx=28,
|
|
||||||
pady=22,
|
|
||||||
highlightthickness=2,
|
|
||||||
highlightbackground=ERROR_FG,
|
|
||||||
)
|
|
||||||
overlay.place(relx=0.5, rely=0.52, anchor="center")
|
|
||||||
self._modal_overlay = overlay
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
overlay,
|
|
||||||
text=t("sol_forfeit_title"),
|
|
||||||
font=("Georgia", 15, "bold"),
|
|
||||||
fg=ERROR_FG,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
).pack(pady=(0, 8))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
overlay,
|
|
||||||
text=t("sol_forfeit_desc", penalty),
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
wraplength=430,
|
|
||||||
justify="center",
|
|
||||||
).pack(pady=(0, 18))
|
|
||||||
|
|
||||||
row = tk.Frame(overlay, bg=MODAL_BG)
|
|
||||||
row.pack()
|
|
||||||
|
|
||||||
def forfeit_and_start():
|
|
||||||
floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0
|
|
||||||
Database.record_game_result(
|
|
||||||
pid,
|
|
||||||
variant_key=old_v,
|
|
||||||
won=False,
|
|
||||||
duration_sec=saved_meta["elapsed_sec"],
|
|
||||||
points_gained=0,
|
|
||||||
)
|
|
||||||
Database.adjust_game_points(pid, GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp)
|
|
||||||
self.ctx.refresh_game_progress()
|
|
||||||
self._clear_modal()
|
|
||||||
self._launch_fresh_game(new_variant_key, new_difficulty)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
row,
|
|
||||||
t("sol_resume_btn"),
|
|
||||||
self.ctx.assets.raw_btn,
|
|
||||||
self.ctx.assets.raw_btn_active,
|
|
||||||
lambda: self._resume_saved(saved, old_diff),
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=165,
|
|
||||||
height=34,
|
|
||||||
font=("Helvetica", 9, "bold"),
|
|
||||||
).pack(side="left", padx=5)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
row,
|
|
||||||
t("sol_forfeit_confirm_new"),
|
|
||||||
self.ctx.assets.raw_sel,
|
|
||||||
self.ctx.assets.raw_sel_active,
|
|
||||||
forfeit_and_start,
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=175,
|
|
||||||
height=34,
|
|
||||||
font=("Helvetica", 9, "bold"),
|
|
||||||
).pack(side="left", padx=5)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
row,
|
|
||||||
t("bj_popup_to_menu_btn"),
|
|
||||||
self.ctx.assets.raw_sel,
|
|
||||||
self.ctx.assets.raw_sel_active,
|
|
||||||
self._clear_modal,
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=155,
|
|
||||||
height=34,
|
|
||||||
font=("Helvetica", 9, "bold"),
|
|
||||||
).pack(side="left", padx=5)
|
|
||||||
|
|
||||||
def _launch_fresh_game(self, variant_key: str, difficulty: int):
|
|
||||||
pid = self.ctx.profile["id"]
|
|
||||||
Database.save_setting(f"freecell_diff_{pid}", str(difficulty))
|
|
||||||
Database.delete_game_state(pid, GAME_FOLDER_ID)
|
|
||||||
FreeCellTableView(
|
FreeCellTableView(
|
||||||
self.ctx,
|
self.ctx,
|
||||||
variant_key=variant_key,
|
variant_key=variant_key,
|
||||||
difficulty=difficulty,
|
difficulty=difficulty,
|
||||||
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
|
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
|
||||||
|
resume_state_json=resume_state_json,
|
||||||
)
|
)
|
||||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
|
@ -7,17 +7,13 @@ from games.solitaire.base.solitaire_core import (
|
||||||
SolitaireCard,
|
SolitaireCard,
|
||||||
is_alternating_descending,
|
is_alternating_descending,
|
||||||
)
|
)
|
||||||
|
from games.solitaire.klondike.models.klondike_hint_analyzer import KlondikeHintAnalyzer
|
||||||
from games.solitaire.klondike.models.klondike_solver import generate_solvable_klondike_deck
|
from games.solitaire.klondike.models.klondike_solver import generate_solvable_klondike_deck
|
||||||
from resources.code_res.game_constants import SOLITAIRE_DIFFICULTIES, SUITS
|
from resources.code_res.game_constants import SOLITAIRE_DIFFICULTIES, SUITS
|
||||||
|
|
||||||
|
|
||||||
class KlondikeEngine(SolitaireBaseEngine):
|
class KlondikeEngine(SolitaireBaseEngine):
|
||||||
"""
|
"""Klondike-Spiellogik (Draw 1 & Draw 3) mit garantierter Lösbarkeit & Stagnationssperre."""
|
||||||
Klondike-Spiellogik (Draw 1 & Draw 3) mit:
|
|
||||||
- garantierter Lösbarkeit
|
|
||||||
- 3-Zyklen-Stagnationssperre auf dem Stock (rotes X, per Undo auflösbar)
|
|
||||||
- automatischer Sackgassen-Erkennung (has_any_meaningful_move)
|
|
||||||
"""
|
|
||||||
|
|
||||||
NUM_TABLEAU = 7
|
NUM_TABLEAU = 7
|
||||||
NUM_FOUNDATIONS = 4
|
NUM_FOUNDATIONS = 4
|
||||||
|
|
@ -37,8 +33,6 @@ class KlondikeEngine(SolitaireBaseEngine):
|
||||||
self.seed: int | None = seed
|
self.seed: int | None = seed
|
||||||
self.redeals_used: int = 0
|
self.redeals_used: int = 0
|
||||||
self.redeal_limit: int | None = None
|
self.redeal_limit: int | None = None
|
||||||
|
|
||||||
# Zählt volle Stock-Durchläufe ohne jeglichen Spielfortschritt
|
|
||||||
self.stagnant_cycles: int = 0
|
self.stagnant_cycles: int = 0
|
||||||
self.progress_in_current_cycle: bool = False
|
self.progress_in_current_cycle: bool = False
|
||||||
|
|
||||||
|
|
@ -96,7 +90,6 @@ class KlondikeEngine(SolitaireBaseEngine):
|
||||||
self.capture_initial_state()
|
self.capture_initial_state()
|
||||||
|
|
||||||
def _mark_board_progress(self):
|
def _mark_board_progress(self):
|
||||||
"""Sobald eine Karte auf dem Spielfeld bewegt wird, wird der Stagnationszähler zurückgesetzt."""
|
|
||||||
self.stagnant_cycles = 0
|
self.stagnant_cycles = 0
|
||||||
self.progress_in_current_cycle = True
|
self.progress_in_current_cycle = True
|
||||||
|
|
||||||
|
|
@ -117,20 +110,16 @@ class KlondikeEngine(SolitaireBaseEngine):
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# --- Regel-Prüfungen ---
|
|
||||||
def foundation_index_for_suit(self, suit: str) -> int:
|
def foundation_index_for_suit(self, suit: str) -> int:
|
||||||
return SUITS.index(suit)
|
return SUITS.index(suit)
|
||||||
|
|
||||||
def can_move_to_foundation(self, card: SolitaireCard, found_idx: int) -> bool:
|
def can_move_to_foundation(self, card: SolitaireCard, found_idx: int) -> bool:
|
||||||
if not card.face_up or not (0 <= found_idx < self.NUM_FOUNDATIONS):
|
if not card.face_up or not (0 <= found_idx < self.NUM_FOUNDATIONS):
|
||||||
return False
|
return False
|
||||||
target_suit = SUITS[found_idx]
|
if card.suit != SUITS[found_idx]:
|
||||||
if card.suit != target_suit:
|
|
||||||
return False
|
return False
|
||||||
pile = self.foundations[found_idx]
|
pile = self.foundations[found_idx]
|
||||||
if not pile:
|
return (card.value == 1) if not pile else (card.value == pile[-1].value + 1)
|
||||||
return card.value == 1
|
|
||||||
return card.value == pile[-1].value + 1
|
|
||||||
|
|
||||||
def can_move_to_tableau(self, moving_cards: list[SolitaireCard], dst_col: int) -> bool:
|
def can_move_to_tableau(self, moving_cards: list[SolitaireCard], dst_col: int) -> bool:
|
||||||
if not moving_cards or not (0 <= dst_col < self.NUM_TABLEAU):
|
if not moving_cards or not (0 <= dst_col < self.NUM_TABLEAU):
|
||||||
|
|
@ -144,9 +133,7 @@ class KlondikeEngine(SolitaireBaseEngine):
|
||||||
top = dst[-1]
|
top = dst[-1]
|
||||||
return top.face_up and (top.is_red != head.is_red) and (top.value == head.value + 1)
|
return top.face_up and (top.is_red != head.is_red) and (top.value == head.value + 1)
|
||||||
|
|
||||||
# --- Stock, Redeal-Limit & 3-Zyklen-Stagnationssperre ---
|
|
||||||
def is_stagnation_locked(self) -> bool:
|
def is_stagnation_locked(self) -> bool:
|
||||||
"""True, wenn 3 volle Durchläufe des Decks ohne jede Änderung erfolgt sind."""
|
|
||||||
return (
|
return (
|
||||||
not self.stock
|
not self.stock
|
||||||
and bool(self.waste)
|
and bool(self.waste)
|
||||||
|
|
@ -162,15 +149,10 @@ class KlondikeEngine(SolitaireBaseEngine):
|
||||||
)
|
)
|
||||||
|
|
||||||
def is_stock_locked(self) -> bool:
|
def is_stock_locked(self) -> bool:
|
||||||
"""True, wenn der Stapel nicht mehr neu umgedreht werden darf (Rotes X)."""
|
|
||||||
return self.is_stagnation_locked() or self.is_redeal_exhausted()
|
return self.is_stagnation_locked() or self.is_redeal_exhausted()
|
||||||
|
|
||||||
def can_draw_or_recycle(self) -> bool:
|
def can_draw_or_recycle(self) -> bool:
|
||||||
if self.stock:
|
return bool(self.stock) or (bool(self.waste) and not self.is_stock_locked())
|
||||||
return True
|
|
||||||
if self.waste and not self.is_stock_locked():
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
def draw_from_stock(self) -> bool:
|
def draw_from_stock(self) -> bool:
|
||||||
if self.won:
|
if self.won:
|
||||||
|
|
@ -183,9 +165,6 @@ class KlondikeEngine(SolitaireBaseEngine):
|
||||||
card.face_up = True
|
card.face_up = True
|
||||||
self.waste.append(card)
|
self.waste.append(card)
|
||||||
self.moves += 1
|
self.moves += 1
|
||||||
|
|
||||||
# Wenn gerade die letzte Karte eines kompletten ereignislosen Durchlaufs aufgedeckt wurde,
|
|
||||||
# zählt dieser Zyklus als abgeschlossen -> beim 3. Mal erscheint sofort das rote X!
|
|
||||||
if not self.stock and not self.progress_in_current_cycle:
|
if not self.stock and not self.progress_in_current_cycle:
|
||||||
self.stagnant_cycles += 1
|
self.stagnant_cycles += 1
|
||||||
return True
|
return True
|
||||||
|
|
@ -204,10 +183,8 @@ class KlondikeEngine(SolitaireBaseEngine):
|
||||||
elif self.redeals_used > 3:
|
elif self.redeals_used > 3:
|
||||||
self._add_score(self.SCORE_RECYCLE_DRAW3)
|
self._add_score(self.SCORE_RECYCLE_DRAW3)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# --- Aktionen: Kartenverschiebungen ---
|
|
||||||
def move_waste_to_foundation(self, found_idx: int | None = None) -> bool:
|
def move_waste_to_foundation(self, found_idx: int | None = None) -> bool:
|
||||||
if self.won or not self.waste:
|
if self.won or not self.waste:
|
||||||
return False
|
return False
|
||||||
|
|
@ -283,21 +260,17 @@ class KlondikeEngine(SolitaireBaseEngine):
|
||||||
if self.won or not (0 <= found_idx < self.NUM_FOUNDATIONS):
|
if self.won or not (0 <= found_idx < self.NUM_FOUNDATIONS):
|
||||||
return False
|
return False
|
||||||
f_pile = self.foundations[found_idx]
|
f_pile = self.foundations[found_idx]
|
||||||
if not f_pile:
|
if not f_pile or not self.can_move_to_tableau([f_pile[-1]], dst_col):
|
||||||
return False
|
|
||||||
card = f_pile[-1]
|
|
||||||
if not self.can_move_to_tableau([card], dst_col):
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
self.push_undo()
|
self.push_undo()
|
||||||
f_pile.pop()
|
card = f_pile.pop()
|
||||||
self.tableau[dst_col].append(card)
|
self.tableau[dst_col].append(card)
|
||||||
self.moves += 1
|
self.moves += 1
|
||||||
self._mark_board_progress()
|
self._mark_board_progress()
|
||||||
self._add_score(self.SCORE_FOUNDATION_TO_TABLEAU)
|
self._add_score(self.SCORE_FOUNDATION_TO_TABLEAU)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# --- Komfort: Auto-Complete, Hinweise & Sackgassen-Prüfung ---
|
|
||||||
def can_auto_complete(self) -> bool:
|
def can_auto_complete(self) -> bool:
|
||||||
if self.won or self.stock or self.waste:
|
if self.won or self.stock or self.waste:
|
||||||
return False
|
return False
|
||||||
|
|
@ -306,7 +279,6 @@ class KlondikeEngine(SolitaireBaseEngine):
|
||||||
def auto_complete_step(self, record_undo: bool = False) -> tuple[int, int] | None:
|
def auto_complete_step(self, record_undo: bool = False) -> tuple[int, int] | None:
|
||||||
if self.won:
|
if self.won:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
candidates: list[tuple[int, int, int]] = []
|
candidates: list[tuple[int, int, int]] = []
|
||||||
for col_idx, col in enumerate(self.tableau):
|
for col_idx, col in enumerate(self.tableau):
|
||||||
if not col:
|
if not col:
|
||||||
|
|
@ -315,7 +287,6 @@ class KlondikeEngine(SolitaireBaseEngine):
|
||||||
f_idx = self.foundation_index_for_suit(card.suit)
|
f_idx = self.foundation_index_for_suit(card.suit)
|
||||||
if self.can_move_to_foundation(card, f_idx):
|
if self.can_move_to_foundation(card, f_idx):
|
||||||
candidates.append((card.value, col_idx, f_idx))
|
candidates.append((card.value, col_idx, f_idx))
|
||||||
|
|
||||||
if not candidates:
|
if not candidates:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
@ -332,166 +303,12 @@ class KlondikeEngine(SolitaireBaseEngine):
|
||||||
self._check_victory()
|
self._check_victory()
|
||||||
return best_col, best_f_idx
|
return best_col, best_f_idx
|
||||||
|
|
||||||
def _card_can_play_anywhere(self, card: SolitaireCard) -> bool:
|
|
||||||
probe = SolitaireCard(suit=card.suit, rank=card.rank, face_up=True, deck_id=card.deck_id)
|
|
||||||
if self.can_move_to_foundation(probe, self.foundation_index_for_suit(probe.suit)):
|
|
||||||
return True
|
|
||||||
return any(self.can_move_to_tableau([probe], dst_col) for dst_col in range(self.NUM_TABLEAU))
|
|
||||||
|
|
||||||
def _reachable_stock_waste_cards(self) -> list[SolitaireCard]:
|
|
||||||
"""Ermittelt alle Karten, die durch Ziehen/Recyclen aktuell noch oben auf dem Waste landen können."""
|
|
||||||
reachable: list[SolitaireCard] = []
|
|
||||||
if self.waste:
|
|
||||||
reachable.append(self.waste[-1])
|
|
||||||
|
|
||||||
# 1. Restlichen aktuellen Stock in draw_count-Schritten simulieren
|
|
||||||
if self.stock:
|
|
||||||
sim_stk = list(self.stock)
|
|
||||||
while sim_stk:
|
|
||||||
step = min(self.draw_count, len(sim_stk))
|
|
||||||
top_drawn = None
|
|
||||||
for _ in range(step):
|
|
||||||
top_drawn = sim_stk.pop()
|
|
||||||
if top_drawn is not None:
|
|
||||||
reachable.append(top_drawn)
|
|
||||||
|
|
||||||
# 2. Falls danach noch ein Recycle erlaubt wäre, auch den nächsten Zyklus prüfen
|
|
||||||
will_lock_after_stock = (
|
|
||||||
bool(self.stock)
|
|
||||||
and (not self.progress_in_current_cycle)
|
|
||||||
and (self.stagnant_cycles + 1 >= self.MAX_STAGNANT_CYCLES)
|
|
||||||
)
|
|
||||||
can_recycle_next = (
|
|
||||||
not self.is_stock_locked()
|
|
||||||
and not will_lock_after_stock
|
|
||||||
and (self.redeal_limit is None or self.redeals_used < self.redeal_limit)
|
|
||||||
)
|
|
||||||
if can_recycle_next and (self.stock or self.waste):
|
|
||||||
full_cycle = list(self.waste) + list(reversed(self.stock))
|
|
||||||
sim_stk2 = list(reversed(full_cycle))
|
|
||||||
while sim_stk2:
|
|
||||||
step = min(self.draw_count, len(sim_stk2))
|
|
||||||
top_drawn = None
|
|
||||||
for _ in range(step):
|
|
||||||
top_drawn = sim_stk2.pop()
|
|
||||||
if top_drawn is not None:
|
|
||||||
reachable.append(top_drawn)
|
|
||||||
|
|
||||||
return reachable
|
|
||||||
|
|
||||||
def has_any_meaningful_move(self) -> bool:
|
def has_any_meaningful_move(self) -> bool:
|
||||||
"""
|
return KlondikeHintAnalyzer.has_any_meaningful_move(self)
|
||||||
Prüft, ob noch irgendein sinnvoller Zug existiert.
|
|
||||||
Reine Endlos-Züge (König von leerer Spalte zu leerer Spalte, grundloses Hin-und-Her-Schieben
|
|
||||||
von Teil-Runs ohne Freilegung einer verdeckten oder Foundation-fähigen Karte) zählen NICHT.
|
|
||||||
"""
|
|
||||||
if self.won:
|
|
||||||
return True
|
|
||||||
|
|
||||||
# 1. Tableau-Spitze -> Foundation
|
|
||||||
for col_idx, col in enumerate(self.tableau):
|
|
||||||
if col:
|
|
||||||
top = col[-1]
|
|
||||||
if self.can_move_to_foundation(top, self.foundation_index_for_suit(top.suit)):
|
|
||||||
return True
|
|
||||||
|
|
||||||
# 2. Sinnvolle Tableau -> Tableau Züge
|
|
||||||
for src_col, col in enumerate(self.tableau):
|
|
||||||
if not col:
|
|
||||||
continue
|
|
||||||
first_up = next((i for i, c in enumerate(col) if c.face_up), len(col))
|
|
||||||
if first_up >= len(col):
|
|
||||||
continue
|
|
||||||
|
|
||||||
# a) Ganzen offenen Stapel bewegen (legt verdeckte Karte frei oder räumt Spalte für anderen König)
|
|
||||||
whole_run = col[first_up:]
|
|
||||||
if not (first_up == 0 and whole_run[0].value == 13):
|
|
||||||
for dst_col in range(self.NUM_TABLEAU):
|
|
||||||
if src_col != dst_col and self.can_move_to_tableau(whole_run, dst_col):
|
|
||||||
# Leert es nur eine Spalte (first_up == 0, Karte != K), ist das immer produktiv
|
|
||||||
return True
|
|
||||||
|
|
||||||
# b) Teil-Run splitten, falls die freigelegte Karte darunter direkt auf die Foundation passt
|
|
||||||
for split_idx in range(first_up + 1, len(col)):
|
|
||||||
exposed = col[split_idx - 1]
|
|
||||||
if self.can_move_to_foundation(exposed, self.foundation_index_for_suit(exposed.suit)):
|
|
||||||
sub_run = col[split_idx:]
|
|
||||||
for dst_col in range(self.NUM_TABLEAU):
|
|
||||||
if src_col != dst_col and self.can_move_to_tableau(sub_run, dst_col):
|
|
||||||
return True
|
|
||||||
|
|
||||||
# 3. Erreichbare Karten aus Waste / Stock prüfen
|
|
||||||
for r_card in self._reachable_stock_waste_cards():
|
|
||||||
if self._card_can_play_anywhere(r_card):
|
|
||||||
return True
|
|
||||||
|
|
||||||
# 4. Falls der Stock noch ungezogene / recyclebare Karten hat, die der Spieler noch selbst aufdecken darf,
|
|
||||||
# erst dann als Deadlock melden, wenn entweder gar keine spielbare Karte drin steckt ODER das rote X aktiv ist.
|
|
||||||
# (Schritt 3 hat bereits geprüft, ob im erreichbaren Stock überhaupt noch eine spielbare Karte liegt!)
|
|
||||||
|
|
||||||
# 5. Seltener Rettungszug: Karte von Foundation aufs Tableau holen, um damit sofort eine Tableau-Spitze aufzunehmen
|
|
||||||
for f_idx, f_pile in enumerate(self.foundations):
|
|
||||||
if not f_pile or f_pile[-1].value <= 2:
|
|
||||||
continue
|
|
||||||
f_card = f_pile[-1]
|
|
||||||
for dst_col in range(self.NUM_TABLEAU):
|
|
||||||
if not self.can_move_to_tableau([f_card], dst_col):
|
|
||||||
continue
|
|
||||||
# Bringt dieser Rückzug einer anderen Tableau-Karte sofort ein neues Ziel?
|
|
||||||
for other_col, o_pile in enumerate(self.tableau):
|
|
||||||
if other_col == dst_col or not o_pile:
|
|
||||||
continue
|
|
||||||
o_first_up = next((i for i, c in enumerate(o_pile) if c.face_up), len(o_pile))
|
|
||||||
head = o_pile[o_first_up]
|
|
||||||
if head.is_red != f_card.is_red and head.value + 1 == f_card.value:
|
|
||||||
return True
|
|
||||||
|
|
||||||
return False
|
|
||||||
|
|
||||||
def get_hint(self) -> dict | None:
|
def get_hint(self) -> dict | None:
|
||||||
if self.waste:
|
return KlondikeHintAnalyzer.get_hint(self)
|
||||||
w_card = self.waste[-1]
|
|
||||||
f_idx = self.foundation_index_for_suit(w_card.suit)
|
|
||||||
if self.can_move_to_foundation(w_card, f_idx):
|
|
||||||
return {"type": "waste_to_foundation", "dst": f_idx}
|
|
||||||
|
|
||||||
for col_idx, col in enumerate(self.tableau):
|
|
||||||
if col:
|
|
||||||
t_card = col[-1]
|
|
||||||
f_idx = self.foundation_index_for_suit(t_card.suit)
|
|
||||||
if self.can_move_to_foundation(t_card, f_idx):
|
|
||||||
return {"type": "tableau_to_foundation", "src_col": col_idx, "dst": f_idx}
|
|
||||||
|
|
||||||
for src_col, col in enumerate(self.tableau):
|
|
||||||
if not col:
|
|
||||||
continue
|
|
||||||
first_up_idx = next((i for i, c in enumerate(col) if c.face_up), len(col))
|
|
||||||
if first_up_idx >= len(col):
|
|
||||||
continue
|
|
||||||
moving = col[first_up_idx:]
|
|
||||||
if first_up_idx == 0 and moving[0].value == 13:
|
|
||||||
continue
|
|
||||||
for dst_col in range(self.NUM_TABLEAU):
|
|
||||||
if src_col != dst_col and self.can_move_to_tableau(moving, dst_col):
|
|
||||||
return {
|
|
||||||
"type": "tableau_to_tableau",
|
|
||||||
"src_col": src_col,
|
|
||||||
"card_idx": first_up_idx,
|
|
||||||
"dst_col": dst_col,
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.waste:
|
|
||||||
w_card = self.waste[-1]
|
|
||||||
for dst_col in range(self.NUM_TABLEAU):
|
|
||||||
if self.can_move_to_tableau([w_card], dst_col):
|
|
||||||
return {"type": "waste_to_tableau", "dst_col": dst_col}
|
|
||||||
|
|
||||||
if self.can_draw_or_recycle():
|
|
||||||
return {"type": "draw_stock"}
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
# --- Persistenz ---
|
|
||||||
def serialize_board(self) -> dict:
|
def serialize_board(self) -> dict:
|
||||||
return {
|
return {
|
||||||
"draw_count": self.draw_count,
|
"draw_count": self.draw_count,
|
||||||
|
|
@ -516,9 +333,5 @@ class KlondikeEngine(SolitaireBaseEngine):
|
||||||
self.progress_in_current_cycle = bool(board.get("progress_in_cycle", 0))
|
self.progress_in_current_cycle = bool(board.get("progress_in_cycle", 0))
|
||||||
self.stock = [SolitaireCard.from_dict(d) for d in board["stock"]]
|
self.stock = [SolitaireCard.from_dict(d) for d in board["stock"]]
|
||||||
self.waste = [SolitaireCard.from_dict(d) for d in board["waste"]]
|
self.waste = [SolitaireCard.from_dict(d) for d in board["waste"]]
|
||||||
self.foundations = [
|
self.foundations = [[SolitaireCard.from_dict(d) for d in f] for f in board["foundations"]]
|
||||||
[SolitaireCard.from_dict(d) for d in f] for f in board["foundations"]
|
self.tableau = [[SolitaireCard.from_dict(d) for d in col] for col in board["tableau"]]
|
||||||
]
|
|
||||||
self.tableau = [
|
|
||||||
[SolitaireCard.from_dict(d) for d in col] for col in board["tableau"]
|
|
||||||
]
|
|
||||||
|
|
@ -0,0 +1,152 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/klondike/models/klondike_hint_analyzer.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from games.solitaire.base.solitaire_core import SolitaireCard
|
||||||
|
|
||||||
|
|
||||||
|
class KlondikeHintAnalyzer:
|
||||||
|
"""Kapselt Erreichbarkeits-Analyse, Deadlock-Prüfung und Zug-Tipps für KlondikeEngine."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def card_can_play_anywhere(eng, card: SolitaireCard) -> bool:
|
||||||
|
probe = SolitaireCard(suit=card.suit, rank=card.rank, face_up=True, deck_id=card.deck_id)
|
||||||
|
if eng.can_move_to_foundation(probe, eng.foundation_index_for_suit(probe.suit)):
|
||||||
|
return True
|
||||||
|
return any(eng.can_move_to_tableau([probe], dst_col) for dst_col in range(eng.NUM_TABLEAU))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def reachable_stock_waste_cards(eng) -> list[SolitaireCard]:
|
||||||
|
reachable: list[SolitaireCard] = []
|
||||||
|
if eng.waste:
|
||||||
|
reachable.append(eng.waste[-1])
|
||||||
|
|
||||||
|
if eng.stock:
|
||||||
|
sim_stk = list(eng.stock)
|
||||||
|
while sim_stk:
|
||||||
|
step = min(eng.draw_count, len(sim_stk))
|
||||||
|
top_drawn = None
|
||||||
|
for _ in range(step):
|
||||||
|
top_drawn = sim_stk.pop()
|
||||||
|
if top_drawn is not None:
|
||||||
|
reachable.append(top_drawn)
|
||||||
|
|
||||||
|
will_lock_after_stock = (
|
||||||
|
bool(eng.stock)
|
||||||
|
and (not eng.progress_in_current_cycle)
|
||||||
|
and (eng.stagnant_cycles + 1 >= eng.MAX_STAGNANT_CYCLES)
|
||||||
|
)
|
||||||
|
can_recycle_next = (
|
||||||
|
not eng.is_stock_locked()
|
||||||
|
and not will_lock_after_stock
|
||||||
|
and (eng.redeal_limit is None or eng.redeals_used < eng.redeal_limit)
|
||||||
|
)
|
||||||
|
if can_recycle_next and (eng.stock or eng.waste):
|
||||||
|
full_cycle = list(eng.waste) + list(reversed(eng.stock))
|
||||||
|
sim_stk2 = list(reversed(full_cycle))
|
||||||
|
while sim_stk2:
|
||||||
|
step = min(eng.draw_count, len(sim_stk2))
|
||||||
|
top_drawn = None
|
||||||
|
for _ in range(step):
|
||||||
|
top_drawn = sim_stk2.pop()
|
||||||
|
if top_drawn is not None:
|
||||||
|
reachable.append(top_drawn)
|
||||||
|
|
||||||
|
return reachable
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def has_any_meaningful_move(cls, eng) -> bool:
|
||||||
|
if eng.won:
|
||||||
|
return True
|
||||||
|
|
||||||
|
for col in eng.tableau:
|
||||||
|
if col:
|
||||||
|
top = col[-1]
|
||||||
|
if eng.can_move_to_foundation(top, eng.foundation_index_for_suit(top.suit)):
|
||||||
|
return True
|
||||||
|
|
||||||
|
for src_col, col in enumerate(eng.tableau):
|
||||||
|
if not col:
|
||||||
|
continue
|
||||||
|
first_up = next((i for i, c in enumerate(col) if c.face_up), len(col))
|
||||||
|
if first_up >= len(col):
|
||||||
|
continue
|
||||||
|
|
||||||
|
whole_run = col[first_up:]
|
||||||
|
if not (first_up == 0 and whole_run[0].value == 13):
|
||||||
|
for dst_col in range(eng.NUM_TABLEAU):
|
||||||
|
if src_col != dst_col and eng.can_move_to_tableau(whole_run, dst_col):
|
||||||
|
return True
|
||||||
|
|
||||||
|
for split_idx in range(first_up + 1, len(col)):
|
||||||
|
exposed = col[split_idx - 1]
|
||||||
|
if eng.can_move_to_foundation(exposed, eng.foundation_index_for_suit(exposed.suit)):
|
||||||
|
sub_run = col[split_idx:]
|
||||||
|
for dst_col in range(eng.NUM_TABLEAU):
|
||||||
|
if src_col != dst_col and eng.can_move_to_tableau(sub_run, dst_col):
|
||||||
|
return True
|
||||||
|
|
||||||
|
for r_card in cls.reachable_stock_waste_cards(eng):
|
||||||
|
if cls.card_can_play_anywhere(eng, r_card):
|
||||||
|
return True
|
||||||
|
|
||||||
|
for f_pile in eng.foundations:
|
||||||
|
if not f_pile or f_pile[-1].value <= 2:
|
||||||
|
continue
|
||||||
|
f_card = f_pile[-1]
|
||||||
|
for dst_col in range(eng.NUM_TABLEAU):
|
||||||
|
if not eng.can_move_to_tableau([f_card], dst_col):
|
||||||
|
continue
|
||||||
|
for other_col, o_pile in enumerate(eng.tableau):
|
||||||
|
if other_col == dst_col or not o_pile:
|
||||||
|
continue
|
||||||
|
o_first_up = next((i for i, c in enumerate(o_pile) if c.face_up), len(o_pile))
|
||||||
|
head = o_pile[o_first_up]
|
||||||
|
if head.is_red != f_card.is_red and head.value + 1 == f_card.value:
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_hint(eng) -> dict | None:
|
||||||
|
if eng.waste:
|
||||||
|
w_card = eng.waste[-1]
|
||||||
|
f_idx = eng.foundation_index_for_suit(w_card.suit)
|
||||||
|
if eng.can_move_to_foundation(w_card, f_idx):
|
||||||
|
return {"type": "waste_to_foundation", "dst": f_idx}
|
||||||
|
|
||||||
|
for col_idx, col in enumerate(eng.tableau):
|
||||||
|
if col:
|
||||||
|
t_card = col[-1]
|
||||||
|
f_idx = eng.foundation_index_for_suit(t_card.suit)
|
||||||
|
if eng.can_move_to_foundation(t_card, f_idx):
|
||||||
|
return {"type": "tableau_to_foundation", "src_col": col_idx, "dst": f_idx}
|
||||||
|
|
||||||
|
for src_col, col in enumerate(eng.tableau):
|
||||||
|
if not col:
|
||||||
|
continue
|
||||||
|
first_up_idx = next((i for i, c in enumerate(col) if c.face_up), len(col))
|
||||||
|
if first_up_idx >= len(col):
|
||||||
|
continue
|
||||||
|
moving = col[first_up_idx:]
|
||||||
|
if first_up_idx == 0 and moving[0].value == 13:
|
||||||
|
continue
|
||||||
|
for dst_col in range(eng.NUM_TABLEAU):
|
||||||
|
if src_col != dst_col and eng.can_move_to_tableau(moving, dst_col):
|
||||||
|
return {
|
||||||
|
"type": "tableau_to_tableau",
|
||||||
|
"src_col": src_col,
|
||||||
|
"card_idx": first_up_idx,
|
||||||
|
"dst_col": dst_col,
|
||||||
|
}
|
||||||
|
|
||||||
|
if eng.waste:
|
||||||
|
w_card = eng.waste[-1]
|
||||||
|
for dst_col in range(eng.NUM_TABLEAU):
|
||||||
|
if eng.can_move_to_tableau([w_card], dst_col):
|
||||||
|
return {"type": "waste_to_tableau", "dst_col": dst_col}
|
||||||
|
|
||||||
|
if eng.can_draw_or_recycle():
|
||||||
|
return {"type": "draw_stock"}
|
||||||
|
|
||||||
|
return None
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -2,542 +2,44 @@
|
||||||
# games/solitaire/klondike/views/klondike_menu_view.py
|
# games/solitaire/klondike/views/klondike_menu_view.py
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
|
||||||
import tkinter as tk
|
|
||||||
from tkinter import ttk
|
|
||||||
|
|
||||||
from games.solitaire.base.solitaire_stats_view import SolitaireStatsView
|
|
||||||
from games.solitaire.klondike.views.klondike_table_view import KlondikeTableView
|
from games.solitaire.klondike.views.klondike_table_view import KlondikeTableView
|
||||||
from models.database import Database
|
from resources.code_res.game_constants import KLONDIKE_VARIANTS
|
||||||
from models.progression import Progression
|
|
||||||
from resources.code_res.game_constants import (
|
|
||||||
ACCENT_GOLD,
|
|
||||||
ACCENT_GOTH,
|
|
||||||
BG_COLOR,
|
|
||||||
BORDER_COLOR,
|
|
||||||
CELL_BG,
|
|
||||||
ERROR_FG,
|
|
||||||
FG_COLOR,
|
|
||||||
KLONDIKE_VARIANTS,
|
|
||||||
MODAL_BG,
|
|
||||||
MUTED_FG,
|
|
||||||
PANEL_BG,
|
|
||||||
SOLITAIRE_DIFFICULTIES,
|
|
||||||
SOLO_FORFEIT_XP_RATIO,
|
|
||||||
SUBTLE_BORDER,
|
|
||||||
)
|
|
||||||
from resources.code_res.i18n import t
|
|
||||||
from view.widgets.image_button import ImageButton
|
|
||||||
|
|
||||||
GAME_FOLDER_ID = "solitaire/klondike"
|
GAME_FOLDER_ID = "solitaire/klondike"
|
||||||
GAME_TITLE_KEY = "game_title_klondike"
|
GAME_TITLE_KEY = "game_title_klondike"
|
||||||
|
|
||||||
|
|
||||||
class KlondikeMenuView:
|
class KlondikeMenuView(SolitaireMenuBase):
|
||||||
def __init__(self, context):
|
GAME_FOLDER_ID = GAME_FOLDER_ID
|
||||||
self.ctx = context
|
GAME_TITLE_KEY = GAME_TITLE_KEY
|
||||||
self._modal_overlay: tk.Frame | None = None
|
TOPBAR_KEY = "kl_menu_topbar"
|
||||||
self._return_bind_id: str | None = None
|
SUBTITLE_KEY = "sol_menu_subtitle"
|
||||||
|
CONTROLS_HINT_KEY = "kl_controls_hint"
|
||||||
|
|
||||||
def _clear_modal(self):
|
DIFF_SETTING_PREFIX = "klondike_diff"
|
||||||
if self._return_bind_id is not None:
|
VARIANT_SETTING_PREFIX = "klondike_variant"
|
||||||
try:
|
DEFAULT_VARIANT_KEY = "klondike_1"
|
||||||
self.ctx.root.unbind("<Return>", self._return_bind_id)
|
REQUIRED_BOARD_KEYS = ("tableau",)
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
self._return_bind_id = None
|
|
||||||
if self._modal_overlay is not None:
|
|
||||||
try:
|
|
||||||
self._modal_overlay.destroy()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
self._modal_overlay = None
|
|
||||||
|
|
||||||
def show(
|
MODE_LABEL_KEY = "sol_draw_mode_lbl"
|
||||||
self,
|
VARIANT_TOGGLES = (
|
||||||
status_msg: str = "",
|
("klondike_1", "kl_draw_toggle_1"),
|
||||||
status_is_ok: bool = False,
|
("klondike_3", "kl_draw_toggle_3"),
|
||||||
ask_resume_popup: bool = False,
|
)
|
||||||
):
|
TOGGLE_BTN_WIDTH = 162
|
||||||
self._clear_modal()
|
DESC_KEY_PREFIX = "kl_desc_"
|
||||||
pid = self.ctx.profile["id"]
|
|
||||||
self.ctx.sounds.play_menu_music()
|
|
||||||
self.ctx.root.clear_window(apply_global_bg=True)
|
|
||||||
prog = self.ctx.refresh_game_progress()
|
|
||||||
|
|
||||||
diff_setting_key = f"klondike_diff_{pid}"
|
def _variants_dict(self) -> dict[str, dict]:
|
||||||
draw_setting_key = f"klondike_variant_{pid}"
|
return KLONDIKE_VARIANTS
|
||||||
|
|
||||||
saved_diff_str = Database.load_setting(diff_setting_key, "1")
|
def _launch_table_view(
|
||||||
selected_diff = (
|
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
|
||||||
int(saved_diff_str)
|
) -> None:
|
||||||
if saved_diff_str.isdigit() and int(saved_diff_str) in SOLITAIRE_DIFFICULTIES
|
|
||||||
else 1
|
|
||||||
)
|
|
||||||
|
|
||||||
selected_variant = Database.load_setting(draw_setting_key, "klondike_1")
|
|
||||||
if selected_variant not in KLONDIKE_VARIANTS:
|
|
||||||
selected_variant = "klondike_1"
|
|
||||||
|
|
||||||
def open_stats():
|
|
||||||
self._clear_modal()
|
|
||||||
variants = Database.get_variants_for_filter(GAME_FOLDER_ID)
|
|
||||||
pre_id = next((v["id"] for v in variants if v["variant_key"] == selected_variant), None)
|
|
||||||
SolitaireStatsView(
|
|
||||||
self.ctx,
|
|
||||||
game_folder=GAME_FOLDER_ID,
|
|
||||||
game_title_key=GAME_TITLE_KEY,
|
|
||||||
on_back=lambda: self.show(),
|
|
||||||
).show(preselect_variant_id=pre_id)
|
|
||||||
|
|
||||||
rank_badge = f"{prog['title']} (Lv. {prog['level']} • {prog['current_xp']}/{prog['needed_xp']} XP)"
|
|
||||||
self.ctx.build_game_topbar(
|
|
||||||
self.ctx.root,
|
|
||||||
t("kl_menu_topbar"),
|
|
||||||
on_game_menu=None,
|
|
||||||
on_stats=open_stats,
|
|
||||||
stats_enabled=True,
|
|
||||||
extra_right_text=rank_badge,
|
|
||||||
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
|
|
||||||
)
|
|
||||||
|
|
||||||
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=14)
|
|
||||||
container.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.88, relheight=0.84)
|
|
||||||
|
|
||||||
main_card = tk.Frame(
|
|
||||||
container,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
padx=26,
|
|
||||||
pady=20,
|
|
||||||
highlightthickness=1,
|
|
||||||
highlightbackground=BORDER_COLOR,
|
|
||||||
)
|
|
||||||
main_card.pack(fill="x")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=t(GAME_TITLE_KEY),
|
|
||||||
font=("Georgia", 18, "bold"),
|
|
||||||
fg=ACCENT_GOLD,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=t("sol_menu_subtitle"),
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
fg=MUTED_FG,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w", pady=(4, 14))
|
|
||||||
|
|
||||||
if status_msg:
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=status_msg,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
fg="#7be08a" if status_is_ok else ERROR_FG,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w", pady=(0, 12))
|
|
||||||
|
|
||||||
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
|
|
||||||
saved_meta = self._parse_saved_meta(saved)
|
|
||||||
|
|
||||||
if saved and saved_meta is not None:
|
|
||||||
resume_box = tk.Frame(
|
|
||||||
main_card,
|
|
||||||
bg=CELL_BG,
|
|
||||||
padx=18,
|
|
||||||
pady=12,
|
|
||||||
highlightthickness=1,
|
|
||||||
highlightbackground=ACCENT_GOTH,
|
|
||||||
)
|
|
||||||
resume_box.pack(fill="x", pady=(0, 16))
|
|
||||||
|
|
||||||
left_info = tk.Frame(resume_box, bg=CELL_BG)
|
|
||||||
left_info.pack(side="left", fill="x", expand=True)
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
left_info,
|
|
||||||
text=t("sol_resume_box_title"),
|
|
||||||
font=("Georgia", 12, "bold"),
|
|
||||||
fg=ACCENT_GOTH,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(anchor="w")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
left_info,
|
|
||||||
text=t(
|
|
||||||
"sol_resume_info",
|
|
||||||
t(f"variant_{saved['variant_key']}"),
|
|
||||||
t(f"sol_diff_short_{saved_meta['difficulty']}"),
|
|
||||||
saved_meta["moves"],
|
|
||||||
saved_meta["score"],
|
|
||||||
Database.format_seconds(saved_meta["elapsed_sec"]),
|
|
||||||
),
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(anchor="w", pady=(4, 0))
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
resume_box,
|
|
||||||
t("sol_resume_btn"),
|
|
||||||
self.ctx.assets.raw_btn,
|
|
||||||
self.ctx.assets.raw_btn_active,
|
|
||||||
lambda: self._resume_saved(saved, saved_meta["difficulty"]),
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=185,
|
|
||||||
height=36,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="right", padx=(12, 0))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=t("sol_setup_sec_title"),
|
|
||||||
font=("Georgia", 12, "bold"),
|
|
||||||
fg=ACCENT_GOTH,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w", pady=(2, 8))
|
|
||||||
|
|
||||||
setup_box = tk.Frame(
|
|
||||||
main_card,
|
|
||||||
bg=CELL_BG,
|
|
||||||
padx=20,
|
|
||||||
pady=18,
|
|
||||||
highlightthickness=1,
|
|
||||||
highlightbackground=SUBTLE_BORDER,
|
|
||||||
)
|
|
||||||
setup_box.pack(fill="x")
|
|
||||||
|
|
||||||
draw_row = tk.Frame(setup_box, bg=CELL_BG)
|
|
||||||
draw_row.pack(fill="x", pady=(0, 12))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
draw_row,
|
|
||||||
text=t("sol_draw_mode_lbl"),
|
|
||||||
width=16,
|
|
||||||
anchor="w",
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(side="left")
|
|
||||||
|
|
||||||
def switch_draw_mode(v_key: str):
|
|
||||||
if v_key == selected_variant or self._modal_overlay is not None:
|
|
||||||
return
|
|
||||||
Database.save_setting(draw_setting_key, v_key)
|
|
||||||
self.show(status_msg=status_msg, status_is_ok=status_is_ok)
|
|
||||||
|
|
||||||
for v_key, toggle_lbl_key in (("klondike_1", "kl_draw_toggle_1"), ("klondike_3", "kl_draw_toggle_3")):
|
|
||||||
is_sel = selected_variant == v_key
|
|
||||||
raw_norm = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel
|
|
||||||
raw_act = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel_active
|
|
||||||
ImageButton(
|
|
||||||
draw_row,
|
|
||||||
t(toggle_lbl_key),
|
|
||||||
raw_norm,
|
|
||||||
raw_act,
|
|
||||||
lambda k=v_key: switch_draw_mode(k),
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=170,
|
|
||||||
height=34,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="left", padx=(0, 10))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
draw_row,
|
|
||||||
text=t(f"kl_desc_{selected_variant}"),
|
|
||||||
font=("Helvetica", 9),
|
|
||||||
fg=MUTED_FG,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(side="left", padx=(8, 0))
|
|
||||||
|
|
||||||
diff_row = tk.Frame(setup_box, bg=CELL_BG)
|
|
||||||
diff_row.pack(fill="x", pady=(0, 16))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
diff_row,
|
|
||||||
text=t("sol_diff_lbl"),
|
|
||||||
width=16,
|
|
||||||
anchor="w",
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(side="left")
|
|
||||||
|
|
||||||
diff_labels = [t(f"sol_diff_{lvl}") for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())]
|
|
||||||
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())}
|
|
||||||
diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}"))
|
|
||||||
|
|
||||||
diff_cb = ttk.Combobox(
|
|
||||||
diff_row,
|
|
||||||
textvariable=diff_var,
|
|
||||||
values=diff_labels,
|
|
||||||
state="readonly",
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
style="Goth.TCombobox",
|
|
||||||
)
|
|
||||||
diff_cb.pack(side="left", fill="x", expand=True, ipady=3)
|
|
||||||
|
|
||||||
def on_diff_changed(*_):
|
|
||||||
chosen = diff_map.get(diff_var.get(), 1)
|
|
||||||
Database.save_setting(diff_setting_key, str(chosen))
|
|
||||||
|
|
||||||
diff_cb.bind("<<ComboboxSelected>>", on_diff_changed)
|
|
||||||
|
|
||||||
action_row = tk.Frame(setup_box, bg=CELL_BG)
|
|
||||||
action_row.pack(fill="x")
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
action_row,
|
|
||||||
t("sol_start_btn"),
|
|
||||||
self.ctx.assets.raw_btn,
|
|
||||||
self.ctx.assets.raw_btn_active,
|
|
||||||
lambda: self._on_start_clicked(
|
|
||||||
selected_variant, diff_map.get(diff_var.get(), 1), saved, saved_meta
|
|
||||||
),
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=210,
|
|
||||||
height=38,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="right")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=t("kl_controls_hint"),
|
|
||||||
font=("Helvetica", 9),
|
|
||||||
fg=MUTED_FG,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w", pady=(14, 0))
|
|
||||||
|
|
||||||
# Direktes Wiederaufnahme-Popup beim Öffnen von Klondike (auch bei 0 Zügen nach Neustart)
|
|
||||||
if ask_resume_popup and saved and saved_meta is not None:
|
|
||||||
self._show_resume_prompt_modal(saved, saved_meta)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _parse_saved_meta(saved: dict | None) -> dict | None:
|
|
||||||
if not saved:
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
data = json.loads(saved["state_json"])
|
|
||||||
if data.get("won"):
|
|
||||||
return None
|
|
||||||
board = data.get("board", {})
|
|
||||||
if not board or "tableau" not in board:
|
|
||||||
return None
|
|
||||||
return {
|
|
||||||
"moves": max(0, int(data.get("moves", 0))),
|
|
||||||
"score": int(data.get("score", 0)),
|
|
||||||
"elapsed_sec": float(data.get("elapsed_sec", 0.0)),
|
|
||||||
"difficulty": max(0, min(3, int(board.get("difficulty", 1)))),
|
|
||||||
}
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
|
|
||||||
self._clear_modal()
|
|
||||||
overlay = tk.Frame(
|
|
||||||
self.ctx.root,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
padx=30,
|
|
||||||
pady=24,
|
|
||||||
highlightthickness=2,
|
|
||||||
highlightbackground=ACCENT_GOTH,
|
|
||||||
)
|
|
||||||
overlay.place(relx=0.5, rely=0.52, anchor="center")
|
|
||||||
self._modal_overlay = overlay
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
overlay,
|
|
||||||
text=t("sol_resume_box_title"),
|
|
||||||
font=("Georgia", 16, "bold"),
|
|
||||||
fg=ACCENT_GOLD,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
).pack(pady=(0, 10))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
overlay,
|
|
||||||
text=t(
|
|
||||||
"sol_resume_info",
|
|
||||||
t(f"variant_{saved['variant_key']}"),
|
|
||||||
t(f"sol_diff_short_{saved_meta['difficulty']}"),
|
|
||||||
saved_meta["moves"],
|
|
||||||
saved_meta["score"],
|
|
||||||
Database.format_seconds(saved_meta["elapsed_sec"]),
|
|
||||||
),
|
|
||||||
font=("Helvetica", 11),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
justify="center",
|
|
||||||
).pack(pady=(0, 20))
|
|
||||||
|
|
||||||
btn_row = tk.Frame(overlay, bg=MODAL_BG)
|
|
||||||
btn_row.pack()
|
|
||||||
|
|
||||||
def resume_now(_event=None):
|
|
||||||
self._clear_modal()
|
|
||||||
self._resume_saved(saved, saved_meta["difficulty"])
|
|
||||||
|
|
||||||
try:
|
|
||||||
self._return_bind_id = self.ctx.root.bind("<Return>", resume_now, add="+")
|
|
||||||
except tk.TclError:
|
|
||||||
self._return_bind_id = None
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
btn_row,
|
|
||||||
t("sol_resume_btn"),
|
|
||||||
self.ctx.assets.raw_btn,
|
|
||||||
self.ctx.assets.raw_btn_active,
|
|
||||||
resume_now,
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=190,
|
|
||||||
height=38,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="left", padx=6)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
btn_row,
|
|
||||||
t("bj_popup_to_menu_btn"),
|
|
||||||
self.ctx.assets.raw_sel,
|
|
||||||
self.ctx.assets.raw_sel_active,
|
|
||||||
self._clear_modal,
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=175,
|
|
||||||
height=38,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="left", padx=6)
|
|
||||||
|
|
||||||
def _resume_saved(self, saved: dict, difficulty: int):
|
|
||||||
self._clear_modal()
|
|
||||||
KlondikeTableView(
|
|
||||||
self.ctx,
|
|
||||||
variant_key=saved["variant_key"],
|
|
||||||
difficulty=difficulty,
|
|
||||||
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
|
|
||||||
resume_state_json=saved["state_json"],
|
|
||||||
)
|
|
||||||
|
|
||||||
def _on_start_clicked(
|
|
||||||
self,
|
|
||||||
variant_key: str,
|
|
||||||
difficulty: int,
|
|
||||||
saved: dict | None,
|
|
||||||
saved_meta: dict | None,
|
|
||||||
):
|
|
||||||
if self._modal_overlay is not None:
|
|
||||||
return
|
|
||||||
# Nur wenn bereits Züge gemacht wurden, kostet das Verwerfen XP -> Sicherheitsabfrage
|
|
||||||
if saved and saved_meta and saved_meta["moves"] > 0:
|
|
||||||
self._show_overwrite_confirm_modal(variant_key, difficulty, saved, saved_meta)
|
|
||||||
return
|
|
||||||
self._launch_fresh_game(variant_key, difficulty)
|
|
||||||
|
|
||||||
def _show_overwrite_confirm_modal(
|
|
||||||
self,
|
|
||||||
new_variant_key: str,
|
|
||||||
new_difficulty: int,
|
|
||||||
saved: dict,
|
|
||||||
saved_meta: dict,
|
|
||||||
):
|
|
||||||
pid = self.ctx.profile["id"]
|
|
||||||
old_v = saved["variant_key"]
|
|
||||||
old_diff = saved_meta["difficulty"]
|
|
||||||
prog = Database.get_game_progress(pid, GAME_FOLDER_ID)
|
|
||||||
v_mult = KLONDIKE_VARIANTS.get(old_v, {"xp_mult": 1.0})["xp_mult"]
|
|
||||||
d_mult = SOLITAIRE_DIFFICULTIES.get(old_diff, SOLITAIRE_DIFFICULTIES[1])["xp_mult"]
|
|
||||||
win_xp = Progression.calculate_match_xp(prog["level"], [], "WIN", variant_mult=v_mult * d_mult)
|
|
||||||
penalty = max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO)))
|
|
||||||
|
|
||||||
overlay = tk.Frame(
|
|
||||||
self.ctx.root,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
padx=28,
|
|
||||||
pady=22,
|
|
||||||
highlightthickness=2,
|
|
||||||
highlightbackground=ERROR_FG,
|
|
||||||
)
|
|
||||||
overlay.place(relx=0.5, rely=0.52, anchor="center")
|
|
||||||
self._modal_overlay = overlay
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
overlay,
|
|
||||||
text=t("sol_forfeit_title"),
|
|
||||||
font=("Georgia", 15, "bold"),
|
|
||||||
fg=ERROR_FG,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
).pack(pady=(0, 8))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
overlay,
|
|
||||||
text=t("sol_forfeit_desc", penalty),
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
wraplength=430,
|
|
||||||
justify="center",
|
|
||||||
).pack(pady=(0, 18))
|
|
||||||
|
|
||||||
row = tk.Frame(overlay, bg=MODAL_BG)
|
|
||||||
row.pack()
|
|
||||||
|
|
||||||
def forfeit_and_start():
|
|
||||||
floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0
|
|
||||||
Database.record_game_result(
|
|
||||||
pid,
|
|
||||||
variant_key=old_v,
|
|
||||||
won=False,
|
|
||||||
duration_sec=saved_meta["elapsed_sec"],
|
|
||||||
points_gained=0,
|
|
||||||
)
|
|
||||||
Database.adjust_game_points(pid, GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp)
|
|
||||||
self.ctx.refresh_game_progress()
|
|
||||||
self._clear_modal()
|
|
||||||
self._launch_fresh_game(new_variant_key, new_difficulty)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
row,
|
|
||||||
t("sol_resume_btn"),
|
|
||||||
self.ctx.assets.raw_btn,
|
|
||||||
self.ctx.assets.raw_btn_active,
|
|
||||||
lambda: self._resume_saved(saved, old_diff),
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=165,
|
|
||||||
height=34,
|
|
||||||
font=("Helvetica", 9, "bold"),
|
|
||||||
).pack(side="left", padx=5)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
row,
|
|
||||||
t("sol_forfeit_confirm_new"),
|
|
||||||
self.ctx.assets.raw_sel,
|
|
||||||
self.ctx.assets.raw_sel_active,
|
|
||||||
forfeit_and_start,
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=175,
|
|
||||||
height=34,
|
|
||||||
font=("Helvetica", 9, "bold"),
|
|
||||||
).pack(side="left", padx=5)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
row,
|
|
||||||
t("bj_popup_to_menu_btn"),
|
|
||||||
self.ctx.assets.raw_sel,
|
|
||||||
self.ctx.assets.raw_sel_active,
|
|
||||||
self._clear_modal,
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=155,
|
|
||||||
height=34,
|
|
||||||
font=("Helvetica", 9, "bold"),
|
|
||||||
).pack(side="left", padx=5)
|
|
||||||
|
|
||||||
def _launch_fresh_game(self, variant_key: str, difficulty: int):
|
|
||||||
pid = self.ctx.profile["id"]
|
|
||||||
Database.save_setting(f"klondike_diff_{pid}", str(difficulty))
|
|
||||||
Database.save_setting(f"klondike_variant_{pid}", variant_key)
|
|
||||||
Database.delete_game_state(pid, GAME_FOLDER_ID)
|
|
||||||
KlondikeTableView(
|
KlondikeTableView(
|
||||||
self.ctx,
|
self.ctx,
|
||||||
variant_key=variant_key,
|
variant_key=variant_key,
|
||||||
difficulty=difficulty,
|
difficulty=difficulty,
|
||||||
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
|
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
|
||||||
|
resume_state_json=resume_state_json,
|
||||||
)
|
)
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,312 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/pyramid/models/pyramid_engine.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from games.solitaire.base.solitaire_core import SolitaireBaseEngine, SolitaireCard
|
||||||
|
from games.solitaire.pyramid.models.pyramid_solver import generate_solvable_pyramid_deal
|
||||||
|
from resources.code_res.game_constants import PYRAMID_REDEALS_BY_DIFF
|
||||||
|
|
||||||
|
|
||||||
|
class PyramidEngine(SolitaireBaseEngine):
|
||||||
|
"""
|
||||||
|
Spiellogik für Pyramid Solitaire:
|
||||||
|
- 7-reihige Pyramide (28 offene Karten; frei, sobald beide Kinder darunter entfernt wurden)
|
||||||
|
- Rechts zwei offene Stapel: Linker Stapel (stock, aufgedeckt) & rechte Ablage (waste, aufgedeckt)
|
||||||
|
- Sowohl Pyramide+Stapel als auch Linker Stapel + Rechte Ablage können auf 13 gepaart werden!
|
||||||
|
- Weiterblättern erfolgt explizit über den Button "Nächste Karte".
|
||||||
|
"""
|
||||||
|
|
||||||
|
NUM_ROWS = 7
|
||||||
|
SCORE_PYRAMID_CARD = 15
|
||||||
|
SCORE_PILE_CARD = 5
|
||||||
|
SCORE_ROW_CLEAR_BONUS = 25
|
||||||
|
|
||||||
|
def __init__(self, difficulty: int = 1, seed: int | None = None):
|
||||||
|
super().__init__()
|
||||||
|
self.difficulty: int = max(0, min(3, int(difficulty)))
|
||||||
|
self.seed: int | None = seed
|
||||||
|
self.max_redeals: int = PYRAMID_REDEALS_BY_DIFF.get(self.difficulty, 2)
|
||||||
|
self.redeals_used: int = 0
|
||||||
|
self.stagnant_cycles: int = 0
|
||||||
|
self._progress_in_cycle: bool = False
|
||||||
|
|
||||||
|
self.pyramid: list[list[SolitaireCard | None]] = []
|
||||||
|
self.stock: list[SolitaireCard] = []
|
||||||
|
self.waste: list[SolitaireCard] = []
|
||||||
|
self.removed: list[SolitaireCard] = []
|
||||||
|
|
||||||
|
self.new_game(difficulty=self.difficulty, seed=seed)
|
||||||
|
|
||||||
|
def new_game(self, difficulty: int | None = None, seed: int | None = None):
|
||||||
|
if difficulty is not None:
|
||||||
|
self.difficulty = max(0, min(3, int(difficulty)))
|
||||||
|
self.seed = seed
|
||||||
|
self.max_redeals = PYRAMID_REDEALS_BY_DIFF.get(self.difficulty, 2)
|
||||||
|
self.redeals_used = 0
|
||||||
|
self.stagnant_cycles = 0
|
||||||
|
self._progress_in_cycle = False
|
||||||
|
self.reset_tracking()
|
||||||
|
|
||||||
|
self.pyramid, self.stock = generate_solvable_pyramid_deal(
|
||||||
|
difficulty=self.difficulty, seed=seed
|
||||||
|
)
|
||||||
|
self.waste = []
|
||||||
|
self.removed = []
|
||||||
|
self.capture_initial_state()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def redeals_remaining(self) -> int:
|
||||||
|
return max(0, self.max_redeals - self.redeals_used)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def pyramid_remaining_count(self) -> int:
|
||||||
|
return sum(1 for row in self.pyramid for c in row if c is not None)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def pyramid_cleared_count(self) -> int:
|
||||||
|
return 28 - self.pyramid_remaining_count
|
||||||
|
|
||||||
|
@property
|
||||||
|
def can_advance_stock(self) -> bool:
|
||||||
|
if self.won:
|
||||||
|
return False
|
||||||
|
if self.stock:
|
||||||
|
return True
|
||||||
|
return bool(
|
||||||
|
self.waste
|
||||||
|
and self.redeals_used < self.max_redeals
|
||||||
|
and self.stagnant_cycles < 3
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_stock_locked(self) -> bool:
|
||||||
|
if self.stock:
|
||||||
|
return False
|
||||||
|
if not self.waste:
|
||||||
|
return True
|
||||||
|
return self.redeals_used >= self.max_redeals or self.stagnant_cycles >= 3
|
||||||
|
|
||||||
|
def is_pyramid_exposed(self, row: int, col: int) -> bool:
|
||||||
|
if not (0 <= row < self.NUM_ROWS and 0 <= col <= row):
|
||||||
|
return False
|
||||||
|
if self.pyramid[row][col] is None:
|
||||||
|
return False
|
||||||
|
if row == self.NUM_ROWS - 1:
|
||||||
|
return True
|
||||||
|
return (
|
||||||
|
self.pyramid[row + 1][col] is None
|
||||||
|
and self.pyramid[row + 1][col + 1] is None
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_card_at_ref(self, ref: tuple) -> SolitaireCard | None:
|
||||||
|
zone = ref[0]
|
||||||
|
if zone == "pyramid":
|
||||||
|
_, r, c = ref
|
||||||
|
if self.is_pyramid_exposed(r, c):
|
||||||
|
return self.pyramid[r][c]
|
||||||
|
return None
|
||||||
|
if zone == "stock":
|
||||||
|
return self.stock[-1] if self.stock else None
|
||||||
|
if zone == "waste":
|
||||||
|
return self.waste[-1] if self.waste else None
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _pop_ref(self, ref: tuple) -> SolitaireCard:
|
||||||
|
zone = ref[0]
|
||||||
|
if zone == "pyramid":
|
||||||
|
_, r, c = ref
|
||||||
|
card = self.pyramid[r][c]
|
||||||
|
assert card is not None
|
||||||
|
self.pyramid[r][c] = None
|
||||||
|
row_cleared = all(x is None for x in self.pyramid[r])
|
||||||
|
self._score_add(
|
||||||
|
self.SCORE_PYRAMID_CARD + (self.SCORE_ROW_CLEAR_BONUS if row_cleared else 0)
|
||||||
|
)
|
||||||
|
return card
|
||||||
|
if zone == "stock":
|
||||||
|
card = self.stock.pop()
|
||||||
|
self._score_add(self.SCORE_PILE_CARD)
|
||||||
|
return card
|
||||||
|
card = self.waste.pop()
|
||||||
|
self._score_add(self.SCORE_PILE_CARD)
|
||||||
|
return card
|
||||||
|
|
||||||
|
def _score_add(self, pts: int):
|
||||||
|
self.score = max(0, self.score + pts)
|
||||||
|
|
||||||
|
def _check_victory(self) -> bool:
|
||||||
|
if self.pyramid_remaining_count == 0:
|
||||||
|
self.mark_won()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def can_remove_single(self, ref: tuple) -> bool:
|
||||||
|
if self.won:
|
||||||
|
return False
|
||||||
|
c = self.get_card_at_ref(ref)
|
||||||
|
return c is not None and c.value == 13
|
||||||
|
|
||||||
|
def can_pair_refs(self, ref_a: tuple, ref_b: tuple) -> tuple[bool, int]:
|
||||||
|
if self.won or ref_a == ref_b:
|
||||||
|
return False, 0
|
||||||
|
ca = self.get_card_at_ref(ref_a)
|
||||||
|
cb = self.get_card_at_ref(ref_b)
|
||||||
|
if ca is None or cb is None:
|
||||||
|
return False, 0
|
||||||
|
total = ca.value + cb.value
|
||||||
|
return (total == 13), total
|
||||||
|
|
||||||
|
def remove_king(self, ref: tuple, record_undo: bool = True) -> bool:
|
||||||
|
if not self.can_remove_single(ref):
|
||||||
|
return False
|
||||||
|
if record_undo:
|
||||||
|
self.push_undo()
|
||||||
|
card = self._pop_ref(ref)
|
||||||
|
self.removed.append(card)
|
||||||
|
self.moves += 1
|
||||||
|
self._progress_in_cycle = True
|
||||||
|
self.stagnant_cycles = 0
|
||||||
|
self._check_victory()
|
||||||
|
return True
|
||||||
|
|
||||||
|
def remove_pair(self, ref_a: tuple, ref_b: tuple, record_undo: bool = True) -> bool:
|
||||||
|
ok, _s = self.can_pair_refs(ref_a, ref_b)
|
||||||
|
if not ok:
|
||||||
|
return False
|
||||||
|
if record_undo:
|
||||||
|
self.push_undo()
|
||||||
|
c1 = self._pop_ref(ref_a)
|
||||||
|
c2 = self._pop_ref(ref_b)
|
||||||
|
self.removed.extend([c1, c2])
|
||||||
|
self.moves += 1
|
||||||
|
self._progress_in_cycle = True
|
||||||
|
self.stagnant_cycles = 0
|
||||||
|
self._check_victory()
|
||||||
|
return True
|
||||||
|
|
||||||
|
def draw_or_recycle_stock(self) -> tuple[bool, str]:
|
||||||
|
"""Button 'Nächste Karte': Schiebt die linke offene Karte auf die rechte Ablage (oder Redeal)."""
|
||||||
|
if self.won:
|
||||||
|
return False, ""
|
||||||
|
if self.stock:
|
||||||
|
self.push_undo()
|
||||||
|
card = self.stock.pop()
|
||||||
|
card.face_up = True
|
||||||
|
self.waste.append(card)
|
||||||
|
self.moves += 1
|
||||||
|
return True, "draw"
|
||||||
|
|
||||||
|
if not self.waste:
|
||||||
|
return False, "empty"
|
||||||
|
if self.redeals_used >= self.max_redeals:
|
||||||
|
return False, "redeal_limit"
|
||||||
|
if self.stagnant_cycles >= 3:
|
||||||
|
return False, "stagnant"
|
||||||
|
|
||||||
|
self.push_undo()
|
||||||
|
if not self._progress_in_cycle:
|
||||||
|
self.stagnant_cycles += 1
|
||||||
|
if self.stagnant_cycles >= 3:
|
||||||
|
self._undo_stack.pop()
|
||||||
|
return False, "stagnant"
|
||||||
|
self._progress_in_cycle = False
|
||||||
|
self.redeals_used += 1
|
||||||
|
recycled = list(reversed(self.waste))
|
||||||
|
for c in recycled:
|
||||||
|
c.face_up = True
|
||||||
|
self.stock = recycled
|
||||||
|
self.waste = []
|
||||||
|
self.moves += 1
|
||||||
|
return True, "recycle"
|
||||||
|
|
||||||
|
def get_all_exposed_refs(self) -> list[tuple]:
|
||||||
|
refs: list[tuple] = [
|
||||||
|
("pyramid", r, c)
|
||||||
|
for r in range(self.NUM_ROWS)
|
||||||
|
for c in range(r + 1)
|
||||||
|
if self.is_pyramid_exposed(r, c)
|
||||||
|
]
|
||||||
|
if self.stock:
|
||||||
|
refs.append(("stock",))
|
||||||
|
if self.waste:
|
||||||
|
refs.append(("waste",))
|
||||||
|
return refs
|
||||||
|
|
||||||
|
def can_auto_complete(self) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def auto_complete_step(self, record_undo: bool = False) -> bool:
|
||||||
|
_ = record_undo
|
||||||
|
return False
|
||||||
|
|
||||||
|
def has_any_meaningful_move(self) -> bool:
|
||||||
|
if self.won:
|
||||||
|
return True
|
||||||
|
refs = self.get_all_exposed_refs()
|
||||||
|
for i, ra in enumerate(refs):
|
||||||
|
ca = self.get_card_at_ref(ra)
|
||||||
|
if ca is None:
|
||||||
|
continue
|
||||||
|
if ca.value == 13:
|
||||||
|
return True
|
||||||
|
for rb in refs[i + 1 :]:
|
||||||
|
cb = self.get_card_at_ref(rb)
|
||||||
|
if cb is not None and ca.value + cb.value == 13:
|
||||||
|
return True
|
||||||
|
return self.can_advance_stock
|
||||||
|
|
||||||
|
def get_hint(self) -> dict | None:
|
||||||
|
refs = self.get_all_exposed_refs()
|
||||||
|
for ref in refs:
|
||||||
|
c = self.get_card_at_ref(ref)
|
||||||
|
if c is not None and c.value == 13:
|
||||||
|
return {"type": "single", "refs": [ref]}
|
||||||
|
|
||||||
|
for i, ra in enumerate(refs):
|
||||||
|
ca = self.get_card_at_ref(ra)
|
||||||
|
if ca is None:
|
||||||
|
continue
|
||||||
|
for rb in refs[i + 1 :]:
|
||||||
|
cb = self.get_card_at_ref(rb)
|
||||||
|
if cb is not None and ca.value + cb.value == 13:
|
||||||
|
return {"type": "pair", "refs": [ra, rb]}
|
||||||
|
|
||||||
|
if self.can_advance_stock:
|
||||||
|
return {"type": "draw", "refs": [("next_btn",)]}
|
||||||
|
return None
|
||||||
|
|
||||||
|
def serialize_board(self) -> dict:
|
||||||
|
return {
|
||||||
|
"difficulty": self.difficulty,
|
||||||
|
"max_redeals": self.max_redeals,
|
||||||
|
"redeals_used": self.redeals_used,
|
||||||
|
"stagnant_cycles": self.stagnant_cycles,
|
||||||
|
"progress_in_cycle": self._progress_in_cycle,
|
||||||
|
"pyramid": [
|
||||||
|
[c.to_dict() if c is not None else None for c in row]
|
||||||
|
for row in self.pyramid
|
||||||
|
],
|
||||||
|
"stock": [c.to_dict() for c in self.stock],
|
||||||
|
"waste": [c.to_dict() for c in self.waste],
|
||||||
|
"removed": [c.to_dict() for c in self.removed],
|
||||||
|
}
|
||||||
|
|
||||||
|
def restore_board(self, board: dict):
|
||||||
|
self.difficulty = max(0, min(3, int(board.get("difficulty", 1))))
|
||||||
|
self.max_redeals = int(
|
||||||
|
board.get("max_redeals", PYRAMID_REDEALS_BY_DIFF.get(self.difficulty, 2))
|
||||||
|
)
|
||||||
|
self.redeals_used = int(board.get("redeals_used", 0))
|
||||||
|
self.stagnant_cycles = int(board.get("stagnant_cycles", 0))
|
||||||
|
self._progress_in_cycle = bool(board.get("progress_in_cycle", False))
|
||||||
|
self.pyramid = [
|
||||||
|
[SolitaireCard.from_dict(d) if d is not None else None for d in row]
|
||||||
|
for row in board["pyramid"]
|
||||||
|
]
|
||||||
|
self.stock = [SolitaireCard.from_dict(d) for d in board.get("stock", [])]
|
||||||
|
for c in self.stock:
|
||||||
|
c.face_up = True
|
||||||
|
self.waste = [SolitaireCard.from_dict(d) for d in board.get("waste", [])]
|
||||||
|
for c in self.waste:
|
||||||
|
c.face_up = True
|
||||||
|
self.removed = [SolitaireCard.from_dict(d) for d in board.get("removed", [])]
|
||||||
|
|
@ -0,0 +1,238 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/pyramid/models/pyramid_solver.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import heapq
|
||||||
|
import random
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from games.solitaire.base.solitaire_core import SOLITAIRE_RANKS, SolitaireCard
|
||||||
|
from resources.code_res.game_constants import PYRAMID_REDEALS_BY_DIFF, SUITS
|
||||||
|
|
||||||
|
_SUIT = tuple(c // 13 for c in range(52))
|
||||||
|
_VAL = tuple((c % 13) + 1 for c in range(52))
|
||||||
|
|
||||||
|
_CHILD_MASKS: tuple[int, ...] = tuple(
|
||||||
|
0
|
||||||
|
if r == 6
|
||||||
|
else (
|
||||||
|
(1 << (((r + 1) * (r + 2)) // 2 + c))
|
||||||
|
| (1 << (((r + 1) * (r + 2)) // 2 + c + 1))
|
||||||
|
)
|
||||||
|
for r in range(7)
|
||||||
|
for c in range(r + 1)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PyramidSolveReport:
|
||||||
|
solvable: bool
|
||||||
|
nodes_expanded: int
|
||||||
|
layout_hardness: float
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_card(cid: int) -> SolitaireCard:
|
||||||
|
return SolitaireCard(
|
||||||
|
suit=SUITS[_SUIT[cid]],
|
||||||
|
rank=SOLITAIRE_RANKS[cid % 13],
|
||||||
|
face_up=True,
|
||||||
|
deck_id=0,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _exposed_pyramid_indices(pyr_mask: int) -> list[int]:
|
||||||
|
out: list[int] = []
|
||||||
|
m = pyr_mask
|
||||||
|
while m:
|
||||||
|
lsb = m & -m
|
||||||
|
idx = lsb.bit_length() - 1
|
||||||
|
if (pyr_mask & _CHILD_MASKS[idx]) == 0:
|
||||||
|
out.append(idx)
|
||||||
|
m ^= lsb
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_pyramid_hardness(pyr_ids: list[int], stock_ids: list[int]) -> float:
|
||||||
|
score = 0.0
|
||||||
|
for r in range(7):
|
||||||
|
row_base = (r * (r + 1)) // 2
|
||||||
|
depth_weight = (6 - r) * 1.6
|
||||||
|
for c in range(r + 1):
|
||||||
|
idx = row_base + c
|
||||||
|
v = _VAL[pyr_ids[idx]]
|
||||||
|
if v == 13:
|
||||||
|
score -= 2.8 if r == 6 else 1.2
|
||||||
|
if r < 6:
|
||||||
|
left_v = _VAL[pyr_ids[((r + 1) * (r + 2)) // 2 + c]]
|
||||||
|
right_v = _VAL[pyr_ids[((r + 1) * (r + 2)) // 2 + c + 1]]
|
||||||
|
if v + left_v == 13:
|
||||||
|
score += 6.5 + depth_weight
|
||||||
|
if v + right_v == 13:
|
||||||
|
score += 6.5 + depth_weight
|
||||||
|
|
||||||
|
bottom_vals = [_VAL[pyr_ids[21 + c]] for c in range(7)]
|
||||||
|
if stock_ids:
|
||||||
|
bottom_vals.append(_VAL[stock_ids[-1]])
|
||||||
|
immediate_pairs = sum(1 for v in bottom_vals if v == 13)
|
||||||
|
for i in range(len(bottom_vals)):
|
||||||
|
for j in range(i + 1, len(bottom_vals)):
|
||||||
|
if bottom_vals[i] + bottom_vals[j] == 13:
|
||||||
|
immediate_pairs += 1
|
||||||
|
score -= immediate_pairs * 4.0
|
||||||
|
return score
|
||||||
|
|
||||||
|
|
||||||
|
def solve_pyramid_deal(
|
||||||
|
deck_ids: list[int], max_redeals: int, max_nodes: int = 3800
|
||||||
|
) -> PyramidSolveReport:
|
||||||
|
"""
|
||||||
|
Prüft Lösbarkeit mit offenem Talon (stock_t[-1]) + offener Ablage (waste_t[-1]):
|
||||||
|
Beide Oberkarten sind mit freien Pyramidenkarten UND direkt miteinander kombinierbar.
|
||||||
|
"""
|
||||||
|
pyr_ids = deck_ids[:28]
|
||||||
|
stock_ids = deck_ids[28:]
|
||||||
|
hardness = evaluate_pyramid_hardness(pyr_ids, stock_ids)
|
||||||
|
|
||||||
|
init_mask = (1 << 28) - 1
|
||||||
|
start_state = (init_mask, tuple(stock_ids), (), max_redeals)
|
||||||
|
visited: set[tuple] = {start_state}
|
||||||
|
pq: list[tuple[int, int, int, tuple]] = []
|
||||||
|
counter = 0
|
||||||
|
|
||||||
|
def heuristic(pyr_m: int, redeals_rem: int) -> int:
|
||||||
|
return pyr_m.bit_count() * 4 - redeals_rem * 2
|
||||||
|
|
||||||
|
heapq.heappush(pq, (heuristic(init_mask, max_redeals), 0, counter, start_state))
|
||||||
|
nodes = 0
|
||||||
|
|
||||||
|
while pq and nodes < max_nodes:
|
||||||
|
_prio, depth, _tie, state = heapq.heappop(pq)
|
||||||
|
pyr_m, stock_t, waste_t, redeals_rem = state
|
||||||
|
nodes += 1
|
||||||
|
|
||||||
|
if pyr_m == 0:
|
||||||
|
return PyramidSolveReport(True, nodes, hardness)
|
||||||
|
|
||||||
|
exposed = _exposed_pyramid_indices(pyr_m)
|
||||||
|
next_states: list[tuple] = []
|
||||||
|
|
||||||
|
# 1. Freie Könige (13) direkt abräumen (Pyramide, linker Stapel oder rechte Ablage)
|
||||||
|
king_cleared = False
|
||||||
|
for idx in exposed:
|
||||||
|
if _VAL[pyr_ids[idx]] == 13:
|
||||||
|
next_states.append((pyr_m & ~(1 << idx), stock_t, waste_t, redeals_rem))
|
||||||
|
king_cleared = True
|
||||||
|
break
|
||||||
|
|
||||||
|
if not king_cleared and stock_t and _VAL[stock_t[-1]] == 13:
|
||||||
|
next_states.append((pyr_m, stock_t[:-1], waste_t, redeals_rem))
|
||||||
|
king_cleared = True
|
||||||
|
|
||||||
|
if not king_cleared and waste_t and _VAL[waste_t[-1]] == 13:
|
||||||
|
next_states.append((pyr_m, stock_t, waste_t[:-1], redeals_rem))
|
||||||
|
king_cleared = True
|
||||||
|
|
||||||
|
if not king_cleared:
|
||||||
|
# 2. Zwei freie Pyramidenkarten paaren
|
||||||
|
for i_pos in range(len(exposed)):
|
||||||
|
idx_a = exposed[i_pos]
|
||||||
|
va = _VAL[pyr_ids[idx_a]]
|
||||||
|
for j_pos in range(i_pos + 1, len(exposed)):
|
||||||
|
idx_b = exposed[j_pos]
|
||||||
|
if va + _VAL[pyr_ids[idx_b]] == 13:
|
||||||
|
nm = pyr_m & ~((1 << idx_a) | (1 << idx_b))
|
||||||
|
next_states.append((nm, stock_t, waste_t, redeals_rem))
|
||||||
|
|
||||||
|
# 3. Pyramidenkarte + linker Stapel / rechte Ablage
|
||||||
|
if stock_t:
|
||||||
|
vs = _VAL[stock_t[-1]]
|
||||||
|
for idx_a in exposed:
|
||||||
|
if _VAL[pyr_ids[idx_a]] + vs == 13:
|
||||||
|
next_states.append((pyr_m & ~(1 << idx_a), stock_t[:-1], waste_t, redeals_rem))
|
||||||
|
if waste_t:
|
||||||
|
vw = _VAL[waste_t[-1]]
|
||||||
|
for idx_a in exposed:
|
||||||
|
if _VAL[pyr_ids[idx_a]] + vw == 13:
|
||||||
|
next_states.append((pyr_m & ~(1 << idx_a), stock_t, waste_t[:-1], redeals_rem))
|
||||||
|
|
||||||
|
# 4. Linker Stapel + rechte Ablage direkt miteinander paaren
|
||||||
|
if stock_t and waste_t and (_VAL[stock_t[-1]] + _VAL[waste_t[-1]] == 13):
|
||||||
|
next_states.append((pyr_m, stock_t[:-1], waste_t[:-1], redeals_rem))
|
||||||
|
|
||||||
|
# 5. Button "Nächste Karte": Linke Karte nach rechts legen oder Redeal
|
||||||
|
if stock_t:
|
||||||
|
next_states.append((pyr_m, stock_t[:-1], waste_t + (stock_t[-1],), redeals_rem))
|
||||||
|
elif waste_t and redeals_rem > 0:
|
||||||
|
recycled_stock = tuple(reversed(waste_t))
|
||||||
|
next_states.append((pyr_m, recycled_stock, (), redeals_rem - 1))
|
||||||
|
|
||||||
|
for ns in next_states:
|
||||||
|
if ns[0] == 0:
|
||||||
|
return PyramidSolveReport(True, nodes, hardness)
|
||||||
|
if ns not in visited:
|
||||||
|
visited.add(ns)
|
||||||
|
counter += 1
|
||||||
|
heapq.heappush(
|
||||||
|
pq, (heuristic(ns[0], ns[3]) + depth // 3, depth + 1, counter, ns)
|
||||||
|
)
|
||||||
|
|
||||||
|
return PyramidSolveReport(False, nodes, hardness)
|
||||||
|
|
||||||
|
|
||||||
|
def generate_solvable_pyramid_deal(
|
||||||
|
difficulty: int = 1,
|
||||||
|
seed: int | None = None,
|
||||||
|
) -> tuple[list[list[SolitaireCard | None]], list[SolitaireCard]]:
|
||||||
|
rng = random.Random(seed) if seed is not None else random.Random()
|
||||||
|
diff = max(0, min(3, int(difficulty)))
|
||||||
|
max_redeals = PYRAMID_REDEALS_BY_DIFF.get(diff, 2)
|
||||||
|
|
||||||
|
hardness_targets = {0: -6.0, 1: 8.0, 2: 18.0, 3: 28.0}
|
||||||
|
target = hardness_targets[diff]
|
||||||
|
node_budget = 2800 if diff <= 1 else 4400
|
||||||
|
|
||||||
|
base_deck = list(range(52))
|
||||||
|
candidates: list[tuple[float, list[int]]] = []
|
||||||
|
|
||||||
|
for _attempt in range(280):
|
||||||
|
trial = list(base_deck)
|
||||||
|
rng.shuffle(trial)
|
||||||
|
report = solve_pyramid_deal(trial, max_redeals=max_redeals, max_nodes=node_budget)
|
||||||
|
if not report.solvable:
|
||||||
|
continue
|
||||||
|
composite = report.layout_hardness + (report.nodes_expanded / 45.0)
|
||||||
|
candidates.append((composite, trial))
|
||||||
|
if diff == 0 and composite <= 2.0:
|
||||||
|
break
|
||||||
|
if diff == 1 and 2.0 <= composite <= 22.0:
|
||||||
|
break
|
||||||
|
if diff == 2 and composite >= 14.0 and len(candidates) >= 2:
|
||||||
|
break
|
||||||
|
if diff == 3 and len(candidates) >= 2:
|
||||||
|
break
|
||||||
|
if len(candidates) >= 3:
|
||||||
|
break
|
||||||
|
|
||||||
|
while not candidates:
|
||||||
|
trial = list(base_deck)
|
||||||
|
rng.shuffle(trial)
|
||||||
|
report = solve_pyramid_deal(trial, max_redeals=max_redeals, max_nodes=5200)
|
||||||
|
if report.solvable:
|
||||||
|
candidates.append((report.layout_hardness + report.nodes_expanded / 45.0, trial))
|
||||||
|
|
||||||
|
if diff == 3:
|
||||||
|
best_ids = max(candidates, key=lambda x: x[0])[1]
|
||||||
|
elif diff == 0:
|
||||||
|
best_ids = min(candidates, key=lambda x: x[0])[1]
|
||||||
|
else:
|
||||||
|
best_ids = min(candidates, key=lambda x: abs(x[0] - target))[1]
|
||||||
|
|
||||||
|
pyramid: list[list[SolitaireCard | None]] = []
|
||||||
|
cursor = 0
|
||||||
|
for r in range(7):
|
||||||
|
row = [_decode_card(best_ids[cursor + c]) for c in range(r + 1)]
|
||||||
|
pyramid.append(row)
|
||||||
|
cursor += r + 1
|
||||||
|
|
||||||
|
stock = [_decode_card(cid) for cid in best_ids[28:]]
|
||||||
|
return pyramid, stock
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/pyramid/start.py
|
||||||
|
from games.solitaire.pyramid.views.pyramid_menu_view import PyramidMenuView
|
||||||
|
from resources.code_res.game_constants import CAT_SOLO
|
||||||
|
|
||||||
|
GAME_TITLE_KEY = "game_title_pyramid"
|
||||||
|
GAME_FOLDER_ID = "solitaire/pyramid"
|
||||||
|
GAME_CATEGORY = CAT_SOLO
|
||||||
|
|
||||||
|
|
||||||
|
def start_game(context):
|
||||||
|
PyramidMenuView(context).show(ask_resume_popup=True)
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/pyramid/views/pyramid_menu_view.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
|
||||||
|
from games.solitaire.pyramid.views.pyramid_table_view import PyramidTableView
|
||||||
|
from resources.code_res.game_constants import PYRAMID_VARIANTS
|
||||||
|
|
||||||
|
GAME_FOLDER_ID = "solitaire/pyramid"
|
||||||
|
GAME_TITLE_KEY = "game_title_pyramid"
|
||||||
|
|
||||||
|
|
||||||
|
class PyramidMenuView(SolitaireMenuBase):
|
||||||
|
GAME_FOLDER_ID = GAME_FOLDER_ID
|
||||||
|
GAME_TITLE_KEY = GAME_TITLE_KEY
|
||||||
|
TOPBAR_KEY = "py_menu_topbar"
|
||||||
|
SUBTITLE_KEY = "py_menu_subtitle"
|
||||||
|
CONTROLS_HINT_KEY = "py_controls_hint"
|
||||||
|
|
||||||
|
DIFF_SETTING_PREFIX = "pyramid_diff"
|
||||||
|
DEFAULT_VARIANT_KEY = "pyramid_std"
|
||||||
|
REQUIRED_BOARD_KEYS = ("pyramid", "stock")
|
||||||
|
|
||||||
|
MODE_LABEL_KEY = "py_variant_info_lbl"
|
||||||
|
DESC_KEY_PREFIX = "py_desc_"
|
||||||
|
|
||||||
|
def _variants_dict(self) -> dict[str, dict]:
|
||||||
|
return PYRAMID_VARIANTS
|
||||||
|
|
||||||
|
def _launch_table_view(
|
||||||
|
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
|
||||||
|
) -> None:
|
||||||
|
PyramidTableView(
|
||||||
|
self.ctx,
|
||||||
|
variant_key=variant_key,
|
||||||
|
difficulty=difficulty,
|
||||||
|
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
|
||||||
|
resume_state_json=resume_state_json,
|
||||||
|
)
|
||||||
|
|
@ -0,0 +1,652 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# games/solitaire/pyramid/views/pyramid_table_view.py
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from games.solitaire.base.solitaire_core import SolitaireCard
|
||||||
|
from games.solitaire.base.solitaire_table_controller import SolitaireTableController
|
||||||
|
from games.solitaire.pyramid.models.pyramid_engine import PyramidEngine
|
||||||
|
from resources.code_res.game_constants import (
|
||||||
|
ACCENT_GOLD,
|
||||||
|
BORDER_COLOR,
|
||||||
|
CELL_BG,
|
||||||
|
ERROR_FG,
|
||||||
|
FONT_COLOR_BODY_MUTED,
|
||||||
|
FONT_SIZE_SMALL_MIN,
|
||||||
|
PYRAMID_VARIANTS,
|
||||||
|
SUBTLE_BORDER,
|
||||||
|
)
|
||||||
|
from resources.code_res.i18n import t
|
||||||
|
from view.widgets.image_button import ImageButton
|
||||||
|
|
||||||
|
GAME_FOLDER_ID = "solitaire/pyramid"
|
||||||
|
GAME_TITLE_KEY = "game_title_pyramid"
|
||||||
|
|
||||||
|
|
||||||
|
class PyramidTableView(SolitaireTableController):
|
||||||
|
GAME_FOLDER_ID = GAME_FOLDER_ID
|
||||||
|
HAS_AUTOCOMPLETE_BTN = False
|
||||||
|
SPEED_THRESHOLDS_SEC = (120, 220)
|
||||||
|
|
||||||
|
SOCKET_PAD_PX = 6
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
context,
|
||||||
|
variant_key: str = "pyramid_std",
|
||||||
|
difficulty: int = 1,
|
||||||
|
on_back_to_menu=None,
|
||||||
|
resume_state_json: str | None = None,
|
||||||
|
):
|
||||||
|
v_key = variant_key if variant_key in PYRAMID_VARIANTS else "pyramid_std"
|
||||||
|
cfg = PYRAMID_VARIANTS[v_key]
|
||||||
|
self._init_controller_state(context, v_key, cfg, difficulty, on_back_to_menu)
|
||||||
|
|
||||||
|
self._selected_ref: tuple | None = None
|
||||||
|
self.next_card_btn: ImageButton | None = None
|
||||||
|
|
||||||
|
self._pyr_coords: list[list[tuple[int, int]]] = [
|
||||||
|
[(0, 0) for _ in range(r + 1)] for r in range(7)
|
||||||
|
]
|
||||||
|
self._stock_xy: tuple[int, int] = (0, 0)
|
||||||
|
self._waste_xy: tuple[int, int] = (0, 0)
|
||||||
|
self._next_btn_center: tuple[int, int] = (0, 0)
|
||||||
|
|
||||||
|
if resume_state_json:
|
||||||
|
self.engine = PyramidEngine.__new__(PyramidEngine)
|
||||||
|
super(PyramidEngine, self.engine).__init__()
|
||||||
|
self.engine.difficulty = self.difficulty
|
||||||
|
self.engine.seed = None
|
||||||
|
self.engine.max_redeals = 2
|
||||||
|
self.engine.redeals_used = 0
|
||||||
|
self.engine.stagnant_cycles = 0
|
||||||
|
self.engine._progress_in_cycle = False
|
||||||
|
self.engine.pyramid = []
|
||||||
|
self.engine.stock = []
|
||||||
|
self.engine.waste = []
|
||||||
|
self.engine.removed = []
|
||||||
|
try:
|
||||||
|
self.engine.load_json(resume_state_json)
|
||||||
|
self.difficulty = self.engine.difficulty
|
||||||
|
except Exception:
|
||||||
|
self.engine.new_game(difficulty=self.difficulty)
|
||||||
|
else:
|
||||||
|
self.engine = PyramidEngine(difficulty=self.difficulty)
|
||||||
|
|
||||||
|
self._finish_startup(is_resumed=bool(resume_state_json))
|
||||||
|
|
||||||
|
def _build_ui(self):
|
||||||
|
super()._build_ui()
|
||||||
|
btn_norm = self.ctx.assets.raw_btn_default
|
||||||
|
btn_purp = self.ctx.assets.raw_btn_purple
|
||||||
|
self.next_card_btn = ImageButton(
|
||||||
|
self.canvas,
|
||||||
|
t("py_btn_next_card", len(self.engine.stock)),
|
||||||
|
btn_norm,
|
||||||
|
btn_purp,
|
||||||
|
self._on_next_card_clicked,
|
||||||
|
sound_mgr=self.ctx.sounds,
|
||||||
|
width=196,
|
||||||
|
height=36,
|
||||||
|
style="amethyst",
|
||||||
|
)
|
||||||
|
self._bind_root("<space>", lambda _e: self._on_next_card_shortcut())
|
||||||
|
|
||||||
|
def _on_next_card_shortcut(self) -> str:
|
||||||
|
if not self._is_ui_locked():
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
self._on_next_card_clicked()
|
||||||
|
return "break"
|
||||||
|
|
||||||
|
def _sync_buttons(self):
|
||||||
|
super()._sync_buttons()
|
||||||
|
if self.next_card_btn is not None and self.next_card_btn.winfo_exists():
|
||||||
|
locked = self._is_ui_locked()
|
||||||
|
lbl = (
|
||||||
|
t("py_btn_next_card", len(self.engine.stock))
|
||||||
|
if self.engine.stock
|
||||||
|
else t("py_btn_redeal", self.engine.redeals_remaining)
|
||||||
|
)
|
||||||
|
self.next_card_btn.set_text(lbl)
|
||||||
|
self.next_card_btn.set_enabled((not locked) and self.engine.can_advance_stock)
|
||||||
|
|
||||||
|
def _extra_hud_suffix(self) -> str:
|
||||||
|
return t(
|
||||||
|
"py_hud_extra",
|
||||||
|
self.engine.pyramid_cleared_count,
|
||||||
|
self.engine.redeals_remaining,
|
||||||
|
self.engine.max_redeals,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _reset_engine_for_new_deal(self):
|
||||||
|
if self.animator:
|
||||||
|
self.animator.cancel_shake()
|
||||||
|
self.animator.cancel_falling()
|
||||||
|
self._selected_ref = None
|
||||||
|
self.engine.new_game(difficulty=self.difficulty)
|
||||||
|
|
||||||
|
def _on_undo(self):
|
||||||
|
if self.animator:
|
||||||
|
self.animator.cancel_shake()
|
||||||
|
self.animator.cancel_falling()
|
||||||
|
self._selected_ref = None
|
||||||
|
super()._on_undo()
|
||||||
|
|
||||||
|
def _on_undo_all(self):
|
||||||
|
if self.animator:
|
||||||
|
self.animator.cancel_shake()
|
||||||
|
self.animator.cancel_falling()
|
||||||
|
self._selected_ref = None
|
||||||
|
super()._on_undo_all()
|
||||||
|
|
||||||
|
def _ref_screen_xy(self, ref: tuple) -> tuple[int, int]:
|
||||||
|
if ref[0] == "pyramid":
|
||||||
|
return self._pyr_coords[ref[1]][ref[2]]
|
||||||
|
if ref[0] == "waste":
|
||||||
|
return self._waste_xy
|
||||||
|
return self._stock_xy
|
||||||
|
|
||||||
|
def _trigger_mismatch_shake(self, refs: list[tuple]):
|
||||||
|
if self.hover_zoom is not None:
|
||||||
|
self.hover_zoom.cancel()
|
||||||
|
if self.animator is not None:
|
||||||
|
self.animator.start_shake(refs, self.redraw)
|
||||||
|
|
||||||
|
def _execute_clear_with_fall(
|
||||||
|
self, refs: list[tuple], engine_action_fn, override_first_xy: tuple[int, int] | None = None
|
||||||
|
) -> bool:
|
||||||
|
spawn_items: list[tuple[SolitaireCard, tuple[int, int]]] = []
|
||||||
|
for idx, r in enumerate(refs):
|
||||||
|
c = self.engine.get_card_at_ref(r)
|
||||||
|
if c is not None:
|
||||||
|
xy = override_first_xy if (idx == 0 and override_first_xy is not None) else self._ref_screen_xy(r)
|
||||||
|
spawn_items.append((c, xy))
|
||||||
|
|
||||||
|
if not engine_action_fn():
|
||||||
|
return False
|
||||||
|
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
self._after_player_move()
|
||||||
|
if not self.engine.won and self.animator is not None:
|
||||||
|
self.animator.spawn_falling_cards(self.ctx.assets, self.card_size, spawn_items)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _snapshot_card_positions(self) -> dict[tuple[str, str, int], tuple[int, int]]:
|
||||||
|
pos: dict[tuple[str, str, int], tuple[int, int]] = {}
|
||||||
|
for r in range(7):
|
||||||
|
for c in range(r + 1):
|
||||||
|
card = self.engine.pyramid[r][c]
|
||||||
|
if card is not None:
|
||||||
|
pos[self._card_key(card)] = self._pyr_coords[r][c]
|
||||||
|
for card in self.engine.stock:
|
||||||
|
pos[self._card_key(card)] = self._stock_xy
|
||||||
|
for card in self.engine.waste:
|
||||||
|
pos[self._card_key(card)] = self._waste_xy
|
||||||
|
off_y = max(560, self.canvas.winfo_height()) + 30
|
||||||
|
for card in self.engine.removed:
|
||||||
|
pos[self._card_key(card)] = (self.canvas.winfo_width() // 2, off_y)
|
||||||
|
return pos
|
||||||
|
|
||||||
|
def _ordered_moved_cards(self, moved_keys: set[tuple[str, str, int]]) -> list[SolitaireCard]:
|
||||||
|
ordered: list[SolitaireCard] = []
|
||||||
|
for r in range(7):
|
||||||
|
for c in range(r + 1):
|
||||||
|
card = self.engine.pyramid[r][c]
|
||||||
|
if card is not None and self._card_key(card) in moved_keys:
|
||||||
|
ordered.append(card)
|
||||||
|
for pile in (self.engine.stock, self.engine.waste):
|
||||||
|
for card in pile:
|
||||||
|
if self._card_key(card) in moved_keys:
|
||||||
|
ordered.append(card)
|
||||||
|
return ordered
|
||||||
|
|
||||||
|
def _recompute_and_draw(self):
|
||||||
|
self._resize_job = None
|
||||||
|
if not self._canvas_alive() or self._fx_overlay is not None:
|
||||||
|
return
|
||||||
|
cw, ch = max(680, self.canvas.winfo_width()), max(420, self.canvas.winfo_height())
|
||||||
|
aspect = self._get_card_aspect()
|
||||||
|
margin_x, top_pad, bot_pad = self._bg_renderer.get_frame_insets(cw, ch)
|
||||||
|
|
||||||
|
v_top = max(16, int(top_pad * 0.36))
|
||||||
|
v_bot = max(14, int(bot_pad * 0.34))
|
||||||
|
self._frame_bot_pad = v_bot
|
||||||
|
|
||||||
|
usable_w = max(560, cw - 2 * margin_x)
|
||||||
|
usable_h = max(260, ch - v_top - v_bot)
|
||||||
|
|
||||||
|
card_w_by_h = int(round((usable_h / (1.0 + 6 * 0.39)) / aspect))
|
||||||
|
card_w_by_w = int(usable_w / 10.35)
|
||||||
|
card_w = max(64, min(138, card_w_by_w, card_w_by_h))
|
||||||
|
card_h = int(round(card_w * aspect))
|
||||||
|
self.card_size = (card_w, card_h)
|
||||||
|
|
||||||
|
col_gap = max(8, int(card_w * 0.10))
|
||||||
|
step_x = card_w + col_gap
|
||||||
|
row_dy = max(28, min(int(card_h * 0.40), (usable_h - card_h) // 6))
|
||||||
|
|
||||||
|
pyr_total_w = 6 * step_x + card_w
|
||||||
|
pyr_total_h = 6 * row_dy + card_h
|
||||||
|
|
||||||
|
side_gap = max(34, int(card_w * 0.50))
|
||||||
|
pair_gap = max(22, int(card_w * 0.28))
|
||||||
|
side_total_w = 2 * card_w + pair_gap
|
||||||
|
|
||||||
|
full_w = pyr_total_w + side_gap + side_total_w
|
||||||
|
start_x = max(margin_x, (cw - full_w) // 2)
|
||||||
|
pyr_apex_x = start_x + (pyr_total_w - card_w) // 2
|
||||||
|
pyr_top_y = v_top + max(0, (usable_h - pyr_total_h) // 2)
|
||||||
|
|
||||||
|
for r in range(7):
|
||||||
|
row_x0 = int(round(pyr_apex_x - r * (step_x / 2.0)))
|
||||||
|
ry = pyr_top_y + r * row_dy
|
||||||
|
for c in range(r + 1):
|
||||||
|
self._pyr_coords[r][c] = (row_x0 + c * step_x, ry)
|
||||||
|
|
||||||
|
# Beide offenen Stapel + Button "Nächste Karte" sauber vertikal zentrieren
|
||||||
|
side_block_h = card_h + 62
|
||||||
|
deck_y = pyr_top_y + max(22, (pyr_total_h - side_block_h) // 2)
|
||||||
|
stock_x = start_x + pyr_total_w + side_gap
|
||||||
|
waste_x = stock_x + card_w + pair_gap
|
||||||
|
|
||||||
|
self._stock_xy = (stock_x, deck_y)
|
||||||
|
self._waste_xy = (waste_x, deck_y)
|
||||||
|
self._next_btn_center = (
|
||||||
|
stock_x + side_total_w // 2,
|
||||||
|
deck_y + card_h + self.SOCKET_PAD_PX + 28,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.redraw()
|
||||||
|
|
||||||
|
def _draw_deck_socket(self, x: int, y: int, highlight_color: str | None = None):
|
||||||
|
cw, ch = self.card_size
|
||||||
|
pad = self.SOCKET_PAD_PX
|
||||||
|
outer_col = highlight_color if highlight_color else BORDER_COLOR
|
||||||
|
outer_w = 2 if highlight_color else 1
|
||||||
|
self.canvas.create_rectangle(
|
||||||
|
x - pad,
|
||||||
|
y - pad,
|
||||||
|
x + cw + pad,
|
||||||
|
y + ch + pad,
|
||||||
|
fill=CELL_BG,
|
||||||
|
outline=outer_col,
|
||||||
|
width=outer_w,
|
||||||
|
)
|
||||||
|
self.canvas.create_rectangle(
|
||||||
|
x - 2, y - 2, x + cw + 2, y + ch + 2,
|
||||||
|
fill="", outline=SUBTLE_BORDER, width=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _draw_pile_caption(self, cx: int, y: int, txt: str, color: str = FONT_COLOR_BODY_MUTED):
|
||||||
|
ph = self.ctx.assets.get_goth_text_photo(txt, FONT_SIZE_SMALL_MIN, color)
|
||||||
|
self._canvas_ui_refs.append(ph)
|
||||||
|
self.canvas.create_image(cx, y, image=ph, anchor="center")
|
||||||
|
|
||||||
|
def redraw(
|
||||||
|
self,
|
||||||
|
exclude_source: dict | None = None,
|
||||||
|
hidden_card_keys: set[tuple[str, str, int]] | None = None,
|
||||||
|
):
|
||||||
|
if not self._canvas_alive():
|
||||||
|
return
|
||||||
|
canvas_w, canvas_h = self._prepare_canvas_frame(680, 420)
|
||||||
|
cw, _ch = self.card_size
|
||||||
|
hidden = hidden_card_keys or set()
|
||||||
|
|
||||||
|
if self._selected_ref is not None and self.engine.get_card_at_ref(self._selected_ref) is None:
|
||||||
|
self._selected_ref = None
|
||||||
|
|
||||||
|
hint_refs = set(self._active_hint.get("refs", [])) if self._active_hint else set()
|
||||||
|
|
||||||
|
# 1. 7-stufige Pyramide zeichnen
|
||||||
|
for r in range(7):
|
||||||
|
for c in range(r + 1):
|
||||||
|
px, py = self._pyr_coords[r][c]
|
||||||
|
card = self.engine.pyramid[r][c]
|
||||||
|
ref = ("pyramid", r, c)
|
||||||
|
if exclude_source and exclude_source.get("ref") == ref:
|
||||||
|
card = None
|
||||||
|
if card is None or self._card_key(card) in hidden:
|
||||||
|
if r == 0 and self.engine.pyramid[0][0] is None:
|
||||||
|
self._draw_slot(px, py, symbol="13", symbol_color=ACCENT_GOLD)
|
||||||
|
continue
|
||||||
|
|
||||||
|
exposed = self.engine.is_pyramid_exposed(r, c)
|
||||||
|
is_shaking, s_dx = (
|
||||||
|
self.animator.shake_state_for(ref) if self.animator else (False, 0)
|
||||||
|
)
|
||||||
|
hl = (
|
||||||
|
ERROR_FG
|
||||||
|
if is_shaking
|
||||||
|
else (ACCENT_GOLD if (ref == self._selected_ref or ref in hint_refs) else None)
|
||||||
|
)
|
||||||
|
self._draw_card_at(
|
||||||
|
card,
|
||||||
|
px + s_dx,
|
||||||
|
py,
|
||||||
|
tags=(f"pyr_{r}_{c}",),
|
||||||
|
highlight_color=hl,
|
||||||
|
dim_non_movable=not exposed,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2. Linker Stapel (OFFEN aufgedeckt & direkt auswählbar!)
|
||||||
|
sx, sy = self._stock_xy
|
||||||
|
stock_ref = ("stock",)
|
||||||
|
st_shaking, st_dx = (
|
||||||
|
self.animator.shake_state_for(stock_ref) if self.animator else (False, 0)
|
||||||
|
)
|
||||||
|
st_hl = (
|
||||||
|
ERROR_FG
|
||||||
|
if st_shaking
|
||||||
|
else (ACCENT_GOLD if (stock_ref == self._selected_ref or stock_ref in hint_refs) else None)
|
||||||
|
)
|
||||||
|
self._draw_deck_socket(sx, sy, highlight_color=None if st_shaking else st_hl)
|
||||||
|
|
||||||
|
s_pile = list(self.engine.stock)
|
||||||
|
if exclude_source and exclude_source.get("ref") == stock_ref and s_pile:
|
||||||
|
s_pile = s_pile[:-1]
|
||||||
|
s_pile = [c for c in s_pile if self._card_key(c) not in hidden]
|
||||||
|
if s_pile:
|
||||||
|
if st_shaking and len(s_pile) >= 2:
|
||||||
|
self._draw_card_at(s_pile[-2], sx, sy, tags=("pyr_stock_under",))
|
||||||
|
elif len(s_pile) >= 4:
|
||||||
|
self._draw_card_at(s_pile[-2], sx - 2, sy - 2)
|
||||||
|
self._draw_card_at(
|
||||||
|
s_pile[-1], sx + st_dx, sy, tags=("pyr_stock_top",), highlight_color=st_hl
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
locked = self.engine.is_stock_locked
|
||||||
|
sym = "" if locked else ("↻" if self.engine.waste else "—")
|
||||||
|
self._draw_slot(
|
||||||
|
sx,
|
||||||
|
sy,
|
||||||
|
symbol=sym,
|
||||||
|
symbol_color=ACCENT_GOLD if sym == "↻" else SUBTLE_BORDER,
|
||||||
|
draw_red_cross=bool(locked and self.engine.waste),
|
||||||
|
)
|
||||||
|
self._draw_pile_caption(
|
||||||
|
sx + cw // 2, sy - self.SOCKET_PAD_PX - 14, t("py_lbl_stock", len(self.engine.stock))
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Rechter Ablagestapel (OFFEN aufgedeckt & mit Links oder Pyramide kombinierbar!)
|
||||||
|
wx, wy = self._waste_xy
|
||||||
|
waste_ref = ("waste",)
|
||||||
|
w_shaking, w_dx = (
|
||||||
|
self.animator.shake_state_for(waste_ref) if self.animator else (False, 0)
|
||||||
|
)
|
||||||
|
w_hl = (
|
||||||
|
ERROR_FG
|
||||||
|
if w_shaking
|
||||||
|
else (ACCENT_GOLD if (waste_ref == self._selected_ref or waste_ref in hint_refs) else None)
|
||||||
|
)
|
||||||
|
self._draw_deck_socket(wx, wy, highlight_color=None if w_shaking else w_hl)
|
||||||
|
|
||||||
|
w_pile = list(self.engine.waste)
|
||||||
|
if exclude_source and exclude_source.get("ref") == waste_ref and w_pile:
|
||||||
|
w_pile = w_pile[:-1]
|
||||||
|
w_pile = [c for c in w_pile if self._card_key(c) not in hidden]
|
||||||
|
if w_pile:
|
||||||
|
if w_shaking and len(w_pile) >= 2:
|
||||||
|
self._draw_card_at(w_pile[-2], wx, wy, tags=("pyr_waste_under",))
|
||||||
|
self._draw_card_at(
|
||||||
|
w_pile[-1], wx + w_dx, wy, tags=("pyr_waste_top",), highlight_color=w_hl
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._draw_slot(wx, wy, symbol="◇", symbol_color=SUBTLE_BORDER)
|
||||||
|
self._draw_pile_caption(
|
||||||
|
wx + cw // 2, wy - self.SOCKET_PAD_PX - 14, t("py_lbl_waste", len(self.engine.waste))
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. Button "Nächste Karte" mittig unter den beiden Stapeln platzieren
|
||||||
|
if self.next_card_btn is not None and self.next_card_btn.winfo_exists():
|
||||||
|
bx, by = self._next_btn_center
|
||||||
|
if ("next_btn",) in hint_refs:
|
||||||
|
bw, bh = self.next_card_btn.pixel_width, self.next_card_btn.pixel_height
|
||||||
|
self.canvas.create_rectangle(
|
||||||
|
bx - bw // 2 - 4,
|
||||||
|
by - bh // 2 - 4,
|
||||||
|
bx + bw // 2 + 4,
|
||||||
|
by + bh // 2 + 4,
|
||||||
|
outline=ACCENT_GOLD,
|
||||||
|
width=2,
|
||||||
|
)
|
||||||
|
self.canvas.create_window(bx, by, window=self.next_card_btn, anchor="center")
|
||||||
|
|
||||||
|
if self.animator is not None:
|
||||||
|
self.animator.redraw_falling_layer()
|
||||||
|
|
||||||
|
self._finish_canvas_frame(canvas_w, canvas_h, exclude_source, hidden)
|
||||||
|
|
||||||
|
def _find_first_overlapping_tag(self, row: int, col: int) -> str | None:
|
||||||
|
for nr in range(row + 1, 7):
|
||||||
|
for nc in range(nr + 1):
|
||||||
|
if self.engine.pyramid[nr][nc] is not None:
|
||||||
|
tag = f"pyr_{nr}_{nc}"
|
||||||
|
if self.canvas.find_withtag(tag):
|
||||||
|
return tag
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _hover_card_probe(self, x: int, y: int) -> dict | None:
|
||||||
|
if self.animator and self.animator.has_shake:
|
||||||
|
return None
|
||||||
|
cw, ch = self.card_size
|
||||||
|
for r in range(6, -1, -1):
|
||||||
|
for c in range(r, -1, -1):
|
||||||
|
card = self.engine.pyramid[r][c]
|
||||||
|
if card is None:
|
||||||
|
continue
|
||||||
|
px, py = self._pyr_coords[r][c]
|
||||||
|
if px <= x <= px + cw and py <= y <= py + ch:
|
||||||
|
under_tag = (
|
||||||
|
None
|
||||||
|
if self.engine.is_pyramid_exposed(r, c)
|
||||||
|
else self._find_first_overlapping_tag(r, c)
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"card": card,
|
||||||
|
"x": px,
|
||||||
|
"y": py,
|
||||||
|
"size": self.card_size,
|
||||||
|
"under_tag": under_tag,
|
||||||
|
}
|
||||||
|
|
||||||
|
sx, sy = self._stock_xy
|
||||||
|
if self.engine.stock and sx <= x <= sx + cw and sy <= y <= sy + ch:
|
||||||
|
return {"card": self.engine.stock[-1], "x": sx, "y": sy, "size": self.card_size, "under_tag": None}
|
||||||
|
|
||||||
|
wx, wy = self._waste_xy
|
||||||
|
if self.engine.waste and wx <= x <= wx + cw and wy <= y <= wy + ch:
|
||||||
|
return {"card": self.engine.waste[-1], "x": wx, "y": wy, "size": self.card_size, "under_tag": None}
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _hit_test(self, x: int, y: int) -> dict | None:
|
||||||
|
cw, ch = self.card_size
|
||||||
|
for r in range(6, -1, -1):
|
||||||
|
for c in range(r, -1, -1):
|
||||||
|
card = self.engine.pyramid[r][c]
|
||||||
|
if card is None:
|
||||||
|
continue
|
||||||
|
px, py = self._pyr_coords[r][c]
|
||||||
|
if px <= x <= px + cw and py <= y <= py + ch:
|
||||||
|
if not self.engine.is_pyramid_exposed(r, c):
|
||||||
|
return None
|
||||||
|
ref = ("pyramid", r, c)
|
||||||
|
return {"zone": "pyramid", "ref": ref, "cards": [card], "origin": (px, py)}
|
||||||
|
|
||||||
|
# Klick auf den linken Stapel wählt IMMER die offene Karte aus (oder bei leerem Stapel Redeal)
|
||||||
|
sx, sy = self._stock_xy
|
||||||
|
if sx <= x <= sx + cw and sy <= y <= sy + ch:
|
||||||
|
if self.engine.stock:
|
||||||
|
ref = ("stock",)
|
||||||
|
return {"zone": "stock", "ref": ref, "cards": [self.engine.stock[-1]], "origin": (sx, sy)}
|
||||||
|
return None
|
||||||
|
|
||||||
|
wx, wy = self._waste_xy
|
||||||
|
if self.engine.waste and wx <= x <= wx + cw and wy <= y <= wy + ch:
|
||||||
|
ref = ("waste",)
|
||||||
|
return {"zone": "waste", "ref": ref, "cards": [self.engine.waste[-1]], "origin": (wx, wy)}
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _on_next_card_clicked(self):
|
||||||
|
"""Schiebt per Button 'Nächste Karte' die linke Karte nach rechts (oder Redeal)."""
|
||||||
|
if self._is_ui_locked():
|
||||||
|
return
|
||||||
|
if self.hover_zoom is not None:
|
||||||
|
self.hover_zoom.cancel()
|
||||||
|
if self.animator:
|
||||||
|
self.animator.flush()
|
||||||
|
self.animator.cancel_shake()
|
||||||
|
self._clear_hint()
|
||||||
|
self._selected_ref = None
|
||||||
|
self.engine.start_timer_if_needed()
|
||||||
|
|
||||||
|
def do_advance() -> bool:
|
||||||
|
ok, reason = self.engine.draw_or_recycle_stock()
|
||||||
|
if not ok:
|
||||||
|
if reason == "redeal_limit":
|
||||||
|
self.status_var.set(t("sol_redeal_limit_msg", self.engine.max_redeals))
|
||||||
|
elif reason == "stagnant":
|
||||||
|
self.status_var.set(t("sol_stock_stagnant_msg"))
|
||||||
|
self.redraw()
|
||||||
|
self._check_deadlock_and_prompt()
|
||||||
|
return ok
|
||||||
|
|
||||||
|
self._run_animated_action(do_advance, duration_ms=95, after_cb=self._after_player_move)
|
||||||
|
|
||||||
|
def _handle_click(self, info: dict):
|
||||||
|
if self.animator:
|
||||||
|
self.animator.cancel_shake()
|
||||||
|
ref = info.get("ref")
|
||||||
|
if ref is None:
|
||||||
|
return
|
||||||
|
card = self.engine.get_card_at_ref(ref)
|
||||||
|
if card is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
# König (13) ohne aktive Vorwahl -> sofort drehend herausfallen lassen
|
||||||
|
if card.value == 13 and self._selected_ref is None:
|
||||||
|
self._execute_clear_with_fall([ref], lambda: self.engine.remove_king(ref))
|
||||||
|
return
|
||||||
|
|
||||||
|
# Zweite Karte angeklickt -> Paar (inkl. Links + Rechts!) prüfen
|
||||||
|
if self._selected_ref is not None:
|
||||||
|
if self._selected_ref == ref:
|
||||||
|
self._selected_ref = None
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
self.redraw()
|
||||||
|
return
|
||||||
|
|
||||||
|
prev_ref = self._selected_ref
|
||||||
|
prev_card = self.engine.get_card_at_ref(prev_ref)
|
||||||
|
ok, total = self.engine.can_pair_refs(prev_ref, ref)
|
||||||
|
self._selected_ref = None
|
||||||
|
if ok:
|
||||||
|
self._execute_clear_with_fall(
|
||||||
|
[prev_ref, ref], lambda: self.engine.remove_pair(prev_ref, ref)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if prev_card is not None:
|
||||||
|
self.status_var.set(
|
||||||
|
t("py_sum_mismatch_msg", prev_card.label, prev_card.value, card.label, card.value, total)
|
||||||
|
)
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
self._trigger_mismatch_shake([prev_ref, ref])
|
||||||
|
return
|
||||||
|
|
||||||
|
# Erste Karte angeklickt (auch links auf dem Stapel!) -> immer erst auswählen!
|
||||||
|
self._selected_ref = ref
|
||||||
|
self.status_var.set("")
|
||||||
|
self.ctx.sounds.play("click")
|
||||||
|
self.redraw()
|
||||||
|
|
||||||
|
def _smart_auto_move(self, info: dict):
|
||||||
|
self._handle_click(info)
|
||||||
|
|
||||||
|
def _on_mouse_up(self, event):
|
||||||
|
info, was_dragging = self._press_info, self._dragging
|
||||||
|
self._press_info, self._dragging = None, False
|
||||||
|
if not info:
|
||||||
|
return
|
||||||
|
if not was_dragging:
|
||||||
|
self._handle_click(info)
|
||||||
|
return
|
||||||
|
|
||||||
|
self.canvas.delete("drag_ghost")
|
||||||
|
ox, oy = info["origin"]
|
||||||
|
sx, sy = info["start_xy"]
|
||||||
|
drop_x, drop_y = ox + (event.x - sx), oy + (event.y - sy)
|
||||||
|
|
||||||
|
if self._try_drop(info, drop_x, drop_y):
|
||||||
|
return
|
||||||
|
|
||||||
|
cards: list[SolitaireCard] = info.get("cards", [])
|
||||||
|
if cards and self.animator:
|
||||||
|
hidden_keys = {self._card_key(cards[0])}
|
||||||
|
self.redraw(hidden_card_keys=hidden_keys)
|
||||||
|
self.animator.start(
|
||||||
|
[{"card": cards[0], "start": (drop_x, drop_y), "end": (ox, oy)}],
|
||||||
|
self._draw_card_at,
|
||||||
|
duration_ms=85,
|
||||||
|
on_done=self.redraw,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.redraw()
|
||||||
|
|
||||||
|
def _try_drop(self, info: dict, drop_x: int, drop_y: int) -> bool:
|
||||||
|
if self.animator:
|
||||||
|
self.animator.cancel_shake()
|
||||||
|
src_ref = info.get("ref")
|
||||||
|
cards = info.get("cards", [])
|
||||||
|
if src_ref is None or not cards:
|
||||||
|
return False
|
||||||
|
cw, ch = self.card_size
|
||||||
|
cx, cy = drop_x + cw // 2, drop_y + ch // 2
|
||||||
|
|
||||||
|
if cards[0].value == 13 and self._selected_ref is None:
|
||||||
|
ox, oy = info["origin"]
|
||||||
|
if abs(drop_x - ox) > 18 or abs(drop_y - oy) > 18:
|
||||||
|
return self._execute_clear_with_fall(
|
||||||
|
[src_ref],
|
||||||
|
lambda: self.engine.remove_king(src_ref),
|
||||||
|
override_first_xy=(drop_x, drop_y),
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
candidates: list[tuple[int, tuple]] = []
|
||||||
|
for r in range(7):
|
||||||
|
for c in range(r + 1):
|
||||||
|
if not self.engine.is_pyramid_exposed(r, c):
|
||||||
|
continue
|
||||||
|
t_ref = ("pyramid", r, c)
|
||||||
|
if t_ref == src_ref:
|
||||||
|
continue
|
||||||
|
px, py = self._pyr_coords[r][c]
|
||||||
|
dx, dy = abs(cx - (px + cw // 2)), abs(cy - (py + ch // 2))
|
||||||
|
if dx <= int(cw * 0.72) and dy <= int(ch * 0.72):
|
||||||
|
candidates.append((dx + dy, t_ref))
|
||||||
|
|
||||||
|
for t_ref, (tx, ty) in ((("stock",), self._stock_xy), (("waste",), self._waste_xy)):
|
||||||
|
if t_ref == src_ref or self.engine.get_card_at_ref(t_ref) is None:
|
||||||
|
continue
|
||||||
|
dx, dy = abs(cx - (tx + cw // 2)), abs(cy - (ty + ch // 2))
|
||||||
|
if dx <= int(cw * 0.72) and dy <= int(ch * 0.72):
|
||||||
|
candidates.append((dx + dy, t_ref))
|
||||||
|
|
||||||
|
candidates.sort(key=lambda item: item[0])
|
||||||
|
for _dist, dst_ref in candidates:
|
||||||
|
ok, total = self.engine.can_pair_refs(src_ref, dst_ref)
|
||||||
|
self._selected_ref = None
|
||||||
|
if ok:
|
||||||
|
return self._execute_clear_with_fall(
|
||||||
|
[src_ref, dst_ref],
|
||||||
|
lambda: self.engine.remove_pair(src_ref, dst_ref),
|
||||||
|
override_first_xy=(drop_x, drop_y),
|
||||||
|
)
|
||||||
|
dst_card = self.engine.get_card_at_ref(dst_ref)
|
||||||
|
if dst_card is not None:
|
||||||
|
self.status_var.set(
|
||||||
|
t("py_sum_mismatch_msg", cards[0].label, cards[0].value, dst_card.label, dst_card.value, total)
|
||||||
|
)
|
||||||
|
self.ctx.root.after(95, lambda a=src_ref, b=dst_ref: self._trigger_mismatch_shake([a, b]))
|
||||||
|
return False
|
||||||
|
return False
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -2,552 +2,46 @@
|
||||||
# games/solitaire/spider_solitaire/views/spider_menu_view.py
|
# games/solitaire/spider_solitaire/views/spider_menu_view.py
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
|
||||||
import tkinter as tk
|
|
||||||
from tkinter import ttk
|
|
||||||
|
|
||||||
from games.solitaire.base.solitaire_stats_view import SolitaireStatsView
|
|
||||||
from games.solitaire.spider_solitaire.views.spider_table_view import SpiderTableView
|
from games.solitaire.spider_solitaire.views.spider_table_view import SpiderTableView
|
||||||
from models.database import Database
|
from resources.code_res.game_constants import SPIDER_VARIANTS
|
||||||
from models.progression import Progression
|
|
||||||
from resources.code_res.game_constants import (
|
|
||||||
ACCENT_GOLD,
|
|
||||||
ACCENT_GOTH,
|
|
||||||
BG_COLOR,
|
|
||||||
BORDER_COLOR,
|
|
||||||
CELL_BG,
|
|
||||||
ERROR_FG,
|
|
||||||
FG_COLOR,
|
|
||||||
MODAL_BG,
|
|
||||||
MUTED_FG,
|
|
||||||
PANEL_BG,
|
|
||||||
SOLITAIRE_DIFFICULTIES,
|
|
||||||
SOLO_FORFEIT_XP_RATIO,
|
|
||||||
SPIDER_VARIANTS,
|
|
||||||
SUBTLE_BORDER,
|
|
||||||
)
|
|
||||||
from resources.code_res.i18n import t
|
|
||||||
from view.widgets.image_button import ImageButton
|
|
||||||
|
|
||||||
GAME_FOLDER_ID = "solitaire/spider_solitaire"
|
GAME_FOLDER_ID = "solitaire/spider_solitaire"
|
||||||
GAME_TITLE_KEY = "game_title_spider_solitaire"
|
GAME_TITLE_KEY = "game_title_spider_solitaire"
|
||||||
|
|
||||||
|
|
||||||
class SpiderMenuView:
|
class SpiderMenuView(SolitaireMenuBase):
|
||||||
def __init__(self, context):
|
GAME_FOLDER_ID = GAME_FOLDER_ID
|
||||||
self.ctx = context
|
GAME_TITLE_KEY = GAME_TITLE_KEY
|
||||||
self._modal_overlay: tk.Frame | None = None
|
TOPBAR_KEY = "sp_menu_topbar"
|
||||||
self._return_bind_id: str | None = None
|
SUBTITLE_KEY = "sp_menu_subtitle"
|
||||||
|
CONTROLS_HINT_KEY = "sp_controls_hint"
|
||||||
|
|
||||||
def _clear_modal(self):
|
DIFF_SETTING_PREFIX = "spider_diff"
|
||||||
if self._return_bind_id is not None:
|
VARIANT_SETTING_PREFIX = "spider_variant"
|
||||||
try:
|
DEFAULT_VARIANT_KEY = "spider_1suit"
|
||||||
self.ctx.root.unbind("<Return>", self._return_bind_id)
|
DEFAULT_SCORE = 500
|
||||||
except Exception:
|
REQUIRED_BOARD_KEYS = ("tableau", "stock_deals")
|
||||||
pass
|
|
||||||
self._return_bind_id = None
|
|
||||||
if self._modal_overlay is not None:
|
|
||||||
try:
|
|
||||||
self._modal_overlay.destroy()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
self._modal_overlay = None
|
|
||||||
|
|
||||||
def show(
|
MODE_LABEL_KEY = "sp_suit_mode_lbl"
|
||||||
self,
|
VARIANT_TOGGLES = (
|
||||||
status_msg: str = "",
|
("spider_1suit", "sp_suit_toggle_1"),
|
||||||
status_is_ok: bool = False,
|
("spider_2suit", "sp_suit_toggle_2"),
|
||||||
ask_resume_popup: bool = False,
|
("spider_4suit", "sp_suit_toggle_4"),
|
||||||
):
|
)
|
||||||
self._clear_modal()
|
TOGGLE_BTN_WIDTH = 158
|
||||||
pid = self.ctx.profile["id"]
|
DESC_KEY_PREFIX = "sp_desc_"
|
||||||
self.ctx.sounds.play_menu_music()
|
|
||||||
self.ctx.root.clear_window(apply_global_bg=True)
|
|
||||||
prog = self.ctx.refresh_game_progress()
|
|
||||||
|
|
||||||
diff_setting_key = f"spider_diff_{pid}"
|
def _variants_dict(self) -> dict[str, dict]:
|
||||||
var_setting_key = f"spider_variant_{pid}"
|
return SPIDER_VARIANTS
|
||||||
|
|
||||||
saved_diff_str = Database.load_setting(diff_setting_key, "1")
|
def _launch_table_view(
|
||||||
selected_diff = (
|
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
|
||||||
int(saved_diff_str)
|
) -> None:
|
||||||
if saved_diff_str.isdigit() and int(saved_diff_str) in SOLITAIRE_DIFFICULTIES
|
|
||||||
else 1
|
|
||||||
)
|
|
||||||
|
|
||||||
selected_variant = Database.load_setting(var_setting_key, "spider_1suit")
|
|
||||||
if selected_variant not in SPIDER_VARIANTS:
|
|
||||||
selected_variant = "spider_1suit"
|
|
||||||
|
|
||||||
def open_stats():
|
|
||||||
self._clear_modal()
|
|
||||||
variants = Database.get_variants_for_filter(GAME_FOLDER_ID)
|
|
||||||
pre_id = next((v["id"] for v in variants if v["variant_key"] == selected_variant), None)
|
|
||||||
SolitaireStatsView(
|
|
||||||
self.ctx,
|
|
||||||
game_folder=GAME_FOLDER_ID,
|
|
||||||
game_title_key=GAME_TITLE_KEY,
|
|
||||||
on_back=lambda: self.show(),
|
|
||||||
).show(preselect_variant_id=pre_id)
|
|
||||||
|
|
||||||
rank_badge = f"{prog['title']} (Lv. {prog['level']} • {prog['current_xp']}/{prog['needed_xp']} XP)"
|
|
||||||
self.ctx.build_game_topbar(
|
|
||||||
self.ctx.root,
|
|
||||||
t("sp_menu_topbar"),
|
|
||||||
on_game_menu=None,
|
|
||||||
on_stats=open_stats,
|
|
||||||
stats_enabled=True,
|
|
||||||
extra_right_text=rank_badge,
|
|
||||||
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
|
|
||||||
)
|
|
||||||
|
|
||||||
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=14)
|
|
||||||
container.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.88, relheight=0.84)
|
|
||||||
|
|
||||||
main_card = tk.Frame(
|
|
||||||
container,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
padx=26,
|
|
||||||
pady=20,
|
|
||||||
highlightthickness=1,
|
|
||||||
highlightbackground=BORDER_COLOR,
|
|
||||||
)
|
|
||||||
main_card.pack(fill="x")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=t(GAME_TITLE_KEY),
|
|
||||||
font=("Georgia", 18, "bold"),
|
|
||||||
fg=ACCENT_GOLD,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=t("sp_menu_subtitle"),
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
fg=MUTED_FG,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w", pady=(4, 14))
|
|
||||||
|
|
||||||
if status_msg:
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=status_msg,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
fg="#7be08a" if status_is_ok else ERROR_FG,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w", pady=(0, 12))
|
|
||||||
|
|
||||||
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
|
|
||||||
saved_meta = self._parse_saved_meta(saved)
|
|
||||||
|
|
||||||
if saved and saved_meta is not None:
|
|
||||||
resume_box = tk.Frame(
|
|
||||||
main_card,
|
|
||||||
bg=CELL_BG,
|
|
||||||
padx=18,
|
|
||||||
pady=12,
|
|
||||||
highlightthickness=1,
|
|
||||||
highlightbackground=ACCENT_GOTH,
|
|
||||||
)
|
|
||||||
resume_box.pack(fill="x", pady=(0, 16))
|
|
||||||
|
|
||||||
left_info = tk.Frame(resume_box, bg=CELL_BG)
|
|
||||||
left_info.pack(side="left", fill="x", expand=True)
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
left_info,
|
|
||||||
text=t("sol_resume_box_title"),
|
|
||||||
font=("Georgia", 12, "bold"),
|
|
||||||
fg=ACCENT_GOTH,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(anchor="w")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
left_info,
|
|
||||||
text=t(
|
|
||||||
"sol_resume_info",
|
|
||||||
t(f"variant_{saved['variant_key']}"),
|
|
||||||
t(f"sol_diff_short_{saved_meta['difficulty']}"),
|
|
||||||
saved_meta["moves"],
|
|
||||||
saved_meta["score"],
|
|
||||||
Database.format_seconds(saved_meta["elapsed_sec"]),
|
|
||||||
),
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(anchor="w", pady=(4, 0))
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
resume_box,
|
|
||||||
t("sol_resume_btn"),
|
|
||||||
self.ctx.assets.raw_btn,
|
|
||||||
self.ctx.assets.raw_btn_active,
|
|
||||||
lambda: self._resume_saved(saved, saved_meta["difficulty"]),
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=185,
|
|
||||||
height=36,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="right", padx=(12, 0))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=t("sol_setup_sec_title"),
|
|
||||||
font=("Georgia", 12, "bold"),
|
|
||||||
fg=ACCENT_GOTH,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w", pady=(2, 8))
|
|
||||||
|
|
||||||
setup_box = tk.Frame(
|
|
||||||
main_card,
|
|
||||||
bg=CELL_BG,
|
|
||||||
padx=20,
|
|
||||||
pady=18,
|
|
||||||
highlightthickness=1,
|
|
||||||
highlightbackground=SUBTLE_BORDER,
|
|
||||||
)
|
|
||||||
setup_box.pack(fill="x")
|
|
||||||
|
|
||||||
# Zeile 1: 1 / 2 / 4 Farben Direkt-Umschalter
|
|
||||||
suit_row = tk.Frame(setup_box, bg=CELL_BG)
|
|
||||||
suit_row.pack(fill="x", pady=(0, 8))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
suit_row,
|
|
||||||
text=t("sp_suit_mode_lbl"),
|
|
||||||
width=16,
|
|
||||||
anchor="w",
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(side="left")
|
|
||||||
|
|
||||||
def switch_suit_mode(v_key: str):
|
|
||||||
if v_key == selected_variant or self._modal_overlay is not None:
|
|
||||||
return
|
|
||||||
Database.save_setting(var_setting_key, v_key)
|
|
||||||
self.show(status_msg=status_msg, status_is_ok=status_is_ok)
|
|
||||||
|
|
||||||
suit_toggles = (
|
|
||||||
("spider_1suit", "sp_suit_toggle_1"),
|
|
||||||
("spider_2suit", "sp_suit_toggle_2"),
|
|
||||||
("spider_4suit", "sp_suit_toggle_4"),
|
|
||||||
)
|
|
||||||
for v_key, lbl_key in suit_toggles:
|
|
||||||
is_sel = selected_variant == v_key
|
|
||||||
raw_norm = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel
|
|
||||||
raw_act = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel_active
|
|
||||||
ImageButton(
|
|
||||||
suit_row,
|
|
||||||
t(lbl_key),
|
|
||||||
raw_norm,
|
|
||||||
raw_act,
|
|
||||||
lambda k=v_key: switch_suit_mode(k),
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=165,
|
|
||||||
height=34,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="left", padx=(0, 10))
|
|
||||||
|
|
||||||
# Kurze Infozeile zur gewählten Farb-Variante
|
|
||||||
desc_row = tk.Frame(setup_box, bg=CELL_BG)
|
|
||||||
desc_row.pack(fill="x", pady=(0, 12))
|
|
||||||
tk.Label(desc_row, text="", width=16, bg=CELL_BG).pack(side="left")
|
|
||||||
tk.Label(
|
|
||||||
desc_row,
|
|
||||||
text=t(f"sp_desc_{selected_variant}"),
|
|
||||||
font=("Helvetica", 9),
|
|
||||||
fg=MUTED_FG,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(side="left")
|
|
||||||
|
|
||||||
# Zeile 2: Schwierigkeitsgrad
|
|
||||||
diff_row = tk.Frame(setup_box, bg=CELL_BG)
|
|
||||||
diff_row.pack(fill="x", pady=(0, 16))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
diff_row,
|
|
||||||
text=t("sol_diff_lbl"),
|
|
||||||
width=16,
|
|
||||||
anchor="w",
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=CELL_BG,
|
|
||||||
).pack(side="left")
|
|
||||||
|
|
||||||
diff_labels = [t(f"sol_diff_{lvl}") for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())]
|
|
||||||
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())}
|
|
||||||
diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}"))
|
|
||||||
|
|
||||||
diff_cb = ttk.Combobox(
|
|
||||||
diff_row,
|
|
||||||
textvariable=diff_var,
|
|
||||||
values=diff_labels,
|
|
||||||
state="readonly",
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
style="Goth.TCombobox",
|
|
||||||
)
|
|
||||||
diff_cb.pack(side="left", fill="x", expand=True, ipady=3)
|
|
||||||
|
|
||||||
def on_diff_changed(*_):
|
|
||||||
chosen = diff_map.get(diff_var.get(), 1)
|
|
||||||
Database.save_setting(diff_setting_key, str(chosen))
|
|
||||||
|
|
||||||
diff_cb.bind("<<ComboboxSelected>>", on_diff_changed)
|
|
||||||
|
|
||||||
# Zeile 3: Start
|
|
||||||
action_row = tk.Frame(setup_box, bg=CELL_BG)
|
|
||||||
action_row.pack(fill="x")
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
action_row,
|
|
||||||
t("sol_start_btn"),
|
|
||||||
self.ctx.assets.raw_btn,
|
|
||||||
self.ctx.assets.raw_btn_active,
|
|
||||||
lambda: self._on_start_clicked(
|
|
||||||
selected_variant, diff_map.get(diff_var.get(), 1), saved, saved_meta
|
|
||||||
),
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=210,
|
|
||||||
height=38,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="right")
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
main_card,
|
|
||||||
text=t("sp_controls_hint"),
|
|
||||||
font=("Helvetica", 9),
|
|
||||||
fg=MUTED_FG,
|
|
||||||
bg=PANEL_BG,
|
|
||||||
).pack(anchor="w", pady=(14, 0))
|
|
||||||
|
|
||||||
if ask_resume_popup and saved and saved_meta is not None:
|
|
||||||
self._show_resume_prompt_modal(saved, saved_meta)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _parse_saved_meta(saved: dict | None) -> dict | None:
|
|
||||||
if not saved:
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
data = json.loads(saved["state_json"])
|
|
||||||
if data.get("won"):
|
|
||||||
return None
|
|
||||||
board = data.get("board", {})
|
|
||||||
if not board or "tableau" not in board or "stock_deals" not in board:
|
|
||||||
return None
|
|
||||||
return {
|
|
||||||
"moves": max(0, int(data.get("moves", 0))),
|
|
||||||
"score": int(data.get("score", 500)),
|
|
||||||
"elapsed_sec": float(data.get("elapsed_sec", 0.0)),
|
|
||||||
"difficulty": max(0, min(3, int(board.get("difficulty", 1)))),
|
|
||||||
}
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
|
|
||||||
self._clear_modal()
|
|
||||||
overlay = tk.Frame(
|
|
||||||
self.ctx.root,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
padx=30,
|
|
||||||
pady=24,
|
|
||||||
highlightthickness=2,
|
|
||||||
highlightbackground=ACCENT_GOTH,
|
|
||||||
)
|
|
||||||
overlay.place(relx=0.5, rely=0.52, anchor="center")
|
|
||||||
self._modal_overlay = overlay
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
overlay,
|
|
||||||
text=t("sol_resume_box_title"),
|
|
||||||
font=("Georgia", 16, "bold"),
|
|
||||||
fg=ACCENT_GOLD,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
).pack(pady=(0, 10))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
overlay,
|
|
||||||
text=t(
|
|
||||||
"sol_resume_info",
|
|
||||||
t(f"variant_{saved['variant_key']}"),
|
|
||||||
t(f"sol_diff_short_{saved_meta['difficulty']}"),
|
|
||||||
saved_meta["moves"],
|
|
||||||
saved_meta["score"],
|
|
||||||
Database.format_seconds(saved_meta["elapsed_sec"]),
|
|
||||||
),
|
|
||||||
font=("Helvetica", 11),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
justify="center",
|
|
||||||
).pack(pady=(0, 20))
|
|
||||||
|
|
||||||
btn_row = tk.Frame(overlay, bg=MODAL_BG)
|
|
||||||
btn_row.pack()
|
|
||||||
|
|
||||||
def resume_now(_event=None):
|
|
||||||
self._clear_modal()
|
|
||||||
self._resume_saved(saved, saved_meta["difficulty"])
|
|
||||||
|
|
||||||
try:
|
|
||||||
self._return_bind_id = self.ctx.root.bind("<Return>", resume_now, add="+")
|
|
||||||
except tk.TclError:
|
|
||||||
self._return_bind_id = None
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
btn_row,
|
|
||||||
t("sol_resume_btn"),
|
|
||||||
self.ctx.assets.raw_btn,
|
|
||||||
self.ctx.assets.raw_btn_active,
|
|
||||||
resume_now,
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=190,
|
|
||||||
height=38,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="left", padx=6)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
btn_row,
|
|
||||||
t("bj_popup_to_menu_btn"),
|
|
||||||
self.ctx.assets.raw_sel,
|
|
||||||
self.ctx.assets.raw_sel_active,
|
|
||||||
self._clear_modal,
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=175,
|
|
||||||
height=38,
|
|
||||||
font=("Helvetica", 10, "bold"),
|
|
||||||
).pack(side="left", padx=6)
|
|
||||||
|
|
||||||
def _resume_saved(self, saved: dict, difficulty: int):
|
|
||||||
self._clear_modal()
|
|
||||||
SpiderTableView(
|
|
||||||
self.ctx,
|
|
||||||
variant_key=saved["variant_key"],
|
|
||||||
difficulty=difficulty,
|
|
||||||
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
|
|
||||||
resume_state_json=saved["state_json"],
|
|
||||||
)
|
|
||||||
|
|
||||||
def _on_start_clicked(
|
|
||||||
self,
|
|
||||||
variant_key: str,
|
|
||||||
difficulty: int,
|
|
||||||
saved: dict | None,
|
|
||||||
saved_meta: dict | None,
|
|
||||||
):
|
|
||||||
if self._modal_overlay is not None:
|
|
||||||
return
|
|
||||||
if saved and saved_meta and saved_meta["moves"] > 0:
|
|
||||||
self._show_overwrite_confirm_modal(variant_key, difficulty, saved, saved_meta)
|
|
||||||
return
|
|
||||||
self._launch_fresh_game(variant_key, difficulty)
|
|
||||||
|
|
||||||
def _show_overwrite_confirm_modal(
|
|
||||||
self,
|
|
||||||
new_variant_key: str,
|
|
||||||
new_difficulty: int,
|
|
||||||
saved: dict,
|
|
||||||
saved_meta: dict,
|
|
||||||
):
|
|
||||||
pid = self.ctx.profile["id"]
|
|
||||||
old_v = saved["variant_key"]
|
|
||||||
old_diff = saved_meta["difficulty"]
|
|
||||||
prog = Database.get_game_progress(pid, GAME_FOLDER_ID)
|
|
||||||
v_mult = SPIDER_VARIANTS.get(old_v, {"xp_mult": 1.10})["xp_mult"]
|
|
||||||
d_mult = SOLITAIRE_DIFFICULTIES.get(old_diff, SOLITAIRE_DIFFICULTIES[1])["xp_mult"]
|
|
||||||
win_xp = Progression.calculate_match_xp(prog["level"], [], "WIN", variant_mult=v_mult * d_mult)
|
|
||||||
penalty = max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO)))
|
|
||||||
|
|
||||||
overlay = tk.Frame(
|
|
||||||
self.ctx.root,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
padx=28,
|
|
||||||
pady=22,
|
|
||||||
highlightthickness=2,
|
|
||||||
highlightbackground=ERROR_FG,
|
|
||||||
)
|
|
||||||
overlay.place(relx=0.5, rely=0.52, anchor="center")
|
|
||||||
self._modal_overlay = overlay
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
overlay,
|
|
||||||
text=t("sol_forfeit_title"),
|
|
||||||
font=("Georgia", 15, "bold"),
|
|
||||||
fg=ERROR_FG,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
).pack(pady=(0, 8))
|
|
||||||
|
|
||||||
tk.Label(
|
|
||||||
overlay,
|
|
||||||
text=t("sol_forfeit_desc", penalty),
|
|
||||||
font=("Helvetica", 10),
|
|
||||||
fg=FG_COLOR,
|
|
||||||
bg=MODAL_BG,
|
|
||||||
wraplength=430,
|
|
||||||
justify="center",
|
|
||||||
).pack(pady=(0, 18))
|
|
||||||
|
|
||||||
row = tk.Frame(overlay, bg=MODAL_BG)
|
|
||||||
row.pack()
|
|
||||||
|
|
||||||
def forfeit_and_start():
|
|
||||||
floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0
|
|
||||||
Database.record_game_result(
|
|
||||||
pid,
|
|
||||||
variant_key=old_v,
|
|
||||||
won=False,
|
|
||||||
duration_sec=saved_meta["elapsed_sec"],
|
|
||||||
points_gained=0,
|
|
||||||
)
|
|
||||||
Database.adjust_game_points(pid, GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp)
|
|
||||||
self.ctx.refresh_game_progress()
|
|
||||||
self._clear_modal()
|
|
||||||
self._launch_fresh_game(new_variant_key, new_difficulty)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
row,
|
|
||||||
t("sol_resume_btn"),
|
|
||||||
self.ctx.assets.raw_btn,
|
|
||||||
self.ctx.assets.raw_btn_active,
|
|
||||||
lambda: self._resume_saved(saved, old_diff),
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=165,
|
|
||||||
height=34,
|
|
||||||
font=("Helvetica", 9, "bold"),
|
|
||||||
).pack(side="left", padx=5)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
row,
|
|
||||||
t("sol_forfeit_confirm_new"),
|
|
||||||
self.ctx.assets.raw_sel,
|
|
||||||
self.ctx.assets.raw_sel_active,
|
|
||||||
forfeit_and_start,
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=175,
|
|
||||||
height=34,
|
|
||||||
font=("Helvetica", 9, "bold"),
|
|
||||||
).pack(side="left", padx=5)
|
|
||||||
|
|
||||||
ImageButton(
|
|
||||||
row,
|
|
||||||
t("bj_popup_to_menu_btn"),
|
|
||||||
self.ctx.assets.raw_sel,
|
|
||||||
self.ctx.assets.raw_sel_active,
|
|
||||||
self._clear_modal,
|
|
||||||
sound_mgr=self.ctx.sounds,
|
|
||||||
width=155,
|
|
||||||
height=34,
|
|
||||||
font=("Helvetica", 9, "bold"),
|
|
||||||
).pack(side="left", padx=5)
|
|
||||||
|
|
||||||
def _launch_fresh_game(self, variant_key: str, difficulty: int):
|
|
||||||
pid = self.ctx.profile["id"]
|
|
||||||
Database.save_setting(f"spider_diff_{pid}", str(difficulty))
|
|
||||||
Database.save_setting(f"spider_variant_{pid}", variant_key)
|
|
||||||
Database.delete_game_state(pid, GAME_FOLDER_ID)
|
|
||||||
SpiderTableView(
|
SpiderTableView(
|
||||||
self.ctx,
|
self.ctx,
|
||||||
variant_key=variant_key,
|
variant_key=variant_key,
|
||||||
difficulty=difficulty,
|
difficulty=difficulty,
|
||||||
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
|
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
|
||||||
|
resume_state_json=resume_state_json,
|
||||||
)
|
)
|
||||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue